content
stringlengths 7
2.61M
|
---|
def cancel_callback(self, name):
self._callbacks[name].stop()
del self._callbacks[name] |
// Copyright 2018 The Operator-SDK 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.
package flags
import (
"strings"
"time"
"github.com/spf13/pflag"
)
// AnsibleOperatorFlags - Options to be used by an ansible operator
type AnsibleOperatorFlags struct {
ReconcilePeriod time.Duration
WatchesFile string
}
// AddTo - Add the ansible operator flags to the the flagset
// helpTextPrefix will allow you add a prefix to default help text. Joined by a space.
func AddTo(flagSet *pflag.FlagSet, helpTextPrefix ...string) *AnsibleOperatorFlags {
aof := &AnsibleOperatorFlags{}
flagSet.DurationVar(&aof.ReconcilePeriod,
"reconcile-period",
time.Minute,
strings.Join(append(helpTextPrefix, "Default reconcile period for controllers"), " "),
)
flagSet.StringVar(&aof.WatchesFile,
"watches-file",
"./watches.yaml",
strings.Join(append(helpTextPrefix, "Path to the watches file to use"), " "),
)
return aof
}
|
Island Tourism or Tourism on Islands? Islands are, and always have been, fascinating places. Associated with notions of remoteness, separateness, difference and the exotic, they are the stuff of romance and adventure, of fantasy and escape, of 'otherness'. Not surprisingly, then, islands have long been the subject of myth and legend or, as Gillis (2007: 274) puts it, they 'have long held a central place in Western cultures' mythical geographies. They have been associated for centuries with heroic journeys and holy quests, imagined realms of magical transformations.' Since Plato first described Atlantis, the lost city still sought by historians, archaeologists and others, islands have stirred the imagination of writers, artists and poets, and more contemporary literature is replete with tales of fantasy, discovery, survival, love, mystery and transformation in island settings. Indeed, Baldacchino (2008: 44) suggests that the 'richness of literary and cultural islanding', or the dominance of islands in literature, art, cinema and other cultural endeavour, is such that it is easy to forget that islands are real, physical entities. A similar point is made by Hay (2006: 30) who argues that 'so powerful is the metaphorical idea of the island that it can be deployed in the absence of even the slightest reference to the reality of islands.' |
<reponame>Rkhoiwal/Competitive-prog-Archive
#include <iostream>
using namespace std;
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
int main()
{
use_io_optimizations();
unsigned int candles;
unsigned int old_for_new;
cin >> candles >> old_for_new;
unsigned int hours {candles};
for (unsigned int old_candles {candles}; old_candles >= old_for_new; )
{
unsigned int new_candles {old_candles / old_for_new};
old_candles %= old_for_new;
old_candles += new_candles;
hours += new_candles;
}
cout << hours << '\n';
return 0;
}
|
Stonewall, Manitoba
Provincial
Stonewall is located in the Riding of Lakeside of Legislative Assembly of Manitoba and is currently represented by Ralph Eichler of the Progressive Conservative Party of Manitoba.
Federal
Stonewall is located in the Selkirk—Interlake electoral district which returns one Member of Parliament who currently is James Bezan of the Conservative Party of Canada.
The Winnipeg-Interlake division of the Senate is represented by Janis Johnson who was appointed by Brian Mulroney and who is a member of the Conservative Party of Canada.
Sports
Stonewall is home to the Stonewall Jets of the MMJHL and the Stonewall Rams of the WHSHL.
Stonewall has two Hockey rinks: the Stonewall Arena (Ice Palace) and the Veterans Memorial Sports Complex. The only curling rink is the Sunova Credit Union Curling Rink.
Stonewall has a senior baseball team named the Stonewall Blue Jays.
Stonewall Quarry Park
The Stonewall Quarry Park has been maintained as a natural area on the edge of town and provides picnic facilities and walking trails for visitors and residents alike. The nine baseball diamonds are available for hire and have been used for the Blue Jays Cups in 1997 and 1998, the Pan Am Games in 1999 and the Western Canada Summer Games in 2003. There is also a campsite and swimming available in Kinsmen Lake. Stonewall Quarry Park also displays the many aspects of limestone production. There was a museum and visitor centre, however these were destroyed by fire in the early hours of November 11, 2007. The new interpretive centre was opened in fall 2011.
Oak Hammock Marsh Interpretive Centre
Oak Hammock Marsh Interpretive Centre is a 36 km² (14 sq mi) restored prairie marsh featuring artesian springs, aspen-oak bluff, waterfowl lure crop, tall-grass prairie and 30 kilometres (19 mi) of trails. The marsh is home to mammals, birds, amphibians, reptiles, fish and invertebrates. During the migration season, the number of waterfowl using the marsh can exceed 400,000 a day.
The Stonewall Post Office
The Stonewall Post Office is an example of the prairie style of architecture which was popular between late 19th and early 20th century. It was built in 1914 using local limestone and used as a post office until 1979. The Canadian Postmasters and Assistants Association was founded at the previous Stonewall post office in 1902. |
#!/usr/bin/env python
################################################################################
#
# Copyright (c) 2013, <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
################################################################################
from pygments import token
from pygments.filter import Filter
class JavaAPIFilter(Filter):
"""
Custom Java filter for Pygments.
Yields only package/class/interface/method definitions.
See http://cui.unige.ch/isi/bnf/JAVA/BNFindex.html
https://en.wikipedia.org/wiki/Java_syntax
"""
# def __init__(self, **options):
# Filter.__init__(self, **options)
def filter(self, lexer, stream):
def_started = False
open_brackets = 0
modifiers = [
"public",
"private",
"protected",
"static",
"final",
"native",
"synchronized",
"abstract",
"threadsafe",
"transient",
"strictfp"
]
for ttype, value in stream:
# start of package definition
# start of decorator definition
# start of class/interface/method/variable declaration
if ((ttype is token.Keyword.Namespace) and (value == 'package')) or \
(ttype is token.Name.Decorator) or \
((ttype is token.Keyword.Declaration) and (value in modifiers)):
if not def_started:
def_started = True
yield token.Text, " " * open_brackets
if (ttype is token.Operator):
svalue = value.strip()
if svalue.startswith('{'): # should be the same as endswith
open_brackets += 1
elif svalue.endswith('{'): # e.g. ){
open_brackets += 1
elif svalue.startswith('}'): # e.g. }, or })
open_brackets -= 1
elif svalue.endswith('}'): # e.g. ;}
open_brackets -= 1
# end of package or variable definition
if (ttype is token.Operator) and (value == ';') and def_started:
def_started = False
yield token.Text, ";\n"
# end of decorator definition
# NB: @Decorator w/o brackets will not be matched here but will be matched below
# when the method/class definition is complete
if (ttype is token.Operator) and (value == ')') and def_started:
def_started = False
yield token.Text, ")\n"
# end of class/interface/method declaration
# BUG: this breaks decorators which have curly braces inside them, like
# @Target({ElementType.METHOD, ElementType.TYPE}) - only @Target( is shown
if (ttype is token.Operator) and (value == '{') and def_started:
def_started = False
yield token.Text, "\n"
if def_started:
yield ttype, value
if __name__ == "__main__":
import os
from pygments import highlight
from pygments.lexers import JavaLexer
from pygments.formatters import NullFormatter
lex = JavaLexer()
lex.add_filter(JavaAPIFilter())
for (path, dirs, files) in os.walk('~/repos/git/junit:junit/src/main/java/org/junit'):
for fname in files:
f = os.path.join(path, fname)
if f.endswith("src/main/java/org/junit/Ignore.java"):
code = open(f, 'r').read()
print "---------- start %s ----------" % f
print highlight(code, lex, NullFormatter())
print "---------- end %s ----------" % f
|
With improved speed and support for HTML 5, Internet Explorer 9 could be Microsoft's next step toward restoring its old mojo.
Microsoft hasn't shown very much of its next Web browser, and hasn't announced a release date. The most you can do is preview some of Internet Explorer 9's capabilities, which say nothing about the browser's user interface. Still, what Microsoft has shown so far is enough to get people excited.
What we don't know about yet are user interface and security. Even if Microsoft overhauled neither, Internet Explorer 9 would still be in pretty good shape. IE8 got creative with accelerators and Web slices. It also caught up with the competition on features like drag-and-drop tabs and private browsing. With the addition of other security features, a test by NSS Labs, albeit sponsored by Microsoft, found that Internet Explorer 8 was the safest browser.
But users of Chrome and Firefox are likely to say that something just feels faster about their browsers, and for good reason: PCWorld's speed tests from last summer put Chrome ahead of the pack, and Firefox in front of Internet Explorer. With IE9, Microsoft's at least showing a willingness to join the horse race.
Of course, Microsoft still has a wide lead in the browser wars. In the most recent market share estimates from NetApplications, Internet Explorer has 61.2 percent, compared to 24.2 percent for its closest competitor, Firefox. However, IE's share slides every month, and the browser now faces tougher competition from Google Chrome.
It's possible that Microsoft will be powerless to bring back defecting users. There may be something about the look and feel of Internet Explorer, or its standing as the most common target for security attacks, that drives people away. But at least Microsoft's tackling the issues that have held its browser back from greatness. |
<filename>main/java/com/example/mauro/yasts/BackgroundTaskDrawPath.java<gh_stars>0
package com.example.mauro.yasts;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class BackgroundTaskDrawPath extends AsyncTask<String, Void, String> {
String test;
String JSON_STRING;
String colore;
Polyline line;
Context ctx;
GoogleMap mGoogleMap;
AlertDialog.Builder builder;
public BackgroundTaskDrawPath(Context ctx, GoogleMap map,String colore){
this.ctx = ctx;
this.mGoogleMap = map;
this.colore = colore;
}
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... args) {
Object partenza, arrivo;
partenza = args[0];
arrivo = args[1];
try {
String key = URLEncoder.encode("<KEY>");
StringBuilder sb = new StringBuilder();
sb.append("https://maps.googleapis.com/maps/api/directions/json");
//sb.append("?origin=Napoli,IT");
//sb.append(",&destination=Quarto,IT");
sb.append("?origin="+partenza+",IT");
sb.append(",&destination="+arrivo+",IT");
sb.append("&sensor=false&mode=driving&alternatives=true&key=" + key);
test = sb.toString();
URL url = new URL(test);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null) {
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
String esito = stringBuilder.toString().trim();
return esito;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
drawPath(result);
}
public void drawPath(String result) {
try {
Random rnd = new Random();
//int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
//int color = Color.BLUE;
int color = 0;
if ( colore.equals("blue") )
color = Color.BLUE;
if ( colore.equals("red") )
color = Color.RED;
if ( colore.equals("tra") )
color = Color.CYAN;
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
//PolylineOptions options = new PolylineOptions().width(20).color(color).geodesic(true);
PolylineOptions options = new PolylineOptions().width(10).color(color).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
line = mGoogleMap.addPolyline(options);
} catch (Exception e) {
e.printStackTrace();
}
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
} |
Mitigation of Larkspur Poisoning on Rangelands Through the Selection of Cattle On the Ground Toxic larkspur (Delphinium species) cause large economic losses from cattle deaths, increased management costs, and reduced utilization of pastures and rangelands. We recommend that you obtain a risk assessment for larkspur on your range before turning out the cattle. Submit samples to USDAARS Poisonous Plant Research Laboratory for chemical evaluation at no charge. Information is available at: http://www.ars.usda.gov/main/site_main.htm?modecode=54-28-20-00. Selection of cattle resistant to larkspur poisoning could reduce cattle losses and improve rangeland utilization. The use of genetic-based herd management decisions can provide a tool for livestock producers to improve their profit margin and enhance the economic sustainability of rural American communities. |
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/mts/model/SubmitAnalysisJobResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Mts;
using namespace AlibabaCloud::Mts::Model;
SubmitAnalysisJobResult::SubmitAnalysisJobResult() :
ServiceResult()
{}
SubmitAnalysisJobResult::SubmitAnalysisJobResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
SubmitAnalysisJobResult::~SubmitAnalysisJobResult()
{}
void SubmitAnalysisJobResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto analysisJobNode = value["AnalysisJob"];
if(!analysisJobNode["CreationTime"].isNull())
analysisJob_.creationTime = analysisJobNode["CreationTime"].asString();
if(!analysisJobNode["Percent"].isNull())
analysisJob_.percent = std::stol(analysisJobNode["Percent"].asString());
if(!analysisJobNode["State"].isNull())
analysisJob_.state = analysisJobNode["State"].asString();
if(!analysisJobNode["Message"].isNull())
analysisJob_.message = analysisJobNode["Message"].asString();
if(!analysisJobNode["Priority"].isNull())
analysisJob_.priority = analysisJobNode["Priority"].asString();
if(!analysisJobNode["UserData"].isNull())
analysisJob_.userData = analysisJobNode["UserData"].asString();
if(!analysisJobNode["Code"].isNull())
analysisJob_.code = analysisJobNode["Code"].asString();
if(!analysisJobNode["PipelineId"].isNull())
analysisJob_.pipelineId = analysisJobNode["PipelineId"].asString();
if(!analysisJobNode["Id"].isNull())
analysisJob_.id = analysisJobNode["Id"].asString();
auto allTemplateListNode = analysisJobNode["TemplateList"]["Template"];
for (auto analysisJobNodeTemplateListTemplate : allTemplateListNode)
{
AnalysisJob::_Template _templateObject;
if(!analysisJobNodeTemplateListTemplate["State"].isNull())
_templateObject.state = analysisJobNodeTemplateListTemplate["State"].asString();
if(!analysisJobNodeTemplateListTemplate["Name"].isNull())
_templateObject.name = analysisJobNodeTemplateListTemplate["Name"].asString();
if(!analysisJobNodeTemplateListTemplate["Id"].isNull())
_templateObject.id = analysisJobNodeTemplateListTemplate["Id"].asString();
auto videoNode = value["Video"];
if(!videoNode["Bufsize"].isNull())
_templateObject.video.bufsize = videoNode["Bufsize"].asString();
if(!videoNode["Degrain"].isNull())
_templateObject.video.degrain = videoNode["Degrain"].asString();
if(!videoNode["PixFmt"].isNull())
_templateObject.video.pixFmt = videoNode["PixFmt"].asString();
if(!videoNode["Codec"].isNull())
_templateObject.video.codec = videoNode["Codec"].asString();
if(!videoNode["Height"].isNull())
_templateObject.video.height = videoNode["Height"].asString();
if(!videoNode["Qscale"].isNull())
_templateObject.video.qscale = videoNode["Qscale"].asString();
if(!videoNode["Bitrate"].isNull())
_templateObject.video.bitrate = videoNode["Bitrate"].asString();
if(!videoNode["Maxrate"].isNull())
_templateObject.video.maxrate = videoNode["Maxrate"].asString();
if(!videoNode["Profile"].isNull())
_templateObject.video.profile = videoNode["Profile"].asString();
if(!videoNode["Crf"].isNull())
_templateObject.video.crf = videoNode["Crf"].asString();
if(!videoNode["Gop"].isNull())
_templateObject.video.gop = videoNode["Gop"].asString();
if(!videoNode["Width"].isNull())
_templateObject.video.width = videoNode["Width"].asString();
if(!videoNode["Fps"].isNull())
_templateObject.video.fps = videoNode["Fps"].asString();
if(!videoNode["Preset"].isNull())
_templateObject.video.preset = videoNode["Preset"].asString();
if(!videoNode["ScanMode"].isNull())
_templateObject.video.scanMode = videoNode["ScanMode"].asString();
auto bitrateBndNode = videoNode["BitrateBnd"];
if(!bitrateBndNode["Max"].isNull())
_templateObject.video.bitrateBnd.max = bitrateBndNode["Max"].asString();
if(!bitrateBndNode["Min"].isNull())
_templateObject.video.bitrateBnd.min = bitrateBndNode["Min"].asString();
auto transConfigNode = value["TransConfig"];
if(!transConfigNode["TransMode"].isNull())
_templateObject.transConfig.transMode = transConfigNode["TransMode"].asString();
auto muxConfigNode = value["MuxConfig"];
auto gifNode = muxConfigNode["Gif"];
if(!gifNode["FinalDelay"].isNull())
_templateObject.muxConfig.gif.finalDelay = gifNode["FinalDelay"].asString();
if(!gifNode["Loop"].isNull())
_templateObject.muxConfig.gif.loop = gifNode["Loop"].asString();
auto segmentNode = muxConfigNode["Segment"];
if(!segmentNode["Duration"].isNull())
_templateObject.muxConfig.segment.duration = segmentNode["Duration"].asString();
auto audioNode = value["Audio"];
if(!audioNode["Profile"].isNull())
_templateObject.audio.profile = audioNode["Profile"].asString();
if(!audioNode["Codec"].isNull())
_templateObject.audio.codec = audioNode["Codec"].asString();
if(!audioNode["Samplerate"].isNull())
_templateObject.audio.samplerate = audioNode["Samplerate"].asString();
if(!audioNode["Qscale"].isNull())
_templateObject.audio.qscale = audioNode["Qscale"].asString();
if(!audioNode["Channels"].isNull())
_templateObject.audio.channels = audioNode["Channels"].asString();
if(!audioNode["Bitrate"].isNull())
_templateObject.audio.bitrate = audioNode["Bitrate"].asString();
auto containerNode = value["Container"];
if(!containerNode["Format"].isNull())
_templateObject.container.format = containerNode["Format"].asString();
analysisJob_.templateList.push_back(_templateObject);
}
auto analysisConfigNode = analysisJobNode["AnalysisConfig"];
auto qualityControlNode = analysisConfigNode["QualityControl"];
if(!qualityControlNode["MethodStreaming"].isNull())
analysisJob_.analysisConfig.qualityControl.methodStreaming = qualityControlNode["MethodStreaming"].asString();
if(!qualityControlNode["RateQuality"].isNull())
analysisJob_.analysisConfig.qualityControl.rateQuality = qualityControlNode["RateQuality"].asString();
auto propertiesControlNode = analysisConfigNode["PropertiesControl"];
if(!propertiesControlNode["Deinterlace"].isNull())
analysisJob_.analysisConfig.propertiesControl.deinterlace = propertiesControlNode["Deinterlace"].asString();
auto cropNode = propertiesControlNode["Crop"];
if(!cropNode["Top"].isNull())
analysisJob_.analysisConfig.propertiesControl.crop.top = cropNode["Top"].asString();
if(!cropNode["Width"].isNull())
analysisJob_.analysisConfig.propertiesControl.crop.width = cropNode["Width"].asString();
if(!cropNode["Height"].isNull())
analysisJob_.analysisConfig.propertiesControl.crop.height = cropNode["Height"].asString();
if(!cropNode["Left"].isNull())
analysisJob_.analysisConfig.propertiesControl.crop.left = cropNode["Left"].asString();
if(!cropNode["Mode"].isNull())
analysisJob_.analysisConfig.propertiesControl.crop.mode = cropNode["Mode"].asString();
auto mNSMessageResultNode = analysisJobNode["MNSMessageResult"];
if(!mNSMessageResultNode["MessageId"].isNull())
analysisJob_.mNSMessageResult.messageId = mNSMessageResultNode["MessageId"].asString();
if(!mNSMessageResultNode["ErrorMessage"].isNull())
analysisJob_.mNSMessageResult.errorMessage = mNSMessageResultNode["ErrorMessage"].asString();
if(!mNSMessageResultNode["ErrorCode"].isNull())
analysisJob_.mNSMessageResult.errorCode = mNSMessageResultNode["ErrorCode"].asString();
auto inputFileNode = analysisJobNode["InputFile"];
if(!inputFileNode["Object"].isNull())
analysisJob_.inputFile.object = inputFileNode["Object"].asString();
if(!inputFileNode["Location"].isNull())
analysisJob_.inputFile.location = inputFileNode["Location"].asString();
if(!inputFileNode["Bucket"].isNull())
analysisJob_.inputFile.bucket = inputFileNode["Bucket"].asString();
}
SubmitAnalysisJobResult::AnalysisJob SubmitAnalysisJobResult::getAnalysisJob()const
{
return analysisJob_;
}
|
#!/bin/python2
def dict_invert(d):
inverted = {}
for key, val in d.items():
if val in inverted:
inverted[val].append(key)
inverted[val].sort()
else:
inverted[val] = [key]
return inverted
# Test Cases
d = {1: 10, 2: 20, 3: 30}
print dict_invert(d) == {10: [1], 20: [2], 30: [3]}
d = {1: 10, 2: 20, 3: 30, 4: 30}
print dict_invert(d) == {10: [1], 20: [2], 30: [3, 4]}
d = {4: True, 2: True, 0: True}
print dict_invert(d) == {True: [0, 2, 4]}
d = {30000: 30, 600: 30, 2: 10}
print dict_invert(d) == {10: [2], 30: [600, 30000]}
|
2012 Kohistan video case
Events
The video was originally shot at a mixed gathering of a wedding celebration in Sartai, a remote village in Kohistan. The video that was circulated among villagers before it was shared with the jirga|jirga, in one of the most conservative parts of the province was immediately taken as dishonour and a violation of the norms of the tribal area.
The incident made it to the mainstream media in 2012 when Muhammad Afzal Kohistani, the brother of one of the boys in the video, alleged that the women were all killed in May 2012 on orders of the jirga, consisting of 40-50 members led by clerics. However, in the wake of this news, officials from the area denied the killing of the women claiming that all people were alive. The case was disposed off when rights activists went to the village to meet the girls as ordered by the Supreme Court of Pakistan.
Afzal Kohistani, in response to this report, asserted that the women in fact have been killed and imposters were presented to the investigations team, disrupting the judicial process.
Kohistani filed an application to reopen the case, as a result of which three of his brothers - including the two boys in the video - were shot dead in early January 2013. Four suspects were arrested for the triple murder.
In 2014, National Commission on the Status of Women took notice of the killings of the girls and moved the case to a local court that ordered police to produce girls in front of the judge to verify that the girls were alive. However, the police failed to recover the girls and bring them in court, that probed a second notice being produced the same year.
The defence lawyer argued that the girls wouldn't be brought in court because of the local restrictions making it a matter of honour and shame. After rejection of the argument from Justice Ejaz Afzal, some underage girls were produced in court to prove that the girls were alive but in 2016, rights activist Farzana Bari disputed the claim saying that the girls seen in the video have been killed, and the ones brought to court are different girls.
"Photos of the girls taken during the commission session were given to a Reuters' journalist, Katharine Houreld, who got the matching done through a renowned independent British agency 'Digital Barriers'. It was found in the said report that the photos of the girls, who were made to appear before the commission, did not match the images of the girls appearing in the said video," Bari stated in her witness statement.
Later in 2016, a report submitted to the Supreme Court expressed fear that the five girls might not be alive as the girls presented in front of the court did not match the description of the girls in the video. It mentioned, "The view taken and expressed... is the outcome of human observations, not free from error, maybe right or wrong, and can lead to an inference that either the girls are not alive or they have fled away and gone into missing being well aware of [the] consequences of traditional approach of their elders in such case."
The report also collected data on the girls from National Database and Registration Authority (NADRA) database to match the age of the girls at the time the video was recorded in comparison to the girls presented to the investigations committee.
After eight years of the original event, in August 2018, the Kohistan police registered FIR under Section 364 of the Pakistan Penal Code for alleged honour killing of the five women and two men seen in the video. The investigation that began on order of the Supreme Court later found in December 2018 that two out of five victims were reportedly alive, as claimed by the four suspects arrested in November that year.
Afzal Kohistani, negating the report, claimed that the suspects were lying. "They killed all five girls by severe torture and are not identifying graves as it will reveal their brutality," he said.
However, in a turn of events, Afzal Kohistani was shot dead in Abbottabad, Khyber Pakhtunkhwa, in January 2019. Kohistani was calling for justice against the alleged killing of the five women and two of his brothers seen in the video. According to witnesses, Afzal was shot multiple times and died on the spot, while three passersby were also injured. In March 2019, the KP police arrested the suspects involved in his murder. |
<gh_stars>1000+
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use anyhow::Result;
use symbolic::{
debuginfo::Object,
symcache::{SymCache, SymCacheWriter},
};
#[cfg(windows)]
use goblin::pe::PE;
#[cfg(windows)]
use symbolic::debuginfo::pe;
/// Caching provider of debug info for executable code modules.
#[derive(Default)]
pub struct DebugInfo {
// Cached debug info, keyed by module path.
modules: HashMap<PathBuf, ModuleDebugInfo>,
// Set of module paths known to lack debug info.
no_debug_info: HashSet<PathBuf>,
}
impl DebugInfo {
/// Try to load debug info for a module.
///
/// If debug info was founded and loaded (now or previously), returns
/// `true`. If the module does not have debug info, returns `false`.
pub fn load_module(&mut self, module: PathBuf) -> Result<bool> {
if self.no_debug_info.contains(&module) {
return Ok(false);
}
if self.modules.get(&module).is_some() {
return Ok(true);
}
let info = match ModuleDebugInfo::load(&module)? {
Some(info) => info,
None => {
self.no_debug_info.insert(module);
return Ok(false);
}
};
self.modules.insert(module, info);
Ok(true)
}
/// Fetch debug info for `module`, if loaded.
///
/// Does not attempt to load debug info for the module.
pub fn get(&self, module: impl AsRef<Path>) -> Option<&ModuleDebugInfo> {
self.modules.get(module.as_ref())
}
}
/// Debug info for a single executable module.
pub struct ModuleDebugInfo {
/// Backing debug info file data for the module.
///
/// May not include the actual executable code.
pub object: Object<'static>,
/// Cache which allows efficient source line lookups.
pub source: SymCache<'static>,
}
impl ModuleDebugInfo {
/// Load debug info for a module.
///
/// Returns `None` when the module was found and loadable, but no matching
/// debug info could be found.
///
/// Leaks module and symbol data.
fn load(module: &Path) -> Result<Option<Self>> {
// Used when `cfg(windows)`.
#[allow(unused_mut)]
let mut data = fs::read(&module)?.into_boxed_slice();
// Conditional so we can use `dbghelp`.
#[cfg(windows)]
{
// If our module is a PE file, the debug info will be in the PDB.
//
// We will need a similar check to support split DWARF.
let is_pe = pe::PeObject::test(&data);
if is_pe {
let pe = PE::parse(&data)?;
// Search the symbol path for a PDB for this PE, which we'll use instead.
if let Some(pdb) = crate::pdb::find_pdb_path(module, &pe, None)? {
data = fs::read(&pdb)?.into_boxed_slice();
}
}
}
// Now we're more sure we want this data. Leak it so the parsed object
// will have a `static` lifetime.
let data = Box::leak(data);
// Save a raw pointer to the file data. If object parsing fails, or
// there is no debuginfo, we will use this to avoid leaking memory.
let data_ptr = data as *mut _;
let object = match Object::parse(data) {
Ok(object) => {
if !object.has_debug_info() {
// Drop the object to drop its static references to the leaked data.
drop(object);
// Reconstruct to free data on drop.
//
// Safety: we leaked this box locally, and only `object` had a reference to it
// via `Object::parse()`. We manually dropped `object`, so the raw pointer is no
// longer aliased.
unsafe {
Box::from_raw(data_ptr);
}
return Ok(None);
}
object
}
Err(err) => {
// Reconstruct to free data on drop.
//
// Safety: we leaked this box locally, and only passed the leaked ref once, to
// `Object::parse()`. In this branch, it returned an `ObjectError`, which does not
// hold a reference to the leaked data. The raw pointer is no longer aliased, so we
// can both free its referent and also return the error.
unsafe {
Box::from_raw(data_ptr);
}
return Err(err.into());
}
};
let cursor = io::Cursor::new(vec![]);
let cursor = SymCacheWriter::write_object(&object, cursor)?;
let cache_data = Box::leak(cursor.into_inner().into_boxed_slice());
// Save a raw pointer to the cache data. If cache parsing fails, we will use this to
// avoid leaking memory.
let cache_data_ptr = cache_data as *mut _;
match SymCache::parse(cache_data) {
Ok(source) => Ok(Some(Self { object, source })),
Err(err) => {
// Reconstruct to free data on drop.
//
// Safety: we leaked this box locally, and only passed the leaked ref once, to
// `SymCache::parse()`. In this branch, it returned a `SymCacheError`, which does
// not hold a reference to the leaked data. The pointer is no longer aliased, so we
// can both free its referent and also return the error.
unsafe {
Box::from_raw(cache_data_ptr);
}
Err(err.into())
}
}
}
}
|
/**
* Servlet implementation class HelloWorld
*/
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HelloWorld() {
super();
// TODO Auto-generated constructor stub
}
@PostConstruct
private void initPost() {
// TODO Auto-generated method stub
System.out.println("init post Method");
}
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
System.out.println("init method");
super.init();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println("get access");
response.setContentType("text/html; charset=euc-kr");
PrintWriter writer = response.getWriter();
writer.println("<html><head></haed>");
writer.println("<body>");
writer.println("<h1>Hello Servlet</h1>");
writer.println("</body>");
writer.println("</html>");
writer.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("Destroy method");
super.destroy();
}
@PreDestroy
private void destroyPre() {
// TODO Auto-generated method stub
System.out.println("Pre Destroy");
}
} |
/**
* This represents a {@link TimeBucket} which can be a multiple of a time unit.
*
* @since 3.2.0
*/
public class CustomTimeBucket implements Serializable, Comparable<CustomTimeBucket>
{
private static final long serialVersionUID = 201509221545L;
public static final String TIME_BUCKET_NAME_REGEX = "(\\d+)([a-zA-Z]+)";
public static final Pattern TIME_BUCKET_NAME_PATTERN = Pattern.compile(TIME_BUCKET_NAME_REGEX);
private TimeBucket timeBucket;
private long count;
private String text;
private long numMillis;
private CustomTimeBucket()
{
//For kryo
}
public CustomTimeBucket(String timeBucketText)
{
if (timeBucketText.equals(TimeBucket.ALL.getText())) {
initialize(TimeBucket.ALL, 0L);
} else {
Matcher matcher = TIME_BUCKET_NAME_PATTERN.matcher(timeBucketText);
if (!matcher.matches()) {
throw new IllegalArgumentException("The given text for the variable time bucket " + timeBucketText
+ " does not match the regex for a variable time bucket " + TIME_BUCKET_NAME_REGEX);
}
String amountString = matcher.group(1);
long amount = Long.parseLong(amountString);
String suffix = matcher.group(2);
@SuppressWarnings("LocalVariableHidesMemberVariable")
TimeBucket timeBucket = TimeBucket.getTimeBucketForSuffixEx(suffix);
initialize(timeBucket, amount);
}
}
public CustomTimeBucket(TimeBucket timeBucket, long count)
{
initialize(timeBucket, count);
}
public CustomTimeBucket(TimeBucket timeBucket)
{
if (timeBucket == TimeBucket.ALL) {
initialize(timeBucket, 0L);
} else {
initialize(timeBucket, 1L);
}
}
private void initialize(TimeBucket timeBucket, long count)
{
this.timeBucket = Preconditions.checkNotNull(timeBucket);
this.count = count;
if (timeBucket != TimeBucket.ALL) {
Preconditions.checkArgument(count > 0, "The TimeBucket cannot be ALL.");
} else {
Preconditions.checkArgument(count == 0, "The count must be zero for the all TimeBucket.");
}
if (timeBucket != TimeBucket.ALL) {
text = count + timeBucket.getSuffix();
numMillis = timeBucket.getTimeUnit().toMillis(1) * count;
} else {
text = TimeBucket.ALL.getText();
}
}
public boolean isUnit()
{
return count == 1;
}
public TimeBucket getTimeBucket()
{
return timeBucket;
}
public long getCount()
{
return count;
}
public long getNumMillis()
{
return numMillis;
}
public long toMillis(long multCount)
{
return numMillis * multCount;
}
/**
* Rounds down the given time stamp to the nearest {@link TimeUnit} corresponding
* to this TimeBucket.
*
* @param timestamp The timestamp to round down.
* @return The rounded down timestamp.
*/
public long roundDown(long timestamp)
{
if (timeBucket == TimeBucket.ALL) {
return 0;
}
return (timestamp / numMillis) * numMillis;
}
public String getText()
{
return text;
}
@Override
public String toString()
{
if (timeBucket == TimeBucket.ALL) {
return TimeBucket.ALL.getText();
} else {
return count + timeBucket.getSuffix();
}
}
@Override
public int hashCode()
{
int hash = 3;
hash = 97 * hash + Objects.hashCode(this.timeBucket);
hash = 97 * hash + (int)(this.count ^ (this.count >>> 32));
return hash;
}
@Override
public boolean equals(Object obj)
{
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final CustomTimeBucket other = (CustomTimeBucket)obj;
if (this.timeBucket != other.timeBucket) {
return false;
}
if (this.count != other.count) {
return false;
}
return true;
}
@Override
public int compareTo(CustomTimeBucket other)
{
if (this.numMillis < other.numMillis) {
return -1;
} else if (this.numMillis == other.numMillis) {
return 0;
}
return 1;
}
} |
<filename>src/projects/translator/translator.service.ts
import { Injectable, UnprocessableEntityException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { isValidObjectId, Model } from 'mongoose';
import { CreateWordDTO } from './dtos/CreateWord.dto';
import { UpdateWordDTO } from './dtos/UpdateWord.dto';
import { IWord } from './interfaces/IWord.interface';
import { Word } from './schemas/Word.schema';
@Injectable()
export class TranslatorService {
constructor(@InjectModel(Word.name) private wordModel: Model<Word>) {}
public async getWords(): Promise<IWord[]> {
return await this.wordModel.find();
}
public async createWord(createWordDTO: CreateWordDTO): Promise<IWord> {
const { acronym, description, meaning } = createWordDTO;
if (!acronym || acronym.length === 0)
throw new UnprocessableEntityException('acronym missing');
if (!description || description.length === 0)
throw new UnprocessableEntityException('description missing');
if (!meaning || meaning.length === 0)
throw new UnprocessableEntityException('meaning missing');
return await this.wordModel.create(createWordDTO);
}
public async updateWord(updateWordDTO: UpdateWordDTO): Promise<IWord> {
const { _id } = updateWordDTO;
if (!_id || _id.length === 0 || !isValidObjectId(_id))
throw new UnprocessableEntityException('_id missing');
await this.wordModel.updateOne({ _id: _id }, { $set: updateWordDTO });
return await this.wordModel.findOne({ _id: _id });
}
public async deleteWord(id: string): Promise<void> {
if (id && id.length === 0 && !isValidObjectId(id)) {
await this.wordModel.deleteOne({ _id: id });
}
}
}
|
WASHINGTON, Nov. 17 (UPI) -- A motion filed by the Obama administration in the Fast and Furious case asks for a higher court to rule on the question of executive privilege.
The standoff between U.S. Attorney General Eric Holder and the House of Representatives is currently before a U.S. District Court judge; however Holder and the Justice Department want the U.S. Court of Appeals in Washington to weigh in before the litigation proceeds further.
The House is seeking documents related to Operation Fast and Furious, a controversial investigation into gun smuggling into Mexico carried out by the Bureau of Alcohol, Tobacco, Firearms and Explosives.
Holder has refused to turn the paperwork over to Congress on the grounds of the administration's executive-privilege authority. The House countered by holding Holder in contempt of Congress.
The administration had urged U.S. District Court Judge Amy Berman Jackson to throw out the contempt case on the grounds the courts were not the proper venue for a dispute between the executive and legislative branches of government. Jackson rejected that claim in September.
Politico said Holder's appeal, which was filed Friday night, says the appellate court should step in right away so that the case does not get ahead of itself and proceed without a definitive ruling on the pivotal question.
"The very experience of participating in such proceedings will cause harm -- to the defendant, the executive branch, and the separation of powers -- that cannot be reversed if the D.C. Circuit [appeals court] ultimately rules in defendant's favor on the threshold questions presented," the motion said. |
<gh_stars>1-10
//
// Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <objc/NSObject.h>
#import "MBPeerMessagable-Protocol.h"
@class NSData, NSString;
@interface MBPeerPreflightResponse : NSObject <MBPeerMessagable>
{
unsigned long long _uploadSize; // 8 = 0x8
unsigned long long _uploadFileCount; // 16 = 0x10
unsigned long long _freeDiskSpace; // 24 = 0x18
unsigned long long _purgeableDiskSpace; // 32 = 0x20
NSData *_propertiesData; // 40 = 0x28
}
- (void).cxx_destruct; // IMP=0x000000010010c8fc
@property(retain) NSData *propertiesData; // @synthesize propertiesData=_propertiesData;
@property(readonly) unsigned long long purgeableDiskSpace; // @synthesize purgeableDiskSpace=_purgeableDiskSpace;
@property(readonly) unsigned long long freeDiskSpace; // @synthesize freeDiskSpace=_freeDiskSpace;
@property(readonly) unsigned long long uploadFileCount; // @synthesize uploadFileCount=_uploadFileCount;
@property(readonly) unsigned long long uploadSize; // @synthesize uploadSize=_uploadSize;
@property(readonly, copy) NSString *description;
- (id)dictionaryRepresentation; // IMP=0x000000010010c4ac
- (id)initWithDictionary:(id)arg1 error:(id *)arg2; // IMP=0x000000010010c288
- (id)initWithUploadSize:(unsigned long long)arg1 uploadFileCount:(unsigned long long)arg2 freeDiskSpace:(unsigned long long)arg3 purgeableDiskSpace:(unsigned long long)arg4; // IMP=0x000000010010c228
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
|
Multi Agent System Based Clinical Diagnosis System : An Algorithmic Approach Modernization of medical health care system using agent technology has become an important research direction today. It is a true fact that agent based health care system can provide better healthcare than the traditional medical system. An advanced scheme of agentbased healthcare and medical diagnosis system can take care of every stage of patient such as initial check up, treatment and report for the patient. A user friendly interface is also required to provide high performance, reliability and functionality in this regard. In this paper we have tried to propose an operational algorithm to describe the individual working operations of a hybrid multi agent system based intelligent medical diagnosis system called Clinical Diagnosis System(CDS). Using the knowledge base and collaborative as well as co-operative intelligent agents and residing on a multi-agent platform, that CDS provides a communicative task-sharing environment. |
Pointofcare ultrasound: Closing guideline gaps in screening for valvular heart disease Abstract Background A linear increase in the number of valvular heart disease is expected due to the aging population, yet most patients with severe valvular heart disease remain undiagnosed. Hypothesis POCUS can serve as a screening tool for valvular heart disease. Methods We reviewed the literature to assess the strengths and limitations of POCUS in screening and diagnosing valvular heart disease. Results POCUS is an accurate, affordable, accessible, and comprehensive tool. It has a fast learning curve and can prevent unnecessary and more expensive imaging. Challenges include training availability, lack of simplified screening protocols, and reimbursement. Large scale valvular screening data utilizing POCUS is not available. Conclusion POCUS can serve as a screening tool and guide the management of patients with valvular heart disease. More data is needed about its efficacy and costeffectiveness in the screening of patients with valvular heart disease. high-end ultrasound system, and small handheld ultrasound devices (HUD). Point of care ultrasound (POCUS) refers to a goal-oriented, limited ultrasound examination of a particular body structure with a predefined limited protocol. 8 Performing POCUS using HUD is an accurate, affordable, accessible tool that can aid physical exam and streamline unnecessary clinical testing. 6,9 In addition, visual representation allows physicians to glimpse inside the patient to better examine and diagnose a condition. 6,9 POCUS has a high correlation with standard echocardiogram in evaluating left ventricular function and valvular abnormalities, making it a potential useful tool for screening for valvular abnormalities. We aim in this article to review the role of POCUS in cardiac evaluation and its potential rule in screening for valvular heart disease. | CURRENT SCREENING METHODS FOR VALVULAR HEART DISEASE -A ROOM FOR IMPROVEMENT The current screening practice of valvular heart disease is mainly dependent on cardiac auscultation. Only those with abnormal findings, are referred for a standard echocardiogram. There are no clear recommendations about who and how to screen by neither the American college of cardiology, nor American heart association. 7 The stethoscope, a 200 year old device discovered by Dr Laennec, remains the solo screening tool for valvular abnormalities. 10,11 Yet the amount of information that can be gained through auscultation is not comparable to that of the ultrasound. 12 Expert cardiologists still experience the limitation of auscultation when it comes to confidently diagnosing valvular abnormalities. 11, POCUS has been shown to perform better than traditional auscultation methods in evaluating valvular heart disease, even when carried-out by non-cardiologists. 13, Initial diagnosis gathered through traditional methods like auscultation, can be easily verified using POCUS, making ultrasound imaging a better option. 20 Therefore, performing POCUS examination improves the accuracy of diagnosis of valvular heart disease from 50% to 80% in as little as 15 minutes after a patient exam has started. 21 After the introduction of HUD, physicians have been able to increase the range of acute and chronic conditions that can be diagnosed using POCUS. 22 One small study has compared the performance of board certified cardiologists utilizing standard physical exams, with medical students trained for 18 hours to perform POCUS using HUD. The use of POCUS outperformed the experienced cardiologists in detecting abnormal cardiac pathologies (75% accuracy), and valvular pathology (93% vs 49%). 23 Another study has compared the results of physical examination performed by board certified cardiologist with the results of POCUS in a sample of 36 patients with cardiovascular disease. Cardiac examination alone failed to detect 59% of the overall cardiovascular findings and missed about 43% of the major findings. POCUS reduced this to 21% without significant inter-physician variation. 13 Thus, POCUS can reduce the time it takes to reach a conclusion and the price of the device can reduce the cost of echocardiography as well. 6,24-27 | HUD VS STANDARD ECHOCARDIOGRAPHY Though portable echocardiogram devices have the potential to enhance auscultation, they are by no means a substitute for standard echocardiography. Therefore, its optimal role in healthcare has yet to be officially defined. Currently, standard echocardiography machines tend to be too big and expensive for primary care medical clinics, potentially hindering immediate ultrasound access. 9,13 Performing POCUS using HUD has been shown by one study to decrease the number of rarely appropriate standard echocardiography by 59%. 6,9 The study by Vourvouri et al, has shown that screening with point of care ultrasound avoids the use of standard echocardiography in approximately 80% of unselected patients and leads to a 33% cost reduction. 28 HUDs are equipped with color Doppler, which can provide a qualitative evaluation of valvular heart disease. However, the lack of spectral Doppler limits their ability for quantitative assessment. 6,29,30 HUDs have good sensitivity and specificity in evaluating regional wall motion abnormality and left ventricular global function. However, they have only modest accuracy in evaluating valvular heart abnormalities such as severe aortic stenosis, and mitral/tricuspid valve regurgitation. 6,8,31,32 POCUS using HUD has been shown to have a very good sensitivity and specificity for diagnosis of rheumatic heart disease. 31,33 Several devices are now equipped with online internet connection and Cloud image storage. Newer devices are also equipped with artificial intelligence which can guide the provider how to improve image acquisition. 34 | HUD AND POCUS IN CLINICAL PRACTICE With the expansion of availability of HUD and portable ultrasound stations, there have been several developments on how they can be utilized. 35 POCUS was first utilized in trauma patients in the 1970s in Europe, and later on was adopted in the US in the 1990s, mainly in the emergency department where the health care provider can rapidly identify life threatening conditions, such as pericardial effusion, pneumothorax, and bowel injury. 33,36,37 Several protocols were adopted by different centers and utilized by providers with variable degree of training. 20,26, Currently, POCUS is mainly used in the emergency department and intensive care units. Its role in nonemergent settings is still emerging. Among non-emergent conditions, POCUS can improve physical exam, 46 guide diuresis, 47 predict risk of rehospitalization, 48 and safely discharge cardiac patients from the clinic. 36 | POCUS TRAINING AND CHALLENGES Although the HUD has been available since the 1970s, there is still hesitancy by many physicians about incorporating POCUS in their clinical practice, mainly due to a lack of formal rules or guidance on when and how a proper exam should be conducted. 21,26,35,49,50 Given its importance, increasing availability and high accuracy, POCUS could became an essential part of the physical exam and can provide comparable information to auscultation and palpation. 26,50 Limitations in training availability has slowed its implementation. Though progress has been slow, there has been an increase in POCUS training in undergraduate and graduate level and continuing in professional programs. 51,52 Recently, Harvard medical school incorporated POCUS training in first-and second-year medical students' curriculum as part of the physical exam training. 53,54 Similarly, residency programs have included POCUS training in their curriculum. 54,55 Though some guidelines currently exist, there is a need for new and updated data on the current methods of practicing. 5 The American Society of Echocardiography has predicted an exponentially increasing number of POCUS users and has emphasized the importance of high quality training, interpretation, and proper usage. 29 Several efforts are being made to encourage physicians to use ultrasound in their practice with hopes of reducing the healthcare cost by not requesting more expensive imaging. 22 It became crucial to better understand the possibilities and necessities for POCUS, and to have guidelines and protocols for its use. For example, the focused assessment with sonography in trauma (FAST) protocol has been widely adopted due to its ease and accuracy, and importantly speeding up and advancing patient care. 39,42,56,57 Currently, the only field that has a dedicated and clear echocardiography training is cardiology. Cardiology fellows need to perform and read certain numbers of echocardiograms, as assigned by the American college of cardiology, to achieve different levels of competencies. 58 The American Society of echocardiography and American college of emergency physician have issued consensus statement about the use of focused cardiac ultrasound in emergency settings. 57 The American college of chest physician (ACCP) as well as several critical care societies have issued several requirements on competencies in critical care ultrasonography and echocardiography. Unfortunately, POCUS training is still not a requirement nor formally incorporated during internal medicine training. 63 A 2014 survey of family medicine program directors found that only 2% of residency programs had a formal POCUS curriculum. 64 There is still no consensus on the training requirements to achieve adequate competency level. However, it's generally agreed that training must include basic ultrasound physics knowledge, supervised image acquisition and interpretation. 46 Some studies showed residents could perform accurate echocardiograms after a training for several hours to only a few days, 54,65,66 or as little as 25 scanning exams. 60 | POCUS IN PRIMARY CARE SETTING In the outpatient setting, the utilization of HUD is also gradually increasing. 64 This technological innovation has brought the clinician closer to patients when it comes to diagnosis, increasing the relationship and overall patient satisfaction. 67,68 POCUS allows patients and physicians to view images together where changes can be easily seen and tracked, and images can serve as a guide to explain more physiological concepts. 69 (Figure 1) This can also improve the quality of care and patient safety. 69 With the advancement of transcatheter treatment, screening for valvular heart disease in the outpatient setting might help in early detection and treatment, which may prevent downstream complications of valvular heart disease. 4,7,68,70 In a recent randomized clinical trial that assessed patient with known structural heart disease, the addition of POCUS to clinic evaluation resulted in earlier referral for valvular intervention, and decreased the risk of hospitalization and mortality. 27 Given its ease and low cost, POCUS using HUD will be the tool of choice to screen high risk patients. 4 Patients with any valvular abnormalities, can be confirmed by standard echocardiography. Those with valvular abnormalities, can also be followed using POCUS without the need for a more expensive echocardiogram. 27 There is an increasing evidence, mainly from low to middle income countries, that HUD can be used to screen for structural heart disease and can improve patients outcomes. 27,31,33, In comparison to the in hospital setting where POCUS can be easily performed in the emergency department and critical care units, POCUS availability and utilization in the primary care setting is still limited and faces multiple challenges including device availability, lack of specific screening protocols, training programs and reimbursement. 64,66,67 With the rapidly growing technology, the cost of HUD is expected to drop significantly, and when compared to the formal echocardiography, they are at least 10 times cheaper. 66 A simplified protocol for screening for valvular heart disease and cardiac abnormalities is needed before POCUS can be used as a practical tool to screen for valvular heart disease. Although it has not been widely adopted, a brief focused POCUS training focused on valvular heart disease and cardiac function is promising. 55 One study has implemented a POCUS training program consist of a 50-question test, 4-lectures on basic echocardiography & imaging interpretation, a supervised interpretation of 50 echocardiograms, and performance of 30 exams using HUD. 55 They have trained 12 residents, and compared their performance in 30 cases to experienced cardiologist. The performance of the trained residents was comparable to experienced cardiologist in detecting normal findings (95% correct interpretation), and to a lesser degree of abnormal findings (75% correct interpretation). The performance of the residents was also very good in detecting valve abnormalities (85% correct interpretation). 55 It remains that, the biggest limitation to this new technology is the fact that there are not enough trainers of POCUS. 55 Learning programs, like the GE Digital Expert that provides virtual and flexible face to face training could also be tailored to teach physicians POCUS and help face some of these challenges mentioned in this review. 59 | USING POCUS IN SCREENING FOR VALVULAR HEART DISEASE The data about using POCUS in screening for valvular heart disease is scarce. Most of the published studies have enrolled small samples of subjects with and without valvular heart disease and focused on sensitivity and accuracy of detecting valvular heart abnormalities. The use POCUS on a large scale to screen individuals without known valvular heart disease yet faces multiple challenges. The prevalence of valvular heart disease increases with age, and this will have implications on the sensitivity and specificity of any screening tests. The prevalence of rheumatic heart disease is higher in younger age and estimated at 12.9 per 1000 people in developing countries, 74 77 and CHS (Cardiovascular Health Study), 78 the age-adjusted prevalence of moderate or severe valvular heart disease was 2.5%, and was significantly influenced by age: <2.0% prevalence in those <65 years of age and 13.2% in those ≥75 years of age. Increasing age (per 10 years) was significantly associated with mitral regurgitation (odds ratio of 1.84; 95% CI: 1.70 to 1.99; P <.0001), mitral stenosis (odds ratio of 1.65; 95% CI: 1.12 to 2.43; P =.01), aortic regurgitation (odds ratio of 1.49; 95% CI: 1.30 to 1.70; P <.0001), and aortic valve stenosis (odds ratio of 2.51; 95% CI: 2.02 to 3.12; P <.0001). In subjects ≥75 years of age, the most frequent valvular heart disease was mitral regurgitation (9.3%), followed by aortic stenosis (2.8%), aortic regurgitation (2.0%) and mitral stenosis (0.2%). 79 The prevalence of moderate to severe aortic stenosis was also reported to range between 2.9% -4% in other smaller studies. 80,81 In a systematic review and meta-analysis including 9723 patients >75 years of age reported that the prevalence of AS was 12.4%, while severe AS was 3.4%. 82 Another study has reported the prevalence of bicuspid aortic valve to be 22% among octogenarians patients undergoing aortic valve surgery. 83 In the Framingham heart study that screened 1696 men and 1893 women (aged 54 +/− 10 years) for valvular regurgitation during routine examination, the prevalence of at least mild mitral regurgitation and tricuspid regurgitation was 19.0% and 14.8% in men, and 19.1% and 18.4% in women, respectively. 84 In the OxVALVE population cohort study that screened individuals aged≥65 years from a primary care population without known valvular heart disease, the prevalence of any valvular heart disease was 51% of participants. 4 The most common abnormali- The other potential group that may benefit from screening using POCUS are the young athletes before participating in strenuous competitive exercises. Sudden cardiac death remains a devastating event F I G U R E 1 Clinical application and limitations of point of care ultrasound among athletes, and the European society of cardiology recommends history, physical exam, and electrocardiogram screening for these individuals. 85 Several studies have utilized POCUS in screening athletes for different causes of sudden cardiac death, such as hypertrophic cardiomyopathy, and anomalous coronary artery. Using a simplified protocol to assess septal wall thickness, left ventricular function, and aortic root dilation, POCUS has been shown to be an easy and effective method for screening for hypertrophic cardiomyopathy. 86 A large metanalysis that included five studies, representing 2646 athletes, demonstrated that electrocardiogram-inclusive preparticipation screening strategies for potential causes of sudden cardiac death, resulted in positive results in 19.9% of the cohort. With the addition of POCUS, positive results were reduced to 4.9%, and 1 additional condition potentially associated with sudden cardiac death was identified. 87 The cost of POCUS was reported to range between $20 to $28 per athlete / student screened. 86,88 If the cost to perform POCUS is modest, and it results in a reduction in false-positive results and subsequent secondary investigations and cardiologic consultations, then POCUS may represent a cost-saving screening modality. However, there are insufficient data to draw conclusions regarding costeffectiveness from these studies. 87 In developing countries, POCUS has been utilized by several largescale studies to screen for rheumatic heart disease. 27,31,33,89,90 The world health organization has developed a standard echocardiography protocol for screening, and the widely available handheld devices allowed for active screening and identification of undiagnosed and subclinical carditis in endemic areas. Most of the studies have screened school students. 31,91 In comparison to a standard echocardiogram, POCUS has been shown to be equally effective in the diagnosis of definite rheumatic heart disease with comparable sensitivity and specificity. 31 More recent studies focused on training non-expert healthcare workers (eg, nurses, medical students, clinical officers), 72,92 in using POCUS to screen for rheumatic heart disease have shown a promise. This might be a viable strategy to implement a screening program in areas where there is a deficiency of highly trained sonographers or cardiologists. 93 | POCUS CHALLENGES AND LIMITATIONS With the decreased resources available and increased need for healthcare, new medical innovations are always being evaluated for cost, effectiveness, and reliability. 50 Individual reimbursement still remains an important barrier for its more ubiquitous use. 29 This is especially true in clinics where physicians get compensated through the relative value unit (RVU). 29 In a RVU-based compensation system, POCUS exam may cause financial loss to the practice, due to increased time of the clinic visit, not appropriate compensation, and less income from ordering additional imaging tests. 6 POCUS was shown to be very successful in reimbursement systems based on time (not RVUs), where the total cost of care matters more than individual income. 66 To improve efficiency, some groups have added a "POCUS clinic" to their primary care clinic, where patients felt to benefit from imaging can get scanned without interrupting the clinic workflow. 66 competence. The trained physicians could recognize the major echocardiographic abnormalities with 58.7% sensitivity and 97.0% specificity (overall k = 0.62, P <.001). Diagnostic accuracy was the best for valve lesions (sensitivity, 80.9%; specificity, 99.8%; k = 0.88; P <.001) and relatively modest for left ventricular systolic dysfunction (sensitivity, 58.0%; specificity, 98.3%; k = 0.62; P <.001). 95 This protocol was then utilized in a randomized control trial lead by the American society of echocardiography foundation (ASEF-VALUES; American Society of Echocardiography Foundation-Valvular Assessment Leading to Unexplored Echocardiographic Stratagems). POCUS in this study was performed by non-cardiologist physicians. Among patients with structural heart disease, and in comparison, to standard clinical practice, the utilization of POCUS has led to early referral for valvular interventions and a lower probability of hospitalization or death. 27 Readers in both of these cohorts were requested to give only visual, and qualitative assessments (mild, moderate, or severe) on specific pathologic issues: left ventricular dilation, wall hypertrophy (concentric or asymmetric), reduction of function (visual ejection fraction), segmental wall motion abnormality (yes or no), right ventricular dilation, left atrial dilatation, aortic root dilatation, valve calcification, pericardial effusion, pleural effusion, and dilation with reduced inspiratory reactivity of inferior vena cava. | CONCLUSION Performing POCUS is an accurate, affordable, accessible, and comprehensive tool. It has a fast learning curve, and can prevent unnecessary and more expensive imaging. 6,9 POCUS can serve as a screening tool and guide management of patients with valvular heart disease. 54 Thus, it is important to acknowledge the limited training availability, lack of simplified screening protocols, and importantly reimbursement. As the utilization of POCUS increases in the outpatient clinic, more research is needed about its impact on screening, management, outcomes and cost of care. DATA AVAILABILITY STATEMENT No new data generated |
<reponame>RedCiudadana/crowdata<filename>crowdataapp/tests.py
from django.test import TestCase
from crowdataapp.models import Document
class DocumentTest(TestCase):
fixtures = ['prod.json']
def setUp(self):
self.not_verified = Document.objects.create(name='not verified document')
def tearDown(self):
self.not_verified.dispose()
self.not_verified = None
# VERIFICACIONES #############################
# Caso 1 -------
# tres usuarios diferentes en entradas
# dos de esas entradas coinciden
# no debe verificar
# Caso 2 --------
# tiene mas de 3 entradas para el mismo usuario
# no tiene entradas de otros usuarios
# no debe verificar
# Caso 3 -------
# tiene 3 entradas de 3 usuarios diferents que coinciden
# si debe verificar
# Caso 4 -----------
# tiene una entrada de usuario staff
# si debe verificar
# Caso 5 ---------
# tiene una entrada de usuario superuser
# si debe verificar
# Caso 6 -------------
# tiene un usuario con muchas entradas
# tiene dos usuarios con entradas que coinciden a las del otro usuario
# si debe verificar
def test_verify(self):
self.not_verified_doc.verify()
# assert that the doc is verified
self.assertTrue(self.not_verified.verified)
# assert that only one entry is verified
# DAR DOCUMENTO A TRANSCRIPT #########
# ENVIO DE DOCUMENTO #################
|
KUALA LUMPUR (REUTERS) - Australian Scott Hend beat Spanish overnight leader Nacho Elvira with a birdie on the first play-off hole to win the co-sanctioned US$3 million (S$4.1 million) Maybank Championship after wild weather triggered a dramatic finish on Sunday (March 24).
They returned after a delay of 100 minutes and Elvira nailed his birdie putt from 30 feet for a two-under 70 to tie the scores at 15-under 273 and force the play-off.
"What a putt by Nacho... it was fantastic," Hend, who shot a 67 for the second day running, told reporters. "If I was to go out there and hit that putt you would say you would hole it one in 10 times. It was an amazing putt, and in the situation he holed it."
Hend looked in trouble when he landed in a greenside bunker on the first play-off hole but it was his turn to celebrate minutes later when he landed a four-footer after his opponent's birdie putt had stopped just short of the hole.
It was a third European Tour and 10th Asian Tour title for the big-hitting 45-year-old, who spent two years on the PGA Tour from 2004.
"Obviously I had a bit of luck on the play-off hole. If you don't have any luck you won't win," Hend added. "I had the luck today, unfortunately for Nacho. His time will come, he's going to win. He's a great player."
"I felt like I played fantastic on the back nine. I nearly holed a lot of putts, just missing," Hend said. "I just had to keep my head on and stay patient. The worst-case scenario was a play-off."
Thailand's Jazz Janewattananond threatened to challenge when he bagged three birdies in his first seven holes but failed to kick on and he finished third with a 69, two shots behind the leaders and a shot in front of fourth-placed American Johannes Veerman (66).
South Africa's former world No. 1 Ernie Els finished in share of seventh on 10-under after a 71. |
// Copyright (c) 2021 <NAME>
// Licensed under an MIT style license, see LICENSE.md for details.
// You are free to copy and modify this code. Happy hacking!
#ifndef GE_IMG_H_
#define GE_IMG_H_
#include "grid_engine/grid.h"
#ifdef __cplusplus
extern "C" {
#endif
ge_grid_t* ge_img_load(const char* filename);
#ifdef __cplusplus
}
#endif
#endif // GE_IMG_H_
|
On what is turning out to be a bad weekend for highly touted quarterbacks from the past few years, the Carolina Panthers have moved on from a former second-round pick.
Per multiple reports, Jimmy Clausen was let go by the Panthers, who also released veteran cornerback Drayton Florence as well.
Clausen now joins Matt Leinart, Tim Tebow and Vince Young as one-time hot shot quarterbacks in college and high draft hopefuls, who have been let go during this weekend of final NFL cuts. |
Firstly at the Théâtre de Gennevilliers we have the show Drugs Kept Me Alive, from 23rd–25th November. And yes, just in case you were wondering, the show is about drugs. This monologue explores the existence of a man who is addicted to the full-on chemical high of living his life 24/7 on pharmaceuticals – and the paradox that the closer these bring him to death, the more drugs he then needs to keep him alive.
Putting Rizzi and Fabre together looks like it will be the theatrical equivalent of inserting a tube of Mentos in a bottle of cola. Aside from the daring originality of this piece, I am also looking forward to learning its message: both men are intelligent, and I am interested to know the role that they assign to death in this play.
Well no-one told me. But then again I suppose they wouldn’t. But seeing as it appears there is now a strong chance that what I am living is not actually real, they could at least have had the compassion to leave out the compacted bathroom U-bend that I had to unblock last week.
World of Wires won Scheib an Obie for Best Direction earlier this year, and he is certainly experimental in his work. In World of Wires Scheib transgresses boundaries not just creatively but also in a literal sense: from the start to finish of the play he films the stage action with a hand-held camera that plays back in real-time to a screen over the stage. How’s that for feeling paranoid that someone’s watching you all the time.
So if your month of November is in need of a colourful injection of alternative realities, take a trip to either one of the shows and you’ll be laughing. Just make sure you’ve stopped by the time you’re on the bus on the way home. People might think you’re mad.
Kirsten Foster loves going to the theatre, and since moving from London to Paris three years ago has seen, almost literally, millions of plays in the capital. This blog takes a look at the hottest shows in town, the best directors to look out for, and why you should always smile at French ushers.
Billet: Secure all breakable objects, it's The Coming Storm! |
<filename>src/test/java/acceptance/toy1/bjs/ToyClass2.java
package acceptance.toy1.bjs;
import bionic.js.Bjs;
import bionic.js.BjsAnyObject;
import bionic.js.BjsObjectTypeInfo;
import bionic.js.BjsTypeInfo;
import bionic.js.Lambda;
import jjbridge.api.runtime.JSReference;
import jjbridge.api.value.strategy.FunctionCallback;
import java.util.Date;
@BjsTypeInfo.BjsLocation(project = "TestProject", module = "ToyClass2")
public class ToyClass2 extends ToyClass1
{
// BJS HELPERS
public static final Bjs.JSReferenceConverter<ToyClass2> bjsFactory = ToyClass2::new;
public static final Bjs bjs = BjsObjectTypeInfo.get(ToyClass2.class).bjsLocator.get();
private static final JSReference bjsClass = BjsObjectTypeInfo.get(ToyClass2.class).bjsClass();
protected <T extends ToyClass1> ToyClass2(Class<T> type, JSReference jsObject) {
super(type, jsObject);
}
protected <T extends ToyClass1> ToyClass2(Class<T> type, JSReference[] arguments) {
super(type, arguments);
}
public ToyClass2(JSReference jsObject) {
this(ToyClass2.class, jsObject);
}
public ToyClass2(JSReference[] arguments) {
this(ToyClass2.class, arguments);
}
public ToyClass2(Boolean bool) {
this(new JSReference[]{bjs.putPrimitive(bool)});
}
// INSTANCE PROPERTIES
public String nativeAutoProp() {
return bjs.getString(bjsGetProperty("nativeAutoProp"));
}
public void nativeAutoProp(String value) {
bjsSetProperty("nativeAutoProp", bjs.putPrimitive(value));
}
public BjsAnyObject anyAutoProp() {
return bjs.getAny(bjsGetProperty("anyAutoProp"));
}
public void anyAutoProp(BjsAnyObject value) {
bjsSetProperty("anyAutoProp", value.jsObj);
}
public ToyClass2 bjsObjAutoProp() {
return bjs.getObj(bjsGetProperty("bjsObjAutoProp"), bjsFactory, ToyClass2.class);
}
public void bjsObjAutoProp(ToyClass2 value) {
bjsSetProperty("bjsObjAutoProp", bjs.putObj(value));
}
public Lambda.F1<String, String> lambdaAutoProp() {
JSReference jsFunc = bjsGetProperty("lambdaAutoProp");
return bjs.getFunc(jsFunc, s -> bjs.getString(bjs.funcCall(jsFunc, bjs.putPrimitive(s))));
}
public void lambdaAutoProp(Lambda.F1<String, String> value) {
FunctionCallback<?> functionCallback = jsReferences -> {
jsReferences = bjs.ensureArraySize(jsReferences, 1);
return bjs.putPrimitive(value.apply(bjs.getString(jsReferences[0])));
};
bjsSetProperty("lambdaAutoProp", bjs.putFunc(value, functionCallback));
}
public String[][][] nativeArrayAutoProp() {
JSReference nativeArrayAutoProp = bjsGetProperty("nativeArrayAutoProp");
return bjs.getArray(nativeArrayAutoProp, r0 ->
bjs.getArray(r0, r1 ->
bjs.getArray(r1, bjs::getString, String.class), String[].class), String[][].class);
}
public void nativeArrayAutoProp(String[][][] value) {
JSReference propertyValue = bjs.putArray(value, nv0 ->
bjs.putArray(nv0, nv1 ->
bjs.putArray(nv1, bjs::putPrimitive)));
bjsSetProperty("nativeArrayAutoProp", propertyValue);
}
public ToyClass2[][][] bjsObjArrayAutoProp() {
JSReference nativeArrayAutoProp = bjsGetProperty("bjsObjArrayAutoProp");
return bjs.getArray(nativeArrayAutoProp, r0 ->
bjs.getArray(r0, r1 ->
bjs.getArray(r1, r2 ->
bjs.getObj(r2, bjsFactory, ToyClass2.class),
ToyClass2.class),
ToyClass2[].class),
ToyClass2[][].class);
}
public void bjsObjArrayAutoProp(ToyClass2[][][] value) {
JSReference propertyValue = bjs.putArray(value, nv0 ->
bjs.putArray(nv0, nv1 ->
bjs.putArray(nv1, bjs::putObj)));
bjsSetProperty("bjsObjArrayAutoProp", propertyValue);
}
public BjsAnyObject[][][] anyArrayAutoProp() {
JSReference nativeArrayAutoProp = bjsGetProperty("anyArrayAutoProp");
return bjs.getArray(nativeArrayAutoProp, r0 ->
bjs.getArray(r0, r1 ->
bjs.getArray(r1, bjs::getAny, BjsAnyObject.class), BjsAnyObject[].class), BjsAnyObject[][].class);
}
public void anyArrayAutoProp(BjsAnyObject[][][] value) {
JSReference propertyValue = bjs.putArray(value, nv0 ->
bjs.putArray(nv0, nv1 ->
bjs.putArray(nv1, nv2 ->
nv2.jsObj)));
bjsSetProperty("anyArrayAutoProp", propertyValue);
}
public Lambda.F1<String, String>[][][] lambdaArrayAutoProp() {
JSReference nativeArrayAutoProp = bjsGetProperty("lambdaArrayAutoProp");
return bjs.getArray(nativeArrayAutoProp, r0 ->
bjs.getArray(r0, r1 ->
bjs.getArray(r1, r2 ->
bjs.getFunc(r2, s -> bjs.getString(bjs.funcCall(r2, bjs.putPrimitive(s)))),
Lambda.F1.class), Lambda.F1[].class), Lambda.F1[][].class);
}
public void lambdaArrayAutoProp(Lambda.F1<String, String>[][][] value) {
JSReference propertyValue = bjs.putArray(value, nv0 ->
bjs.putArray(nv0, nv1 ->
bjs.putArray(nv1, nv2 -> {
FunctionCallback<?> functionCallback = jsReferences -> {
jsReferences = bjs.ensureArraySize(jsReferences, 1);
return bjs.putPrimitive(nv2.apply(bjs.getString(jsReferences[0])));
};
return bjs.putFunc(nv2, functionCallback);
})));
bjsSetProperty("lambdaArrayAutoProp", propertyValue);
}
public String prop() {
return bjs.getString(bjsGetProperty("prop"));
}
public void prop(String value) {
bjsSetProperty("prop", bjs.putPrimitive(value));
}
// INSTANCE METHODS
public void voidFunc() {
bjsCall("voidFunc");
}
public void paramsFunc(Boolean bool, Date date, Double number, Long integer, String string,
BjsAnyObject any, ToyClass2 bjsObj, Long[] array, Lambda.F0<String> lambda) {
bjsCall("paramsFunc", bjs.putPrimitive(bool), bjs.putPrimitive(date),
bjs.putPrimitive(number), bjs.putPrimitive(integer), bjs.putPrimitive(string),
any.jsObj, bjs.putObj(bjsObj), bjs.putArray(array, bjs::putPrimitive),
bjs.putFunc(lambda, jsReferences -> bjs.putPrimitive(lambda.apply())));
}
public Boolean boolFunc() {
return bjs.getBoolean(bjsCall("retValueFunc"));
}
public Date dateFunc() {
return bjs.getDate(bjsCall("retValueFunc"));
}
public Double floatFunc() {
return bjs.getDouble(bjsCall("retValueFunc"));
}
public Long intFunc() {
return bjs.getLong(bjsCall("retValueFunc"));
}
public String stringFunc() {
return bjs.getString(bjsCall("retValueFunc"));
}
public Lambda.F0<Void> lambdaVoidFunc(Lambda.F0<Void> lambda) {
JSReference jsFunc = bjsCall("lambdaVoidFunc", bjs.putFunc(lambda, jsReferences -> {
lambda.apply();
return bjs.jsUndefined();
}));
return bjs.getFunc(jsFunc, () -> {
bjs.funcCall(jsFunc);
return null;
});
}
public void lambdaWithParamsFunc(Lambda.F4<Long, String, BjsAnyObject, ToyClass2, String> lambda) {
bjsCall("lambdaWithParamsFunc", bjs.putFunc(lambda, jsReferences ->
bjs.putPrimitive(lambda.apply(
bjs.getLong(jsReferences[0]),
bjs.getString(jsReferences[1]),
bjs.getAny(jsReferences[2]),
bjs.getObj(jsReferences[3], bjsFactory, ToyClass2.class)))));
}
public Lambda.F4<Long, BjsAnyObject, ToyClass2, Long[], String> returningLambdaWithParamsFunc() {
JSReference jsFunc = bjsCall("returningLambdaWithParamsFunc");
return bjs.getFunc(jsFunc, (integer, any, toyClass1, array) ->
bjs.getString(bjs.funcCall(jsFunc,
bjs.putPrimitive(integer),
any.jsObj,
bjs.putObj(toyClass1),
bjs.putArray(array, bjs::putPrimitive))));
}
} |
A case of focal nodular hyperplasia with growth progression during pregnancy Focal nodular hyperplasia (FNH) is the second most common benign solid tumor of the liver and is usually found in young females. In FNH, spontaneous bleeding or rupture rarely occurs and malignant transformation is unlikely. The etiology of FNH is unclear, but because of female predominance and young age at onset, it seems that female hormone has an important role for the development of FNH. Although the development and the complications of hepatocellular adenomas have been related to the use of oral contraceptives and pregnancy, the influence of oral contraceptives and pregnancy on the growth and complications of FNH is controversial. Most FNH are stable in size and rarely complicated during pregnancy. We describe here a case of FNH with growth progression during pregnancy in a 27-year-old female. Her course of pregnancy and delivery was uneventful. Two months after delivery, the size of FNH was decreased. INTRODUCTION Focal nodular hyperplasia of the liver is the second most common benign tumor, after cavernous hemangioma. This tumor is often diagnosed incidentally without symptoms, and the occurrence of complications is rare with no possibility of malignant transformation. Most of these tumors are known to have no change in size during pregnancy, and no complications such as hemorrhage and rupture. Therefore small-sized focal nodular hyperplasia without symptom diagnosed during pregnancy can be observed without treatment. If the tumor is large or symptomatic, the option of surgical removal could be considered, taking into account the possibilities of hemorrhage and rupture and the complications of surgery during pregnancy. Here we report a case of focal nodular hyperplasia in a woman that enlarged during pregnancy and then decreased in size postpartum. A C B D alpha-fetoprotein level was 2.6 ng/mL, HBsAg negative, HBsAb negative, and anti-HCV negative. On thyroid function test, TSH was 3.22 uIU/mL, and free T4 was 1.83 ng/dL. Radiologic examination: A 5 cm-sized hypoechoic mass was observed in segment 5/6 of the liver on abdominal ultrasonography. On abdominal computed tomography (CT), a well-enhanced 5 cm-sized mass was observed in segment 5/6 of the liver on arterial phase, and the lesion was isoattenuated on portal and delayed phases ( Fig. 1). On magnetic resonance imaging (MRI), the mass showed low signal intensity on T1-weighted image, and weak high signal intensity on T2-weighted image. A strong contrast enhancement was seen on arterial phase using Gadobutrol (Gadovist ® ) as a contrast medium, and weak contrast enhancement was seen on portal and delayed phases (Fig. 2). Histological findings: The findings obtained from percutaneous liver biopsy included increased number of liver cells, mild lobular inflammation, minimal steatosis, and focal portal triaditis. There was no evidence of hepatocellular atypia (Fig. 3). Clinical progress: Although the percutaneous liver biopsy result was not diagnostic of focal nodular hyperplasia, the MRI findings were typical of focal nodular hyperplasia and therefore the patient was followed up in the outpatient clinic. The size of the mass was not changed after 3 and 6 months on abdominal CT. However, 1 year later when the patient was 7 months pregnant, abdominal ultrasonography demonstrated an increase in the size of the hepatic mass to 7 cm, and a serum alpha-fetoprotein level was 204.6 ng/mL. The size of the tumor increased further to 8 cm and 9 cm at her eighth and ninth month of gestation, respectively, on follow up abdominal ultrasonography (Fig. 4), and alpha-fetoprotein levels were further elevated to 308.0 ng/mL and 355.1 ng/mL, respectively. However, complications including hemorrhage, rup- ture, or necrosis of tumor were not observed. She did not have any particular symptoms. After an uneventful normal delivery without complications, a follow up ultrasonography was performed at 2 months postpartum and the size of the mass was not changed. The alpha-fetoprotein level was decreased to 2.4 ng/mL. At 5 months postpartum, the size of the hepatic mass was decreased from 9 cm to 7.5 cm (Fig. 5). The size remained the same for 1 year, and then it enlarged slightly to 8.0 cm. Up to now, there has been no change in size for 3 years, the serum alpha-fetoprotein level was within the normal range, and the patient is now being followed up in the outpatient clinic without particular symptoms. DISCUSSION Focal nodular hyperplasia of the liver accounts for 2.5-8% of primary tumors occurring in the liver, and among benign tumors of the liver, it is the second most common one after cavernous hemangioma. 1,2 It is found in all age groups in both males and females; however, it is more frequent in females, and more frequently between 20 and 50 years of age. 3 Most patients with focal nodular hyperplasia do not have any symptoms. However, it is sometimes discovered because of abdominal discomfort or a palpable mass. Unlike hepatic adenoma which shows a high incidence in women of childbearing ages among other benign tumors occurring in liver, focal nodular hyperplasia does not show complications such as hemorrhage, and malignant transformation has not been reported. The etiology and pathogenesis have not been revealed yet, but based on the result of histopathological analyses, it is presumed to be caused by a hyperplastic response of the hepatic parenchyma against abnormal blood flow brought by malformed vessels at the center of the lesion. 4 Hematological tests are usually normal, and liver function tests are also almost always normal, with normal range serum alpha fetoprotein levels. The alpha fetoprotein level was normal at diagnosis in this case, but it was increased up to 355.1 ng/mL during pregnancy. However, as the normal range for serum alpha fetoprotein is increased to 50-550 ng/mL during pregnancy 5 and continued increasing pattern to late in pregnancy, it is possible that the elevated levels in our case was physiological. For imaging diagnosis, abdominal ultrasonography, CT, and MRI can be used. A characteristic finding is the central stellate scar in the tumor. On ultrasonography, focal nodular hyperplasias appear as well-circumscribed nodules with variable degrees of echogenicity. On CT, they appear as tumors with low density or iso-density before injecting contrast medium, but after injecting contrast medium, contrast enhancement appears during the arterial phase in the tumor and not in the central scar portion. During portal and delayed phases, most of them appear as iso-or hypodense lesions. The central scars sometimes disappear when contrast medium is injected, and in some cases show delayed enhancement. MRI has a high diagnostic rate compared to abdominal ultrasonography or CT because of its sensitivity (68-70%) and specificity (98-100%) in the diagnosis of focal nodular hyperplasia. 2,3,6,7 T1-weighted images show iso-signal or low signal intensity and T2-weighted images show weak high signal or iso-signal intensity. A strong contrast enhancement is shown in arterial phase after injecting contrast medium. The central scar appears as low signal intensity on T1-weighted image and high signal intensity on T2-weighted image. Sometimes, the central scar is not enhanced on arterial phase when contrast agent is injected, but it is enhanced in delayed phase. Recently, MRI using hepatobiliaryspecific contrast agents such as gadoxetic acid and gadobenate dimeglumine is very useful in diagnosing focal nodular hyperplasia. In the hepatobiliary phase, focal nodular hyperplasia shows iso-density or high density. 8,9 MRI using hepatobiliary-specific contrast agent is reported to have 96-97% sensitivity, 100% specificity, and 96% positive predictive value in diagnosing focal nodular hyperplasia. 7,8 Existing extracellular fluid contrast agents circulate in the extracellular space after injection and are mostly excreted through the kidney. The differences in the blood flow between the mass and the liver determine the shape and other properties of the tumor. Because the hepatobiliary-specific contrast agents are taken up by hepatocytes and excreted in bile, the properties of the lesion can be shown depending on the functions of tumoral hepatocytes and bile excretion. Histologically, focal nodular hyperplasia consists of functional hepatocytes associated with abnormal blind-ending biliary ductules, which do not communicate with larger bile ducts. Hence, biliary excretion is slow compared with that of normal liver. Therefore, it shows contrast enhancement due to the retained contrast agent in the hepatobiliary phase. 9 In this case, the image of hepatobiliary phase could not be obtained because MRI was taken using Gadobutrol(Gadovist Ⓡ ), an extracellular fluid contrast agent, before hepatobiliary-specific contrast agent was introduced to Korea, but a typical focal nodular hyperplasia was shown in the existing MRI with relatively high sensitivity and specificity. Also, it showed the findings adequate for focal nodular hyperplasia in ultrasonography and CT. Focal nodular hyperplasia can be diagnosed in 70-83% with a combina-tion of radiological imaging tests. 3,11,12 The usefulness of fine needle aspiration for a definitive diagnosis of focal nodular hyperplasia may be controversial. 13 However, ultrasonography-guided liver needle biopsy is helpful for its diagnosis according to Fabre et al., and moderate subcapsular hematoma occurred in only 1 out of 30 patients, as a complication of liver needle biopsy. 14 Even after careful diagnostic evaluation, patients with focal nodular hyperplasia undergo surgery due to uncertainty of diagnosis or risk factors of hepatocellular carcinoma. On gross examination, focal nodular hyperplasia appears as a mass that is well-demarcated from the adjacent normal liver, and the mass is generally non-encapsulated. The tumor consists of a number of nodules, and the scar located in the center of the nodule is surrounded by multiple radiating fibrous septa. Nguyen et al. divided focal nodular hyperplasia into the classical form that shows abnormal nodular architecture, malformed-appearing vessels, cholangiolar proliferation, and the nonclassical form which shows other characteristics. 15 Although this case showed the findings of focal nodular hyperplasia on radiological imaging tests, the patient was married and planning to get pregnant. Therefore, to completely exclude the possibility of hepatic adenoma which can potentially result in complications such as hemorrhage and rupture during pregnancy and to render a definitive pathological diagnosis of focal nodular hyperplasia, percutaneous liver biopsy was performed. In this case, the typical findings of focal nodular hyperplasia were not observed. The pathological diagnosis of focal nodular hyperplasia may sometimes be difficult, for example, when the typical findings of the lesion are not present on the biopsied tissue or when the biopsy demonstrates atypical features of focal nodular hyperplasia. 15 Recently, molecular biological methods using Angiopoietin1/Angiopoietin2 mRNA ratios, etc. have also been suggested for the differential between focal nodular hyperplasia and hepatocellular adenoma. 11,16 Because focal nodular hyperplasia is often found in women in childbearing years, the relationships between female hormones such as estrogen or progesterone and occurrence and size increase of focal nodular hyperplasia are the subject of concern, but they are still controversial. In the past, it was thought that taking oral contraceptives is closely related to the occurrence of focal nodular hyperplasia, but recent reports show that the administration of oral contraceptives is not related to the occurrence of focal nodular hyperplasia, the size of lesions, and the number of them. Also, there was no change of the size during follow-up. In cases of focal nodular hyperplasia reported in Korea, there was no patient with history of oral contraceptives. According to the medical eligibility criteria for contraceptive use announced by WHO in 2009, patients with focal nodular hyperplasia were classified as having more advantages than potential risks from taking oral contraceptives. Although there are few studies on the effect of pregnancy on the disease course of focal nodular hyperplasia, most of them did not show any changes during pregnancy, and the patients gave birth without particular complications. 17,18,20 There are no reports in Korea regarding the natural course of focal nodular hyperplasia during pregnancy. According to foreign reports, Weimann et al. 20 followed up 82 patients with focal nodular hyperplasia and reported that 10 patients among them got pregnant total 13 times with no change in the size of tumor. Mathieu et al. 17 also followed up 216 patients with focal nodular hyperplasia, and reported that 12 patients among them were pregnant with no change of the size of tumor during their pregnancy. D'halluin et al. 18 studied 44 patients with focal nodular hyperplasia in retrospective view. 6 patients were pregnant, 3 of them had no change in size of tumor during pregnancy, 2 patients showed decreased size, and only 1 patient showed 40% increased size of tumor. In these foreign reports, the diagnosis of focal nodular hyperplasia was mostly conducted by radiological imaging tests such as MRI, and if diagnosis was uncertain from the radiological imaging tests, the patients were diagnosed by the histopathological findings through percutaneous liver biopsy or surgical resection. Among liver benign tumors which usually occur in women in childbearing years, unlike hepatic adenoma that may cause hemorrhage and rupture of tumor during pregnancy, focal nodular hyperplasia shows stable progress even in pregnancy and no complications. Therefore, focal nodular hyperplasias are observed without particular treatment. In this case, the patient diagnosed with focal nodular hyperplasia on imaging tests showed an increased size of the tumor during pregnancy, but had an uneventful delivery without complications. There are no Korean reports of focal nodular hyperplasia in pregnant women so far. Because focal nodular hyperplasia is a benign tumor of liver that mostly occurs in women of childbearing age, it is necessary to have much concern and research for the progress during pregnancy of patients with focal nodular hyperplasia in the future. Conflicts of Interest The authors have no conflicts to disclose. |
Moving away from trading on the margins: Economic empowerment of informal businesses through FinTech While there have been increasing studies on the impact of financial technology (FinTech), limited research has explored how FinTech supports economic empowerment for informal businesses. Drawing on institutional logics and a case study of mobile moneya FinTech innovationthis study develops a model of mobile moneydriven economic empowerment. We argue that this model is important to explain how those at the bottom of the economic pyramid, who are often neglected, use FinTech innovations to create and run informal businesses. Our findings and model explain the dynamics between logics, actors, and mobile money at three levels: regulatory, payments infrastructure, and informal economy. We identify three corresponding effects as outcomes of economic empowerment for informal businesses: greater access to startup capital, new employment opportunities, and improved financial management. By illustrating these effects, our study contributes to a better understanding of how FinTech innovations offer a possible pathway to economic empowerment for informal businesses. |
<reponame>Starlink/hds-v5<filename>datName.c
/*
*+
* Name:
* datName
* Purpose:
* Enquire the object name
* Language:
* Starlink ANSI C
* Type of Module:
* Library routine
* Invocation:
* datName( const HDSLoc * locator, char name_str[DAT__SZNAM+1],
* int * status );
* Arguments:
* locator = const HDSLoc * (Given)
* Object locator
* name_str = char * (Given and Returned)
* Buffer to receive the object name. Must be of size
* DAT__SZNAM+1.
* status = int* (Given and Returned)
* Pointer to global status.
* Description:
* Enquire the object name.
* Authors:
* TIMJ: <NAME> (Cornell)
* {enter_new_authors_here}
* History:
* 2014-08-26 (TIMJ):
* Initial version
* 2014-11-22 (TIMJ):
* Support use of HDF5 root group as HDS root
* {enter_further_changes_here}
* Copyright:
* Copyright (C) 2014 Cornell University
* All Rights Reserved.
* Licence:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the {organization} nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
* Bugs:
* {note_any_bugs_here}
*-
*/
#include <stdlib.h>
#include <string.h>
#include "hdf5.h"
#include "star/one.h"
#include "ems.h"
#include "star/util.h"
#include "hds1.h"
#include "dat1.h"
#include "hds.h"
#include "dat_err.h"
#include "sae_par.h"
int
datName(const HDSLoc *locator,
char name_str[DAT__SZNAM+1],
int *status) {
hid_t objid;
ssize_t lenstr;
char * tempstr = NULL;
char * cleanstr = NULL;
/* Store something in there as a placeholder in case
something goes wrong */
star_strlcpy( name_str, "<<ERROR>>", DAT__SZNAM+1 );
if (*status != SAI__OK) return *status;
/* Validate input locator. */
dat1ValidateLocator( "datName", 1, locator, 1, status );
objid = dat1RetrieveIdentifier( locator, status );
if (*status != SAI__OK) return *status;
/* Get the full name */
tempstr = dat1GetFullName( objid, 0, &lenstr, status );
/* Handle the presence of a HDF5 array structure path
that needs to be converted to HDS hierarchy */
cleanstr = dat1FixNameCell( tempstr, status );
if (cleanstr) {
/* update the string length */
lenstr = strlen(cleanstr);
} else {
/* just copy the pointer, will not free it later */
cleanstr = tempstr;
}
/* Now walk through the string backwards until we find the
"/" character indicating the parent group */
if (*status == SAI__OK) {
ssize_t i;
ssize_t startpos = 0; /* whole string as default */
for (i = 0; i <= lenstr; i++) {
size_t iposn = lenstr - i;
if ( cleanstr[iposn] == '/' ) {
startpos = iposn + 1; /* want the next character */
break;
}
}
/* Now copy what we need unless this is the root group */
if (lenstr == 1) {
/* Must read the attribute */
dat1NeedsRootName( locator->group_id, HDS_FALSE, name_str, DAT__SZNAM+1, status );
} else {
one_strlcpy( name_str, &(cleanstr[startpos]), DAT__SZNAM+1, status );
}
}
if (tempstr != cleanstr) MEM_FREE(cleanstr);
if (tempstr) MEM_FREE(tempstr);
if (*status != SAI__OK) {
emsRep("datName_4", "datName: Error obtaining a name of a locator",
status );
}
return *status;
}
|
Q:
How to add a Google calendar shared with me, to my iCloud calendars
A colleague has shared her Google calendar with me. It appears in Google calendar just fine. In the calendar settings I can see the iCal URL, but when I attempt to subscribe to that address in Apple Calendar, it says "A calendar wasn't found on ... Check the URL.".
I suspect this is because the calendar is shared with my via my Google account, rather than been made public. Is there anyway to sync the calendar with my Apple devices? Can I re-share it from my Google account so I can subscribe to it from iCloud?
I tried the syncselect option, which sounded promising, but couldn't see anything happen. I'm not sure how it would work anyway, since I can't see how it would have access to my iCloud account.
A:
There are two methods:
Method 1:
When you open the link of the calendar shared with you. You could click the plus sign at the right corner to add it into your own google calendar.
Go to https://www.google.com/calendar/syncselect and check the calendar shared with you.
Go to the Mac Calendar and you will find it in your calendar list just under your google account. Check it for display.
Method 2:
As step 1 in Method 1.
Go to the Google Calendar and the shared calendar appears in the "Other calendars", go to the setting of the shared calendar.
Scroll down and find the "Integrate calendar->public address in iCal format" and copy the address.
Open the Mac Calendar and go to "Files -> New Calendar Subscription" and paste the address into the "Calendar URL".
Hope this would work.
A:
Inadvertently found a lovely solution:
Go to System Preferences->Internet Accounts
Add or select your Google account
Click the checkbox next to "Calendars"
Voila, all my Google Calendar calendars appear in Apple Calendar, including the one shared with me. Didn't think there was going to be a solution to this, but so simple once you know. |
Footpoint Motion of the Continuum Emission in the 2002 September 30 White-Light Flare We present observations of the 2002 September 30 white-light flare, in which the optical continuum emission near the Halpha line is enhanced by ~10%. The continuum emission exhibits a close temporal and spatial coincidence with the hard X-ray (HXR) footpoint observed by RHESSI. We find a systematic motion of the flare footpoint seen in the continuum emission; the motion history follows roughly that of the HXR source. This gives strong evidence the this white-light flare is powered by heating of nonthermal electrons. We note that the HXR spectrum in 10-50 keV is quite soft with gamma being ~7 and there is no HXR emission above 50 keV. The magnetic configuration of the flaring region implies magnetic reconnection taking place at a relatively low altitude during the flare. Despite a very soft spectrum of the electron beam, its energy content is still sufficient to produce the heating in the lower atmosphere where the continuum emission originates. This white-light flare highlights the importance of radiative backwarming to transport the energy below when direct heating by beam electrons is obviously impossible. INTRODUCTION Compared to ordinary solar flares, white-light flares (WLFs) manifest themselves with an enhanced emission in the optical continuum of a few or tens of percent, or even more in some extreme cases. The continuum emission originates in the lower chromosphere and below. Therefore, research on WLFs can reveal critical clues to energy transport and heating mechanisms in the solar lower atmosphere (Neidig 1989;Ding, Fang, & Yun 1999). Most of the WLFs observed so far belong to Type I WLFs that are spectrally characterized with a Balmer and Paschen jump and strong broadened hydrogen Balmer lines (). Observations usually demonstrate a close temporal correspondence between the continuum and the hard X-ray (HXR) emissions in these WLFs (e.g., ;Neidig & Kane 1993;;;Hudson, Wolfson, & Metcalf 2005). This implies that the continuum emission is closely related to nonthermal heating of energetic electrons, which are assumed to be accelerated in the corona and then stream downward to the chromosphere. However, this process alone, in most cases, cannot efficiently produce the continuum emission since very few electrons (E ≥ 200 keV) can penetrate to the lower chromosphere and below (b). Therefore, radiative backwarming is further invoked to transfer the enhanced chromospheric radiation to deeper layers to produce the heating there and finally an enhanced continuum emission (Hudson 1972;Aboudarham & Hnoux 1987;Machado, Emslie, & Avrett 1989;a;Metcalf, Canfield, & Saba 1990b;Gan & Mauas 1994;b). A recent radiative hydrodynamic model of solar flares, which includes the electron beam heating and radiative transport in a consistent way, reproduces the continuum enhancement comparable to the observed values (). On the other hand, observations show that in some few very energetic events, electrons can be accelerated to very high energies, e.g., 300-800 keV ((Xu et al., 2005. In such cases, a large amount of nonthermal electrons can penetrate deep into the atmosphere, and direct collisional heating may play an important role in producing the continuum emission. It has been widely accepted that nonthermal electrons, accelerated by magnetic reconnection in the corona, stream downward along magnetic fields and produce the HXR emission in the chromosphere via bremsstrahlung radiation (Brown 1971). According to this scenario, the apparent motions of HXR sources reflect the successive reconnection process between neighboring field lines in the corona (e.g., ). Observations of footpoint motions can thus provide a test or constraint on theoretical models of solar flares. There are, up to now, quite some observations revealing the motions of HXR sources indicative of successive reconnection under various magnetic topologies (e.g., ;Krucker, Hurford, & Lin 2003). However, few examples have shown the motions of white-light continuum kernels that are related with the HXR sources. In this paper, we present observations of a white-light flare on 2002 September 30. We examine the temporal and spatial relationship between the continuum emission and the HXR emission during the flare and discuss its energetics. In particular, We discover a fairly good correlation between the motion history of the white-light kernel and the corresponding HXR source. We explain the observed continuum emission in terms of nonthermal heating by electron beams followed by the radiative backwarming effect. OBSERVATIONS AND DATA ANALYSIS According to the Solar-Geophysical Data, the flare of 2002 September 30 is an M2.1/1B event that occurred in NOAA Active Region 0134 (N13, E10 ). The profiles of GOES soft X-ray (SXR) fluxes show that the flare began at ∼01:44 UT and peaked at ∼01:50 UT. The hard X-ray (HXR) emission up to 50 keV of this flare was observed by the Reuven Ramaty High-Energy Solar Spectroscopic Imager (RHESSI), which provides unprecedented high resolution imaging and spectroscopy capacity for solar flares (). Note that this flare and the M2.6/2B flare on 2002 September 29 (a;Chen & Ding 2005) are two homologous flares in the same active region. Using the imaging spectrograph of the Solar Tower Telescope of Nanjing University () and employing a scanning technique, we obtained a sequence of twodimensional spectra of the H and Ca ii 8542 lines across the whole flaring region at a time cadence of ∼15 s. There are 120 pixels with a spacing of 0. 85 along the slit and 50 steps with a spacing of 2 along the scanning direction. The spectra contain 260 wavelength pixels with a resolution of 0.05 and 0.118 for the H and Ca ii 8542 lines, and thus span a range of about 13 and 30, respectively. During the flare, the line widths of the H and Ca ii 8542 lines increase gradually and then decrease after the maximum phase; the peak values of FWHM are about 4.5 and 1.5, respectively. We extract a narrow window in the far red wing of the H line (e.g., ∆ = 6) and use it as a proxy of the nearby continuum. We check carefully the line profiles and ensure that the line emission has little influence on the continuum window. We define the continuum contrast as (I f − I q )/I q, where I f is the flare intensity and I q the preflare background (taken about one hour before the flare) at the same point. By checking the mean intensity fluctuation outside the flaring region, we further estimate the measurement error of the continuum contrast to be below 1%. Reduction of ground-based data includes dark field and flat field corrections. We coalign the H images in line wings with the Solar and Heliospheric Observatory MDI continuum images () by correlating the sunspot features. The accuracy of image coalignment is estimated to be ∼2. ENERGETICS OF THE CONTINUUM EMISSION We present in Figure 1 a sequence of images of this flare as seen in the H line center (gray scale), the continuum (H + 6, white contours), and RHESSI 12-25 keV HXR (black contours). HXR images are reconstructed with the CLEAN algorithm from detectors 3-8, which yields an angular resolution of ∼7. Note that the flare is located near the solar disk center and the flaring loops are very compact. Therefore, the H or HXR emission from the loop top and the footpoints may probably be spatially mixed together due to projection effect. We also select a 171 EUV image from the Transition Region and Coronal Explorer (TRACE, ) to show the large structure of the flaring region. We investigate the origin of the continuum emission by examining its relationship with the HXR emission during the flare, which provides important information about the heating processes in the flaring atmosphere. As seen in Figure 1, the flare has a simple compact morphology in the continuum and the HXR emission, both of which reside at the main H ribbon; there is a close spatial coincidence between the continuum and the HXR emission. We also examine the temporal variation of the continuum contrast at the position denoted with the plus sign in Figure 1 where the maximum continuum contrast appears during the flare. As seen in Figure 2, the continuum contrast reaches a maximum of ∼10% at ∼01:49:17 UT and correlates well with the HXR emission during the flare. 1 Note that for this flare, the time profiles for the HXR emission below 50 keV are rather gradual and there is no HXR emission above 50 keV. Observations from the solar broad-band Hard X-Ray Spectrometer (HXRS, Frnk, Garcia, & Karlick 2001) give similar results. The close temporal and spatial relationship between the continuum and HXR emission in this flare indicates that the continuum emission is strongly related to nonthermal energy deposition in the chromosphere. Current WLF models have proposed electron beam heating plus the radiative back-1 In the far blue wing of the H line (∆ = −6), the continuum develops similarly and reaches a maximum contrast of ∼8%. In a near-infrared window near the Ca ii 8542 line, we detect a much lower contrast of the continuum (∼2%). warming effect to account for the observed continuum enhancement. Ding et al. (2003b) and Chen & Ding calculated the continuum contrast near the Ca ii 8542 and the H lines, respectively, as a function of the energy flux of the electron beam impacting a model atmosphere. For this flare, we can apply a single power-law fitting to the photon spectrum for the HXR source during the maximum phase, as seen in Figure 3. The power-law spectrum extends down to ∼10 keV and has an index of = 7.4, which is much larger than the often observed values, e.g., 3-5. In the scenario that the above HXR emission is produced via thick-target bremsstrahlung (Brown 1971) by nonthermal electrons with an assumed lowenergy cutoff of 20 keV, the nonthermal electron power is derived to be ∼3 10 28 ergs s −1 and the energy flux (F 20 ) is estimated to be ∼2.0 10 10 ergs cm −2 s −1 (an average value from 01:49:00 to 01:50:00 UT). According to Chen & Ding, an energy flux of ∼2.0 10 10 ergs cm −2 s −1 can produce an increase of the continuum emission near the H line of roughly 10%, which is consistent with the observed continuum contrast in this WLF. We should note that the estimation of the energy content of nonthermal electrons suffers from great uncertainties, mostly due to the uncertainty of the low-energy cutoff, especially when the spectrum is very steep. Sui, Holman, & Dennis constrained the low-energy cutoff to a very narrow range of 24 ± 2 keV for an M1.2 solar flare by assuming thermal dominance at low energies and a smooth evolution of thermal parameters from the rise to the impulsive phase of the flare. If we take the low-energy cutoff to be 15 or 25 keV, the energy flux would rise to 6 times or drop to only 25% of the above value, respectively. The latter case could not meet the requirement of sufficient heating to account for the continuum contrast. The observational facts that the continuum contrast reaches ∼10% and that the HXR spectrum is very soft imply that electrons of very high energies are not the necessary condition for the generation of the continuum emission in WLFs. Nonthermal electrons of intermediate energies deposit most of their energy in the upper chromosphere, while the radiative backwarming effect plays the right role in sufficiently heating the lower chromosphere and below. FOOTPOINT MOTION HISTORY It has been recognized that the apparent HXR footpoint motion maps the successive reconnection process during solar flares. Different magnetic configurations around the flaring regions can result in different patterns of HXR footpoint motions. For example, using the Yohkoh HXT observations, Sakao et al. found that the double HXR footpoints move antiparallel in 7 out of the 14 flares studied. Since the launch of RHESSI in 2002 February, some more research has been dedicated for this topic. For example, Krucker, Hurford, & Lin found a systematic motion of one HXR footpoint nearly parallel to the magnetic neutral line in the 2002 July 23 X4.8 solar flare. Liu et al. observed an increasing separation of two HXR footpoints that is predicted by the magnetic reconnection process in the well adopted solar flare model (Kopp & Pneuman 1976). Compared to the large number of solar flares detected in HXR, SXR, H, etc., detection of WLFs is very sporadic because of the fact that WLFs represent only a small fraction of solar flares; and most importantly, the white-light continuum emission is usually constrained in a small area and limited in a time period during the impulsive phase. There are few studies on the source motion as seen in the continuum in the past decades owing to the rare detection of WLFs and the low cadence of observations. The flare under study has a relatively simple morphology in both the HXR and continuum emission, which enables us to trace and study the footpoint motion in both the two wavelengths during the flare. Comparison of the footpoint motion history in the HXR and continuum emission sheds new lights and put constraints on the modeling of WLFs. We plot in Figure 4 the centroids of the continuum emission (plus sign) at the time during which ground-based observations were made, as well as the centroids of the 12-25 keV HXR emission (diamond sign), superposed on the MDI longitudinal magnetogram. Here the centroid refers to the intensity-weighted mean position of those parts of the source that have intensity ≥50% of the maximum source intensity. It is very obvious that the continuum source and the HXR source move in a similar trend: they first move westward and then turn back to the east after the maximum phase (at ∼01:50:08 UT). Meanwhile, both the westward and eastward motions are nearly parallel to the magnetic neutral line (dashed line). After the turnover, the source moves along a line more apart from the magnetic neutral line. To demonstrate the relationship between the footpoint motion and the magnetic configuration of the flare, we further conduct potential field extrapolation of the MDI magnetogram using the code of Sakurai, which can provide rough information about magnetic con-nectivity around the flaring region. As shown in Figure 5. the flare is confined to a series of low-lying magnetic loops. A possible picture for the flare is as follows: first, the footpoint moves westward as a result of the successive reconnection between the low-lying magnetic loops; then, the reversal of the footpoint motion may be related to triggering of nearby larger loops more distant from the magnetic neutral line. Since the HXR emission in 12-25 keV may contain considerable thermal contribution from the hot plasma in the flaring loop, the HXR centroid mentioned above may represent the weighted center of both the footpoint and loop top sources. However, we believe that the centroid motion is mainly from the motion of the footpoint source. For this sake, we also check the source motion in 25-50 keV, at which thick-target bremsstrahlung emission is dominant. The results show that the motion pattern is similar to what is found above during the maximum phase when the 25-50 keV HXR images are available. Although there is a very good spatial correspondence of the continuum emission to the 12-25 HXR emission as the flare goes on, there still exists a clear offset of 2 -4 between the centroids of the continuum and the HXR source, as shown in Figure 4. Because of the limit of spatial resolution and uncertainty of image coalignment, we cannot draw a clear conclusion whether the offset is really physical or not. On the other hand, some studies of two-ribbon flares have shown that the nonthermal signal revealed in H spectra is much more distinct at the outer edges (e.g., ;Li & Ding 2004), where an electron beam streams down along newly reconnected lines and bombards the chromosphere. In our case, both the HXR emission and the continuum emission are found to be more apparent at the outer edges of the main flare ribbon, which is consistent with the previous results. MAGNETIC RECONNECTION AT LOW ALTITUDES Generally, magnetic reconnection and subsequent energy release in solar flares are assumed to occur in the corona. On the other hand, some active phenomena show evidence of local heating in the lower atmosphere (at chromospheric levels and below), such as the Type II WLFs and Ellerman bombs (e.g., Ding, Fang, & Yun 1999;Chen, Fang, & Ding 2001). In such cases, magnetic reconnection is assumed to take place in the lower atmosphere where the plasma is much denser and partially ionized. There is, however, no theory that can deal with the particle acceleration in the lower atmosphere. In such levels, the plasma is highly collisional, and the energy released through magnetic reconnection is mostly consumed to ionize the plasma. Therefore, we can postulate that few particles can be accelerated to very high energies. If the accelerated electrons still follow a power-law distribution, the slope may be much steeper as compared to those cases in which reconnection occurs in the corona. Now we discuss the details of the flare on 2002 September 30. First, there are some aspects similar to the Type A flares or Thermal Hot Flares mentioned by Tanaka and Dennis : the time evolution of the HXR emission below 50 keV is very gradual and there is no visible increase of HXR emission above 50 keV; the HXR spectrum in 10-50 keV follows a nonthermal power-law with a very steep slope of ≈ 7. Such features are possibly linked to a higher density at the energy release site (Dennis 1988). Second, as seen from Figure 4, the magnetic configuration and the footpoint motion imply a scenario of magnetic reconnection taking place in a series of low-lying magnetic loops during the flare. Thus, we propose that the scenario of magnetic reconnection relatively low in the atmosphere may explain the quite soft HXR spectrum observed in this flare. However, we also note that this explanation is very speculative. Since we do not find a HXR footpoint pair from RHESSI images, we are unable to directly measure the loop size and altitude. By assuming semicircular loops symmetrically straddling over the magnetic neutral line, the loop altitude is roughly estimated to be the mean distance between the footpoint and the neutral line, i.e., ∼2-5 (∼1500-3500 km) above the photosphere, which falls in between the upper chromosphere and the lower corona. This fact seems to support our conjecture that this flare occurs in a relative low site. As shown in §3.2, during the maximum phase, the HXR spectrum follows a power-law that extends down to ∼10 keV and the derived energy flux of beam electrons is sufficient to account for the continuum contrast. On the other hand, since the HXR spectrum is very soft, thermal plasma may contribute largely to the HXR emission in the low energies, e.g., below ∼20 keV. We show in Figure 2 that the plasma temperature, which is derived from the background-subtracted GOES 0.5-4 and 1-8 SXR fluxes (e.g., Thomas, Starr, & Crannell 1985;Garcia 1994), well matches the development of the continuum emission. Matthews et al. also showed that some WLFs exhibit a stronger correlation with the SXR emission than with the HXR emission. Therefore, another possible origin of the continuum emission, i.e., thermal heating plus preferentially the backwarming effect, is worth investigating in the future. CONCLUSIONS After a synthesising analysis of the WLF on 2002 September 30, we find that there is a fairly close relationship in both time and space between the continuum and the HXR emission during the flare. We discover a footpoint motion seen in the optical continuum; the motion history follows roughly that of the HXR source. This gives strong evidence that this WLF is powered by energetic electrons followed by the radiative backwarming effect. The magnetic configuration of the flaring region implies magnetic reconnection taking place at a relatively low layer during the flare. The HXR spectrum is thus very soft, possibly, due to a low efficiency of electron acceleration at low altitudes. However, the energy content of the electron beam is still enough to produce the heating in the lower atmosphere where the continuum emission originates. Radiative backwarming is of course an important mechanism to transport the energy below when direct heating is obviously impossible. We would like to thank H. Hudson and the referee for constructive comments that help improve the paper. We are grateful to the RHESSI, SOHO/MDI, TRACE, and HXRS teams for providing the observational data and to T. Sakurai for providing the current-free magnetic extrapolation program. We thank S. Krucker for help in RHESSI data analysis and F. Frnk for interpreting the HXRS data. SOHO is a project of international cooperation between ESA and NASA. This work was supported by NKBRSF under grant G20000784, NSFC under grants 10025315, 10221001, and 10333040, and FANEDD under grant 200226. |
// RemoveByAccess removes token from database
func (tokenstore *TokenStore) RemoveByAccess(ctx context.Context, access string) error {
tokenstore.logger.Debug("RemoveByAccess", zap.String("access", access))
return tokenstore.db.OAuth.OAuthAccessTokenRemoveByAccess(access)
} |
Development of a 1024 x 1024 InSb detector array for astronomy: a status report As part of our instrument development work for the U.S. Air Force Advanced Electron Optical System (AEOS) telescope to be built on Haleakala, Maui, the Institute for Astronomy is contracting with the Santa Barbara Research Center (SBRC) for the development of a 1024 X 1024 InSb detector array with 30 micrometers pixels optimized for groundbased astronomical applications. The device design is based on the successful 256 X 256 InSb devices currently produced by SBRC. |
Sergei Raad
Youth and College
Raad's birth name is Sergei Kolomeites. He moved to the United States in 1995 after his Russian club team came to Orlando, Florida to play in a tournament; he was sponsored by a local family and obtained a student visa so he could learn English, and eventually took on the surname of his adoptive family, Raad. He attended Oviedo High School and played college soccer at Furman University from 2000 to 2004, where he appeared in 62 games, notching 20 goals and 29 assists.
Professional
Raad turned professional in 2004 when he joined the now-defunct A-League team, the Calgary Mustangs. With the Mustangs he played in 20 games, scoring 4 goals and contributing 2 assists, before being released at the end of the season when the team folded.
He spent the early months of 2005 training with Zenit St. Petersburg, but was not offered a contract by the Russian team, and instead returned to the United States, playing for Central Florida Kraze in the USL Premier Development League.
He trained with Major League Soccer side New England Revolution during the second half of 2005, and must have impressed some scouts, as he signed a developmental contract with the Kansas City Wizards on April 1, 2006. He played in one MLS game during the season, before being waived at the end of the 2006 season.
During early 2007 Raad was training with the Seattle Sounders, but eventually returned home to play PDL soccer with the Central Florida Kraze again in 2007. After a couple of years out of the game in 2008 and 2009 Raad embarked on a third stint with the Kraze in 2010; he scored his first ever goal for the team in their 2010 season opener, a 3-1 win over Fort Lauderdale Schulz Academy.
In 2011, Raad signed with the new PDL expansion team, FC Jax Destroyers. |
<filename>src/data/ReadNestedList.py
import pandas as pd
import ast
class ReadNestedList:
def __init__(self, tweets, target, name):
self.tweets = tweets
self.target = target
self.name = name
self.all_elements = list()
self.df = None
self.grpDF = None
def read(self):
for el in self.target:
el = ast.literal_eval(el)
if len(el) > 0:
self.all_elements.extend(el)
return self
def DF(self):
self.df = pd.DataFrame(self.all_elements, columns=[self.name])
self.df['{}_lower_case'.format(self.name)] = self.df[self.name].str.lower()
return self
def computeGrpDF(self):
self.grpDF = self.df.groupby('{}_lower_case'.format(self.name))['{}_lower_case'.format(self.name)].count().reset_index(name = 'count').sort_values(['count'], ascending=False)
return self
|
Maynard and Iris To address the deep contradictions in social and economic life that motivated Keynes, I propose a combination of environmental Keynesianism and deep democracy. Massive state investment in infrastructure and environmental remediation would be an excellent way of soaking up capital in the ground, thus responding to the overaccumulation crisis feared by Keynes. Deep democracy, proposed by Iris Marion Young, proposes a sustained political engagement at different scales with different interlocutors on different issues. This is a kind of politics that, she suggests, requires people to pay attention to each others circumstances, needs and beliefs and thereby arrive at outcomes perceived as fair and fairly arrived at. |
def showCommands(self):
self.ConsoleOutput("List of available commands: ", color = (0.243,0.941,1,1))
for i in self.CommandDictionary:
self.ConsoleOutput("- "+str(i))
self.ConsoleOutput(" ")
self.ConsoleOutput("Use usage(command) for more details on a specific command")
return None |
Stephen Mulhern has praised Declan Donnelly for going it alone without Ant McPartlin.
Dec hosted the final two episodes of Saturday Night Takeaway this year as Ant stepped down from his TV commitments following his drink driving charge.
The episodes included the live finale from Universal Orlando Resort in Florida with over 200 winners of the Place on the Plane competition that had been taking place across the series.
The last show included guests Craig David, Denise Richards and Jason Derulo who led the End of the Show Show. Dec appeared in the carnival themed performance alongside Stephen Mulhern and Scarlett Moffatt.
Stephen, whose SNT skit In For A Penny is being turned into a series, appeared on Lorraine shortly after jetting back into the UK from Florida, and said he thinks Dec did a bang up job.
He told Christine Lampard: ‘I think Dec did incredible on his own.
Stephen is returning to Britain’s Got More Talent for the new series, which kicks off on Saturday, and praised the judges Simon Cowell, David Walliams, Amanda Holden and Alesha Dixon for being such a good team.
Dec is getting another taste of the solo life when he presents the live Britain’s Got Talent shows alone.
Ant, who has re-entered rehab, is due to appear in court this month. |
def for_k():
for row in range(6):
for col in range(4):
if col==0 or row-col==2 or row+col==4:
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_k():
row=0
while row<6:
col=0
while col<4:
if col==0 or row-col==2 or row+col==4 :
print("*",end=" ")
else:
print(" ",end=" ")
col+=1
row+=1
print()
|
/*!
* \internal
* \brief Destroys this VertexArray object.
*
* \param obj VertexArray object
*/
static void m3gDestroyVertexArray(Object *obj)
{
VertexArray *array = (VertexArray *) obj;
M3G_VALIDATE_OBJECT(array);
M3G_ASSERT(array->numLocks == 0);
{
Interface *m3g = M3G_INTERFACE(array);
m3gFreeObject(m3g, array->data);
m3gFreeObject(m3g, array->cachedColors);
}
m3gDestroyObject(&array->object);
} |
<reponame>cortex/pgsql2
package org.postgresql.sql2.operations;
import jdk.incubator.sql2.Operation;
import jdk.incubator.sql2.Submission;
import org.postgresql.sql2.PgSession;
import org.postgresql.sql2.communication.NetworkConnection;
import org.postgresql.sql2.communication.network.CloseRequest;
import org.postgresql.sql2.submissions.CloseSubmission;
import java.time.Duration;
import java.util.function.Consumer;
public class PgCloseOperation implements Operation<Void> {
private PgSession connection;
private Consumer<Throwable> errorHandler;
private NetworkConnection protocol;
public PgCloseOperation(PgSession connection, NetworkConnection protocol) {
this.connection = connection;
this.protocol = protocol;
}
@Override
public Operation<Void> onError(Consumer<Throwable> errorHandler) {
if (this.errorHandler != null) {
throw new IllegalStateException("you are not allowed to call onError multiple times");
}
this.errorHandler = errorHandler;
return this;
}
@Override
public Operation<Void> timeout(Duration minTime) {
return this;
}
@Override
public Submission<Void> submit() {
CloseSubmission submission = new CloseSubmission(this::cancel, errorHandler);
submission.getCompletionStage().thenAccept(s -> connection.setLifeCycleClosed());
CloseRequest closeRequest = new CloseRequest(submission);
protocol.sendNetworkRequest(closeRequest);
// Closing so unregister connection
this.connection.unregister();
return submission;
}
private boolean cancel() {
// todo set life cycle to canceled
return true;
}
}
|
He’s set up two charitable trusts — the Naik Charitable Trust for education and skill training and the Nirali Memorial Medical Trust, named after his grand daughter.
MUMBAI: AM Naik pledged to devote 75% of his lifetime income to charity as he gets ready to step down from active leadership of the $16-billion engineering conglomerate Larsen & Toubro a year from now.
He’s set up two charitable trusts — the Naik Charitable Trust for education and skill training and the Nirali Memorial Medical Trust, named after his grand daughter who died of cancer in 2007. Naik declined to give details of the amount spent so far and the money he will be directing to philanthropy going ahead.
According to the ET Intelligence Group, Naik took home nearly Rs 200 crore in compensation in 2010-16. In FY16, this included stock options awarded by L&T Infotech. According to a source aware of the matter, since 1995, when Naik made his first donation to a hospital in his native village in Gujarat, he has donated about Rs 125 crore to charitable initiatives.
An asset management company handles Naik’s money while his sister’s family assists him in philanthropy. Naik is currently engaged in building a school and hospital close to L&T’s Powai campus and is also keen on setting up a fire station there. “I want to carry out my charity work at my ‘janmabhoomi’ and my ‘karmabhoomi’,” Naik said.
Naik became the chief executive in 1999 and chairman in 2003.
His long stewardship ushered in rapid growth and diversification at Larsen & Toubro, transforming it into a global engineering conglomerate. His trusts run seven projects and two of these will be commissioned in 2017, one of them being a Vedic school named after his wife that will be inaugurated on her birthday.
The succession plan seems to be moving seamlessly forward with SN Subrahmanyan, deputy managing director, seen as succeeding Naik when he retires in September 2017.
There have been hints that Naik may continue as non-executive chairman to guide the company, just as he plans to guide his charitable ventures. |
Representation of semi-structured imprecise data for fuzzy querying This work is part of a national project which aims at building a tool for the analysis of microbiological risks in food products. As a first step, we propose a unified querying system which simultaneously scans two complementary bases, containing microbiological information : a relational database containing structured information and a conceptual graph knowledge base containing semi-structured information. The unified querying system sends the user's query to both of them. Fuzzy queries and imprecise information are handled in both bases. To achieve this goal, we propose a way of representing fuzzy values, including numerical values, in conceptual graphs. |
<gh_stars>1-10
/* -*- Mode:c++; eval:(c-set-style "BSD"); c-basic-offset:4; indent-tabs-mode:nil; tab-width:8 -*- */
#ifndef __THREADSLINGER_H__
#define __THREADSLINGER_H__
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org>
*/
#include <pthread.h>
#include <inttypes.h>
#include <vector>
#include "LockWait.h"
#include "dll3.h"
namespace ThreadSlinger {
/** errors from this library */
struct ThreadSlingerError : BackTraceUtil::BackTrace {
/** errors that this library may throw */
enum errValue {
MessageOnListDestructor, //!< message still on a list during destructor
MessageNotFromThisPool, //!< message freed to wrong pool
DerefNoPool, //!< refcount down to zero but poolptr is null
PoolInitBeforePoolsInit, //!< pool init before pools init
__NUMERRS
} err;
// this can't be a std::string because it may get invoked
// by very early global constructors prior to main() starting,
// which means any std::strings present are not guaranteed to
// be fully constructed yet.
static const char * errStrings[__NUMERRS];
ThreadSlingerError(errValue _e) : err(_e) {
std::cerr << "ThreadSlingerError:\n" << Format();
}
/** handy utility function for printing error and stack backtrace */
/*virtual*/ const std::string _Format(void) const;
};
class thread_slinger_pool_base;
typedef DLL3::List<thread_slinger_pool_base,1> poolList_t;
class thread_slinger_message;
class thread_slinger_pool_base : public poolList_t::Links {
public:
virtual ~thread_slinger_pool_base(void) { }
virtual void release(thread_slinger_message * m) = 0;
virtual void getCounts(int &used, int &free, std::string &name) = 0;
};
typedef DLL3::List<thread_slinger_message,1,false,false> messageList_t;
/** base class for all user messages to go through thread_slinger */
class thread_slinger_message : public messageList_t::Links
{
int refcount;
WaitUtil::Lockable refcountlock;
public:
thread_slinger_pool_base * _slinger_pool;
thread_slinger_message(void);
virtual ~thread_slinger_message(void);
/** return the message's name, user of this class may override this */
virtual const std::string msgName(void) {
return "thread_slinger_message";
}
/** increase reference count */
void ref(void);
/** decrease reference count; if it hits zero, this buffer will be
* automatically returned to the pool */
void deref(void);
};
class _thread_slinger_queue
{
pthread_mutex_t mutex;
pthread_cond_t _waiter;
pthread_cond_t *waiter;
// it's a little bit of a waste to create a sempahore
// in every queue; when using the multiple-queue version
// of _dequeue, only one of the semaphores is used. however,
// this is cheaper IMHO than creating and destroying a semaphore
// every time you enter and leave _dequeue(), which is the alternative.
WaitUtil::Semaphore _waiter_sem;
WaitUtil::Semaphore * waiter_sem;
messageList_t msgs;
void lock( void ) { pthread_mutex_lock ( &mutex ); }
void unlock( void ) { pthread_mutex_unlock( &mutex ); }
inline thread_slinger_message * __dequeue(void);
inline thread_slinger_message * __dequeue_tail(void);
inline thread_slinger_message * _dequeue_int(int uSecs, bool dotail);
static inline struct timespec * setup_abstime(int uSecs,
struct timespec *abstime);
protected:
_thread_slinger_queue(pthread_mutexattr_t *mattr = NULL,
pthread_condattr_t *cattr = NULL);
~_thread_slinger_queue(void);
void _enqueue(thread_slinger_message *);
void _enqueue_head(thread_slinger_message *);
thread_slinger_message * _dequeue(int uSecs);
thread_slinger_message * _dequeue_tail(int uSecs);
int _get_count(void) const { return msgs.get_cnt(); }
static thread_slinger_message * _dequeue(
_thread_slinger_queue ** queues,
int num_queues, int uSecs,
int *which_queue=NULL);
void * _get_head(void) { return msgs.get_head(); }
};
/** a message queue of user objects, declare a derived type from
* thread_slinger_message and specify that as T.
* \param T the type to send through the queue, derived
* from thread_slinger_message base type */
template <class T>
class thread_slinger_queue : public _thread_slinger_queue
{
public:
thread_slinger_queue(pthread_mutexattr_t *mattr = NULL,
pthread_condattr_t *cattr = NULL)
: _thread_slinger_queue(mattr,cattr) { }
/** send a message to the receiver.
* \param msg a user's message derived from thread_slinger_message */
void enqueue(T * msg);
void enqueue_head(T * msg);
/** fetch a message from the sender.
* \param uSecs if >0, wait for that time and return NULL if no
* message; if <0, wait forever for a message; if 0,
* return NULL immediately if no message.
* \return NULL if timeout, or a message pointer */
T * dequeue(int uSecs=0);
T * dequeue_tail(int uSecs=0);
/** find out how many messages are currently queued */
int get_count(void) const;
/** dequeue from a set of queues in priority order.
* \param queues the list of queues to check, the priority is
* specified by the order in this list (first queue in this
* list is checked first).
* \param num_queues the dimension of the queues array
* \param uSecs the time to wait for a message: >0 wait up to
* that many usecs; <0 wait forever; ==0 return NULL
* immediately if all queues empty.
* \param which_queue an optional pointer to an integer, which
* on return of a valid message pointer will indicate which
* queue this message came from (an index in queues array)
* \return a message pointer or NULL if timeout */
static T * dequeue(thread_slinger_queue<T> * queues[],
int num_queues,
int uSecs, int *which_queue=NULL);
T * get_head(void) { return (T*) _get_head(); }
bool empty(void) const { return _get_count() == 0; }
};
/** data for a pool, retrieved from thread_slinger_pools::report_pools */
struct poolReport {
int usedCount; //!< number of buffers currently used by application
int freeCount; //!< number of buffers free in the pool
std::string name; //!< name of the pool according to
//!< thread_slinger_message::msgName
};
/** data for all pools from thread_slinger_pools::report_pools */
typedef std::vector<poolReport> poolReportList_t;
/** a static class which manages list of all known pools */
class thread_slinger_pools
{
static thread_slinger_pools * instance;
poolList_t lst;
public:
thread_slinger_pools(void);
static void register_pool(thread_slinger_pool_base * p);
static void unregister_pool(thread_slinger_pool_base * p);
/** retrieve stats about all pools */
static void report_pools(poolReportList_t &);
};
/** a convenient buffer pool for storing objects of any kind.
* \param T the type of object being stored in the queue,
* derived from thread_slinger_message. */
template <class T>
class thread_slinger_pool : public thread_slinger_pool_base
{
thread_slinger_queue<T> q;
/*virtual*/ void release(thread_slinger_message *);
WaitUtil::Lockable statsLockable;
int usedCount;
int freeCount;
bool nameSet;
std::string msgName;
public:
thread_slinger_pool(pthread_mutexattr_t *mattr = NULL,
pthread_condattr_t *cattr = NULL);
virtual ~thread_slinger_pool(void);
/** add more items to this pool. */
void add(int items);
/** allocate a buffer from the pool.
* \param uSecs how long to wait if the pool is empty:
* <0 means wait forever, ==0 means return NULL
* immediately, >0 means wait that number of usecs.
* \param grow if true, allocate new buffers if pool is empty.
* \return a buffer pointer, or NULL if empty and timeout */
T * alloc(int uSecs=0, bool grow=false);
/** release a buffer into the pool
* \param buf the buffer pointer to release */
void release(T * buf);
/** fetch number of buffers currently in the pool */
void getCounts(int &used, int &free, std::string &name);
/** return true if no items in pool */
bool empty(void) const;
int get_count(void) const { return freeCount; }
};
#include "thread_slinger.tcc"
/** \mainpage threadslinger user's API documentation
This is the user's manual for the threadslinger API.
Interesting classes:
<ul>
<li> \ref thread_slinger_message
<li> \ref thread_slinger_queue
<li> \ref thread_slinger_pool
</ul>
\code
struct myMessage : public thread_slinger_message
{
int a; // some field
int b; // some other field
};
thread_slinger_pool<myMessage,5> p;
typedef thread_slinger_queue<myMessage> myMsgQ;
myMsgQ q;
myMsgQ q2;
void * t3( void * dummy ) {
uintptr_t val = (uintptr_t) dummy;
while (1) {
myMessage * m = p.alloc(random()%5000);
if (m) {
if (val == 0)
q.enqueue(m);
else
q2.enqueue(m);
if (val == 0)
printf("+");
else
printf("=");
} else {
if (val == 0)
printf("-");
else
printf("_");
}
fflush(stdout);
usleep(random()%30000);
}
return NULL;
}
void * t4(void * dummy) {
myMsgQ * qs[2];
qs[0] = &q;
qs[1] = &q2;
while (1) {
int which;
myMessage * m = myMsgQ::dequeue(qs,2,(int)(random()%1000),&which);
if (m) {
if (which == 0)
printf(".");
else
printf(",");
p.release(m);
} else {
printf("!");
}
fflush(stdout);
usleep(random()%10000);
}
return NULL;
}
int main() {
pthread_t id;
pthread_create( &id, NULL, t3, (void*) 0 );
pthread_create( &id, NULL, t3, (void*) 1 );
pthread_create( &id, NULL, t4, (void*) 0 );
pthread_join(id,NULL);
return 0;
}
\endcode
*/
}; // namespace
#endif /* __THREADSLINGER_H__ */
|
<gh_stars>10-100
# coding: utf-8
# # Identifying safe loans with decision trees
# The [LendingClub](https://www.lendingclub.com/) is a peer-to-peer leading company that directly connects borrowers and potential lenders/investors. In this notebook, you will build a classification model to predict whether or not a loan provided by LendingClub is likely to [default](https://en.wikipedia.org/wiki/Default_(finance)).
#
# In this notebook you will use data from the LendingClub to predict whether a loan will be paid off in full or the loan will be [charged off](https://en.wikipedia.org/wiki/Charge-off) and possibly go into default. In this assignment you will:
#
# * Use SFrames to do some feature engineering.
# * Train a decision-tree on the LendingClub dataset.
# * Visualize the tree.
# * Predict whether a loan will default along with prediction probabilities (on a validation set).
# * Train a complex tree model and compare it to simple tree model.
#
# Let's get started!
# ## Fire up Graphlab Create
# Make sure you have the latest version of GraphLab Create. If you don't find the decision tree module, then you would need to upgrade GraphLab Create using
#
# ```
# pip install graphlab-create --upgrade
# ```
# In[1]:
import graphlab
graphlab.canvas.set_target('ipynb')
# # Load LendingClub dataset
# We will be using a dataset from the [LendingClub](https://www.lendingclub.com/). A parsed and cleaned form of the dataset is availiable [here](https://github.com/learnml/machine-learning-specialization-private). Make sure you **download the dataset** before running the following command.
# In[2]:
loans = graphlab.SFrame('lending-club-data.gl/')
# ## Exploring some features
#
# Let's quickly explore what the dataset looks like. First, let's print out the column names to see what features we have in this dataset.
# In[3]:
loans.column_names()
# Here, we see that we have some feature columns that have to do with grade of the loan, annual income, home ownership status, etc. Let's take a look at the distribution of loan grades in the dataset.
# In[4]:
loans['grade'].show()
# We can see that over half of the loan grades are assigned values `B` or `C`. Each loan is assigned one of these grades, along with a more finely discretized feature called `sub_grade` (feel free to explore that feature column as well!). These values depend on the loan application and credit report, and determine the interest rate of the loan. More information can be found [here](https://www.lendingclub.com/public/rates-and-fees.action).
#
# Now, let's look at a different feature.
# In[5]:
loans['home_ownership'].show()
# This feature describes whether the loanee is mortaging, renting, or owns a home. We can see that a small percentage of the loanees own a home.
# ## Exploring the target column
#
# The target column (label column) of the dataset that we are interested in is called `bad_loans`. In this column **1** means a risky (bad) loan **0** means a safe loan.
#
# In order to make this more intuitive and consistent with the lectures, we reassign the target to be:
# * **+1** as a safe loan,
# * **-1** as a risky (bad) loan.
#
# We put this in a new column called `safe_loans`.
# In[7]:
# safe_loans = 1 => safe
# safe_loans = -1 => risky
loans['safe_loans'] = loans['bad_loans'].apply(lambda x : +1 if x==0 else -1)
loans = loans.remove_column('bad_loans')
# Now, let us explore the distribution of the column `safe_loans`. This gives us a sense of how many safe and risky loans are present in the dataset.
# In[8]:
loans['safe_loans'].show(view = 'Categorical')
# You should have:
# * Around 81% safe loans
# * Around 19% risky loans
#
# It looks like most of these loans are safe loans (thankfully). But this does make our problem of identifying risky loans challenging.
# ## Features for the classification algorithm
# In this assignment, we will be using a subset of features (categorical and numeric). The features we will be using are **described in the code comments** below. If you are a finance geek, the [LendingClub](https://www.lendingclub.com/) website has a lot more details about these features.
# In[9]:
features = ['grade', # grade of the loan
'sub_grade', # sub-grade of the loan
'short_emp', # one year or less of employment
'emp_length_num', # number of years of employment
'home_ownership', # home_ownership status: own, mortgage or rent
'dti', # debt to income ratio
'purpose', # the purpose of the loan
'term', # the term of the loan
'last_delinq_none', # has borrower had a delinquincy
'last_major_derog_none', # has borrower had 90 day or worse rating
'revol_util', # percent of available credit being used
'total_rec_late_fee', # total late fees received to day
]
target = 'safe_loans' # prediction target (y) (+1 means safe, -1 is risky)
# Extract the feature columns and target column
loans = loans[features + [target]]
# What remains now is a **subset of features** and the **target** that we will use for the rest of this notebook.
# ## Sample data to balance classes
#
# As we explored above, our data is disproportionally full of safe loans. Let's create two datasets: one with just the safe loans (`safe_loans_raw`) and one with just the risky loans (`risky_loans_raw`).
# In[10]:
safe_loans_raw = loans[loans[target] == +1]
risky_loans_raw = loans[loans[target] == -1]
print "Number of safe loans : %s" % len(safe_loans_raw)
print "Number of risky loans : %s" % len(risky_loans_raw)
# Now, write some code to compute below the percentage of safe and risky loans in the dataset and validate these numbers against what was given using `.show` earlier in the assignment:
# In[12]:
print "Percentage of safe loans :", len(safe_loans_raw) / float(len(safe_loans_raw) + len(risky_loans_raw))
print "Percentage of risky loans :", len(risky_loans_raw) / float(len(safe_loans_raw) + len(risky_loans_raw))
# One way to combat class imbalance is to undersample the larger class until the class distribution is approximately half and half. Here, we will undersample the larger class (safe loans) in order to balance out our dataset. This means we are throwing away many data points. We used `seed=1` so everyone gets the same results.
# In[14]:
# Since there are fewer risky loans than safe loans, find the ratio of the sizes
# and use that percentage to undersample the safe loans.
percentage = len(risky_loans_raw)/float(len(safe_loans_raw))
risky_loans = risky_loans_raw
safe_loans = safe_loans_raw.sample(percentage, seed=1)
# Append the risky_loans with the downsampled version of safe_loans
loans_data = risky_loans.append(safe_loans)
# Now, let's verify that the resulting percentage of safe and risky loans are each nearly 50%.
# In[15]:
print "Percentage of safe loans :", len(safe_loans) / float(len(loans_data))
print "Percentage of risky loans :", len(risky_loans) / float(len(loans_data))
print "Total number of loans in our new dataset :", len(loans_data)
# **Note:** There are many approaches for dealing with imbalanced data, including some where we modify the learning algorithm. These approaches are beyond the scope of this course, but some of them are reviewed in this [paper](http://ieeexplore.ieee.org/xpl/login.jsp?tp=&arnumber=5128907&url=http%3A%2F%2Fieeexplore.ieee.org%2Fiel5%2F69%2F5173046%2F05128907.pdf%3Farnumber%3D5128907 ). For this assignment, we use the simplest possible approach, where we subsample the overly represented class to get a more balanced dataset. In general, and especially when the data is highly imbalanced, we recommend using more advanced methods.
# ## Split data into training and validation sets
# We split the data into training and validation sets using an 80/20 split and specifying `seed=1` so everyone gets the same results.
#
# **Note**: In previous assignments, we have called this a **train-test split**. However, the portion of data that we don't train on will be used to help **select model parameters** (this is known as model selection). Thus, this portion of data should be called a **validation set**. Recall that examining performance of various potential models (i.e. models with different parameters) should be on validation set, while evaluation of the final selected model should always be on test data. Typically, we would also save a portion of the data (a real test set) to test our final model on or use cross-validation on the training set to select our final model. But for the learning purposes of this assignment, we won't do that.
# In[16]:
train_data, validation_data = loans_data.random_split(.8, seed=1)
# # Use decision tree to build a classifier
# Now, let's use the built-in GraphLab Create decision tree learner to create a loan prediction model on the training data. (In the next assignment, you will implement your own decision tree learning algorithm.) Our feature columns and target column have already been decided above. Use `validation_set=None` to get the same results as everyone else.
# In[17]:
decision_tree_model = graphlab.decision_tree_classifier.create(train_data, validation_set=None,
target = target, features = features)
# ## Visualizing a learned model
# As noted in the [documentation](https://dato.com/products/create/docs/generated/graphlab.boosted_trees_classifier.create.html#graphlab.boosted_trees_classifier.create), typically the max depth of the tree is capped at 6. However, such a tree can be hard to visualize graphically. Here, we instead learn a smaller model with **max depth of 2** to gain some intuition by visualizing the learned tree.
# In[18]:
small_model = graphlab.decision_tree_classifier.create(train_data, validation_set=None,
target = target, features = features, max_depth = 2)
# In the view that is provided by GraphLab Create, you can see each node, and each split at each node. This visualization is great for considering what happens when this model predicts the target of a new data point.
#
# **Note:** To better understand this visual:
# * The root node is represented using pink.
# * Intermediate nodes are in green.
# * Leaf nodes in blue and orange.
# In[19]:
small_model.show(view="Tree")
# # Making predictions
#
# Let's consider two positive and two negative examples **from the validation set** and see what the model predicts. We will do the following:
# * Predict whether or not a loan is safe.
# * Predict the probability that a loan is safe.
# In[20]:
validation_safe_loans = validation_data[validation_data[target] == 1]
validation_risky_loans = validation_data[validation_data[target] == -1]
sample_validation_data_risky = validation_risky_loans[0:2]
sample_validation_data_safe = validation_safe_loans[0:2]
sample_validation_data = sample_validation_data_safe.append(sample_validation_data_risky)
sample_validation_data
# ## Explore label predictions
# Now, we will use our model to predict whether or not a loan is likely to default. For each row in the **sample_validation_data**, use the **decision_tree_model** to predict whether or not the loan is classified as a **safe loan**.
#
# **Hint:** Be sure to use the `.predict()` method.
# In[22]:
decision_tree_model.predict(sample_validation_data)
# In[23]:
predictions = decision_tree_model.predict(sample_validation_data)
print predictions
sample_validation_data[sample_validation_data[target] == predictions]
# **Quiz Question:** What percentage of the predictions on `sample_validation_data` did `decision_tree_model` get correct?
# ## Explore probability predictions
#
# For each row in the **sample_validation_data**, what is the probability (according **decision_tree_model**) of a loan being classified as **safe**?
#
#
# **Hint:** Set `output_type='probability'` to make **probability** predictions using **decision_tree_model** on `sample_validation_data`:
# In[24]:
decision_tree_model.predict(sample_validation_data, output_type='probability')
# **Quiz Question:** Which loan has the highest probability of being classified as a **safe loan**?
#
# **Checkpoint:** Can you verify that for all the predictions with `probability >= 0.5`, the model predicted the label **+1**?
# ### Tricky predictions!
#
# Now, we will explore something pretty interesting. For each row in the **sample_validation_data**, what is the probability (according to **small_model**) of a loan being classified as **safe**?
#
# **Hint:** Set `output_type='probability'` to make **probability** predictions using **small_model** on `sample_validation_data`:
# In[25]:
small_model.predict(sample_validation_data, output_type='probability')
# **Quiz Question:** Notice that the probability preditions are the **exact same** for the 2nd and 3rd loans. Why would this happen?
# ## Visualize the prediction on a tree
#
#
# Note that you should be able to look at the small tree, traverse it yourself, and visualize the prediction being made. Consider the following point in the **sample_validation_data**
# In[27]:
sample_validation_data[1]
# Let's visualize the small tree here to do the traversing for this data point.
# In[28]:
small_model.show(view="Tree")
# **Note:** In the tree visualization above, the values at the leaf nodes are not class predictions but scores (a slightly advanced concept that is out of the scope of this course). You can read more about this [here](https://homes.cs.washington.edu/~tqchen/pdf/BoostedTree.pdf). If the score is $\geq$ 0, the class +1 is predicted. Otherwise, if the score < 0, we predict class -1.
#
#
# **Quiz Question:** Based on the visualized tree, what prediction would you make for this data point?
#
# Now, let's verify your prediction by examining the prediction made using GraphLab Create. Use the `.predict` function on `small_model`.
# In[29]:
small_model.predict(sample_validation_data)
# # Evaluating accuracy of the decision tree model
# Recall that the accuracy is defined as follows:
# $$
# \mbox{accuracy} = \frac{\mbox{# correctly classified examples}}{\mbox{# total examples}}
# $$
#
# Let us start by evaluating the accuracy of the `small_model` and `decision_tree_model` on the training data
# In[30]:
print small_model.evaluate(train_data)['accuracy']
print decision_tree_model.evaluate(train_data)['accuracy']
# **Checkpoint:** You should see that the **small_model** performs worse than the **decision_tree_model** on the training data.
#
#
# Now, let us evaluate the accuracy of the **small_model** and **decision_tree_model** on the entire **validation_data**, not just the subsample considered above.
# In[31]:
print small_model.evaluate(validation_data)['accuracy']
print decision_tree_model.evaluate(validation_data)['accuracy']
# **Quiz Question:** What is the accuracy of `decision_tree_model` on the validation set, rounded to the nearest .01?
# ## Evaluating accuracy of a complex decision tree model
#
# Here, we will train a large decision tree with `max_depth=10`. This will allow the learned tree to become very deep, and result in a very complex model. Recall that in lecture, we prefer simpler models with similar predictive power. This will be an example of a more complicated model which has similar predictive power, i.e. something we don't want.
# In[32]:
big_model = graphlab.decision_tree_classifier.create(train_data, validation_set=None,
target = target, features = features, max_depth = 10)
# Now, let us evaluate **big_model** on the training set and validation set.
# In[33]:
print big_model.evaluate(train_data)['accuracy']
print big_model.evaluate(validation_data)['accuracy']
# **Checkpoint:** We should see that **big_model** has even better performance on the training set than **decision_tree_model** did on the training set.
# **Quiz Question:** How does the performance of **big_model** on the validation set compare to **decision_tree_model** on the validation set? Is this a sign of overfitting?
# ### Quantifying the cost of mistakes
#
# Every mistake the model makes costs money. In this section, we will try and quantify the cost of each mistake made by the model.
#
# Assume the following:
#
# * **False negatives**: Loans that were actually safe but were predicted to be risky. This results in an oppurtunity cost of losing a loan that would have otherwise been accepted.
# * **False positives**: Loans that were actually risky but were predicted to be safe. These are much more expensive because it results in a risky loan being given.
# * **Correct predictions**: All correct predictions don't typically incur any cost.
#
#
# Let's write code that can compute the cost of mistakes made by the model. Complete the following 4 steps:
# 1. First, let us compute the predictions made by the model.
# 1. Second, compute the number of false positives.
# 2. Third, compute the number of false negatives.
# 3. Finally, compute the cost of mistakes made by the model by adding up the costs of true positives and false positives.
#
# First, let us make predictions on `validation_data` using the `decision_tree_model`:
# In[34]:
predictions = decision_tree_model.predict(validation_data)
# **False positives** are predictions where the model predicts +1 but the true label is -1. Complete the following code block for the number of false positives:
# In[35]:
false_positives = 0
false_negatives = 0
for item in xrange(len(validation_data)):
if predictions[item] != validation_data['safe_loans'][item]:
if predictions[item] == 1:
false_positives += 1
else:
false_negatives += 1
print false_positives
# **False negatives** are predictions where the model predicts -1 but the true label is +1. Complete the following code block for the number of false negatives:
# In[36]:
print false_negatives
# **Quiz Question:** Let us assume that each mistake costs money:
# * Assume a cost of \$10,000 per false negative.
# * Assume a cost of \$20,000 per false positive.
#
# What is the total cost of mistakes made by `decision_tree_model` on `validation_data`?
# In[38]:
false_negatives * 10000 + false_positives * 20000
# In[ ]:
|
Comparative Advantage, Firm Heterogeneity, and Selection of Exporters This paper investigates how the fraction of exporting firms among domestic firms in a country differs across industries, depending on a countrys comparative advantage. A model, which extends work by Melitz and Bernard, Redding and Schott, describes an economy that comprises two countries asymmetrically endowed with two production factors, many industries differing in the relative intensity of the two production factors, and a continuum of firms differing in productivity. The model predicts a comparative advantage driven pattern of the exporter selection: the fractions of exporting firms among all domestic firms are ranked according to the order of industries relative intensities of a production factor with which the country is relatively well-endowed. This quasi-Heckscher-Ohlin prediction about the exporter fraction is empirically tested using data from the manufacturing censuses of Chile, Colombia, India, and the United States. The result of the analysis shows that the correlation between the exporter fractions and industry skill intensities is larger, or more positive, for a country with higher skilled-labor abundance, which confirms the theoretical prediction and demonstrates the role of comparative advantage in exporter selection. |
Evaluation of Cosmetic Liquid Penetration Using Terahertz Time-of-Flight Method It is important to evaluate the penetration depth and speed of cosmetics into the skin for the cosmetic industry. However, the conventional method for measuring those parameters has some drawbacks. In this study, a terahertz time-of-flight method with Si-based emitter was applied for evaluation. The penetration of the liquid into a pig skin was measured as a travelling time of the THz pulses irradiating on a pigskin, where the glycerin concentration in the liquid was varied. |
Defense Secretary James Mattis on Thursday said that there was "very little doubt" Russia has attempted to interfere in democratic elections in the past.
"There is very little doubt that they have either interfered or attempted to interfere in a number of elections in democracies," Mattis said while answering questions at NATO headquarters in Brussels.
He added that he does not feel compelled to respond to Russian officials who were not pleased with his call to deal with Moscow from a position of strength.
ADVERTISEMENT
"I have no need to respond to the Russian statement at all. NATO has always stood for military strength and protection of democracies and the freedoms we intend to pass on to our children," he said.
Mattis maintained that Russia needs to "live by international law" and "prove itself" when it comes to its international commitments.
The Defense secretary also reiterated that Washington is fully committed to backing NATO members under Article Five's principle of collective defense.
Mattis on Tuesday threatened to "moderate" U.S. support for NATO if its allies do not increase their contribution.
"The commitment to Article Five remains rock solid. The message that I brought here about everyone carrying their fair share of burden, of sacrifice to maintain the best defense in the world was very well received. It was not contentious," he said.
President Trump's calls for a closer relationship with Russia and criticism of NATO during the campaign and since Election Day have created concerns among NATO nations about the United States' commitment to the treaty. |
// A simple circular buffer implementation used by the CircularOutput class.
class CircularBuffer
{
public:
CircularBuffer(size_t size) : size_(size), buf_(size), rptr_(0), wptr_(0) {}
bool Empty() const { return rptr_ == wptr_; }
size_t Available() const { return (size_ - wptr_ + rptr_) % size_ - 1; }
void Skip(unsigned int n) { rptr_ = (rptr_ + n) % size_; }
void Read(std::function<void(void *src, unsigned int n)> dst, unsigned int n)
{
if (rptr_ + n >= size_)
{
dst(&buf_[rptr_], size_ - rptr_);
n -= size_ - rptr_;
rptr_ = 0;
}
dst(&buf_[rptr_], n);
rptr_ += n;
}
void Pad(unsigned int n) { wptr_ = (wptr_ + n) % size_; }
void Write(const void *ptr, unsigned int n)
{
if (wptr_ + n >= size_)
{
memcpy(&buf_[wptr_], ptr, size_ - wptr_);
n -= size_ - wptr_;
ptr = static_cast<const uint8_t *>(ptr) + size_ - wptr_;
wptr_ = 0;
}
memcpy(&buf_[wptr_], ptr, n);
wptr_ += n;
}
private:
const size_t size_;
std::vector<uint8_t> buf_;
size_t rptr_, wptr_;
} |
Decrease of ethanol intake following repeated injection of serotonin-1A agonist in rats: relationship with receptor responsiveness. OBJECTIVE To monitor pre and postsynaptic receptor responsiveness and consumption of ethanol following the repeated administration of a selective serotonin-1A receptor agonist, 8-hydroxy-2-di-n-propylaminotetralin (8-OH-DPAT), to ethanol treated rats. DESIGN The experimental protocol was designed to administer ethanol orally to rats for three weeks and 8-OH-DPAT during the 3rd week. PLACE AND DURATION OF STUDY The experiments were performed in the department of Biochemistry, Karachi University. Samples collected after three weeks of treatment were analyzed within a week. SUBJECTS AND METHODS The study was conducted on 24 males albino Wistar rats treated with ethanol for three weeks. 8-OH-DPAT at a dose of 1mg/kg or saline was injected to ethanol treated rats from day 1 to day 5 during the 3rd week to monitor the effects on ethanol consumption. Pre and postsynaptic responses to 8-OH-DPAT were monitored by injecting the drug on the 6th day to a group of 5-day saline and a group of 5-day 8-OH-DPAT injected animals. Control animals of the two groups were injected with saline. RESULTS Before the injection of 8-OH-DPAT, weekly intakes of ethanol were highly comparable in the two groups. Administration of 8-OH-DPAT, from day 1 to day 5, decreased ethanol intake. Pre and postsynaptic serotonin-1A receptor dependent responses monitored on the 6th day were higher in 5-day saline than 5-day 8-OH-DPAT injected animals. CONCLUSION A decrease in the effectiveness of negative feedback control over the synaptic availability of serotonin following 5-day administration of 8-OH-DPAT is involved in the decreases of ethanol consumption. |
package lol.kent.practice.spring.mongo.dto;
import java.util.List;
import lombok.Builder;
import lombok.Data;
import lombok.experimental.Tolerate;
/**
* <pre>
* 类描述:
* </pre>
* <p>
* Copyright: Copyright (c) 2020年09月01日 19:04
* <p>
* Company: AMPM Fit
* <p>
*
* @author Shunqin.Chen
* @version 1.0.0
*/
@Data
@Builder
public class PostDTO {
private String title;
private String userId;
private List<String> commentUserIds;
@Tolerate
public PostDTO() {
}
}
|
Island of Fogs: Archaeological and Ethnohistorical Investigations of Isla Cedros, Baja California By mid-twentieth century, the Ice Age peopling of North America and cultural diversification of its indigenous peoples was coming into continental-scale focus in volumes like Jesse Jennings Danger Cave or James B. Griffins Green Bible, Archaeology of Eastern United States. Many other volumes reflect the astonishing progress of archaeology over the last century in synthesizing North American indigenous cultural origins. Yet these landmark publications also testify to the persistently landlocked perspectives of most archaeologists. Until the close of the twentieth century, the story of North American cultural origins was almost entirely focused on the continents interior and its terrestrial foragers. In what promises to be one of the most |
// The upstream supports http/1.1,custom-alpn, and we configure the upstream TLS context to
// negotiate custom-alpn. No attempt to negotiate http/1.1 should happen, so we should select
// custom-alpn.
// TODO(snowp): We should actually fail the handshake in case of negotiation failure,
// fix that and update these tests.
TEST_F(AlpnSelectionIntegrationTest, Http11UpstreamConfiguredALPN) {
upstream_alpn_.emplace_back(Http::Utility::AlpnNames::get().Http11);
upstream_alpn_.emplace_back("custom-alpn");
configured_alpn_.emplace_back("custom-alpn");
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
IntegrationStreamDecoderPtr response =
codec_client_->makeHeaderOnlyRequest(default_request_headers_);
waitForNextUpstreamRequest();
EXPECT_EQ("custom-alpn", fake_upstream_connection_->connection().nextProtocol());
upstream_request_->encodeHeaders(default_response_headers_, true);
ASSERT_TRUE(response->waitForEndStream());
EXPECT_EQ("200", response->headers().getStatusValue());
} |
Modulated structures in electroconvection in nematic liquid crystals Motivated by experiments in electroconvection in nematic liquid crystals with homeotropic alignment we study the coupled amplitude equations describing the formation of a stationary roll pattern in the presence of a weakly-damped mode that breaks isotropy. The equations can be generalized to describe the planarly aligned case if the orienting effect of the boundaries is small, which can be achieved by a destabilizing magnetic field. The slow mode represents the in-plane director at the center of the cell. The simplest uniform states are normal rolls which may undergo a pitchfork bifurcation to abnormal rolls with a misaligned in-plane director.We present a new class of defect-free solutions with spatial modulations perpendicular to the rolls. In a parameter range where the zig-zag instability is not relevant these solutions are stable attractors, as observed in experiments. We also present two-dimensionally modulated states with and without defects which result from the destabilization of the one-dimensionally modulated structures. Finally, for no (or very small) damping, and away from the rotationally symmetric case, we find static chevrons made up of a periodic arrangement of defect chains (or bands of defects) separating homogeneous regions of oblique rolls with very small amplitude. These states may provide a model for a class of poorly understood stationary structures observed in various highly-conducting materials ("prechevrons"or"broad domains"). I. INTRODUCTION Nematic liquid crystals, the simplest type of intrinsically anisotropic fluids, continue to provide model systems for a wide variety of interesting nonlinear dynamical phenomena like optical instabilities, flow-induced nonlinear waves, critical properties of nonequilibrium transitions, and in particular electrically or thermally driven convection instabilities (see also and references therein). In nematics the mean orientation of the rod-like molecules is described by the directorn. Electroconvection (EC) driven by an ac voltage U at frequency is commonly observed in thin nematic layers sandwiched between glass plates with transparent electrodes using nematics with positive conductivity anisotropy ( a > 0) and negative or slightly positive dielectric anisotropy a. In the well studied planarly aligned case, wheren is anchored parallel to the bounding plates along a direction which we will take as x (we choose the layer in the x-y plane) EC sets in directly from the homogeneous state at a critical voltage U c () and leads slightly above threshold to ordered roll patterns associated with a periodic director distortion with the critical wave vector q c (). Here we will only consider the most common situation where the bifurcation is supercritical and leads to stationary rolls with q c parallel tox (normal rolls (NRs)). In the usual low-frequency conduction regime, where the wavelength is controlled by the cell thickness, this may exclude in particular very low frequencies where the rolls at threshold may be oriented obliquely (depending on the material). In NRs near threshold the director remains in the x-z plane, i.e., perpendicular to the roll axis. The investigation of homeotropically oriented cells using nematics with manifestly negative dielectric anisotropy a < 0 was initiated rather recently, see for experimental and for theoretical work. In this case the director is initially oriented perpendicular to the layer, i.e., in the z direction, so the system is isotropic in the x-y plane. Then the first instability is the spatially homogeneous Freedericksz transition where the director bends away from the z direction, singling out spontaneously a direction in the x-y plane. After the transition the slow, undamped variation of the inplane director (the Goldstone mode) may be described by an angle. At higher voltages there is a further transition to EC which is in many respects similar to that in cells with planarly aligned nematics. However, now the Goldstone mode has to be included in the description even right at threshold. It turns out that the torque arising when the in-plane director and the wavevector are (slightly) misaligned is destabilizing, i.e., it acts to increase the misalignment ("abnormal torque"). Then the in-plane director in NRs is not perpendicular to the (local) roll axis. These NRs with a misaligned in-plane director were termed "abnormal rolls" (ARs). Furthermore one may expect spatio-temporal disorder right at threshold and this has indeed been observed, at least in the oblique roll regime, where one expects faster dynamics. For NRs the experimental situation is not totally clear. By applying an in-plane magnetic field, which now defines the x direction and exerts an aligning torque on, the disorder at threshold can be suppressed. Indeed the situation then is similar to that in the planar case. However, for a small field a small abnormal torque will suffice to overcome the magnetic alignment, and then one has a transition to ordered ARs, where the in-plane director is homogeneously rotated out of the x direction. For NRs this symmetry breaking is spontaneous, either to the left or to the right, and the transition is described by a supercritical pitchfork bifurcation, which has been verified experimentally. In the planarly aligned case one also has a transition to ordered ARs, although this occurs at a distance from threshold such that a quantitative description is more difficult. Since now the director is aligned at the cell boundaries the distortion of the in-plane director is confined to the center part of the cell leading to a twist distortion. Incidentally, this is the reason why the phenomenon has been identified only recently in planar convection. By applying a magnetic field in the y direction one can now destabilize and thus move the AR transition downward towards the primary instability. The AR transition merges with the primary bifurcation when the field reaches the strength of the twist Freedericksz field. When the two transitions are near each other a simple reduced description can be used. This shows that the two classes of systems are in many ways similar. Above the AR transition one often observes more complicated structures with or without defects. In particular, in homeotropic EC, modulations of the AR mode have been observed which leave the roll pattern (i.e., its phase) virtually unchanged. Ideally, such structures can be considered quasi one-dimensional (1D) with spatial variations only perpendicular to the (normally oriented) rolls. We wish to address in particular such structures by studying the simplest set of coupled amplitude equations capable of describing the AR scenario. These equations were first derived for homeotropic systems near threshold but with a slight generalization they can also illustrate the planar case. We here present for the first time 1D solutions of the appropriate type. We will then briefly discuss the destabilization of these 1D structures. Finally we present a new class of fully ordered 2D solutions occurring at higher voltage (or smaller magnetic fields) involving periodic arrangements of defect chains (or bands of defects). We call them static chevrons since they are reminiscent of the dynamic chevrons observed in the dielectric range of EC, and more recently, also in homeotropic convection. Our results could also be of relevance for the higherfrequency dielectric regime, where the rolls are very narrow and therefore the orienting effect of planar boundary conditions is substantially weaker than in the conduction range. Recently the weakly nonlinear description of the dielectric regime in planarly aligned systems has been investigated in detail. In Sec. II we discuss the basic equations, which take the form of an activator-inhibitor system, and their homogeneous solutions. In Sec. III we study 1D modulated solutions. Their stability within the full 2D equations is investigated in Sec. IV A and in Sec. IV B some 2D structures, in particular defect-free solutions, are presented. In Sec. V we present the static chevron states. We conclude by putting our results into a more general context, relate them to experiments, and present an outlook. II. BASIC EQUATIONS AND HOMOGENEOUS SOLUTIONS In situations where the in-plane director, described by an angle measured from the x direction, becomes an active mode already near the threshold to NRs one can describe the system by the following set of coupled Ginzburg-Landau equations for the complex patterning mode A and the slowly varying angle Here we have chosen the x direction along the wavevector of the NRs. The angle of the in-plane director is measured from the x axis. The validity of Eqs. is restricted to small values of the reduced control parameter (more precisely /g ≪ 1 and angles || ≪ 1). Special attention should be paid to the sign of the parameter. If were positive the field would be stabilized by the roll pattern. However, is negative, at least for the standard nematics which have been used in relevant experiments. This gives rise to the transition to abnormal rolls and to interesting dynamical phenomena. Note that yy tends to zero at the transition from normal to oblique rolls at threshold. The equations can be justified most convincingly for homeotropic orientation near the EC threshold (reduced control parameter ≪ 1). Overall rotation invariance then requires that the three terms multiplying 2 yy in Eq. combine to (∂y − iq c ) 2, so that C 1 = C 2 = 1. Without the isotropy-breaking term −T, which is realized easily by an in-plane magnetic field (then T = a H 2 ), the angle may not saturate. Then one has to resort to a globally rotational invariant generalization of Eqs.. We will see that this is not always necessary. The parameters C 1, C 2 were introduced to allow for more general situations like in planar alignment (for structural stability one needs C 2 > C 2 1 > 0). Then the magnetic field term in Eq. actually models the orienting effect of the boundaries. In the common conduction range, where the wavelength is of the order of the cell thickness, the orienting effects are sufficiently strong so that interesting dynamics of sets in at values of which are too large to allow quantitative description by Eqs.. Then, in particular, singular mean flow has to be included. To reduce the damping of one can either apply a destabilizing in-plane magnetic field and/or go to the dielectric range where the effect of boundaries is weaker. When T becomes too small higher-order terms are needed in Eq.. For calculations it is useful to introduce a scaled version of Eqs. for > 0 The damping parameter h gives the ratio of the aligning (=isotropy-breaking) torque over the abnormal torque of NRs. For large values of h one can set = 0 and disregard Eq.. h can be decreased by either decreasing a stabilizing magnetic field (increasing a destabilizing field) or by increasing. Below we will show that, keeping the aligning torque fixed, one can write where AR is the reduced control parameter where the transition from NRs to ARs takes place. The parameter describes the action of the gradient of the in-plane director on the phase of the rolls. Experimentally it can be controlled by varying the frequency. In this paper we will be concerned with the range > 0 where NRs are first destabilized by the transition to ARs (see below). For < 0 the zig-zag instability comes in earlier. Various features of Eqs. have been analyzed in and comparison with experiment has given evidence for their validity. We first discuss the homogenous solutions of for rolls with modulation wavevector (Q, P ) where A = A 0 e i(Qx+P y), A 0 ≥ 0, and a constant in space angle = 0. One is left with the dynamical system These equations can be classified as an activator-inhibitor system with activator A 0 (positive linear growth rate for not too large wavevector) and inhibitor 0. For simplicity we will in the following consider Q = 0 (the results are easily generalized). For P = 0 (rolls exactly in the x direction; we will deal with this case, except in Sec. V) there is the symmetry → −. The basic uniform state A 0 = 0, 0 = 0, is an unstable solution of, and the NR state A 0 = 1, 0 = 0, is stable only for h ≥ 1. Finally, the abnormal roll (AR) states exist in the range 0 ≤ h < 1. They bifurcate from the NRs at h = 1 and they break the symmetry → − of the equations. For h > 0 the two AR states are global attractors with regions of attraction A 0 > 0, 0 > / < 0, respectively. For h > 4 /(1+4 ) the AR states represent saddles (two real eigenvalues), otherwise spiral points. The case h = 0 needs special attention. Clearly the whole band is solution of the equation. The segment | 0 | < 1 is repulsive whereas the regions | 0 | > 1 are attractive. The AR state (for h = 0) separates the two cases. There is a separatrix A 2 0 + 1/(1 + ) 2 0 = 1, which separates trajectories flowing out of the repulsive segment from those coming from infinity. The degeneracy for h = 0 is presumably realistic for homeotropic EC. It is a consequence of rotational invariance. For planar EC the degeneracy is removed by higher-order terms, in particular a term proportional to 3 in Eq.. Nevertheless it is instructive to study this limit where results simplify. III. 1D MODULATED STRUCTURES Next we consider modulated structures that leave the roll pattern untouched, i.e., which do not involve the phase of the complex field A. This can occur generically only for spatial variations along x. Then the equations take the form In this section we will study these equations. We will choose A > 0. A. Single domain walls We start by discussing domain walls that connect the two variants of AR solutions and their interaction. Near the AR transition (h near 1) domain walls attract each other, so that modulated states are unstable. This can be seen from the fact that for 1 − h ≪ 1 the amplitude can be eliminated adiabatically from Eq. leading to In this equation all modulated states (they can be expressed in terms of an elliptic integral) are unstable, although their lifetimes are exceedingly long due to the exponentially weak (attractive) interaction between well separated domain walls (see below). Surprisingly, for lower damping, the interaction acquires repulsive parts, so that stable modulated structures can emerge. In fact, for h → 0 the interaction becomes purely repulsive so that only periodic modulations exist (see below). Actually, for h = 0 a static domain wall solution can be found analytically. It reads where It selects the states A = A 0, = ± 0 from the continuum of states. We have checked numerically and could find no stable static domain wall solution other than. We note that since 2 0 > 1 connects stable states. We mention that the stationary wall is embedded in a continuous family of moving walls connecting inequivalent states. Their study is beyond the scopes of the present paper. Since for h = 0 the walls can connect only to the AR states and AR → ±1 ( = 0 ) for h → 0, this limit has to be clarified. An example of a numerically stable (within the 1D equations) wall for small h is shown in Fig. 1. The fields go to their AR values at spatial infinity. However, in the wall region the field exhibits an overshoot approaching the values ± 0 of. The overshoot becomes longer and approaches nearer to ± 0 as h → 0. In order to understand this behavior better we study the spatial decay of the solution into the AR state. This is obtained by linearizing Eqs. around an AR solution and calculating the spatial exponents. They are For h → 0 the exponents are complex and tend to zero, which explains the slow decay. The exponents p ± remain complex for damping constants h < h osc ≡ (1 + D 1 /4) −1. We will show that this is the bound up to which domain walls may repel and thus form stable bound states. B. Interaction of domain walls, modulated structures In simulations of Eqs. one easily finds stable stationary solutions with more than one domain wall. In particular there are periodic solutions which come in two varieties: the ones that preserve the global symmetry → − ("symmetric") and others that do not preserve it ("nonsymmetric"). This section is mainly devoted to periodic solutions. There are also pulse-type states localized around one of the AR solutions as well as nonperiodic extended solutions. Let us first approach these modulated solutions from the side of large separation between domain walls by studying their interaction. Repulsive interaction is a prerequisite to form stable periodic states and interaction of both signs are necessary to form nonperiodic arrays. The problem is formulated as follows: Two walls are placed symmetrically around the origin at positions ±x 0. Then the fields have zero derivative at x = 0. We now focus on the region x > 0, write the amplitude and angle as, t) and substitute these expressions into Eqs.. In the spirit of small variations and slow ("slaved") dynamics we keep the terms linear in a and, but neglect the ones that are small and contain time derivative where the dot denotes time derivatives and the argument of all functions is x − x 0. To satisfy the boundary conditions one needs At the other end x → ∞ the perturbations a and should vanish. Multiplying by the adjoint of the translational mode (A w, − w ) and integrating from zero to infinity, we obtain an equation which has on the right hand side only the boundary terms at x = 0. On the left hand side the integrals may be extended to −∞ with negligible error leading to. This formula can be used only when the term in brackets on the left hand side is positive, i.e., for Otherwise translation becomes an active mode, i.e., one expects spontaneous acceleration of the domain wall. This can be shown by retaining the small time derivative terms omitted in Eqs.. We will here assume to hold (experimentally this appears to be the case) and comment briefly on the acceleration instability at the end of this section. In the special case h = 0 and for the wall, expression can be evaluated leading to Thus, at least for < accel one has 0 > 0, i.e., the interaction among walls is repulsive everywhere. This is consistent with the numerical observation of stable periodic solutions and no nonperiodic states. For h = 0 we may use the asymptotic behavior characterized by the exponents in Eq. to evaluate the right hand side of. In the range of complex exponents p ±, i.e., for h < h osc, the interaction is repulsive or attractive depending on the distance between walls. Thus one expects stable periodic solutions in appropriate wavelength intervals as well as nonperiodic structures, in agreement with simulations. An example of a periodic solution is given in Fig. 2 for a field value h = 0.1. Finally, in the monotonic range h osc < h < 1, the right hand side of is where c is a factor that cannot be determined from the asymptotic analysis and p − is given in. One easily sees that the term in square brackets is negative, so that the interaction between domain walls is now attractive. In this range we expect neither stable periodic nor nonperiodic solutions, although, as pointed out before, the lifetime of modulations may be very long. Let us now continue the symmetric periodic solutions to small wavelengths. Since they conserve the global → − symmetry one expects them to bifurcate from the NRs. This is indeed the case. From a simple linear stability analysis one finds that NRs are unstable with respect to periodic modes with wavenumber |q| < q c where Indeed, the bifurcation is of supercritical type. In Fig. 3, which summarizes our results on symmetric periodic solutions, the minimum period L min = 2/q c (h) is shown (dotted curve). When the (symmetric) periodic solutions are born they inherit the instability of the NRs with respect to symmetry breaking. For a fixed h and by increasing the period we find that they are stabilized at some period L 1 (h). The curve L 1 (h) can be calculated by a linear stability analysis. It diverges to infinity for h → h osc since above this value no stable periodic solutions are expected to exist according to the asymptotic analysis given earlier. At L 1 (h) a branch of unstable periodic solutions with broken → − symmetry bifurcates from the symmetric periodic solutions. We find that the symmetric periodic solutions lose stability (for the first time) at L 2 (h) in Fig. 3 and from here on one has a stable nonsymmetric periodic solution, where long and short domains alternate. An example of such a solution is shown in Fig. 4 for h = 0.1. Clearly this is the result of the nonmonotonic behavior of the interaction between domain walls. Presumably the curve L 2 (h) also diverges at h osc. An example of a more complicated nonperiodic solution is shown in Fig. 5. Such states have been also observed in Ref.. There is no definite distance between the walls and there seems to be no repeated structure. The state can be spatially chaotic. Equation Computer simulations show that the static wall is unstable, for ≥ accel, to a steadily traveling wall. One sees that on crossing the value accel the wall is accelerated while the direction of motion is spontaneously chosen. No further study of moving walls will be given in this paper. We find numerically that accel, as calculated from Eq., increases with h ( accel (h = 0) = 12, accel (h = 0.1) ≃ 16.6, accel (h = 0.5) ≃ 26.6 for D 1 = 0.2). One could see this also by inspecting the form of the walls. A. Stability of 1D modulations in the plane In view of the experimental observation of periodic modulations it is essential to study the stability of the solutions discussed in the previous section in the context of the full Eqs. in two dimensions. In order to reduce the number of parameters we will in this section consider the case c 1 = c 2 = 1 appropriate for homeotropic systems. Some results on the case when c 1 is smaller than 1 will be given in the next section. For the AR solution one can go through a standard linear stability analysis which gives in the long wavelength limit that, for > 0, ARs become unstable against zig-zag perturbations at h = 2/3. We should also recall that ARs are born from NRs as a stable state at h = 1 which means that they exist stably for The value h AR is denoted by a dash-dotted line in Fig. 3. We use in this paper parameter values typical for the standard substance MBBA. Specifically we take The positive value for indicates that we deal with frequencies above the codimension-2 point where the zig-zag instability of NRs is not operative. In order to check the stability of the symmetric periodic solutions found in the previous section against twodimensional perturbations we have performed a numerical Floquet analysis. Thus we write the perturbations a, of a periodic solution A L (x), L (x) with period L as a(x, y, t) = e t+isy y ∞ n=−∞ a n exp(i2nx/L), (x, y, t) = e t+isy y ∞ n=−∞ where a n, n are constants. We linearize in the perturbations and expand the coefficient functions in the linearized equation, which have the periodicity L, also in a Fourier series. After truncation a system of linear equations is obtained which can be solved numerically to give the growth rate i (s y ) for the linear mode with wave vector s y. The index i runs over the number of Fourier modes used. The number of modes necessary to achieve a prescribed accuracy is found easily by numerical experimentation. We have focused on periods which lie between the limits L 1 and L 2 in Fig. 3, i.e., to solutions which are stable with respect to x perturbations. For the parameter values our results are included in Fig. 3 (dashed line). The thin dashes (for 7.5 < ∼ L < ∼ 13) indicate a short wave instability of the corresponding period when crossing the line to the left. The thick dashes (for 5.7 < ∼ L < ∼ 7.5) indicate a long wave instability. It is most interesting that the present instabilities occur for a value of h considerably smaller than h AR which means that there are stable periodic solutions for values of h for which the ARs are unstable. We give the numerical values for the stability limits and the wave vector s y of the unstable mode for some periodic solutions that we typically use in the simulations of this section (they fit into our typical system length of 64): period 8 : 0.23 < h < 0.67, s y = 0.67, period 9.14 : 0.30 < h < 0.74, s y = 0.69, period 12.8 : 0.42 < h < 0.85, s y = 0.66. The lower limit corresponds to the short wave instability along the y direction with wave vector s y. The upper limit is due to the instability along the x direction (curve L 1 in Fig. 3). We conclude that by decreasing the parameter h (which corresponds to increasing the voltage or decreasing the magnetic field in a relevant experiment) below h AR the ARs become unstable but periodic states with certain periods remain stable. They are then expected to be observable under appropriate experimental conditions. As an example we quote the experiments of Ref. for which the appropriate parameter values are close to that we use throughout this section. It is reported that for a control parameter corresponding to h = 0.4 in our theory, periodic modulations of the director orientation are observed. Indeed this value falls into the range where ARs are unstable but some periodic states are expected to be stable. Concerning the periodicity, the tendency towards shorter wavelengths with increasing voltage reported in is consistent with our results. B. 2D modulated structures We now proceed to investigate how the system evolves once the periodic states are destabilized at small values of h, that is, once we cross to the left of the dashed line in Fig. 3. For this purpose we have used a pseudospectral algorithm which simulates the time evolution of Eqs. which we describe briefly in the following. The linear part of the equation is tranformed into Fourier space and the analytic formula for its time evolution is implemented in the algorithm. For the nonlinear part we work in real space and integrate it in time using a variation of the Euler method. We use periodic boundary conditions in both space dimensions which are practically enforced by the use of Fourier modes. We typically use 128128 modes in the two space directions while our physical space has dimensions 6464 units. Due to the special treatment of the linear part, pseudospectral algorithms allow for a relatively large time step. We typically take t = 0.05 when we use the parameter values. We start a simulation of Eqs. with a state that is periodic in x, e.g. with period 9.14. The state is stable in the parameter range given in Eq.. When we reduce the field h slightly below the value 0.30 we find that the pattern is destabilized and modulations along the y direction appear. The pattern becomes periodic in, c1 = c2 = 1, and h = 0.27. Initial conditions: a slightly perturbed periodic modulation state with period 9.14. Shown is a grey-scale representation of |A|. White corresponds to the maximum value and black corresponds to the minimum (|A| = 0). The state is dynamic but always remains close to the one shown. The physical dimensions of our space are 6464 and we have used periodic boundary conditions. both spatial dimensions. We give an example of such a state in Figs. 6, 7 where the fields |A| and are shown, respectively. The state describes modulations in 2D and has no defects. It was obtained for h = 0.28. We note that the state in Figs. 6,7 is not fully static. It persist for a long time but it is eventually modified through the creation of defects. The system presents persistent dynamics until the end of our simulation, nevertheless, the 2D correlations are preserved to a large extent. In general, the 2D modulated states reached slightly below the destabilization of 1D periodic modulations are delicate and we have not been able to find a truly static one. The near-periodicity of the final states in both spatial directions is readily seen in the figures resulting from our simulations. An interesting point is that the defects which are typically created in these processes also show strong 2D correlations. In fact a slightly disordered defect lattice is the usual outcome of such numerical simulations. An example of a reasonably developed defect lattice is presented in Fig. 8 through the field |A|. It was obtained by starting the simulation with a periodic state with period 9.14. We used the value h = 0.27 and the other parameters as in. The initial 1D periodic state is then unstable and evolves into the defect lattice. The time evolution shows that the state has some substantial dynamics but it always remains close to the picture of Fig. 8. Finally, in Fig. 9 we give the field of the defect lattice of Fig. 8. The field is predominantly varying in the x direction with small modulations in y. On further reducing the parameter h the resulting pattern becomes progressively more disordered. A defect chaotic state is eventually obtained for small values of the parameter. In Fig. 10 we show such a state for h = 0.1. These defect-chaotic states deserve to be studied on their own right but a full investigation of this problem is beyond the scopes of the present paper. It is not easy to predict in what way the states that we study here would appear in an experiment. Details of the experimental procedure could be important and the final result can be complicated as is indicated, e.g., by Fig. 7 in where roughly periodic states without defects are found. In order to observe defect lattices in homeotropic cells one should remain at small values of so that the director angle does not become very large. Otherwise a transition to CRAZY rolls occurs first, which entails formation of disclinations in the director field. Also, at higher values of, mean-flow effects not included in our simple description become important. Let us describe the protocol of a numerical simulation which may give some guidance for experiments. The simulations are performed on a 6464 domain. We start at a field h above h AR (h = 0.7) with small spatially random initial conditions of the fields A,. Experimentally this corresponds to jumping from below the EC threshold directly into the region of stable ARs. Typically, large domains with both AR states appear, separated by walls in the x direction. We then jump to h = 0.4 where ARs are destabilized while defects are created and a state with 2D correlations sets in. The final state is roughly periodic with period 12.8 in the x direction (5 periods in the domain) and 16 in the y direction (4 periods in the domain). The defects are also roughly ordered in a lattice. After this we increase h gradually in steps of h = 0.02 and let the system relax in every step for 1000 time units. Although the system never relaxes to a static state, we observe clearly correlations in both spatial directions with the defects approximately ordered in arrays until h = 0.44 is reached. For h ≥ 0.46 the defects annihilate and the system relaxes to a static 1D periodic state with period 12.8. The process described above seems robust in our simulations. Note the interesting fact that there is a range of stable coexistence of the fully ordered 1D state (it is stable down to h = 0.42) and the 2D solution. Defect lattices have in fact been observed in planar EC at fairly high frequencies. A theoretical description for these systems by a much more elaborate quantitative theory has been developed recently. V. STATIC CHEVRONS Here we will relax the condition c 1 = c 2 = 1 by reducing c 1 (slightly) below 1. This has no influence on the 1D solutions and their stability with respect to x dependent fluctuations and increases the range of stability with respect to y variations. In fact the critical value of h for the zig-zag destabilization of the periodic solutions (dashed line in Fig. 3) is reduced. For example, the period 9.14 is stable in the range 0.19 < h < 0.74, when c 1 = 0.9, c 2 = 1, which should be compared to Eq.. For values of h beyond the instability the states that we obtain are similar to the ones found above for c 1 = 1. Namely, we observe states with 2D order close to the instability point (with some hysteresis), which get progressively less ordered as h is decreased. When c 1 is decreased further the stable range of the periodic solutions extends to progressively lower values of h. In fact, for c 1 < 0.77 the 1D solutions with period 9.14 are stable down to h = 0. For h = 0 we obtain a novel static pattern containing lines (or bands, i.e., multiple lines) of defects along the y direction which resemble the usual chevron states, except that those are dynamic. In Figs. 11 and 12 such a solution is presented for c 1 = 0.9. The defects (zeros of |A|) are located at the dark points in Fig. 11. Within one band all defects have the same topological charge and this is alternating from band to band. The dark regions between defect bands imply a small value of |A|. As one sees from Fig. 12 the field varies periodically essentially only in x, and thus is very reminiscent of the 1D patterns discussed before. We call these new patterns "static chevrons". They are formed from random initial conditions. The static chevrons persist for small nonzero values of the parameter h. If we let the chevron states be created for h = 0 and then increase h the static chevrons persist up to h ≤ 0.015 for the parameters used here. Increasing h further (h = 0.02) we observe that more defect bands are created, that is, we have chevrons with a shorter period, but these are now the dynamic chevrons presented previously for c 1 = 1. For even larger values of h one reaches the much less correlated defect chaotic state discussed before. For c 1 closer to 1 the correlations become weaker. To gain an understanding of static chevrons we first note that the states between the defect bands should be interpreted as (approximately) homogeneous states with nonzero wavenumber P in the y direction, i.e., with complex amplitude where the sign in the exponent alternates between neighboring regions and the magnitude of P is related to the number of defects per unit length in one band through the relation This follows directly from the fact that each defect contributes a phase change of ±2, depending on its topological charge. In the simulations we find that and P take values close to in the region between the defect bands while A 0 is small as was already mentioned. The uniform solutions are described by equating the right-hand sides of Eqs. to zero. The resulting cubic equation for 0 can be written as In the limit h → 0 one of the solutions tends to and the other two tend to Here one has to impose the additional restriction that 0 /( 0 −c 2 P ) > 0, since otherwise A 2 0 is not positive for h slightly away from zero. In Fig. 13 is sketched for these limiting solutions as a function of P (solid lines). The solution is the continuation of the NRs to nonzero P. Similarly, represents the continuation of ARs. The two lines join at point B in Fig. 13. We can now see that the states between the defect bands given in Eq. correspond (approximately) to the continued ARs of Eq. with the maximal | 0 |. Thus the defect bands connect between the two symmetry degenerate versions of this state. A simple stability analysis explains why this state is selected. We write A = A 0 + a and = 0 + and linearize Eqs. in a,. For A 0 = 0 the two equations separate and we obtain the following expression for the growth rate of the mode involving a One easily checks that all states are unstable against fluctuations along y except for the state, which is marginally stable. The latter is denoted by the letter A in Fig. 13. The static chevron states which are periodic and describe spatial oscillations between the states need not be themselves marginally stable. On the contrary, they are numerically found to be quite robust. This observation is in agreement with the results of Sec. IV A that the 1D periodic states are stable even for parameter values for which the uniform states are unstable. The effect of the value of c 1 on the chevron states is rather profound. This is seen by the (approximate) relation giving the density of defects in the chevrons which can be found using Eqs. and : Thus, as c 1 approaches 1 the defect bands become broader (the separation between defects inside a band is rather independent of parameters). In the limit c 1 → 1 one expects existence of an infinite lattice of defects with the same polarity, but this is not accessible numerically, and presumably also not experimentally. On the other hand, as c 1 decreases, the number of defects per unit length decreases quickly reaching a situation with a single chain in a band. Decreasing c 1 further one reaches a critical value below which no defects are created. Instead one has the 1D periodic modulations without defects which are here stable also for h = 0 (see above). We have mentioned already that static chevrons persist to slightly nonzero h. In order to understand the defectfree regions for this case we have studied the homogeneous solutions as obtained from Eq.. In Fig. 13 we also show 0 for the case h = 0.1 (dashed). Analyzing the stability we found that there is a small interval around the states with maximal | 0 | which are stable. This shows that the disappearance of static chevrons for increasing h is not a result of the homogeneous regions becoming unstable, but rather the defect bands destabilize, which is also observed in simulations. VI. CONCLUDING REMARKS Motivated in particular by experiments in electroconvection in homeotropically aligned nematics we have studied some classes of modulated solutions of the Ginzburg-Landau equation for the complex order parameter A describing the bifurcation to a stationary roll pattern, coupled to a weakly damped (or even undamped) homogeneous mode describing the orientation of the in-plane director, see Eqs. (unscaled) or Eqs. (scaled). The most important parameter h in these equations gives the ratio of the aligning torque on the director over the destabilizing torque of normal rolls. The latter is proportional to the supercriticality parameter. Another important parameter in the equations characterizes the action of the gradient of the in-plane director on the phase of the rolls, which can be controlled experimentally by varying the frequency. Our study is relevant for > 0, which is the case in the upper-frequency conduction range and presumably also in the dielectric range. The solutions we considered are characterized by modulations in the direction perpendicular to normal rolls (parallel to the wave vector). There exists a surprisingly rich spectrum of stable solutions of this type even in the range of control parameter where most homogeneous states have lost stability. The simplest type has only variations in the direction of the wavevector (1D structures). When such variations arise they lead to the creation of defects, except in a small control parameter region where 2D defect-free modulations may exist metastably. The solutions with defects range from essentially fully spatially ordered defect lattices to defect chaos with various degrees of spatial correlations. Their detailed study appears interesting, but is beyond the scope of this paper. The complexity of the solutions, as well as their dynamics, generally increase with decreasing h. For very small values of h, however, defects show the tendency to order along chains (or bands) yielding chevron structures. One mechanism for the generation of dynamic chevrons has been related to a Turing instability. We have found for c 1 < 1 a new type of fully ordered, static chevrons that appear more related to the 1D structures. Focusing on the in-plane (=) director field, the modulations occur along the direction of prealignment of the in-plane director (from this point of view they give rise to "bend" distortions). In fact, there is a long history of observations of such modulated states under an electric field in highly-doped MBBA and other nematic materials at high frequency, often without detectable convection rolls. They come under the name of "wide domains" or "prechevrons". Since such structures cannot be explained purely statically, it seems reasonable to assume that they are secondary structures of the type discussed here. The mechanism for the generation of the primary roll pattern, which may not be visible, is presumably different from the usual Carr-Helfrich mechanism. In fact, it was shown that the driving mechanism persisted above the nematic-isotropic transition. Moreover, in it was shown that a treatment of the bounding plates by tensides led to a considerable increase of the frequency range where the wide domains appeared. These findings, which are consistent with some old results, indicate that an isotropic mechanism with rolls confined to the boundaries is involved. It was found that even after the wide domains have formed the usual electroconvection would set in at the expected threshold. In the dielectric regime this would lead directly to perfectly ordered chevrons that have an appearance like the static chevrons presented above. While states modulated only along the direction of the wavevector have been observed to some extent, the observation of corresponding two-dimensional modulations without defects is lacking. This may be due to the small parameter range where such 2D modulations occur and also because of their apparent metastability. An experimental effort in this direction appears interesting. The present results suggest that the objective should be to observe successively the 1D and 2D modulations and the chevron states and to test if they can be related to each other according to the present theory. Equations also allow for solutions which are modulated only along the rolls (perpendicular to the prealignment of the in-plane director, giving rise to a "splay" distortion). Then the phase of the patterning mode (i.e., the phase of A) comes into play, and the periodic solutions in fact correspond to zig-zag patterns. Such states are of relevance for smaller values of, in particular for < 0. Near the zig-zag instability of normal rolls, which occurs at h = 1 −, and thus precedes the transition to abnormal rolls for < 0, the periodic patterns are unstable. For smaller values of h (larger ) there are various types of periodic patterns. The scenario is enriched by the fact that the usual defects (point dislocations) can extend in the direction perpendicular to the rolls to form phase slip lines. In order to extend the treatment to larger one has to use more complicated equations derivable from an extended nonlinear analysis, which includes in particular mean flow. For planar convection in the conduction regime the analysis has been carried out and relevant solutions involving in particular realistic defect lattices have been studied. For the dielectric regime an extended weakly nonlinear study was presented in. The system appears interesting in view of its parameters c 1 = c 2 = = 0.98 calculated under neglect of flexoelectric effects, which are of more relevance in the dielectric regime (note that in Ref. the c i correspond to our C i ). There is hope to find static chevrons if the align-ing torque could be made sufficiently small by applying a destabilizing magnetic field. One might use this technique also in the conduction range where c 1 is substantially smaller than 1. However, one may then have to include higher-order terms in Eq.. |
<gh_stars>10-100
#import "RKDeviceResponse.h"
#import "RKTypes.h"
@interface RKGetChargerStateResponse : RKDeviceResponse
@property (nonatomic, assign, readonly) RKBatteryPowerState batteryState;
@property (nonatomic, assign, readonly) RKChargerState chargerState;
@end
|
<reponame>cloudwan/edgelq-sdk
// Code generated by protoc-gen-goten-resource
// Resource: AlertingPolicy
// DO NOT EDIT!!!
package alerting_policy
import (
"context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/cloudwan/goten-sdk/runtime/api/watch_type"
gotenobject "github.com/cloudwan/goten-sdk/runtime/object"
gotenresource "github.com/cloudwan/goten-sdk/runtime/resource"
)
// proto imports
import (
ntt_meta "github.com/cloudwan/edgelq-sdk/common/types/meta"
project "github.com/cloudwan/edgelq-sdk/monitoring/resources/v3/project"
)
// ensure the imports are used
var (
_ = context.Context(nil)
_ = codes.Internal
_ = status.Status{}
_ = watch_type.WatchType_STATEFUL
_ = gotenobject.FieldPath(nil)
_ = gotenresource.ListQuery(nil)
)
// make sure we're using proto imports
var (
_ = &ntt_meta.Meta{}
_ = &project.Project{}
)
type AlertingPolicyAccess interface {
GetAlertingPolicy(context.Context, *GetQuery) (*AlertingPolicy, error)
BatchGetAlertingPolicies(context.Context, []*Reference, ...gotenresource.BatchGetOption) error
QueryAlertingPolicies(context.Context, *ListQuery) (*QueryResultSnapshot, error)
WatchAlertingPolicy(context.Context, *GetQuery, func(*AlertingPolicyChange) error) error
WatchAlertingPolicies(context.Context, *WatchQuery, func(*QueryResultChange) error) error
SaveAlertingPolicy(context.Context, *AlertingPolicy, ...gotenresource.SaveOption) error
DeleteAlertingPolicy(context.Context, *Reference, ...gotenresource.DeleteOption) error
}
type anyCastAccess struct {
AlertingPolicyAccess
}
func AsAnyCastAccess(access AlertingPolicyAccess) gotenresource.Access {
return &anyCastAccess{AlertingPolicyAccess: access}
}
func (a *anyCastAccess) Get(ctx context.Context, q gotenresource.GetQuery) (gotenresource.Resource, error) {
if asAlertingPolicyQuery, ok := q.(*GetQuery); ok {
return a.GetAlertingPolicy(ctx, asAlertingPolicyQuery)
}
return nil, status.Errorf(codes.Internal,
"Unrecognized descriptor, expected AlertingPolicy, got: %s",
q.GetResourceDescriptor().GetResourceTypeName().FullyQualifiedTypeName())
}
func (a *anyCastAccess) Query(ctx context.Context, q gotenresource.ListQuery) (gotenresource.QueryResultSnapshot, error) {
if asAlertingPolicyQuery, ok := q.(*ListQuery); ok {
return a.QueryAlertingPolicies(ctx, asAlertingPolicyQuery)
}
return nil, status.Errorf(codes.Internal,
"Unrecognized descriptor, expected AlertingPolicy, got: %s",
q.GetResourceDescriptor().GetResourceTypeName().FullyQualifiedTypeName())
}
func (a *anyCastAccess) Search(ctx context.Context, q gotenresource.SearchQuery) (gotenresource.SearchQueryResultSnapshot, error) {
return nil, status.Errorf(codes.Internal, "Search is not available for AlertingPolicy")
}
func (a *anyCastAccess) Watch(ctx context.Context, q gotenresource.GetQuery, cb func(ch gotenresource.ResourceChange) error) error {
if asAlertingPolicyQuery, ok := q.(*GetQuery); ok {
return a.WatchAlertingPolicy(ctx, asAlertingPolicyQuery, func(change *AlertingPolicyChange) error {
return cb(change)
})
}
return status.Errorf(codes.Internal,
"Unrecognized descriptor, expected AlertingPolicy, got: %s",
q.GetResourceDescriptor().GetResourceTypeName().FullyQualifiedTypeName())
}
func (a *anyCastAccess) WatchQuery(ctx context.Context, q gotenresource.WatchQuery, cb func(ch gotenresource.QueryResultChange) error) error {
if asAlertingPolicyQuery, ok := q.(*WatchQuery); ok {
return a.WatchAlertingPolicies(ctx, asAlertingPolicyQuery, func(change *QueryResultChange) error {
return cb(change)
})
}
return status.Errorf(codes.Internal,
"Unrecognized descriptor, expected AlertingPolicy, got: %s",
q.GetResourceDescriptor().GetResourceTypeName().FullyQualifiedTypeName())
}
func (a *anyCastAccess) Save(ctx context.Context, res gotenresource.Resource, opts ...gotenresource.SaveOption) error {
if asAlertingPolicyRes, ok := res.(*AlertingPolicy); ok {
return a.SaveAlertingPolicy(ctx, asAlertingPolicyRes, opts...)
}
return status.Errorf(codes.Internal,
"Unrecognized descriptor, expected AlertingPolicy, got: %s",
res.GetResourceDescriptor().GetResourceTypeName().FullyQualifiedTypeName())
}
func (a *anyCastAccess) Delete(ctx context.Context, ref gotenresource.Reference, opts ...gotenresource.DeleteOption) error {
if asAlertingPolicyRef, ok := ref.(*Reference); ok {
return a.DeleteAlertingPolicy(ctx, asAlertingPolicyRef, opts...)
}
return status.Errorf(codes.Internal,
"Unrecognized descriptor, expected AlertingPolicy, got: %s",
ref.GetResourceDescriptor().GetResourceTypeName().FullyQualifiedTypeName())
}
func (a *anyCastAccess) BatchGet(ctx context.Context, toGet []gotenresource.Reference, opts ...gotenresource.BatchGetOption) error {
alertingPolicyRefs := make([]*Reference, 0, len(toGet))
for _, ref := range toGet {
if asAlertingPolicyRef, ok := ref.(*Reference); !ok {
return status.Errorf(codes.Internal,
"Unrecognized descriptor, expected AlertingPolicy, got: %s",
ref.GetResourceDescriptor().GetResourceTypeName().FullyQualifiedTypeName())
} else {
alertingPolicyRefs = append(alertingPolicyRefs, asAlertingPolicyRef)
}
}
return a.BatchGetAlertingPolicies(ctx, alertingPolicyRefs, opts...)
}
func (a *anyCastAccess) GetResourceDescriptors() []gotenresource.Descriptor {
return []gotenresource.Descriptor{
GetDescriptor(),
}
}
|
1. Field of the Invention
The present invention relates to a driver circuit of an AMOLED (active matrix organic light emitting diode) with gamma correction, and more particularly, to a driver circuit of a current type AMOLED with gamma correction.
2. Description of the Related Art
Gamma correction is used to control the overall brightness of images shown on a display device. Images that are not properly corrected can look either bleached out or too dark. Generally, the optical characteristics of panel modules such as an LCD (liquid crystal display) and an electroluminescence panel have a nonlinear light transmission characteristic with respect to an applied voltage. Therefore, the drive circuit should drive the panel modules after the gamma correction is performed to correct the voltage in such a way as to match with the nonlinear light transmission characteristic of the panel modules. FIG. 1 illustrates a typical gamma correction curve with a gamma value of 2.2, in which both the x-axis (gray scale) and y-axis (relative luminance) are normalized. The applied voltage corresponding to a specific gray level is inputted into the panel module and then a relative luminance that is based on the gamma correction curve of FIG. 1 and corresponds to a specific light transmission is outputted.
FIG. 2 shows a conventional driver circuit 10 used in an LCD driver or in a voltage type AMOLED (active matrix organic light emitting diode) driver. The driver circuit 10 includes a gamma correction circuit 11, plural digital-to-analog converters DAC1-DACM, and plural operational amplifier buffers OPB. Each digital-to-analog convert DACi receives a digital code (i.e., a gray level or a pixel value) DGLi, and generates an analog driving signal ADSi in accordance with a reference voltage Vi generated from the gamma correction circuit 11. The analog driving signal ADSi is sent to drive the LCD panel or the voltage type AMOLED panel through the corresponding operational amplifier buffer OPB. The gamma correction circuit 11 includes plural resistors Ri connected in series between a high-potential power supply VH and a low-potential power supply VL, which is also called an R-string. It is easy to perform the gamma correction by the R-string configuration. The proper reference voltages Vi can be obtained by merely adjusting the resistances of the resistors Ri of the R-string to produce the desired gamma correction curve shown in FIG. 1 or the like. However, for a current type AMOLED driver, it is not so easy to achieve the desire gamma correction curve by the R-string.
FIG. 3 shows a conventional driver circuit 20 used in a current type AMOLED driver with a four-bit resolution. The driver circuit 20 includes plural groups of current mirrors. Each group of current mirrors includes four PMOS transistors and four corresponding switches b3-b0. For the current type AMOLED, the luminance thereof is proportional to the driving current flowing to the current type AMOLED. The arrangement of states (ON or OFF) of the four switches b3-b0 presents 16 different states to provide 16 levels of current to drive an AMOLED circuit. The switches b3 and b0 correspond to the MSB (most significant bit) and the LSB (least significant bit) of a digital input gray code, respectively. Therefore, the magnitude of the driving current is linearly dependent upon the pixel value. The driver circuit 20 can not achieve a non-linear gamma curve shown in FIG. 1.
FIGS. 4(a) and 4(b) show two relationship curves C1 and C2 (equivalent to gamma correction curves) between the driving current and the gray scale (six-bit resolution, for example) of two conventional driver circuits 20 with a small current scale and a large current scale, respectively. Another approach like the conventional driver circuit 20 is proposed, which combines FIGS. 4(a) and 4(b) to form FIG. 4(c). That is, the relationship curve C3 in FIG. 4(c) is a superposed curve of the relationship curves C1 and C2. However, the relationship curve C3 still cannot fit the desired gamma correction curve of FIG. 1. Therefore, this approach also fails to perform the gamma correction, and it is necessary to develop a driver circuit with gamma correction to drive a current type AMOLED. |
(Reuters) - The U.S. credit union regulator sued JPMorgan Securities and Bear Stearns & Co on Monday over $3.6 billion in mortgage securities the bank allegedly sold to credit unions that collapsed because of losses from the securities.
JPMorgan Chase & Co's international headquarters are seen on Park Avenue in New York July 13, 2012. REUTERS/Andrew Burton
The lawsuit by the National Credit Union Administration is its second against JPMorgan involving losses to credit unions. In June 2011 the agency sued it over some $1.4 billion in securities in which JPMorgan was the underwriter and seller. That suit is still pending.
The actions add to a growing list of cases the largest U.S. bank is fighting over conduct by Bear Stearns, which JPMorgan acquired in 2008.
After the New York Attorney General sued JPMorgan in October alleging that Bear Stearns deceived investors buying mortgage-backed securities in 2006 and 2007, the bank’s chief executive, Jamie Dimon, lashed out at the government.
Speaking at a Washington event, Dimon said the company lost $5 billion to $10 billion in Bear Stearns-related costs and is still paying the price for doing the Federal Reserve “a favor” by buying the teetering investment bank.
In the Monday lawsuit, the NCUA alleged that Bear Stearns made misrepresentations in connection with the underwriting and subsequent sale of mortgage-backed securities to U.S. Central, Western Corporate, Southwest Corporate and Members United Corporate federal credit unions.
The lawsuit, filed in federal court in Kansas, is the largest such lawsuit the regulator has filed to date.
A JPMorgan spokeswoman declined to comment.
In the past two years the agency has brought similar actions against Barclays Capital, Credit Suisse, Goldman Sachs, RBS Securities, UBS Securities, Wachovia and others.
Most of the cases are pending, but it has settled claims against Citigroup, Deutsche Bank Securities and HSBC for around $170 million.
The credit union regulator has been trying to recover losses related to the failure of five institutions that it seized in 2009 and 2010 after they ran into trouble due to the crumbling housing market.
The wholesale credit unions have experienced more troubles than their retail counterparts because they did not face the same restrictions on permitted investments, leading to big losses during the financial crisis. |
You Know You're From Northern Virginia When...
Posted by: mhkellyxx ()
Date: March 20, 2005 10:10AM
Oldie but goodie. Nice site you guys I'll be around!
1. Speed limits are just suggestions
2. You take a major highway to school (95, 66,28, etc)
3. You constantly complain about there being nothing to do, even though you are right next to DC
4. You have at least 2 friends who have no idea what their parents do because its "top secret" government work
5. 50% of your senior class plans on going either to Mason, JMU, Tech or UVA
6. When people ask where you're from, you tell them DC because its easier to explain
7. You've never told someone you're from Virginia without putting "northern" in front of it
8. When you and your friends get bored you all whip out your cell phones and start playing with them
9. Its not actually tailgating unless your bumper is touching the car in front of you.
10. A yellow light means at least 5 more cars can get through.
11. A red light means 2 more can.
12. It takes you 30 minutes to drive 10 miles
13. Your local news is national news
14. If you hear the word "sniper" one more time you're going to slap someone
15. You actually know what the black boxes at stoplights are for
16. Even if your high school is only a year old, its already overcrowded
17. You have over 500 students in your graduating class
18. Despite the fact that Virginia fought for the south in the Civil War, you are NOT, under ANY circumstances, a "southerner"
19. You are friends with people from at least 2 other high schools
20. You know at least 2 people who drive a mercedes, BMW, Lexus, etc.
21. The cars in the student parking lot are woth 3x those in the teacher parking lot.
22. You are amused by visiting relatives who are actually excited to see Washington DC
23. You are amazed when you go out of town and the people at McDonalds speak english
24. You can cross 4 lanes of traffic in under 30 seconds
25. There are at least 3 malls within 20 minutes of your house
26. There are at least 6 Starbucks within 20 minutes of your house
27. You or someone in your family has a Smart Tag
28. Homework/Extra credit for a class has been to visit a museum in DC
29. When traveling, you have your choice of 3 airports
30. You don't actually like the Redskins/Wizards (except when Jordan was playing)
31. An inch of snow and you miss 3 days of school
32. All the potholes just add a little excitement to your driving experience
33. Stop signs mean slow down a little, but only if you feel like it
34. A rich white kid driving a BMW while blasting rap music is a common occurance
35. You call things "ghetto" even though in most of the rest of the country it'd be high class
36. You or most of your friends have a 3 car garage
37. You don't actually keep your cars in it.
38. When you were driving on the beltway at 2:13am on a Tuesday there was still traffic
39. Crown Victoria = undercover cop
40. A slow driver is someone who isn't going at least 10mph over the speed limit
41. You understand the meaning of "If you don't get it, you don't get it"
42. Subway is a fast food place. The transportation system is known as Metro, and only Metro
43. You've taken a wrong turn somewhere late at night and ended up in a bad part of DC(ex. anacostia)
44. Most of Loudoun County is the "middle of nowhere"
45. They just tore down the old farm house across the street and put 12 new houses in its place
46. The word Hfstival actually means something to you
47. Someone has honked at you because you didn't peal out the second the light turned green.
48. You've honked at someone because they didn't peal out the second the light turned green.
49. Rush hour lasts all day
50. For the cost of your house, you could own a small town in Iowa
51. Helicopters and airplanes flying above your neighborhood is a normal occurance.
52. 9:30 isnt just a time, its a place.
* Added by other people *
53. If you stay on the same road long enough, it will eventually have 3 new names.
54. You have to dial the area code to call your neighbor
55. You live 5 minutes from at least 2 high schools, but you go to one thats 30 minutes away.
56. You know at least 3 alternate routes to avoid sitting at a stop light.
57. You can't pull up to a 7-11 without seeing at least one cop, and usually there's another cop sitting not too far away.
58. You refer to distances in minutes, not miles.
59. When you put on your turn signal to change lanes, the people next to you speed up.
60. Talking on metro in the morning is prohibited |
//-------------------------------------------------
//
// \class L1MuGMTHWFileReader
//
// Description: Puts the GMT input information from
// a GMT ascii HW testfile into the Event
//
//
//
// Author :
// Tobias Noebauer HEPHY Vienna
// Ivan Mikulec HEPHY Vienna
//
//--------------------------------------------------
//-----------------------
// This Class's Header --
//-----------------------
#include "L1Trigger/GlobalMuonTrigger/src/L1MuGMTHWFileReader.h"
//---------------
// C++ Headers --
//---------------
#include <stdexcept>
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
#include "DataFormats/L1GlobalMuonTrigger/interface/L1MuRegionalCand.h"
#include "DataFormats/L1CaloTrigger/interface/L1CaloCollections.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
//----------------
// Constructors --
//----------------
L1MuGMTHWFileReader::L1MuGMTHWFileReader(edm::ParameterSet const& ps, edm::InputSourceDescription const& desc)
: ProducerSourceFromFiles(ps, desc, true) {
produces<std::vector<L1MuRegionalCand> >("DT");
produces<std::vector<L1MuRegionalCand> >("CSC");
produces<std::vector<L1MuRegionalCand> >("RPCb");
produces<std::vector<L1MuRegionalCand> >("RPCf");
produces<L1CaloRegionCollection>();
if (fileNames(0).empty()) {
throw std::runtime_error("L1MuGMTHWFileReader: no input file");
}
edm::LogInfo("GMT_HWFileReader_info") << "opening file " << fileNames(0)[0];
m_in.open((fileNames(0)[0].substr(fileNames(0)[0].find(':') + 1)).c_str());
if (!m_in) {
throw std::runtime_error("L1MuGMTHWFileReader: file " + fileNames(0)[0] + " could not be openned");
}
}
//--------------
// Destructor --
//--------------
L1MuGMTHWFileReader::~L1MuGMTHWFileReader() { m_in.close(); }
//--------------
// Operations --
//--------------
bool L1MuGMTHWFileReader::setRunAndEventInfo(edm::EventID& id,
edm::TimeValue_t& time,
edm::EventAuxiliary::ExperimentType& eType) {
readNextEvent();
if (!m_evt.getRunNumber() && !m_evt.getEventNumber())
return false;
id = edm::EventID(m_evt.getRunNumber(), id.luminosityBlock(), m_evt.getEventNumber());
edm::LogInfo("GMT_HWFileReader_info") << "run: " << m_evt.getRunNumber() << " evt: " << m_evt.getEventNumber();
return true;
}
void L1MuGMTHWFileReader::produce(edm::Event& e) {
L1MuRegionalCand empty_mu;
std::unique_ptr<std::vector<L1MuRegionalCand> > DTCands(new std::vector<L1MuRegionalCand>);
for (unsigned i = 0; i < 4; i++) {
const L1MuRegionalCand* mu = m_evt.getInputMuon("IND", i);
if (!mu)
mu = &empty_mu;
DTCands->push_back(*mu);
}
e.put(std::move(DTCands), "DT");
std::unique_ptr<std::vector<L1MuRegionalCand> > CSCCands(new std::vector<L1MuRegionalCand>);
for (unsigned i = 0; i < 4; i++) {
const L1MuRegionalCand* mu = m_evt.getInputMuon("INC", i);
if (!mu)
mu = &empty_mu;
CSCCands->push_back(*mu);
}
e.put(std::move(CSCCands), "CSC");
std::unique_ptr<std::vector<L1MuRegionalCand> > RPCbCands(new std::vector<L1MuRegionalCand>);
for (unsigned i = 0; i < 4; i++) {
const L1MuRegionalCand* mu = m_evt.getInputMuon("INB", i);
if (!mu)
mu = &empty_mu;
RPCbCands->push_back(*mu);
}
e.put(std::move(RPCbCands), "RPCb");
std::unique_ptr<std::vector<L1MuRegionalCand> > RPCfCands(new std::vector<L1MuRegionalCand>);
for (unsigned i = 0; i < 4; i++) {
const L1MuRegionalCand* mu = m_evt.getInputMuon("INF", i);
if (!mu)
mu = &empty_mu;
RPCfCands->push_back(*mu);
}
e.put(std::move(RPCfCands), "RPCf");
std::unique_ptr<L1CaloRegionCollection> rctRegions(new L1CaloRegionCollection);
for (int ieta = 4; ieta < 18; ieta++) {
for (int iphi = 0; iphi < 18; iphi++) {
rctRegions->push_back(
L1CaloRegion(0, false, true, m_evt.getMipBit(ieta - 4, iphi), m_evt.getIsoBit(ieta - 4, iphi), ieta, iphi));
}
}
e.put(std::move(rctRegions));
}
void L1MuGMTHWFileReader::readNextEvent() {
m_evt.reset();
std::string line_id;
do {
int bx = 0;
m_in >> line_id;
if (line_id == "--")
continue;
if (line_id == "RUN") {
unsigned long runnr;
m_in >> runnr;
m_evt.setRunNumber(runnr);
}
if (line_id == "EVT") {
unsigned long evtnr;
m_in >> evtnr;
m_evt.setEventNumber(evtnr);
}
if (line_id == "DT" || line_id == "CSC" || line_id == "BRPC" || line_id == "FRPC") {
// decode input muon
unsigned inpmu = 0;
unsigned val;
m_in >> val;
inpmu |= (val & 0x01) << 24; // valid charge
m_in >> val;
inpmu |= (val & 0x01) << 23; // charge
m_in >> val;
inpmu |= (val & 0x01) << 22; // halo / fine
m_in >> val;
inpmu |= (val & 0x3f) << 16; // eta
m_in >> val;
inpmu |= (val & 0x07) << 13; // quality
m_in >> val;
inpmu |= (val & 0x1f) << 8; // pt
m_in >> val;
inpmu |= (val & 0xff); // phi
std::string chipid("IN");
chipid += line_id[0];
int type = 0;
if (line_id == "DT")
type = 0;
if (line_id == "CSC")
type = 2;
if (line_id == "BRPC")
type = 1;
if (line_id == "FRPC")
type = 3;
L1MuRegionalCand cand(inpmu);
cand.setType(type);
cand.setBx(bx);
m_evt.addInputMuon(chipid, cand);
}
if (line_id == "MIP") {
int nPairs;
m_in >> nPairs;
for (int i = 0; i < nPairs; i++) {
unsigned eta;
unsigned phi;
m_in >> eta;
m_in >> phi;
if (phi >= 9)
phi -= 9;
else
phi += 9;
m_evt.setMipBit(eta, phi, true);
}
}
if (line_id == "NQ") {
int nPairs;
m_in >> nPairs;
for (int i = 0; i < nPairs; i++) {
unsigned eta;
unsigned phi;
m_in >> eta;
m_in >> phi;
if (phi >= 9)
phi -= 9;
else
phi += 9;
m_evt.setIsoBit(eta, phi, false);
}
}
//read the rest of the line
const int sz = 4000;
char buf[sz];
m_in.getline(buf, sz);
} while (line_id != "NQ" && !m_in.eof());
}
|
Effective fast-track ambulatory care pathway for patients with COVID-19 at risk for poor outcome: the COVID-A2R model in a hospital emergency department. OBJECTIVES The maintenance of sinus rhythm by means of antiarrhythmic drugs and/or upstream therapy to counter cardiac remodeling is fundamental to the management of atrial fibrillation (AF). This study aimed to analyze this approach and its appropriateness in the setting of hospital emergency departments. MATERIAL AND METHODS Secondary analysis of data from the multicenter observational cross-sectional HERMES-AF study carried out in 124 hospitals representative of the Spanish national health service in 2011. Included were consecutive patients with AF restored to sinus rhythm who were discharged home from emergency care. RESULTS A total of 449 patients were included; 204 (45.4%) were already on sinus rhythm maintenance therapy. Of,the 245 remaining patients, 107 (43.67%) were prescribed maintenance treatment in the emergency department, as follows: 41, an antiarrhythmic drug; 19, upstream therapy; and 49, both treatments. The selection of an antiarrhythmic drug did not follow guideline recommendations in 10 patients (11.8%). Antiarrhythmic drug prescription was associated with having had a prior episode of AF (odds ratio , 2.024; 95% CI, 1.196-3.424; P =.009); a heart rate of more than 110 beats/min (OR, 2.147; 95% CI, 1.034-4.456, P = 0.40); and prescription of anticoagulation on discharge (OR, 1.862; 95% CI, 1.094-3.170; P =.022). Upstream therapy prescription was associated only with a heart rate over 110 beats/min (OR, 2.187; 95% CI, 1.005-4.757; P =.018). In total, 311 patients (69.23%) were discharged from the emergency department with sinus rhythm maintenance therapy: 87 with an antiarrhythmic drug, 117 with an upstream therapy, and 107 with both. CONCLUSION Treatment to prevent the recurrence of AF is underprescribed in emergency departments. Increasing such prescription and ensuring the appropriateness of antiarrhythmic therapy prescribed are points emergency departments can improve in the interest of better sinus rhythm maintenance. |
Low Complexity Digit Serial Systolic Montgomery Multipliers for Special Class of ${\rm GF}(2^{m})$ Montgomery Algorithm for modular multiplication with a large modulus has been widely used in public key cryptosystems for secured data communication. This paper presents a digit-serial systolic multiplication architecture for all-one polynomials (AOP) over GF(2m) for efficient implementation of Montgomery Multiplication (MM) Algorithm suitable for cryptosystem. Analysis shows that the latency and circuit complexity of the proposed architecture are significantly less than those of earlier designs for same classes of polynomials. Since the systolic multiplier has the features of regularity, modularity and unidirectional data flow, this structure is well suited to VLSI implementations. The proposed multipliers have clock cycle latency of (2N - 1), where N = m/L, m is the word size and L is the digit size. No digit serial systolic architecture based on MM algorithm over GF(2m) is reported before. The architecture is also compared to two well known digit serial systolic architectures. |
def p_expression_dynamic_dispatch(p):
p[0] = ("dynamic_dispatch", p[1], (p[3],p.lineno(3)), p[5], p[1][-1]) |
The use of metal cans has been a cost effective means for packaging and preserving a wide range of products, from chemicals to foods. A common container used for this purpose is the three-piece can, consisting of two ends and a cylindrical body typically fabricated out of thin sheet steel.
High volume can making machinery is used to produce such containers. The body of the can is made by forming a flat sheet of steel into cylindrical shape and then welding the longitudinal joined edges together. Prior to forming the cylindrical body, a protective coating is applied to both sides of the sheet material to inhibit corrosion of the metal from the contents of the can and from the outside environment. The coating also prevents interaction of the metal with the contents, which could result in contamination or spoilage. The protective coating is applied to both sides of the sheet stock, but is held short of the two edges to be welded together which require bare metal-to-metal contact.
In the can body making operation, can machinery forms the cylinder over an arm or mandrel and then welds the side seam. At this stage of the process, a strip of bare metal on both the internal and external sides of the weld remains to be coated in order to provide complete protection on all surfaces. Respective spray guns are typically used to apply a narrow width stripe of protective coating to the area of the welded seam on both inner and outer sides thereof. As the cylindrical can body passes over the welding arm, the internal coating stripe is applied by a spray gun mounted on the end of the mandrel over which the cylindrical can body passes and the external coating stripe is applied to the outside of the weld seam by means of a second externally mounted spray gun.
While various spray guns have been used for this purpose, they have been relatively complex in construction, have been problem prone, and have not leant themselves to easy field service and maintenance. Some spray guns in current use, for example, operate from a source of compressed air. When the gun operates, a stream of coating material is ejected from the nozzle and mixed with air to create a finely atomized spray to coat the weld seam as the can body travels past the spray gun. In some instances, space limitations require a single air supply line to be used for operating the gun and atomizing the liquid. In order to prevent splattering of the coating as it impinges against the can body, a proper air-to-liquid pressure must be maintained. However, the minimum pressure required to operate the on/off mechanism of the gun may not be optimum for atomizing the spray. This can result in the excessive application and splattering of coating material. Air assisted spray guns of such type also employ seals about a movable valve plunger or needle that controls starting and stopping of the liquid spray, and such seals are susceptible to wear and require periodic replacement and maintenance.
Another type of spray gun in current use is a solenoid operated device, using high pressure liquid to coat the welded seam area. No air is needed for atomization since the relatively high pressure difference between the fluid and the atmosphere causes the necessary atomization. However, the volume of spray needed to cover a narrow weld strip area is very small. A problem with high pressure hydraulic atomization is that in order to effect such narrow width spraying a relatively small orifice must be used, which is susceptible to clogging and results in frequent maintenance and downtime of the production line. Solenoid operated spray guns heretofore have not been used for low pressure air-assisted spraying in can manufacturing lines because of the difficulty in directing both liquid and air supplies through the gun while maintaining a streamlined profile sufficient to permit the passage of cylindrical can bodies over the gun. Electrical solenoids also generate heat which can be difficult to dissipate in such restricted environment.
Leakage or other malfunctions in the operating parts of such spray guns also can cause the high speed can manufacturing lines to be shut down while servicing is accomplished. If removal of the gun from the manufacturing line is required, the fluid, air, and/or electric lines must be disconnected and the gun removed from its mountings and replaced. This can be a time consuming and costly procedure. |
Public Citizen, a nonprofit citizens’ advocacy group, has urged the Virginia Court of Appeals to uphold the privacy rights of seven users of the consumer review service Yelp. The Public Citizen Press Room said on Wednesday that a Washington, D.C. area carpet-cleaning company should not be able to find out identifying information about allegedly dissatisfied customers who gave the company bad reviews.
Hadeed Carpet Cleaning, Inc. is a private company operating in the D.C. area with a well-known promotional campaign that advertises a basic carpet cleaning for $99. However, reviewers on Yelp noted that more often than not, the $99 offer is a ruse. Customers complained that they would drop carpets off for cleaning and then return to find themselves saddled with a bevy of other fees. The company even reportedly refused to surrender the carpets to the owners until the full list of incidental fees was paid off.
The company sued Yelp demanding to know the identity of seven users that Hadeed claimed they could not match to anyone in their database of past and present customers. Alleging that the ads were fake ones placed by a rival company, Hadeed announced its intention to sue the seven anonymous reviewers for defamation.
The website TechDirt said, “(M)any courts have adopted the so-called Dendrite rules for identifying anonymous speakers. The rules require giving the anonymous users a chance to respond and (more importantly) require the plaintiff to present enough evidence to prove there’s an actual case.”
The Virginia court that originally heard the case did not abide by that precedent, but rather allowed Hadeed to subpoena the information from Yelp about the reviewers’ identities. Yelp refused to comply and has been found in contempt of court.
Public Citizen urged the Virginia Court of Appeals to hear Yelp out, arguing that allowing companies to take action against anonymous users undercuts U.S. First Amendment rights to anonymous speech.
“The main question on appeal in this case is whether the trial court applied the proper legal standard in overriding the First Amendment rights of the anonymous speakers,” said Public Citizen. “Courts elsewhere have recognized that before stripping the defendant of a First Amendment right, they should take an early look at the case to confirm that the speaker’s statement appears to be false and defamatory, such that the company’s claim is viable. In this appeal, where the users’ original claims about Hadeed’s practices are echoed by dozens of other users whose reviews have not been challenged as defamatory, Yelp urges Virginia to adopt that approach.”
Public Citizen describes itself as “the people’s voice in the nation’s capital.” Its mission, according to the Public Citizen website is “(t)o ensure that all citizens are represented in the halls of power.”
[Man silenced with duct tape via Shutterstock.com] |
Peer coaching to support writing development. Learning to write well is a difficult but worthwhile effort, as nurses often need to communicate effectively through writing. A range of interventions has been used to promote effective writing by nursing students, but little outcome evidence, beyond student and faculty satisfaction, has been reported. A peer coaching assignment in a senior-level RN-to-BSN nursing complex care theory course required students to complete a scaffolded review of a peer's draft paper and provide constructive feedback to the peer. A masked and a nonmasked faculty rater (with interrater reliability of >0.99) scored the drafts and final papers. The mean scores of the participants' papers improved dramatically (M(change) = 14.24, SD(change) = 15.26, t = 5.03, p = 0.000, 95% CI(diff) ), after peer feedback. Students' responses to the intervention included identification of learning outcomes and the benefits and challenges of providing and receiving peer feedback. |
<reponame>hamaryuginh/d2readers<filename>src/datacenter/mounts/Mount.ts
import EffectInstance from "@datacenter/effects/EffectInstance";
export default class Mount {
public static readonly MODULE: string = 'Mounts';
public id: number;
public familyId: number;
public nameId: number;
public look: string;
public certificateId: number;
public effects: EffectInstance[];
}
|
George Athans
George Athans CM (born 6 July 1952) is a Canadian retired competitive water skier. During his career he won 10 consecutive national titles from 1965 to 1974, the first at age 13. Also known as George Athans Jr. to distinguish him from his father, Canadian Olympic Hall of Fame diver George Athans Sr.
Born in Kelowna, British Columbia, Athans was a member of the Canadian water ski team from 1966 to 1974 and participated in his first world championship in 1967. Athans won the world water ski championship in 1971 and 1973 and was named Canada's male amateur athlete of the year in both of those years. At his final national championship in 1974, his closest competitor was his brother, Greg Athans. A knee injury prevented Athans from competing for the Canadian title in 1975 and he retired from competition.
During his competitive career, Athans moved to Montreal to attend Sir George Williams University. He competed in the Canadian Superstars competition in 1978 (finishing fourth) and 1979 (second). Following his retirement, Athans worked as a commentator for CBC Sports and founded Athans Communications, a video production company based in Montreal.
Athans was made a Member of the Order of Canada in 1974 and has been inducted into the Canadian Olympic Hall of Fame (1971), Canada's Sports Hall of Fame (1974), the Quebec Sports Hall of Fame (1980), the International Water Ski Federation Hall of Fame (1993), and the Water Ski and Wakeboard Canada Hall of Fame (2004). |
#!/usr/bin/env python3
##############################################################################
# EVOLIFE http://evolife.telecom-paris.fr <NAME> #
# Telecom Paris 2021 www.dessalles.fr #
# -------------------------------------------------------------------------- #
# License: Creative Commons BY-NC-SA #
##############################################################################
##############################################################################
# Example to show how to use Evolife's ecology (population and groups) #
##############################################################################
""" This class defines a 2D square grid on which agents can move
"""
import random
# class MySet(set):
# " set without duplicates "
# def append(self, Item): self.add(Item)
# def list(self): return list(self)
class LandCell:
""" Defines what's in one location on the ground
"""
def __init__(self, Content=None, VoidCell=None):
self.VoidCell = VoidCell
self.Present = None # actual content
self.Future = None # future content
self.Previous = None
self.setContent(Content, Future=False)
def Content(self, Future=False): return self.Future if Future else self.Present
def free(self): return (self.Present == self.VoidCell)
def clean(self): return self.setContent(self.VoidCell)
def setContent(self, Content=None, Future=False):
if Content is None: Content = self.VoidCell
self.Previous = (self.Present, self.Future)
if Future and Content != self.Future:
self.Future = Content # here Present and Future diverge
return True # content changed
elif Content != self.Present:
self.Present = Content
self.Future = Content
return True # content changed
return False # content unchanged
def activated(self, Future=False): # indicates relevant change
" tells whether a cell is active "
return self.Content(Future=Future) != self.Previous[1*Future]
def Update(self):
self.Present = self.Future # erases history
return self.free()
def __str__(self): return str(self.Content())
class Landscape:
""" A 2-D square toric grid
"""
def __init__(self, Width=100, Height=0, CellType=LandCell):
self.ContentType = None # may constrain what content can be
self.Size = Width
self.Width = Width
if Height > 0: self.Height = Height
else: self.Height = self.Size
self.Dimension = (self.Width, self.Height)
self.Ground = [[CellType() for y in range(self.Height)] for x in range(self.Width)]
# self.Ground = [[CellType() for y in range(self.Width)] for x in range(self.Height)]
self.ActiveCells = set() # list of Positions that have been modified
self.Statistics = {} # will contain lists of cells for each content type
def setAdmissible(self, ContentType):
self.ContentType = ContentType
self.statistics() # builds lists of cell per content
def Admissible(self, Content):
if self.ContentType: return (Content in self.ContentType)
return True
def ToricConversion(self, P):
# toric landscape
(x,y) = P
return (x % self.Width, y % self.Height)
def Modify(self, P, NewContent, check=False, Future=False):
" Changes content at a location "
# print 'Modyfying', (x,y), NewContent
(x,y) = P
Cell = self.Ground[x][y]
if check:
if NewContent: # put only admissible content only at free location
if not self.Admissible(NewContent) or not Cell.free():
return False
else: # erase only when content is already there
if Cell.free(): return False
Cell.setContent(NewContent, Future=Future)
if Cell.activated(Future=Future):
# only activate cells that have actually changed state
self.ActiveCells.add((x,y))
return True
def Content(self, P, Future=False):
(x,y) = P
return self.Ground[x][y].Content(Future=Future)
def Cell(self, P):
(x,y) = P
try: return self.Ground[x][y]
except IndexError:
raise Exception('Bad coordinates for Cell (%d, %d)' % (x,y))
def __getitem__(self, P): return self.Cell(P)
def free(self, P):
(x,y) = P
return self.Ground[x][y].free() # checks whether cell is free
def neighbourhoodLength(self, Radius=1):
return (2*Radius+1) ** 2 - 5 # square minus self and four corners
def neighbours(self, P, Radius=1):
" returns neighbouring cells "
# N = []
(x,y) = P
for distx in range(-Radius, Radius+1):
for disty in range(-Radius, Radius+1):
if distx == 0 and disty == 0: continue # self not in neighbourhood
if abs(distx) + abs(disty) == 2 * Radius: continue # corners not in neighbourhood
# N.append(self.ToricConversion((x + distx, y + disty)))
yield self.ToricConversion((x + distx, y + disty))
# return N
def segment(self, P0, P1):
(x0,y0) = P0
(x1,y1) = P1
" computes the shorter segment between two points on the tore "
(vx,vy) = self.ToricConversion((x0-x1, y0-y1))
(wx,wy) = self.ToricConversion((x1-x0, y1-y0))
return (min(vx,wx), min(vy,wy))
def InspectNeighbourhood(self, Pos, Radius):
""" Makes statistics about local content
Returns a dictionary by Content.
The center position is omitted
"""
Neighbourhood = self.neighbours(Pos, Radius)
if self.ContentType:
LocalStatistics = dict(map(lambda x: (x,0), self.ContentType)) # {Content_1:0, Content_2:0...}
else: LocalStatistics = dict()
for NPos in Neighbourhood:
if self.Content(NPos):
if self.Content(NPos) in LocalStatistics: LocalStatistics[self.Content(NPos)] += 1
else: LocalStatistics[self.Content(NPos)] = 1
return LocalStatistics
def statistics(self):
" scans ground and builds lists of cells depending on Content "
if self.ContentType:
self.Statistics = dict(map(lambda x: (x,[]), self.ContentType + [None])) # {Content_1:[], Content_2:[]..., None:[]}
for (Pos, Cell) in self.travel():
if Cell.Content() in self.Statistics:
self.Statistics[Cell.Content()].append(Pos)
else:
self.Statistics[Cell.Content()] = [Pos]
def update(self):
" updates the delayed effect of cells that have been modified "
CurrentlyActiveCells = list(self.ActiveCells)
# print '\n%d active cells' % len(CurrentlyActiveCells)
# setting active cells to their last state
for Pos in CurrentlyActiveCells:
if self.Cell(Pos).Update(): # erases history, keeps last state - True if cell ends up empty
self.ActiveCells.remove(Pos) # cell is empty
# self.ActiveCells.reset()
def activation(self):
" Active cells produce their effect "
for Pos in list(self.ActiveCells):
self.activate(Pos) # may activate new cells
def activate(self, Pos):
" Cell located at position 'Pos' has been modified and now produces its effect, possibly on neighbouring cells "
pass # to be overloaded
def randomPosition(self, Content=None, check=False):
" picks an element of the grid with 'Content' in it "
if check and self.Statistics:
for ii in range(10): # as Statistics may not be reliable
if self.Statistics[Content]:
Pos = random.choice(self.Statistics[Content])
if self.Content(Pos) == Content: # should be equal if statistics up to date
return Pos
# at this point, no location found with Content in it - Need to update
self.statistics()
else: # blind search
for ii in range(10):
Row = random.randint(0,self.Height-1)
Col = random.randint(0,self.Width-1)
if check:
if self.Content((Col,Row)) == Content: return (Col, Row)
else: return (Col, Row)
return None
def travel(self):
" Iteratively returns Cells of the grid "
Pos = 0 # used to travel over the grid
for Col in range(self.Width):
for Row in range(self.Height):
try: yield ((Col,Row), self.Ground[Col][Row])
except IndexError:
print(self.Width, self.Height)
print(Col, Row, Pos)
raise
class LandCell_3D(LandCell):
""" Same as LandCell, plus a third dimension
"""
def __init__(self, Altitude=0, Content=None, VoidCell=None):
LandCell.__init__(self, Content=Content, VoidCell=VoidCell)
self.Altitude = Altitude
class Landscape_3D(Landscape):
""" Same as Landscape, but stores a third dimension in cells
"""
def __init__(self, Altitudes=[], AltitudeFile='', CellType=LandCell_3D):
Height = len(Altitudes) # number of rows
if Height == 0:
# Altitudes are retrieved from file
Rows = open(AltitudeFile).readlines()
# Altitudes = [Row.split() for Row in Rows if len(Row.split()) > 1 ]
Altitudes = [list(map(int,Row.split())) for Row in Rows]
Height = len(Altitudes) # number of rows
Width = len(Altitudes[0]) # assuming rectangular array correct
print('Ground = %d x %d' % (Width, Height))
Landscape.__init__(self, Width=Width, Height=Height, CellType=CellType)
for ((Col,Row), Cell) in self.travel():
try:
Cell.Altitude = Altitudes[Height-1-Row][Col]
except IndexError:
print(Width, Height)
print(Col, Row)
raise
if __name__ == "__main__":
print(__doc__)
__author__ = 'Dessalles'
|
<reponame>JaimeSilver/hedera-sdk-js<filename>src/contract/ContractBytecodeQuery.ts<gh_stars>1-10
import { QueryBuilder } from "../QueryBuilder";
import { QueryHeader } from "../generated/QueryHeader_pb";
import { Query } from "../generated/Query_pb";
import { grpc } from "@improbable-eng/grpc-web";
import { Response } from "../generated/Response_pb";
import { SmartContractService } from "../generated/SmartContractService_pb_service";
import { ContractGetBytecodeQuery } from "../generated/ContractGetBytecode_pb";
import { ContractId, ContractIdLike } from "./ContractId";
import { ResponseHeader } from "../generated/ResponseHeader_pb";
/**
* Get the bytecode for a smart contract instance.
*/
export class ContractBytecodeQuery extends QueryBuilder<Uint8Array> {
private readonly _builder: ContractGetBytecodeQuery;
public constructor() {
super();
this._builder = new ContractGetBytecodeQuery();
this._builder.setHeader(new QueryHeader());
this._inner.setContractgetbytecode(this._builder);
}
/**
* The contract for which information is requested.
*/
public setContractId(contractIdLike: ContractIdLike): this {
this._builder.setContractid(new ContractId(contractIdLike)._toProto());
return this;
}
protected _doLocalValidate(errors: string[]): void {
if (!this._builder.hasContractid()) {
errors.push(".setContractId() required");
}
}
protected _getMethod(): grpc.UnaryMethodDefinition<Query, Response> {
return SmartContractService.ContractGetBytecode;
}
protected _getHeader(): QueryHeader {
return this._builder.getHeader()!;
}
protected _mapResponseHeader(response: Response): ResponseHeader {
return response.getContractgetbytecoderesponse()!.getHeader()!;
}
protected _mapResponse(response: Response): Uint8Array {
return response.getContractgetbytecoderesponse()!.getBytecode_asU8()!;
}
}
|
Risk of HIV Infection among Dutch Expatriates in Sub-Saharan Africa In order to study the prevalence of human immunodeficiency virus (HIV) infections and related risk factors, Dutch expatriates returning from sub-Saharan Africa were asked to complete a questionnaire on sexual, occupational and other risk factors, and to donate a sample of blood to test for antibodies against HIV. The 1968 participants were workers of various professions and their family members over 16 years of age posted in sub-Saharan African countries by Dutch governmental, non-governmental and commercial organizations for at least 6 months cumulative time between 1 January 1979 and 1 January 1990. Antibodies against HIV-1 were found among 4 of 1122 men (0.4%) and 1 of 846 women (0.1%). The woman and 3 of the men had had sexual contact with African partners and had been treated for sexually transmitted diseases, 2 of these 3 men also had an African life partner. One man reported occupational exposure only. Of the 1968 participants 89 men (7.9%) and 18 women (2.1%) lived with an African partner; 344 men (30.7%) and 111 women (13.1%) had heterosexual contact with other African partners. Only 22.3% (men) and 18.6% (women) of casual sexual contacts with African partners were always protected by a condom. Two hundred and thirty-two of 408 (56.9%) (para)medics reported needlesticks. Groups at risk of HIV infection through sexual exposure were identified using logistic regression models. In conclusion, the observed prevalence of HIV-1 is low. However, unprotected sexual contact with African partners and needlestick accidents were common. This study underscores the continuous need for health education of expatriates on the risks of transmission of HIV in Africa. |
import collections
n = int(input())
li = list(map(int,input().split()))
ans = 1
ans_li = collections.Counter(li)
if not li[0] == 0:
print(0)
exit()
if not ans_li[0] == 1:
print(0)
exit()
for i in range(max(ans_li)+1):
ans *= ans_li[i] ** ans_li[i+1]
if ans_li[i] == 0:
print(0)
exit()
print(ans % 998244353) |
Towards adaptive discontinuous PetrovGalerkin methods The discontinuous PetrovGalerkin (dPG) method is a minimum residual method with broken test functions for instant stability. The methodology is written in an abstract framework with product spaces. It is applied to the Poisson model problem, the Stokes equation, and linear elasticity with loworder discretizations. The computable residuum leads to guaranteed error bounds and motivates adaptive refinements. (© 2016 WileyVCH Verlag GmbH & Co. KGaA, Weinheim) |
Local time and altitude variation of equatorial thermosphere midnight density maximum (MDM): San Marco drag balance measurements We present the first study of the local time and altitude variation of the MDM, the density component of the equatorial midnight pressure bulge, an important feature in the nighttime motions of the ionospherethermosphere system in the equatorial region. The neutral density data of the San Marco 3 (SM3) and San Marco 5 (SM5) satellites were averaged to obtain 24 hr density variations from April to December in 1971 and 1988. From these variations, the MDM amplitude as a function of altitude and local time was obtained at altitudes from 220 to 400 km at the geographic equator. We show the first evidence of downward phase propagation of the MDM together with a vertical structure not observed before, which may suggest an ionospheric interaction or perhaps a viscous dissipation effect. In 1971, the MDM propagates rather gradually from about 350 to 220 km in about two hours. In 1988, there appear two regions in which the MDM time shows little change with height with a discontinuous jump in between the two regions. The net effect is still a downward displacement of the MDM with local time. The results show significant seasonal and solar activity effects. During low solar activity periods, the MDM occurs earlier in equinox than in solstice for all altitudes, consistent with the seasonal variation of the midnight temperature maximum (MTM). However, with higher solar activity and at altitudes below 340 km, the MDM occurs earlier in solstice than in equinox, raising new questions on solar activity effects on the relative phases of the tidal oscillations of the neutral density and the neutral temperature. |
The emergence of liberal evening hosts on General Electric’s MSNBC has been welcomed by Democrats and others on the American Left as a counterweight to the right and center-right bias of much of the U.S. news media. But there is a difference between GE testing out whether this lineup will produce a ratings boost and actual independence in journalism.
That point was underscored in a New York Times article describing how GE responded to corporate pressure from Fox News by having GE chairman Jeffrey Immelt strike a deal with Fox News boss Rupert Murdoch, a truce that muzzled MSNBC host Keith Olbermann’s criticism of his Fox rival Bill O’Reilly, in exchange for O’Reilly muting his attacks on GE.
Though one can agree that the Olbermann-O’Reilly sniping was getting out of hand – and that there are far more important matters facing the country – the larger message is that the Left’s enthusiasm at having a few news shows reflecting a liberal outlook survives only at the forbearance of GE executives.
There is, after all, a big difference between Murdoch’s News Corporation’s longstanding commitment to a right-wing perspective on Fox News and General Electric experimenting with a lineup of a few liberals after other ratings strategies had failed.
News Corp. has shown that it is not going to budge on its right-wing content, while GE’s record suggests that it would jettison Olbermann, Rachel Maddow and Ed Schultz in a heartbeat if that would advance its corporate interests.
Already, the speak-no-ill-of-Fox mandate appears to be influencing the news content on MSNBC. Not only has Olbermann silenced his attacks on O’Reilly, but MSNBC has left out a key element of the recent right-wing disruptions of Democratic “town hall” meetings on health-care reform – that the hooliganism is being openly encouraged by Fox News.
Olbermann and Maddow have provided in-depth coverage of those near riots that confront congressional Democrats as they speak with their constituents about health care. But it fell to Jon Stewart's "Daily Show" on Comedy Central on Monday night to highlight the circular involvement of Fox News in promoting the anti-reform talking points, egging on the disruptions and then giving them favorable coverage.
Olbermann and Maddow focused on the behind-the-scenes role of medical industry lobbyists but appeared to be wearing blinders when it came to the instigating role of Fox News.
The emergence of the Olbermann-Maddow-Schultz lineup on MSNBC also may have the unintended consequence of lulling American liberals into complacency over the need to build independent media that will fight for truth and rational discourse without fear of corporate pressures.
One of the great myths that I have encountered over the years in trying to raise money for independent journalism at Consortiumnews.com is the notion that a pendulum will automatically swing back from the far right without much exertion or check-writing.
The experimental MSNBC lineup is viewed as proof of that theory, since even a conglomerate as deeply enmeshed in the military-industrial complex as GE is producing some liberal content.
However, the real history of MSNBC – and its sister network CNBC – should give pause to any celebration. As the truce with Fox News suggests, GE will put its larger corporate interests ahead of any commitment to truth-telling.
Since its founding in 1996, MSNBC has rarely confronted the serious political challenges facing the United States – and more often than not – has contributed to the problems.
During the impeachment of President Bill Clinton, the network showed little skepticism about Republican motives and sat mostly mute – along with the bulk of the U.S. news media – as George W. Bush stole the White House by blocking a Florida recount after Election 2000.
As the invasion began, MSNBC adopted the Bush administration’s title for the war – “Operation Iraqi Freedom” – and emblazoned an American flag on the corner of its screens, just like Fox.
As U.S. troops pressed toward Baghdad, MSNBC aired sentimental salutes to the troops, including mini-profiles of U.S. soldiers in a feature called “America’s Bravest.” The network also broadcast Madison Avenue-style promos of the war that featured images of heroic U.S. troops and happy Iraqis.
As unprofessional as MSNBC’s behavior may have been, this flag-waving journalism worked where it counted most – in the ratings race.
Though some Americans switched to BBC or CNN International to find more objective war coverage, large numbers of Americans clearly wanted the “feel-good” nationalism of Fox News and MSNBC. Images of U.S. troops surrounded by smiling Iraqi children were more appealing than knowing the full truth.
As Baghdad fell in April 2003, nearly the entire U.S. press corps was on its knees before “war hero” Bush. MSNBC’s “Hardball” host Chris Matthews was all softballs for Bush and his neoconservative advisers. “We’re all neo-cons now,” purred Matthews.
MSNBC also led the way in punishing out-of-step Americans. Host Joe Scarborough, a former Republican congressman, singled out former U.N. weapons inspector Scott Ritter, who had doubted the existence of Iraqi WMD, as the “chief stooge for Saddam Hussein” and demanded that Ritter and other skeptics apologize.
Scarborough also thought it was entirely appropriate to punish Iraq War critics by denying them employment. He mocked actors Sean Penn and Tim Robbins for complaining about career retaliation for their war opposition.
Despite MSNBC’s unprofessional groveling, the network discovered that it could not win over a significant number of Fox News viewers who could spot the real thing when they saw it. So, as the Iraq War dragged on and especially after Bush’s debacle over Hurricane Katrina in summer 2005, MSNBC began its drift toward a more liberal posture.
Olbermann’s “Countdown” show, which debuted in 2003, became increasingly critical of Bush as the President’s poll numbers declined. Olbermann often ended his show by noting how many days had passed since Bush had declared “Mission Accomplished” in Iraq.
Still, GE’s TV networks, including MSNBC, remained generally either mainstream or tilted to the right. For instance, CNBC filled its ranks of hosts with free-market extremists who fawned over corporate CEOs and disdained government regulation.
Even in recent months, as MSNBC has added evening shows for liberal radio hosts Rachel Maddow and Ed Schultz, CNBC has remained a bulwark against anyone who would question right-wing free-market theories.
Despite the financial meltdown of 2007-08 -- caused by excessive Wall Street risk-taking and the Bush administration’s anti-regulatory zeal -- most CNBC hosts act as if nothing happened that would shake their free-market ideology.
Though President Bush himself acknowledged that government intervention was needed to save the country from falling “into a depression greater than the Great Depression,” CNBC host Larry Kudlow and his various sidekicks refuse to acknowledge the obvious: that their free-market principles had failed.
As U.S. stock markets rebounded – after trillions of dollars of government bailouts had stabilized Wall Street banks – Kudlow declared this week that a “bull market” had arrived “despite” the actions of Washington. The taxpayer’s role in pulling the markets back from the abyss would not be acknowledged.
So, the American Left shouldn’t feel too confident that MSNBC’s liberal evening lineup would survive a shift in the political winds or weather a renewed buffeting of GE corporate offices from an outside storm of pressures.
In that sense, the New York Times story of Aug. 1 about silencing Olbermann’s feud with O’Reilly is instructive. In 2007, O’Reilly moved beyond attacking Olbermann’s network bosses and “started to shift his attention from NBC, up to its parent, GE,” the Times reported.
“Mr. O’Reilly had a young producer, Jesse Walters, ambush Mr. Immelt and ask about GE’s business in Iran, which is legal and which includes sales of energy and medical technology,” the Times wrote.
Last April, critics of MSNBC – accompanied by one of O’Reilly’s producers – stormed a GE shareholders’ meeting in a disruptive tactic that is similar to what is now being deployed against health-reform town meetings. The pressure on GE appears to have worked.
At an off-the-record summit of corporate CEOs in mid-May, PBS interviewer Charlie Rose asked GE’s Immelt and News Corp.’s Murdoch about the cable TV feud and elicited expressions of regret from both executives.
Soon afterwards, the Times reported, Immelt’s and Murdoch’s “lieutenants arranged a cease-fire.” By early June, Olbermann’s regular references to “Bill-O the Clown,” who often topped the show’s “Worst Persons in the World” list, had stopped.
If the truce redirects Olbermann’s attention to topics beyond insular cable TV rivalries, some good might come of it. But it also could impose silence on Olbermann when Fox News is a major factor in right-wing politics as it works to frame issues and to rally the troops, as comedian Jon Stewart noted.
In that sense, censorship can be a disease that may seem harmless at first, even reasonable. But the infection can quickly spread, eating away at the quality and credibility of journalism.
Also, once the first compromises are accepted, other more important ones may follow, especially if corporate executives fear that telling some uncomfortable truths might inflict bottom-line damage.
For those reasons, corporate journalism will never be a substitute for truly independent journalism that operates without fear or favor. |
<filename>src/simplepad/cache-manager.ts
import fs from 'fs-extra'
import os from 'os'
import path from 'path'
import LRU from 'lru-cache'
import { log } from 'brolog'
import FlashStoreSync from 'flash-store'
import {
ChatroomMember,
Contact,
Label,
Message,
MessageRevokeInfo,
SearchContact
} from './defined'
import { FriendshipPayload, RoomInvitationPayload } from 'wechaty-puppet'
const PRE = '[CacheManager]'
export type RoomMemberMap = { [contactId: string]: ChatroomMember }
export class CacheManager {
private readonly _userName: string
private _messageCache?: LRU<string, Message> // because message count may be massive, so we just keep them in memory with LRU and with limited capacity
private _messageRevokeCache?: LRU<string, MessageRevokeInfo>
private _contactCache?: FlashStoreSync<string, Contact>
private _contactSearchCache?: LRU<string, SearchContact>
private _roomCache?: FlashStoreSync<string, Contact>
private _roomMemberCache?: FlashStoreSync<string, RoomMemberMap>
private _roomInvitationCache?: FlashStoreSync<string, RoomInvitationPayload>
private _friendshipCache?: FlashStoreSync<string, FriendshipPayload>
private _labelList?: Label[]
constructor(userName: string) {
this._userName = userName
}
async init(): Promise<void> {
if (this._messageCache) {
throw new Error('already initialized')
}
const baseDir = path.join(
os.homedir(),
path.sep,
'.wechaty',
'puppet-simplepad-cache',
path.sep,
this._userName,
path.sep
)
const baseDirExist = await fs.pathExists(baseDir)
if (!baseDirExist) {
await fs.mkdirp(baseDir)
}
this._messageCache = new LRU<string, Message>({
max: 1000,
// length: function (n) { return n * 2},
dispose(key: string, val: any) {
log.silly(
PRE,
'constructor() lruOptions.dispose(%s, %s)',
key,
JSON.stringify(val)
)
},
maxAge: 1000 * 60 * 60
})
this._messageRevokeCache = new LRU<string, MessageRevokeInfo>({
max: 1000,
// length: function (n) { return n * 2},
dispose(key: string, val: any) {
log.silly(
PRE,
'constructor() lruOptions.dispose(%s, %s)',
key,
JSON.stringify(val)
)
},
maxAge: 1000 * 60 * 60
})
this._contactCache = new FlashStoreSync(
path.join(baseDir, 'contact-raw-payload')
)
this._contactSearchCache = new LRU<string, SearchContact>({
max: 1000,
// length: function (n) { return n * 2},
dispose(key: string, val: any) {
log.silly(
PRE,
'constructor() lruOptions.dispose(%s, %s)',
key,
JSON.stringify(val)
)
},
maxAge: 1000 * 60 * 60
})
this._roomCache = new FlashStoreSync(
path.join(baseDir, 'room-raw-payload')
)
this._roomMemberCache = new FlashStoreSync(
path.join(baseDir, 'room-member-raw-payload')
)
this._roomInvitationCache = new FlashStoreSync(
path.join(baseDir, 'room-invitation-raw-payload')
)
this._friendshipCache = new FlashStoreSync(
path.join(baseDir, 'friendship-raw-payload')
)
const contactTotal = await this._contactCache.size
log.verbose(
PRE,
`initCache() inited ${contactTotal} Contacts, cachedir="${baseDir}"`
)
}
async close() {
log.verbose(PRE, 'close()')
if (
this._contactCache &&
this._roomMemberCache &&
this._roomCache &&
this._friendshipCache &&
this._roomInvitationCache &&
this._messageCache
) {
log.silly(PRE, 'close() closing caches ...')
await Promise.all([
this._contactCache.close(),
this._roomMemberCache.close(),
this._roomCache.close(),
this._friendshipCache.close(),
this._roomInvitationCache.close()
])
this._contactCache = undefined
this._roomMemberCache = undefined
this._roomCache = undefined
this._friendshipCache = undefined
this._roomInvitationCache = undefined
this._messageCache = undefined
log.silly(PRE, 'close() cache closed.')
} else {
log.verbose(PRE, 'close() cache not exist.')
}
}
/**
* -------------------------------
* Message Section
* --------------------------------
*/
async getMessage(messageId: string): Promise<Message | undefined> {
return this._messageCache!.get(messageId)
}
async setMessage(messageId: string, payload: Message): Promise<void> {
await this._messageCache!.set(messageId, payload)
}
async hasMessage(messageId: string): Promise<boolean> {
return this._messageCache!.has(messageId)
}
async getMessageRevokeInfo(
messageId: string
): Promise<MessageRevokeInfo | undefined> {
return this._messageRevokeCache!.get(messageId)
}
async setMessageRevokeInfo(
messageId: string,
messageSendResult: MessageRevokeInfo
): Promise<void> {
await this._messageRevokeCache!.set(messageId, messageSendResult)
}
/**
* -------------------------------
* Contact Section
* --------------------------------
*/
async getContact(contactId: string): Promise<Contact | undefined> {
return this._contactCache!.get(contactId)
}
async setContact(contactId: string, payload: Contact): Promise<void> {
await this._contactCache!.set(contactId, payload)
}
async deleteContact(contactId: string): Promise<void> {
await this._contactCache!.delete(contactId)
}
async getContactIds(): Promise<string[]> {
const result: string[] = []
for await (const key of this._contactCache!.keys()) {
result.push(key)
}
return result
}
async getAllContacts(): Promise<Contact[]> {
const result: Contact[] = []
for await (const value of this._contactCache!.values()) {
result.push(value)
}
return result
}
async hasContact(contactId: string): Promise<boolean> {
return this._contactCache!.has(contactId)
}
async getContactCount(): Promise<number> {
return this._contactCache!.size
}
/**
* contact search
*/
async getContactSearch(id: string): Promise<SearchContact | undefined> {
return this._contactSearchCache!.get(id)
}
async setContactSearch(id: string, payload: SearchContact): Promise<void> {
await this._contactSearchCache!.set(id, payload)
}
async hasContactSearch(id: string): Promise<boolean> {
return this._contactSearchCache!.has(id)
}
/**
* -------------------------------
* Room Section
* --------------------------------
*/
async getRoom(roomId: string): Promise<Contact | undefined> {
return this._roomCache!.get(roomId)
}
async setRoom(roomId: string, payload: Contact): Promise<void> {
await this._roomCache!.set(roomId, payload)
}
async deleteRoom(roomId: string): Promise<void> {
await this._roomCache!.delete(roomId)
}
async getRoomIds(): Promise<string[]> {
const result: string[] = []
for await (const key of this._roomCache!.keys()) {
result.push(key)
}
return result
}
async getRoomCount(): Promise<number> {
return this._roomCache!.size
}
async hasRoom(roomId: string): Promise<boolean> {
return this._roomCache!.has(roomId)
}
/**
* -------------------------------
* Room Member Section
* --------------------------------
*/
async getRoomMember(roomId: string): Promise<RoomMemberMap | undefined> {
return this._roomMemberCache!.get(roomId)
}
async setRoomMember(roomId: string, payload: RoomMemberMap): Promise<void> {
await this._roomMemberCache!.set(roomId, payload)
}
async deleteRoomMember(roomId: string): Promise<void> {
await this._roomMemberCache!.delete(roomId)
}
/**
* -------------------------------
* Room Invitation Section
* -------------------------------
*/
async getRoomInvitation(
messageId: string
): Promise<RoomInvitationPayload | undefined> {
return this._roomInvitationCache!.get(messageId)
}
async setRoomInvitation(
messageId: string,
payload: RoomInvitationPayload
): Promise<void> {
await this._roomInvitationCache!.set(messageId, payload)
}
async deleteRoomInvitation(messageId: string): Promise<void> {
await this._roomInvitationCache!.delete(messageId)
}
/**
* -------------------------------
* Friendship Cache Section
* --------------------------------
*/
async getFriendshipRawPayload(
id: string
): Promise<FriendshipPayload | undefined> {
return this._friendshipCache!.get(id)
}
async setFriendshipRawPayload(id: string, payload: FriendshipPayload) {
await this._friendshipCache!.set(id, payload)
}
getLabelList(): Label[] | undefined {
return this._labelList
}
setLabelList(labelList: Label[]): void {
this._labelList = labelList
}
}
|
def cleanAutoGenMvenProjects(valid_root_list):
cwd = os.getcwd()
for root in valid_root_list:
os.chdir(root + '/0')
sub.run('mvn clean', shell=True, stdout=open(os.devnull, 'w'), \
stderr=open(os.devnull, 'w'))
os.chdir(cwd) |
<gh_stars>1-10
import { Clue } from "./clue";
import { Row, RowState } from "./Row";
import { maxGuesses } from "./util";
export function About() {
return (
<div className="App-about">
<p>
<i>Bradlē</i> is a remake of the word game{" "}
<a href="https://www.powerlanguage.co.uk/wordle/">
<i>Wordle</i>
</a>{" "}
by <a href="https://twitter.com/powerlanguish">powerlanguage</a>. It was forked from <a href="https://github.com/lynn/hello-wordl">hello wordl</a>.
</p>
<p>
You get {maxGuesses} tries to guess a target word.
<br />
After each guess, you get Mastermind-style feedback.
</p>
<hr />
<Row
rowState={RowState.LockedIn}
wordLength={5}
cluedLetters={[
{ clue: Clue.Absent, letter: "h" },
{ clue: Clue.Absent, letter: "u" },
{ clue: Clue.Absent, letter: "m" },
{ clue: Clue.Absent, letter: "a" },
{ clue: Clue.Absent, letter: "n" },
]}
/>
<p>
<b>H</b>, <b>U</b>, <b>M</b>, <b>A</b>, and <b>N</b> aren't in the target word at all.
</p>
<hr/>
<Row
rowState={RowState.LockedIn}
wordLength={5}
cluedLetters={[
{ clue: Clue.Absent, letter: "w" },
{ clue: Clue.Correct, letter: "o" },
{ clue: Clue.Elsewhere, letter: "r" },
{ clue: Clue.Absent, letter: "s" },
{ clue: Clue.Correct, letter: "t" },
]}
/>
<p>
<b className="green-bg">O</b> and <b className="green-bg">T</b> are correct!<br/>
The second letter is {" "} <b className="green-bg">O</b> and the fifth letter is {" "} <b className="green-bg">T</b>.
<br />
<strong>(There may still be a second O in the word.)</strong>
</p>
<p>
<b className="yellow-bg">R</b> occurs <em>elsewhere</em> in the target
word.
<br />
<strong>(Perhaps more than once. 🤔)</strong>
</p>
<hr />
<p>
Let's move the <b>R</b> and guess a couple of new letters:
</p>
<Row
rowState={RowState.LockedIn}
wordLength={5}
cluedLetters={[
{ clue: Clue.Correct, letter: "r" },
{ clue: Clue.Correct, letter: "o" },
{ clue: Clue.Correct, letter: "b" },
{ clue: Clue.Correct, letter: "o" },
{ clue: Clue.Correct, letter: "t" },
]}
annotation={"Got it!"}
/>
<p>
Report issues{" "}
<a href="https://github.com/daynemay/bradle/issues">here</a>, and thanks {" "}
<a href="https://twitter.com/chordbug">@chordbug</a>!
</p>
<p>
This game will be free and ad-free forever, or as long as it exists.
<br />
<em>I</em> don't deserve it but I'm
sure <a href="https://twitter.com/chordbug">@chordbug</a> would <a href="https://ko-fi.com/chordbug">love a coffee</a>.
</p>
</div>
);
}
|
#include<stdio.h>
#include<stdlib.h>
#define MAX_N 100
//???????????????
struct TLine{
int dist;
int a,b;
};
typedef struct TLine Line;
Line *line;
int par[MAX_N];
int rank[MAX_N];
//Union Find Tree?????????????????????
//????????¶?????§??????????????????????????§???
//?????¨??????????´???????????????????
void init(int n){
int i;
for(i=0;i<n;i++){
par[i] = i;
rank[i] = 0;
}
}
//x?????????????´?????±??????????????????£??¨????????????
int find(int x){
if(par[x]==x){
return x;
}else {
return par[x] = find(par[x]);
}
}
//x,y????±?????????????????????¨??????
void unite(int x,int y){
x =find(x);
y =find(y);
if(x==y){
return ;
}
if(rank[x] < rank[y]){
par[x] = y;
}else {
par[y] = x;
if(rank[x] == rank[y])rank[x]++;
}
}
//x,y????±?????????????????????????????????????
int same(int x,int y){
return find(x)==find(y);
}
//?????????????????????(Line.dist?????????)
void LineSort(int s,int e,Line* array){
int i,j,k;
i=s-1;
j=e;
while(i<j){
while(++i<e&&array[i].dist<array[e].dist);
while(--j>=s&&array[j].dist>=array[e].dist);
if(i<j){
//??¢??°????????¨??????????????????
array[i].dist+=array[j].dist;
array[j].dist=array[i].dist-array[j].dist;
array[i].dist-=array[j].dist;
array[i].a+=array[j].a;
array[j].a=array[i].a-array[j].a;
array[i].a-=array[j].a;
array[i].b+=array[j].b;
array[j].b=array[i].b-array[j].b;
array[i].b-=array[j].b;
}
}
if(i<e){
//?????????????????????
array[e].dist+=array[i].dist;
array[i].dist=array[e].dist-array[i].dist;
array[e].dist-=array[i].dist;
array[e].a+=array[i].a;
array[i].a=array[e].a-array[i].a;
array[e].a-=array[i].a;
array[e].b+=array[i].b;
array[i].b=array[e].b-array[i].b;
array[e].b-=array[i].b;
i++;
}
if(s<j)LineSort(s,j,array);
if(e>i)LineSort(i,e,array);
}
int main(){
int n,m;
char s[16];
int i,j,a,b,d;
long long int res;
while(1){
if(!fgets(s,16,stdin))break;
sscanf(s,"%d",&n);
if(n==0)break;
if(!fgets(s,16,stdin))break;
sscanf(s,"%d",&m);
line=(Line*)malloc(sizeof(Line)*m);
init(n);
for(i=0;i<m;i++){
fgets(s,16,stdin);
sscanf(s,"%d,%d,%d",&a,&b,&d);
line[i].a=a;
line[i].b=b;
line[i].dist=d;
}
LineSort(0,m-1,line);
res=0;
for(i=j=0;i<n-1&&j<m;j++){
if(!same(line[j].a,line[j].b)){
unite(line[j].a,line[j].b);
res+=line[j].dist/100-1;
i++;
}
}
free(line);
printf("%lld\n",res);
}
return 0;
} |
Manifold Multiplexer Manifold Multiplexer In wireless communications, bandwidth is a valuable resource that can be smartly shared by multiple users simultaneously utilizing multiplexers. This chapter offers a short review and brief impression of the working principle and the design methodology of the multiplexers in RF and microwave systems. Predominantly used different multi plexer design patterns are discussed here, however the compact manifold multiplexer is discussed in details with an example. It is designed by using advanced design system (ADS) software and implemented utilizing Microstrip technology for its low cost and simplicity. Introduction The idea of multiplexing has been used in different areas. In telegraph systems, it was used for the first time in 1870s, after few decades it was employed in telephony. Multiplexing is a useful process applied in different wireless communication systems where signals from different users (channels) can be multiplexed or demultiplexed by utilizing the multiplexers in order to use the primary recourse (frequency spectrum) intelligently and to increase the speed of the data transmission. Figure 1 shows the basic block diagram of the transmitter-receiver pair in the wireless communication system. It consists of antenna, RF front-end and baseband system. Usually, the RF front-end is the set of circuit component after antenna which down converts the RF frequency into the intermediate frequency for further processing in the baseband. The well-known components in the front-end are low noise amplifier (LNA), band pass filter (BPF), power amplifier (PA), local oscillator (LO) and mixers. Microwave multiplexers can also be found in front-end. Frequencies more than 1 GHz are typically known as microwave frequencies in which most of the systems operate. High-frequency circuit designs are different compared to the lowfrequency circuit design because at high frequency, wave nature of current is needed to be considered (it will be further discussed in microstrip transmission line technology). After the announcement of a wide range of ultra-wide band (UWB) for public use in 2002 by Federal Communication Commission (FCC), many designs dealing with high frequency and wide bandwidth became centre of attraction. With the evolution of the technology, design and implementation of multiplexing networks become more sophisticated. Figure 2 shows the scheme of sharing the bandwidth among N channels using multiplexing. Literature review In RF and microwave systems, different multiplexer design patterns have been adopted. Most of the designs have been implemented by utilizing various technologies such as waveguide and microstrip, and high-temperature superconducting (HTS) materials. Various existing multiplexers are able to deal with the multiple sub-bands with a short guard band. Due to the future generation system, amenable front-end design requirement has become more challenging. Some well-known design patterns of the multiplexer are hybrid-coupled multiplexer, directional filter multiplexer, circulator coupled multiplexer and manifold multiplexer. The hybrid-coupled multiplexer design pattern has been adopted by many researchers. This design approach is easy to tune and there is no interaction between channel filters, so it can accommodate any change in channel frequencies or addition of new channel. Hybrid multiplexers are comparatively large due to the presence of two hybrid and two filters for each channel. Jonathan et al., designed hybrid coupled multiplexer using microstrip technology. Mansour et al. studied the possibility of building HTS using hybrid-coupled multiplexers. Rubin represented the frequency multiplexer with the hybrid-coupled configuration by two-port analysis. In another design pattern of multiplexer, four port directional filters are used. By keeping one port terminated the other three ports are used for incident input, filtered output and reflected signals. Unlike hybrid-coupled multiplexers, it uses one filter per channel which can be designed separately and can be easily modified without changing the whole design. Despite all these benefits, its use is constrained due to narrow bandwidth. Volker et al., in their study, presented a microwave design based on directional filters. This paper shows the measured and simulated results for the triplexer with centre frequencies of 1.472, 2.944 and 4.416 GHz. Ref. shows the design and implementation of the miniaturized coupled-line directional filter multiplexer in a multilayer microstrip technology. The circulator-coupled multiplexer is another design which is used in different applications. This multiplexer consists of channel dropping circulators along with one filter per channel. It provides no interaction between channel filters but have comparatively high insertion loss in later channel circulator. Raafat presents experimental results for a threechannel circulator-coupled multiplexer using HTS materials for microwave. Chen et al. used an optical multiplexer employing multiport optical circulator (MOC) using optical fibre. Theoretical and experimental studies which were carried out upon a waveguide multiplexer that consists of two branches joined by a circulator are presented in Ref.. The manifold multiplexer is a well-known design pattern used to realize multiplexers. This approach is the focus of this chapter. It provides better insertion loss and amplitude response. It has been used in HTS thin film integrated technology and it shows better loss performance but is sensitive to the material defects. On the other hand, tuning this multiplexer is little complex because of its need to deal with all filters at the same time. So, it is not flexible to frequency changes or additional channel frequency and in the case of any modification in frequency arrangement, the whole multiplexer need to be redesigned. This topology has been presented in many research papers using waveguides and microstrip technology. Morinil et al. presented an improvement in the dual manifold multiplexer to design the reconfigurable multiplexer. Ho and Battensby discuss the application of microwave active filter manifold in multiplexing. Ten-channel manifold multiplexer by using waveguide is presented with contiguous and non-contiguous channels. In Ref., the theory of manifold multiplexer using helical filter is discussed. Although the reconfigurable filter technology still not fully developed, a theoretical study of tunable manifold multiplexer has been carried out with five channels. Figure 3 illustrates the most adopted structural patterns of the manifold multiplexer with one filter for each channel and these are the most compact design approach patterns. Several manifold multiplexer designs with all filters on the same side are presented in Figure 3(a). An alternate filter design as shown in Figure 3(b) is presented in Refs.. Both this approaches have been adopted according to requirements. Cameron and Yu classified the manifold multiplexer design patterns into three categories namely comb, herringbone and endfed (can be applicable in both Compared to other multiplexer patterns, manifold has no isolation between channels, which make it act as a whole circuit but at the same time, which make it more complicated when the number of channels are increased. However, it gives small losses due to the absence of the lossy isolation. That is why manifold design is the preferred choice of the circuit designer aiming for small losses and miniaturized circuit. With the help of circuit design software, complexities in the design can be overcome. Figure 4 shows the working principle of the frequency multiplexing network (FMN) using manifold approach for N number of channels with one filter per channel. Filters are interconnected by using quarter wavelength transformer and horizontal transmission line. The available frequency bandwidth is divided into N channels with frequencies f 1, f 2,, f N, where f 1 is lowest frequency band and f N is the highest frequency band. Quarter wave transmission lines provide the high impedance to the corresponding frequency band, where as horizontal transmission lines help in tuning that band. FMN is a passive network that can be used as a multiplexer in the transmitter and demultiplexer in the receiver. The presence of a suitable guard band can prevent overlapping of the sub-bands. The minimum guard band is always preferred as this band will not be used in transmission. Normally the guard band of less than 10% relative bandwidth is used most of the time. Microstrip transmission line technology Transmission line is a special purpose medium intended to transmit high-frequency signals which have short wavelengths. According to the rule of thumb, signal carrying medium will be considered as the transmission line, if the wavelength of the signal is less than the ten times the circuit component. Figure 5 shows the microstrip transmission line, which has two conductors separated by the dielectric material of permittivity r and substrate height h. Here L is the length, W is the width and t is the thickness of the microstrip. It can be manufactured utilizing a double-sided printed circuit board (PCB). Input impedance ( Z in ) of a terminated transmission line can be represented as : where Z L is load impedance, Z o characteristic impedance, d is the length of transmission line and is the wave number. In order to achieve the maximum power transfer we need to match the source and load power, which can be done by using a passive network known as matching network. Many types of matching networks are using discrete components as a cheapest solution in circuit designing such as LC network, T network and Pi network in low-frequency applications. A combination of lumped and discrete component matching network can be used for comparatively high frequencies and purely discrete components have been used in high frequencies of the order GHz. Quarter wavelength transmission line, single and double stub are examples of discrete matching networks. Quarter wavelength transmission line or transformer is a simple matching network. The impedance of the quarter wavelength transmission line can be calculated for matching load and source. Figure 6 shows the quarter wavelength microstrip transmission line. Frequency division multiplexing When the available bandwidth of the medium is more than that of communicating devices, then it is better to share the medium. FDM can enhance the data rate of the transmission by parallel processing. Multiplexing can be done in various ways, which can depend on the target application. Some of these famous schemes for multiplexing are: Frequency division multiplexing (FDM) Time division multiplexing (TDM) Wavelength division multiplexing (WDM) In wireless communications, different schemes are applied to efficiently use the valuable bandwidth. FDM is mostly used in the radio frequency band. It is the analog multiplexing schemes which divide the available bandwidth into two or more frequency bands (channels). Figure 7 shows the schematic of frequency division for the multiple channels utilizing FDM. The guard band (narrow portion of the band spectrum which is not used in communication but used to protect sub-bands from interference) is present between each neighbouring channel. One antenna pair is sufficient for the communication of all the users of the sub-bands. Design and implementation of manifold multiplexer This section will give the detailed designing process of the diplexer (an example of manifold multiplexer) using advanced design circuit (ADS) from Agilent's simulation software and implementation on a double-sided PCB. Finally, the prototype will be measured by a twoport vector network analyser. Frequency diplexer network (manifold multiplexer) By using the working principle of the FMN (discussed earlier), a diplexer is designed. Figure 8 shows the block diagram of the frequency diplexer network (FDN). It has two channels in the UWB frequency range from 6 to 9 GHz. The guard band of 200 MHz is present between these two sub-bands (6-7.4 and 7.6-9 GHz). As discussed earlier all the filters in the manifold design are needed to be tuned at the same time. However, individual channel filters are optimized and then combined with a matching network which is a systematic approach to make the designing process simple. Systematic processes In order to understand the process of design and implementation it is categorised into the four following steps. 1. Schematic designing by using selected substrate properties of PCB to show the ideal behaviour. 2. Layout of the schematic design to see the real behaviour by running momentum tool. 3. Analysis of schematic and momentum results together by using layout in schematic for final simulation results. 4. Implementation of the approved design on to the PCB and comparison of the measured results with simulation results. First step Rogers 4350B is used in many high frequency electronic circuits. It is a double-sided PCB and selected here for the design implementation. Table 1 shows the substrate properties of PCB. Diplexer can be divided in three blocks as first channel filter, second channel filter and matching network. Figure 9 shows the schematic view of the first filter in ADS. MSub and S-parameters show the substrate properties and frequency plan, respectively. Figure 10 presents the simulated forward transmission and input reflection result for the first filter in S-parameter. In a similar way, schematic of the second filter can be designed. After the optimization of the filters, both can be combined by the transmission line network as shown in the FDN figure to form the diplexers. Now tune the whole circuit together to get the optimization. Different tuning tools are available in ADS which can be used to tune the circuit. Second step After getting the optimized diplexer's schematic, second step is to convert the whole schematic into a layout as shown in Figure 11. It has three inputs/outputs and one connected to ground, so four ports are assigned to this FDN. Now run momentum, to see the real behaviour of the design which is a simulation engine use for the layout. It has two modes, RF and microwave (microwave mode gives full electromagnetic simulation with radiation effect and RF mode is quick simulation for the designs which do not radiate). Third step Third step is to convert the layout of the FDN into the component and call this component into the schematic as shown in Figure 12. Here schematic and layout simulate together and provide final simulation results in terms of ideal and real physical design. Fourth step Finally, the layout of the PCB is prepared for the implementation on the double-sided PCB. Figure 14 shows the top ground plane connected with the bottom ground plane through ground via hole. Small diameter circles are placed in already defined layer for holes. The number of holes depend on the highest operating frequency by RF design rules. The ground plane on the top can reduces the possible crosstalk between transmission lines. Now the final design file is ready to be exported from ADS for the implementation on PCB. PCB manufacturing has various steps, such as film processing, CNC drilling, brushing, plating, laminating photoresist on PCB, UV-exposure of photoresist, development of photoresist and etching. After etching, a visual inspection of PCB is needed in order to remove any possible copper remained during etching. Figure 15 shows the final prototype of the diplexer with 50 line at the input/output extended for connecting the big size SMA. Three SMA connectors have been soldered in the PCB in order to measure the results. Figure 16 shows the measured results of the prototype which are measured using a Rhode and Schwartz ZVM vector network analyser. Any possible difference between measured and the simulated results can be due to the soldering and SMA. Note: Here a diplexer is designed and implemented on the basis of FMN (Figure 4) and to see the design and implementation of the triplexer with a different BPF, see Ref.. Imran Mohsin Address all correspondence to: [email protected] |
import { Channel } from "../entity/Channel"
import { List } from "../entity/List"
import { DiscordUtility } from "./DiscordUtility"
const { LIST_MAKER_ROLE_NAME } = require("../../config.json")
export class ListUtility {
public static async newList(channelID: string): Promise<string> {
const channel = await Channel.getChannel(channelID)
console.log("Channel", channel)
if (channel === null || channel.lastListId !== null) {
return "This channel does not have a target set. Please set one first."
}
const list = await List.getNonTakenList(
channel.length,
channel.length !== 0
)
if (!list) {
const channel = await DiscordUtility.getChannelFromId(channelID)
return (
"There are no lists that meet the criteria. <@&" +
channel.guild.roles.cache.find(
(role) => role.name === LIST_MAKER_ROLE_NAME
).id +
">"
)
}
console.log(list)
const dChannel = await DiscordUtility.getChannelFromId(channelID)
const message = await dChannel.send(list.generateEmbed())
channel.lastListId = list.id
list.messageId = message.id
await List.updateList(list)
await Channel.updateChannel(channel)
}
}
|
<reponame>rakib09/spring-cloud-gateway
package com.extremecoder.apigateway;
import lombok.Data;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
@EnableEurekaClient
@SpringBootApplication
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("", r -> r.path("/cars/**")
.filters(
f -> f.hystrix(c -> c.setName("carsFallback")
.setFallbackUri("forward:/car-fallback"))
)
.uri("lb://car-service"))
.build();
}
@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder() {
return WebClient.builder();
}
}
@Data
class Car {
private Integer id;
private String name;
}
@RestController
class FavoriteCarsController {
private final WebClient.Builder carClient;
FavoriteCarsController(WebClient.Builder carClient) {
this.carClient = carClient;
}
@GetMapping("/fav-cars")
public Flux<Car> favCars() {
return carClient.build().get().uri("lb://car-service/cars")
.retrieve().bodyToFlux(Car.class)
.filter(this::isFavorite);
}
private boolean isFavorite(Car car) {
return car.getName().equals("test");
}
}
@RestController
class FallBackController {
@GetMapping("/car-fallback")
public Flux<Car> noCars() {
return Flux.empty();
}
} |
The present invention relates to the field of digital computer systems and, more particularly, to a chip having a PCI interface that supports access for both 16- and 32-bit PCI hosts employing little-endian or big-endian byte ordering.
In computer systems, electronic chips and other components are connected with one another by buses. A variety of components can be connected to the bus, providing intercommunication between all of the devices that are connected to the bus. One type of bus which has gained wide industry acceptance is the peripheral component interconnect (PCI) bus. The PCI bus may be a 32-bit pathway for high-speed data transfer. Essentially, the PCI bus is a parallel data path that may be attached directly to a system host processor and a memory.
The address and data signals on the PCI bus are time multiplexed on the same 32 pins (ADO through AD31). On the one clock cycle, the combined address/data lines carry the address values and set up the location to move information to or from. On the next cycle, the same lines switch to carrying the actual data.
The PCI bus anticipates all devices following the PCI standard will use its full 32-bit bus width. However, it would be desirable to provide a chip having a PCI interface that allows both 16- and 32-bit host processors to access the chip via a PCI bus.
Further, some processors, such as Intel processors, employ little-endian byte ordering that requires the most significant byte to be in the left-most position. Other processors, such as Motorola processors, use big-endian byte ordering that requires the most significant byte to be in the right-most position.
Moreover, a 16-bit little-endian PCI host drives all address bits ADO to AD31 during the address phase of a PCI transfer, but must transfer data on AD15 to AD0 during the data phase of the transfer. By contrast, a 16-bit big-endian PCI host drives all address bits AD0 to AD31 during the address phase of a transfer, but must transfer data on AD31 to AD16 during the data phase of the transfer.
Thus, it would be desirable to provide a PCI interface that supports little-endian host processors as well as big-endian host processors.
Accordingly, an advantage of the present invention is in providing a chip having a PCI interface that allows both 16- and 32-bit host processors to access internal registers on the chip and an external memory via a PCI bus.
Another advantage of the present invention is in providing a PCI interface that supports little-endian host processors as well as big-endian host processors.
The above and other advantages of the invention are achieved, at least in part, by providing a system for enabling a host to access a memory means via a PCI bus. The memory means may include internal registers of a data communication switch and a memory device external with respect to the switch. Write and read buffers may be arranged on the switch for temporarily storing data transferred between the PCI bus and the memory device. A PCI interface arranged on the switch for transferring data between the PCI bus and the memory means may be adjustable to support a first PCI host that handles words of first length and a second PCI host that handles words of second length different from the first length. For example, the PCI interface may support 16- and 32-bit host processors.
In accordance with a first aspect of the present invention, a data steering means may be provided for connecting predetermined data paths of the PCI bus to a predetermined location of the buffer means in response to a data steering signal. For example, the data steering means allows a 16-bit host to perform an 8- or 16-bit read or write access to the memory device.
In accordance with another aspect of the present invention, a byte swapping means may be provided for changing the order of bytes in a data word when the data word is transferred between the memory device and the buffer. In response to a first byte swapping signal, the order of bytes in the data word may be changed, whereas a second swapping signal may maintain the order of bytes in the data word. For example, the first byte swapping signal may be produced when the switch is configured to support a big-endian host processor. The second byte swapping signal may be generated when the switch is configured to support a little-endian host processor.
In accordance with a further aspect of the present invention, a holding register may be provided between an internal register of the switch and the PCI bus. A plurality of consecutive data transfers may be performed for supporting host accesses to the internal register. The holding register temporarily stores data of a first data transfer and transmits the stored data to the internal register when the host performs a second data transfer directly to the internal register. For example, the holding register may enable a 16-bit host to access a 32-bit internal register using two consecutive 16-bit data transfers.
Still other objects and advantages of the present invention will become readily apparent to those skilled in this art from the following detailed description, wherein only the preferred embodiment of the invention is shown and described, simply by way of illustration of the best mode contemplated of carrying out the invention. As will be realized, the invention is capable of other and different embodiments, and its several details are capable of modifications in various obvious respects, all without departing from the invention. Accordingly, the drawings and description are to be regarded as illustrative in nature, and not as restrictive. |
<reponame>stringsync/musicxml
import { t } from '../schema';
/**
* The up-down type is used for the direction of arrows and other pointed symbols like vertical accents, indicating
* which way the tip is pointing.
*
* {@link https://www.w3.org/2021/06/musicxml40/musicxml-reference/data-types/up-down/}
*/
export const upDown = () => t.choices('up' as const, 'down' as const);
|
from bs4 import BeautifulSoup
import requests
from collections import namedtuple
import random
import json
yelp_review = namedtuple('review', ['yelp_rating', 'model_rating', 'text'])
yelp_biz = namedtuple('yelp_biz', ['name', 'yelp_rating', 'review_rating', 'model_rating', 'reviews'])
def transform_yelp_rating(rating: str) -> float:
return float(rating.split(' ')[0])
def translate_model_rating(rating: str) -> float:
return float(rating.data) + 1.
def model_rating(model, text: str) -> float:
cat, _, t = model.predict(text)
return translate_model_rating(cat)
def scrape_yelp_biz(url: str, model) -> yelp_biz:
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
reviews = []
biz_name = soup.find('div', {'class': 'biz-page-header-left'}).find('h1', {'class':'biz-page-title'}).text.strip()
biz_rating = transform_yelp_rating(soup.find('div', {'class': 'biz-rating'}).find('div', {'class':'i-stars'}).get('title'))
for review in soup.find_all(class_='review-content'):
text = review.find('p').text
rating = transform_yelp_rating(review.find('div', {'class':'i-stars'}).get('title'))
# predicted_rating = model_rating(model, text) # TODO: Pass the real model here when trained
predicted_rating = random.randint(1, 5)
reviews.extend([yelp_review(rating, predicted_rating, text)])
review_rating = sum([r.yelp_rating for r in reviews])/len(reviews)
predicted_model_rating = sum([r.model_rating for r in reviews])/len(reviews)
return yelp_biz(biz_name, biz_rating, review_rating, predicted_rating, reviews) |
import { DisciplinasService } from './../../disciplinas/disciplinas.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
procurarDisciplina: string;
constructor(private disciplinasService: DisciplinasService) {
this.procurarDisciplina = '';
}
ngOnInit(): void {}
}
|
Ste-Anne Catholic Church (Ottawa)
History
Bishop Joseph-Bruno Guigues was responsible for the creation of the church, as by the 1870s Ottawa's French Catholic population outgrew the Notre-Dame Cathedral. Pierre Rocque worked as the contractor and assisted LeCourt in the construction. Bishop Guigues laid the cornerstone on May 4, 1873.
In April 2009, part of the roof collapsed, resulting in an 18-month restoration costing more than $1 million. Eight months after the church reopened, it was closed again by the Archdiocese of Ottawa due to dwindling attendance and economic problems. Archbishop Terrence Prendergast offered the building to the community of St. Clement Parish, which agreed to the move and began holding Masses at Ste-Anne's on June 3, 2012.
Heritage Designation
Ste-Anne Catholic Church is a designated heritage property under Part IV of the Ontario Heritage Act. It is commemorated by the City of Ottawa with the following plaque:
1873
Eglise Sainte-Anne
This traditional Québec style church was designed by the architect J.P. Lecourt. The steeply-pitched roof and façade sculptures are common to churches of this type. It originally served the lowertown parish which extended to Notre Dame Cemetery.
Designated Heritage property 1978.
Architecture
The building features a plain stone facade with a medieval-inspired rose window. The doors, windows, and three statuary niches contain classical rounded arches. A detailed three-tiered belfry tops contrasts with the simple stone facade. |
// SerializeSizeWitness returns the number of bytes it would take to serialize the
// transaction input for a witness.
func (ti *TxInput) SerializeSizeWitness() int {
return s.VarIntSerializeSize(uint64(len(ti.SignScript))) + len(ti.SignScript)
} |
<filename>src/benchmarks/gc/src/commonlib/score_spec.py
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the MIT license.
# See the LICENSE file in the project root for more information.
from dataclasses import dataclass
from typing import Optional
from .frozen_dict import FrozenDict
from .type_utils import doc_field, with_slots
@doc_field(
"weight",
"""
When diffing scores for two traces, this Will be multiplied by the percent difference in a metric.
For example, if config A had a metric value of 2 and config B had a metric value of 3,
and weight is 2, the value of the score is 50% * 2 = 100%.
Weights may be negative to indicate that being below par is preferable.
When considering a single trace alone, the percent difference can come from 'par'.
If 'par' is not set, a geometric mean will be used instead.
""",
)
@doc_field("par", "Expected normal value for this metric.")
@with_slots
@dataclass(frozen=True)
class ScoreElement:
weight: float
par: Optional[float] = None
# Maps a metric name to par and weight
# Must be a ReadonlyDict so this is hashable
ScoreSpec = FrozenDict[str, ScoreElement]
|
Unique clade of alphaproteobacterial endosymbionts induces complete cytoplasmic incompatibility in the coconut beetle Significance Maternally inherited bacterial endosymbionts in arthropods manipulate host reproduction to increase the number of infected females. Cytoplasmic incompatibility (CI) is one such manipulation, in which infected females can produce offspring by mating with both infected and uninfected males, but uninfected females cannot or seldom produce offspring with infected males. Two bacterial endosymbionts, Wolbachia and Cardinium, are known CI inducers. Here we report a third CI inducer that belongs to a unique clade of Alphaproteobacteria. This bacterial clade was found to cause complete CI between two clades of the coconut beetle, a serious invasive pest of coconut palms. We discuss the potential use of this bacterium as a biological control agent and its effects on speciation of the coconut beetle. Maternally inherited bacterial endosymbionts in arthropods manipulate host reproduction to increase the fitness of infected females. Cytoplasmic incompatibility (CI) is one such manipulation, in which uninfected females produce few or no offspring when they mate with infected males. To date, two bacterial endosymbionts, Wolbachia and Cardinium, have been reported as CI inducers. Only Wolbachia induces complete CI, which causes 100% offspring mortality in incompatible crosses. Here we report a third CI inducer that belongs to a unique clade of Alphaproteobacteria detected within the coconut beetle, Brontispa longissima. This beetle comprises two cryptic species, the Asian clade and the Pacific clade, which show incompatibility in hybrid crosses. Different bacterial endosymbionts, a unique clade of Alphaproteobacteria in the Pacific clade and Wolbachia in the Asian clade, induced bidirectional CI between hosts. The former induced complete CI (100% mortality), whereas the latter induced partial CI (70% mortality). Illumina MiSeq sequencing and denaturing gradient gel electrophoresis patterns showed that the predominant bacterium detected in the Pacific clade of B. longissima was this unique clade of Alphaproteobacteria alone, indicating that this endosymbiont was responsible for the complete CI. Sex distortion did not occur in any of the tested crosses. The 1,160 bp of 16S rRNA gene sequence obtained for this endosymbiont had only 89.3% identity with that of Wolbachia, indicating that it can be recognized as a distinct species. We discuss the potential use of this bacterium as a biological control agent. |
import os
import argparse
import json
import tqdm
# first run 'make_tok.sh' then run 'mask_span.py'
def subspan_generator(trg_bpe_line, trg_tok_line, lang) :
if lang == 'ko' :
bpe = '▁'
else :
bpe = '@@'
trg_bpe_line_split = trg_bpe_line.split()
trg_tok_line_split = trg_tok_line.split()
idx = 0
spans = []
for ref_token in trg_tok_line_split:
tmp_buf = []
tmp_idx = 0
i = idx
while idx < len(trg_bpe_line_split):
tmp_buf += [trg_bpe_line_split[idx].replace(bpe,'')]
idx+=1
tmp_idx+=1
if ''.join(tmp_buf) == ref_token.replace(bpe,''):
break
if len(tmp_buf) > 0:
spans += [[i, i+tmp_idx]]
return spans
if __name__ == "__main__" :
parser = argparse.ArgumentParser()
# python make_span.py --directory emea_deen --src de --tgt en --saved data-bin/emea_deen
# load model
parser.add_argument('--directory', required=True, help='File path')
parser.add_argument('--src', type=str, default='ko', help='Source language')
parser.add_argument('--tgt', type=str, default='en', help='Source language')
parser.add_argument('--saved', type=str, default='', help='Source language')
args = parser.parse_args()
split = ["train", "valid", "test"]
src = args.src
tgt = args.tgt
directory = args.directory
saved = args.saved
for s in split :
tgt_bpe_line = open(f"{directory}/{s}.{tgt}", "r").readlines()
tgt_tok_line = open(f"{directory}/{s}.tok.{tgt}", "r").readlines()
span = {}
for i, (bpe, tok) in enumerate( zip(tgt_bpe_line, tgt_tok_line) ) :
sample = subspan_generator(bpe, tok, src)
span[int(i)] = {}
anchor_list = [i for i in range( len(bpe.split(" ")) )]
for a in anchor_list :
for sam in sample :
if sam[0] <= a and a < sam[1] :
span[int(i)][int(a)] = sam
with open(f"{saved}/{s}_span.json", "w") as f :
json.dump( span, f)
|
Breaking News Emails Get breaking news alerts and special reports. The news and stories that matter, delivered weekday mornings.
June 1, 2016, 9:23 AM GMT / Updated June 1, 2016, 9:58 AM GMT By Alastair Jamieson
At least 20,0000 children are trapped in Fallujah with limited food and water as coalition-backed Iraqi troops fight to retake the city from ISIS, the U.N.'s children's agency warned Wednesday.
UNICEF said food and medicine are running out and clean water is in short supply in the Islamist-controlled city, about 40 miles west of Baghdad.
Iraqi government troops — backed by air support from the U.S.-led coalition — launched a military operation over a week ago to recapture Fallujah, which has under ISIS control since 2014.
Very few families have been able to flee the city since the start of the offensive, UNICEF’s Iraq representative Peter Hawkins said in a statement.
“Most have moved to two camps while others have sought refuge with relatives and extended families,” he said. "At least 20,000 children remain trapped in the city.
He called on all sides to provide safe passage for those wishing to leave.
Related: ISIS May Be Using ‘Human Shields’ in Fallujah, U.N. Warns
“As the violence continues to escalate in Fallujah and across Iraq, we are concerned over the protection of children in the face of extreme and rising danger,” Hawkins said. “Children face the risk of forced recruitment into the fighting, strict procedures for security screening and separation from their families.”
The U.N. has already raised concerns that ISIS has been using families as human shields.
Brig. Yehya Rasool, the spokesman for Iraq's Joint Operation Command, told NBC News Wednesday that troops had liberated the district of Nuaimiya, about two miles south of the city now will continue their advance towards areas closer to the center of Fallujah.
"In the north, Iraqi forces were able to storm into Saqlawiyah, 5.5 miles from the center of Fallujah, after heavy clashes," he said. "The fighting to retake over the district is still going on."
The fight for Fallujah is expected to be protracted because ISIS has had more than two years to dig in. Hidden bombs are believed to be strewn throughout the city, and the presence of trapped civilians will limit the use of supporting airstrikes.
Fallujah is the last major urban area controlled by ISIS in western Iraq. It still holds the country's second-largest city, Mosul, in the north, as well as smaller towns and patches of territory in the country's west and north. |
/**
* expmod-iterative.c
* An iterative, somewhat efficient implementation of expmod.
*/
// +---------+-------------------------------------------------------
// | Headers |
// +---------+
#include "expmod.h"
#include "logmath.h"
// +--------------------+--------------------------------------------
// | Exported Functions |
// +--------------------+
long
expmod (long x, long n, long m)
{
long result = 1;
while (n > 0)
{
if (MOD(n,2) == 0) // even
{
x = MOD(MULTIPLY(x,x),m);
n = DIVIDE(n,2);
}
else
{
result = MOD(MULTIPLY(result,x),m);
n = n-1;
}
} // while
return result;
} // expmod
|
Using stable isotopes to understand the feeding ecology of the Hokkaido brown bear (Ursus arctos) in Japan Abstract Interactions between brown bears (Ursus arctos) and anadromous salmon (Oncorhynchus spp.) constitute a unique energy pathway that facilitates nutrient cycling between marine and terrestrial ecosystems. Previous studies have documented variation in salmon consumption by brown bears; however, few have addressed potential anthropogenic factors influencing consumption. We assessed diet of brown bears on Hokkaido Island, Japan, using carbon and nitrogen stable isotopes to determine the effect of demographic (age and sex) and environmental (developed and undeveloped area) factors on salmon consumption. We collected thigh bones from 190 harvested bears from 1996 to 2011 and samples of their major dietary foods from 2009 to 2011, and we then estimated the potential contributions of these foods to the diets of brown bears using a Bayesian mixing model. Brown bears consumed more herbs, fruits, and corn than terrestrial animals or salmon at the population level. However, the dietary contribution of salmon varied widely among bears; in some cases, it comprised >30% of the total diet. Salmon consumption also varied by bear age class, sex, and location. Low salmon consumption by adult females with cubs suggested avoidance of salmon-spawning areas to minimize risk to their cubs. Bears inhabiting undeveloped areas were more likely to consume salmon than those inhabiting developed areas, suggesting that human activities restrict brown bears' salmon consumption. The lower salmon intake of Hokkaido brown bears compared with Alaskan brown bears may be attributed in part to extensive human development on Hokkaido Island, including in-stream structures that preclude salmon migrations and agricultural crops that provide an alternative food subsidy. |
<filename>suap_ead/auth/jwt.py<gh_stars>0
from django.contrib.auth import get_user_model, login
def suap_ead_user(user, profile=None):
return {'user': user, 'profile': profile}
class PreExistentUserJwtBackend:
def login_user(self, request, user_data):
user = get_user_model().objects.get(username=user_data['username'])
login(request, user, backend=None)
request.session['suap_ead'] = suap_ead_user(user_data)
class CreateNewUserJwtBackend:
def login_user(self, request, user_data):
user, created = get_user_model().objects.get_or_create(username=user_data['username'])
login(request, user, backend=None)
request.session["suap_ead"] = suap_ead_user(user_data)
|
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkCanvasStack_DEFINED
#define SkCanvasStack_DEFINED
#include "SkNWayCanvas.h"
#include "SkTArray.h"
class SkCanvasStack : public SkNWayCanvas {
public:
SkCanvasStack(int width, int height);
virtual ~SkCanvasStack();
void pushCanvas(SkCanvas* canvas, const SkIPoint& origin);
void removeAll() override;
/*
* The following add/remove canvas methods are overrides from SkNWayCanvas
* that do not make sense in the context of our CanvasStack, but since we
* can share most of the other implementation of NWay we override those
* methods to be no-ops.
*/
void addCanvas(SkCanvas*) override { SkDEBUGFAIL("Invalid Op"); }
void removeCanvas(SkCanvas*) override { SkDEBUGFAIL("Invalid Op"); }
protected:
void didSetMatrix(const SkMatrix&) override;
void onClipRect(const SkRect&, SkRegion::Op, ClipEdgeStyle) override;
void onClipRRect(const SkRRect&, SkRegion::Op, ClipEdgeStyle) override;
void onClipPath(const SkPath&, SkRegion::Op, ClipEdgeStyle) override;
void onClipRegion(const SkRegion&, SkRegion::Op) override;
private:
void clipToZOrderedBounds();
struct CanvasData {
SkIPoint origin;
SkRegion requiredClip;
};
SkTArray<CanvasData> fCanvasData;
typedef SkNWayCanvas INHERITED;
};
#endif
|
def execute(self):
extraction_results = self._fire_extractors()
self._fire_transformers(extraction_results) |
/*
* Copyright (C) 2017, <NAME> <<EMAIL>>
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package io.proleap.vb6.asg.metamodel.registry.impl;
import java.util.HashMap;
import java.util.Map;
import org.antlr.v4.runtime.tree.ParseTree;
import io.proleap.vb6.asg.metamodel.ASGElement;
import io.proleap.vb6.asg.metamodel.registry.ASGElementRegistry;
public class ASGElementRegistryImpl implements ASGElementRegistry {
final protected Map<ParseTree, ASGElement> asgElements = new HashMap<ParseTree, ASGElement>();
@Override
public void addASGElement(final ASGElement asgElement) {
assert asgElement != null;
final ParseTree ctx = asgElement.getCtx();
assert ctx != null;
assert asgElements.get(ctx) == null;
asgElements.put(ctx, asgElement);
}
@Override
public ASGElement getASGElement(final ParseTree ctx) {
final ASGElement result = asgElements.get(ctx);
return result;
}
}
|
<reponame>Drawbotics/urql-computed-exchange<filename>src/types/augmented-operation.ts
import { Operation } from 'urql';
import { DocumentNode } from 'graphql';
export interface AugmentedOperation extends Operation {
originalQuery: DocumentNode;
mixedQuery: DocumentNode;
}
|
GroupM, Magna and Zenith are out with their annual advertising forecasts for 2019, which predict low-to-mid-single-digit increases in ad growth next year.
The good news is that there is growth next year, following a strong 2018 that included a record $4 billion in midterm election spending. Here’s a rundown of the three forecasts.
GroupM has downgraded its global spending forecast for next year, now projecting growth of 3.6% to $563 billion. Previously, the firm, part of WPP, had forecast 3.9% growth for 2019.
GroupM has also downgraded its expectations for this year, now projecting worldwide spending growth of 4.3% to $543.7 billion. Earlier, it had predicted growth of 4.5% for the year.
The group is projecting a spending gain in North America next year of 2.4% to nearly $211 billion. That growth rate will be somewhat weaker than the projected 3.4% gain for 2018 — to about $206 billion.
It’s possible, the report indicated, that one or more of those countries could fall into recession next year.
In the U.S., the forecast notes that lower unemployment and other indicators have boosted consumer confidence but increases in energy prices, rising interest rate rises and low unemployment have many concerned about increased inflation.
Pressure on the auto and consumer package goods sector are suppressing growth to some extent, per GroupM report.
It predicts that 10 countries will provide 83% of all 2019 growth. China remains the largest contributor, but 2019 will be the nation’s sixth successive year, with single-digit ad growth. It will mark its lowest growth rate yet recorded. That said, its $90 billion ad market is second only to the U.S. and has doubled since 2010.
Other big contributors to spending growth next year include the U.S., India, Japan and the UK.
Magna forecasts that global advertising will increase 4.7% to $578 billion next year as the macro-economic environment is expected to remain sturdy in most of the top advertising markets, including the U.S. , China and India.
That’s on top of a strong 2018, which Magna reports will have growth of 7.2% to $552 billion. That’s the strongest growth rate since 2010, when the ad market recovered after two years of recession, and the second strongest since 2004, thanks to the combination of increased demand and cyclical drivers, like election and Olympic advertising.
In the U.S., Magna predicts advertising growth of 2.4% next year to $213 billion. Growth will decelerate versus this year, mostly due to the lack of cyclical events. U.S. ad revenues will climb 7.5% in 2018 to a record $208 billion, including a record $4 billion in mid-term political ads, per Magna’s forecast.
The major cyclical events that took place in 2018 generated approximately $6 billion in incremental ad revenue, a record, mostly due to the aforementioned political spending in the US. Those events contributed 1.2% to global ad growth in 2018.
Sixty-seven of the 70 markets analyzed by Magna showed growth in 2018, with Singapore, Peru and Bahrain the only markets to shrink. The fastest-growing markets were Argentina and the Ukraine (20% and 25% respectively).
Many emerging markets grew by double-digits, including India (14%), Egypt (16%), Vietnam (11%) and Brazil (12%), boosted by the political campaigns and the World Cup.
Digital media sales represent 46% of total ad sales in 2018. Maturity means growth rates will slow down in the next few years, but spending will still grow by double-digits in 2019 (13.3%), which should ensure digital ad sales represent nearly half (49%) of global ad dollars next year.
In the U.S., main drivers of 2018 growth were the strong economic environment, retail sales and business confidence that prompted most industries brands to increase their marketing and advertising spending. Finance, pharma, food and beverage and technology, were among categories that increased advertising spend 10% or more. Retail and personal care were up too, while automotive, movies, restaurants and telecoms reduced ad budgets.
Digital advertising continued to show impressive growth in 2018: paid search advertising grew by 16%, social media ad sales grew by 33% and online video ad sales by 26%. Overall digital ad sales grew by almost 17% while linear ad sales (television, radio, print, out-of-home) were down 1% including special events and down 5% excluding such events.
Digital advertising reached several milestones in 2018: revenues passed the $100 billion mark ($107 billion) and account for half of total U.S. advertising sales for the first time (51.5%).
Publicis Groupe’s Zenith is forecasting 4% global ad growth in 2019 to $604 billion.
For the U.S., Zenith is projecting 3% growth in 2019 to reach $210 billion.
Ecommerce advertising is poised to transform the advertising market in much the same way that paid search did in the last decade, adding about $100 billion of new money into the global advertising market over the coming years.
This growth is fueled by China, where ecommerce advertising — defined by Zenith as advertising that sits alongside and within search results and product listings on ecommerce sites — will spike from 0.8% of all China's ad spend in 2009 to 18.2% this year.
Globally, ecommerce advertising is about as advanced as it was in China at the end of the last decade.
Online video advertising will grow at an average 18% a year over the next few years, twice as fast as other forms of internet advertising and well ahead of any other channel. Online video advertising will grow by $20 billion in the next three years, while paid search will grow by $22 billion. Between them these two channels will account for 60% of the extra ad dollars added to the market over this time.
Online video and television, taken together, are more important to brand-building than ever. Their combined share of ad spend in "display" media — all media except paid search and classified advertising — has risen from a 46% share of the ad pie in 2012 to 48% this year.
By 2021 Zenith expects television and video will have a combined 49% share of global "display" – a higher share than television ever achieved on its own. Further, linear TV's share is projected to drop to 29.9% in 2021, the lowest point since Zenith started tracking the medium in 1980.
Print continues to lose market share at the expense of Internet advertising, with newspapers and magazines shrinking an average rate of 4% and 6% a year respectively, to end with 7% and 3% market shares in 2021.
"Mature" markets — North America, Western Europe and Japan — account for 62% of global ad spend this year, down from 75% 10 years ago. "Rising" markets — everything outside of those three regions — will contribute 54% of the growth in global ad spend between 2018 and 2021, increasing their share of global expenditure from 38% to 40%.
India is a standout market, growing at 13.5% a year from $9.7 billion in 2018 to $14.2 billion in 2021, when it will become the world’s eighth-largest advertising market. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.