content
stringlengths 10
4.9M
|
---|
<commit_msg>Exit when backButton pressed in menu
<commit_before>package com.robitdroid;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
public class RobitDroid extends Activity {
private ImageView imageview;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageview = (ImageView) findViewById(R.id.ImageViewRobit);
imageview.getLayoutParams().height = 400;
}
public void selfStart(View view) {
Log.v("RobitDroid", "In selfStart method");
// Start new game
Intent i = new Intent(view.getContext(), GameScreen.class);
startActivity(i);
}
public void showInstructions(View view) {
showDialog(0);
}
}
<commit_after>package com.robitdroid;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
public class RobitDroid extends Activity {
private ImageView imageview;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageview = (ImageView) findViewById(R.id.ImageViewRobit);
imageview.getLayoutParams().height = 400;
}
public void selfStart(View view) {
Log.v("RobitDroid", "In selfStart method");
// Start new game
Intent i = new Intent(view.getContext(), GameScreen.class);
startActivity(i);
}
public void showInstructions(View view) {
showDialog(0);
}
@Override
public void onBackPressed() {
finish();
}
}
|
/**
* Tests if a linestring is completely contained in the boundary of the target rectangle.
* @param line the linestring to test
* @return true if the linestring is contained in the boundary
*/
private boolean isLineStringContainedInBoundary(LineString line)
{
CoordinateSequence seq = line.getCoordinateSequence();
Coordinate p0 = new Coordinate();
Coordinate p1 = new Coordinate();
for (int i = 0; i < seq.size() - 1; i++) {
seq.getCoordinate(i, p0);
seq.getCoordinate(i + 1, p1);
if (! isLineSegmentContainedInBoundary(p0, p1))
return false;
}
return true;
} |
/** Generates ide-build information for Android Studio. */
public class AndroidStudioInfoAspect extends NativeAspectClass implements ConfiguredAspectFactory {
public static final String NAME = "AndroidStudioInfoAspect";
@Override
public String getName() {
return NAME;
}
@Override
public AspectDefinition getDefinition(AspectParameters aspectParameters) {
return new AspectDefinition.Builder(this).build();
}
@Override
public ConfiguredAspect create(
ConfiguredTarget base, RuleContext ruleContext, AspectParameters parameters) {
// Deprecated for bazel > 0.45
// Can be completely removed after a version or two
ruleContext.ruleError(
"AndroidStudioInfoAspect is deprecated. "
+ "If you are using an IntelliJ bazel plugin, "
+ "please update to the latest plugin version from the Jetbrains plugin repository.");
ConfiguredAspect.Builder builder = new Builder(this, parameters, ruleContext);
return builder.build();
}
} |
package com.clusus.payroll.employee.domain.entity;
import com.clusus.payroll.employee.domain.valueobject.RoleId;
import com.clusus.payroll.employee.domain.valueobject.RoleName;
import com.clusus.payroll.shared.domain.core.Entity;
import java.time.LocalDate;
public class Role extends Entity<RoleId> {
private RoleName name;
public Role(RoleId roleId) {
super(roleId);
}
public void assign(RoleName name) {
this.name = name;
}
public RoleName getName() {
return name;
}
public Role get() {
return this;
}
}
|
/**
* Test of cleanupRedis method, of class SitesRedisExtractor.
*/
@Test
public void testABCleanupRedis() throws InterruptedException {
System.out.println("cleanupRedis");
boolean isSuccess = false;
SitesRedisExtractor instance = new SitesRedisExtractor(filePath);
instance.sites.add(new Site(1, "google.com"));
new Thread(() -> {
instance.storeQueue();
}).start();
Thread.sleep(100);
Jedis jedis = JedisFactory.getInstance().newClient();
Set<String> keys = jedis.keys("*update*");
assertTrue(!keys.isEmpty());
instance.cleanupRedis(isSuccess);
Thread.sleep(1000);
keys = jedis.keys("*update*");
assertTrue(keys.isEmpty() || keys.size() == 1);
} |
<reponame>bakjos/protoreflect
package builder
import (
"fmt"
dpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/bakjos/protoreflect/desc"
)
// FieldType represents the type of a field or extension. It can represent a
// message or enum type or any of the scalar types supported by protobufs.
//
// Message and enum types can reference a message or enum builder. A type that
// refers to a built message or enum descriptor is called an "imported" type.
//
// There are numerous factory methods for creating FieldType instances.
type FieldType struct {
fieldType dpb.FieldDescriptorProto_Type
foreignMsgType *desc.MessageDescriptor
localMsgType *MessageBuilder
foreignEnumType *desc.EnumDescriptor
localEnumType *EnumBuilder
}
// GetType returns the enum value indicating the type of the field. If the type
// is a message (or group) or enum type, GetTypeName provides the name of the
// referenced type.
func (ft *FieldType) GetType() dpb.FieldDescriptorProto_Type {
return ft.fieldType
}
// GetTypeName returns the fully-qualified name of the referenced message or
// enum type. It returns an empty string if this type does not represent a
// message or enum type.
func (ft *FieldType) GetTypeName() string {
if ft.foreignMsgType != nil {
return ft.foreignMsgType.GetFullyQualifiedName()
} else if ft.foreignEnumType != nil {
return ft.foreignEnumType.GetFullyQualifiedName()
} else if ft.localMsgType != nil {
return GetFullyQualifiedName(ft.localMsgType)
} else if ft.localEnumType != nil {
return GetFullyQualifiedName(ft.localEnumType)
} else {
return ""
}
}
var scalarTypes = map[dpb.FieldDescriptorProto_Type]*FieldType{
dpb.FieldDescriptorProto_TYPE_BOOL: {fieldType: dpb.FieldDescriptorProto_TYPE_BOOL},
dpb.FieldDescriptorProto_TYPE_INT32: {fieldType: dpb.FieldDescriptorProto_TYPE_INT32},
dpb.FieldDescriptorProto_TYPE_INT64: {fieldType: dpb.FieldDescriptorProto_TYPE_INT64},
dpb.FieldDescriptorProto_TYPE_SINT32: {fieldType: dpb.FieldDescriptorProto_TYPE_SINT32},
dpb.FieldDescriptorProto_TYPE_SINT64: {fieldType: dpb.FieldDescriptorProto_TYPE_SINT64},
dpb.FieldDescriptorProto_TYPE_UINT32: {fieldType: dpb.FieldDescriptorProto_TYPE_UINT32},
dpb.FieldDescriptorProto_TYPE_UINT64: {fieldType: dpb.FieldDescriptorProto_TYPE_UINT64},
dpb.FieldDescriptorProto_TYPE_FIXED32: {fieldType: dpb.FieldDescriptorProto_TYPE_FIXED32},
dpb.FieldDescriptorProto_TYPE_FIXED64: {fieldType: dpb.FieldDescriptorProto_TYPE_FIXED64},
dpb.FieldDescriptorProto_TYPE_SFIXED32: {fieldType: dpb.FieldDescriptorProto_TYPE_SFIXED32},
dpb.FieldDescriptorProto_TYPE_SFIXED64: {fieldType: dpb.FieldDescriptorProto_TYPE_SFIXED64},
dpb.FieldDescriptorProto_TYPE_FLOAT: {fieldType: dpb.FieldDescriptorProto_TYPE_FLOAT},
dpb.FieldDescriptorProto_TYPE_DOUBLE: {fieldType: dpb.FieldDescriptorProto_TYPE_DOUBLE},
dpb.FieldDescriptorProto_TYPE_STRING: {fieldType: dpb.FieldDescriptorProto_TYPE_STRING},
dpb.FieldDescriptorProto_TYPE_BYTES: {fieldType: dpb.FieldDescriptorProto_TYPE_BYTES},
}
// FieldTypeScalar returns a FieldType for the given scalar type. If the given
// type is not scalar (e.g. it is a message, group, or enum) than this function
// will panic.
func FieldTypeScalar(t dpb.FieldDescriptorProto_Type) *FieldType {
if ft, ok := scalarTypes[t]; ok {
return ft
}
panic(fmt.Sprintf("field %v is not scalar", t))
}
// FieldTypeInt32 returns a FieldType for the int32 scalar type.
func FieldTypeInt32() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_INT32)
}
// FieldTypeUInt32 returns a FieldType for the uint32 scalar type.
func FieldTypeUInt32() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_UINT32)
}
// FieldTypeSInt32 returns a FieldType for the sint32 scalar type.
func FieldTypeSInt32() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_SINT32)
}
// FieldTypeFixed32 returns a FieldType for the fixed32 scalar type.
func FieldTypeFixed32() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_FIXED32)
}
// FieldTypeSFixed32 returns a FieldType for the sfixed32 scalar type.
func FieldTypeSFixed32() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_SFIXED32)
}
// FieldTypeInt64 returns a FieldType for the int64 scalar type.
func FieldTypeInt64() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_INT64)
}
// FieldTypeUInt64 returns a FieldType for the uint64 scalar type.
func FieldTypeUInt64() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_UINT64)
}
// FieldTypeSInt64 returns a FieldType for the sint64 scalar type.
func FieldTypeSInt64() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_SINT64)
}
// FieldTypeFixed64 returns a FieldType for the fixed64 scalar type.
func FieldTypeFixed64() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_FIXED64)
}
// FieldTypeSFixed64 returns a FieldType for the sfixed64 scalar type.
func FieldTypeSFixed64() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_SFIXED64)
}
// FieldTypeFloat returns a FieldType for the float scalar type.
func FieldTypeFloat() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_FLOAT)
}
// FieldTypeDouble returns a FieldType for the double scalar type.
func FieldTypeDouble() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_DOUBLE)
}
// FieldTypeBool returns a FieldType for the bool scalar type.
func FieldTypeBool() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_BOOL)
}
// FieldTypeString returns a FieldType for the string scalar type.
func FieldTypeString() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_STRING)
}
// FieldTypeBytes returns a FieldType for the bytes scalar type.
func FieldTypeBytes() *FieldType {
return FieldTypeScalar(dpb.FieldDescriptorProto_TYPE_BYTES)
}
// FieldTypeMessage returns a FieldType for the given message type.
func FieldTypeMessage(mb *MessageBuilder) *FieldType {
return &FieldType{
fieldType: dpb.FieldDescriptorProto_TYPE_MESSAGE,
localMsgType: mb,
}
}
// FieldTypeImportedMessage returns a FieldType that references the given
// message descriptor.
func FieldTypeImportedMessage(md *desc.MessageDescriptor) *FieldType {
return &FieldType{
fieldType: dpb.FieldDescriptorProto_TYPE_MESSAGE,
foreignMsgType: md,
}
}
// FieldTypeEnum returns a FieldType for the given enum type.
func FieldTypeEnum(eb *EnumBuilder) *FieldType {
return &FieldType{
fieldType: dpb.FieldDescriptorProto_TYPE_ENUM,
localEnumType: eb,
}
}
// FieldTypeImportedEnum returns a FieldType that references the given enum
// descriptor.
func FieldTypeImportedEnum(ed *desc.EnumDescriptor) *FieldType {
return &FieldType{
fieldType: dpb.FieldDescriptorProto_TYPE_ENUM,
foreignEnumType: ed,
}
}
func fieldTypeFromDescriptor(fld *desc.FieldDescriptor) *FieldType {
switch fld.GetType() {
case dpb.FieldDescriptorProto_TYPE_GROUP:
return &FieldType{fieldType: dpb.FieldDescriptorProto_TYPE_GROUP, foreignMsgType: fld.GetMessageType()}
case dpb.FieldDescriptorProto_TYPE_MESSAGE:
return FieldTypeImportedMessage(fld.GetMessageType())
case dpb.FieldDescriptorProto_TYPE_ENUM:
return FieldTypeImportedEnum(fld.GetEnumType())
default:
return FieldTypeScalar(fld.GetType())
}
}
// RpcType represents the type of an RPC request or response. The only allowed
// types are messages, but can be streams or unary messages.
//
// Message types can reference a message builder. A type that refers to a built
// message descriptor is called an "imported" type.
//
// To create an RpcType, see RpcTypeMessage and RpcTypeImportedMessage.
type RpcType struct {
IsStream bool
foreignType *desc.MessageDescriptor
localType *MessageBuilder
}
// RpcTypeMessage creates an RpcType that refers to the given message builder.
func RpcTypeMessage(mb *MessageBuilder, stream bool) *RpcType {
return &RpcType{
IsStream: stream,
localType: mb,
}
}
// RpcTypeImportedMessage creates an RpcType that refers to the given message
// descriptor.
func RpcTypeImportedMessage(md *desc.MessageDescriptor, stream bool) *RpcType {
return &RpcType{
IsStream: stream,
foreignType: md,
}
}
// GetTypeName returns the fully qualified name of the message type to which
// this RpcType refers.
func (rt *RpcType) GetTypeName() string {
if rt.foreignType != nil {
return rt.foreignType.GetFullyQualifiedName()
} else {
return GetFullyQualifiedName(rt.localType)
}
}
|
Facebook chief Mark Zuckerberg set a new record for corporate compensation in 2012 with a package worth more than $2.278 billion, according to a survey by a corporate governance firm.
The report by GMI Ratings showed Zuckerberg’s salary of $503,000 and bonus of $266,000 were eclipsed by stock options worth some $2.27 billion.
This was the first year the survey found any chief executive collected more than $1 billion, according to the GMI report released Tuesday.
One other CEO’s compensation also topped $1 billion in 2012, energy giant Kinder Morgan’s Richard Kinder, paid a salary of $1 and given stock worth more than $1.1 billion.
Those two overshadowed other CEOs, with the third-highest paid being Sirius XM Radio’s Mel Karmazin at $255 million, followed by Liberty Media’s Gregory Maffei ($254 million) and Apple’s Tim Cook ($143 million).
Maffei also collected $136 million for his role of CEO at Liberty Interactive Corp, the seventh highest on the list. Putting those two together would make him the third highest-paid with $390 million.
In the survey of 2,259 North American publicly traded companies, GMI said pay increased a median of 8.47 percent. For the companies in the Standard and Poor’s 500 index, compensation rose 19.65 percent at the median.
The massive compensation packages are generally due to stock awards, often in the form of options which allow a CEO to buy shares at a fixed price and cash in on gains.
GMI said Zuckerberg exercised 60 million stock options, granted in 2005 and fully vested by 2010, at a strike price of just six cents.
When Facebook went public in May 2012, Zuckerberg’s worth vaulted by more than $2.7 billion dollars on the difference.
GMI noted that while stock options are intended to align the interests of top executives with shareholders, “the unintended consequence of these grants is often windfall profits that come from small share price increases.”
The others in the top 10 list were Dick’s Sporting Goods’s CEO Edward Stack, paid $142 million, Starbucks’ Howard Schultz ($117 million), Salesforce’s Marc Benioff ($109 million) and Verisk Analytics’ Frank Coyne ($100 million). |
Sen. Joe Manchin (D-WV) urged President Donald Trump to pick a different nominee for the so-called “Drug Czar” position after a Washington Post and “60 Minutes” investigation revealed that the current nominee, Rep. Tom Marino (R-PA), was behind legislation that significantly constrained the DEA’s ability to freeze shipments of drugs such as opioids.
“I urge you to withdraw the nomination of Congressman Tom Marino to lead the Office of National Drug Control Policy (ONDCP),” Manchin wrote to Trump Monday, adding that the new report “calls into question Congressman Marino’s ability to fill this critical role in a manner that will serve the American people and end the [opioid abuse] epidemic.”
“Congressman Marino no longer has my trust or that of the public that he will aggressively pursue the fight against opioid abuse,” he wrote.
The Post and “60 Minutes” reported, in an extensive investigation, that legislation championed by Marino and the pharmaceutical industry made it significantly more difficult for the DEA to stop potentially harmful shipments of prescription drugs. The law passed by unanimous consent in both the House and Senate and was signed into law by former President Barack Obama with minimal Executive Branch resistance.
According to the investigation:
With a few words, the new law changed four decades of DEA practice. Previously, the DEA could freeze drug shipments that posed an “imminent danger” to the community, giving the agency broad authority. Now, the DEA must demonstrate that a company’s actions represent “a substantial likelihood of an immediate threat,” a much higher bar. “There’s no way that we could meet that burden, the determination that those drugs are going to be an immediate threat, because immediate, by definition, means right now,” [Joseph T.] Rannazzisi [former chief of the DEA’s Office of Diversion Control] said.
(Read the Post and “60 Minutes'” full investigation here.)
Manchin wrote that he’d observed the death toll in his home state increase with the millions of pills shipped in by wholesale drug distributors.
“Despite these devastating numbers and the human lives lost as a result,” Manchin wrote to Trump, “the legislation that Congressman Marino pushed has tied the hands of the DEA in their efforts to enforce our nation’s laws and ensure that these wholesalers and other industry actors alert authorities to these suspicious orders instead of simply profiting from them.
Manchin added of Marino: “His advocacy for this legislation demonstrates that Congressman Marino either does not fully understand the scope and devastation of this epidemic or ties to industry overrode those concerns. Either option leaves him unfit to serve as the head of the ONDCP.”
Read Manchin’s letter below:
Dear Mr. President, As you know, our nation is being devastated by the opioid epidemic. In 2015, we lost more than 33,000 Americans to opioid overdoses and early estimates indicate that that number was significantly higher in 2016. No state in the nation has been harder hit than mine. I have seen this epidemic destroy families and communities throughout West Virginia. In 2016 alone, we lost more than 700 West Virginians to an opioid overdose. That is why it is so important that we work together and do everything in our power to end this crisis. That is also why I urge you to withdraw the nomination of Congressman Tom Marino to lead the Office of National Drug Control Policy (ONDCP). ONDCP is at the forefront of our national effort to stop opioid abuse, administering crucial programs like the High Intensity Drug Trafficking Areas Program (HIDTA) and the Drug Free Communities Program. The head of this office, often called America’s Drug Czar, is a key voice in helping to push and implement strategies to prevent drug abuse, stop drug trafficking, and promote access to substance use disorder treatment. The October 15, 2017 report in the Washington Post, “The Drug Industry’s Triumph over the DEA,” however, calls into question Congressman Marino’s ability to fill this critical role in a manner that will serve the American people and end the epidemic. Congressman Marino no longer has my trust or that of the public that he will aggressively pursue the fight against opioid abuse. Congressman Marino led the effort in Congress to move through a bill that has made it significantly harder for the Drug Enforcement Agency (DEA) to enforce our nation’s anti-drug diversion laws. For years, wholesale drug distributors were sending millions of pills into small communities – far more than was reasonably medically necessary. As the report notes, one such company shipped 20 million doses of oxycodone and hydrocodone to pharmacies in West Virginia between 2007 and 2012. This included 11 million doses in one small county with only 25,000 people in the southern part of the state: Mingo County. As the number of pills in my state increased, so did the death toll in our communities, including Mingo County. Despite these devastating numbers and the human lives lost as a result, the legislation that Congressman Marino pushed has tied the hands of the DEA in their efforts to enforce our nation’s laws and ensure that these wholesalers and other industry actors alert authorities to these suspicious orders instead of simply profiting from them. His advocacy for this legislation demonstrates that Congressman Marino either does not fully understand the scope and devastation of this epidemic or ties to industry overrode those concerns. Either option leaves him unfit to serve as the head of the ONDCP. I am grateful for the work that you have been doing to raise awareness and to promote solutions to address this deadly epidemic. Too many in our communities are losing their lives, families, and futures to opioids and we need to be doing everything humanly possible to help them. That includes having an ONCDP head who is willing to take any steps necessary to stop this crisis, and that is why, again, I urge you to withdraw Congressman Marino’s nomination to serve as the head of ONDCP. I look forward to continuing to work with you to end the opioid epidemic.
This post has been updated. |
def s3_fetch_module(s3_path, file_name, use_creds = True):
s3, bucket = get_s3_client(use_creds = use_creds)
print('Fetching ' + s3_path + file_name)
s3.download_file(Bucket=bucket, Key=s3_path + file_name, Filename=file_name)
dir_name = sub('.tar.gz$', '', file_name)
contains_hyphen = False
if '-' in dir_name:
contains_hyphen = True
print("Module name contains invalid '-' hyphens. Replacing with '_' underscores")
dir_name = dir_name.replace('-','_')
try:
shutil.rmtree('./' + dir_name)
print('Removing old module ' + dir_name)
except:
pass
print('Extracting ' + file_name + ' into ' + dir_name)
archive = tarfile.open(file_name, 'r:gz')
archive.extractall('./')
archive.close()
if contains_hyphen:
os.rename(dir_name.replace('_','-'), dir_name)
try:
os.remove(file_name)
print('Removing ' + file_name)
except:
pass
if ~os.path.exists(dir_name + '/__init__.py'):
print('__init__.py not found. Creating it in ' + dir_name)
open(dir_name + '/__init__.py','w').close() |
From Stomatoscopy to BEA: The History of Hungarian Experimental Phonetics
Hungarian phoneticians were often among the first to do high quality research of certain types or to adopt the most advanced methods of their time. The first objective method in the investigation of the articulation of speech sounds, called „stomatoscopy‟, was used about ten years earlier than Rousselot‟s famous work was first published. More than a hundred years ago various tools were developed for the measurement of the air flow, voicing, articulation, lip movements, and the amount of energy necessary for articulation. At the beginning of the 20th century, research on the artificial recognition of vowels started. These early methods and their results are discussed here. |
/**
* PaymentMethod.java
* @author Vagisha Sharma
* May 5, 2011
*
*/
public class PaymentMethod {
private int id;
private String uwbudgetNumber;
private String ponumber;
public String paymentMethodName;
private String contactFirstName;
private String contactLastName;
private String contactEmail;
private String contactPhone;
private String organization;
private String addressLine1;
private String addressLine2;
private String city;
private String state;
private String zip;
private String country;
private int creatorId;
private Timestamp createDate;
private Timestamp lastUpdateDate;
private boolean isCurrent;
private boolean federalFunding;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUwbudgetNumber() {
return uwbudgetNumber;
}
public void setUwbudgetNumber(String uwbudgetNumber) {
this.uwbudgetNumber = uwbudgetNumber;
}
public String getPonumber() {
return ponumber;
}
public void setPonumber(String ponumber) {
this.ponumber = ponumber;
}
public String getPaymentMethodName()
{
return paymentMethodName;
}
public void setPaymentMethodName(String paymentMethodName)
{
this.paymentMethodName = paymentMethodName;
}
public String getContactFirstName() {
return contactFirstName;
}
public void setContactFirstName(String contactFirstName) {
this.contactFirstName = contactFirstName;
}
public String getContactLastName() {
return contactLastName;
}
public void setContactLastName(String contactLastName) {
this.contactLastName = contactLastName;
}
public String getContactEmail() {
return contactEmail;
}
public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}
public String getContactPhone() {
return contactPhone;
}
public void setContactPhone(String contactPhone) {
this.contactPhone = contactPhone;
}
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getCreatorId() {
return creatorId;
}
public void setCreatorId(int creatorId) {
this.creatorId = creatorId;
}
public boolean isCurrent() {
return isCurrent;
}
public void setCurrent(boolean isCurrent) {
this.isCurrent = isCurrent;
}
public Timestamp getCreateDate() {
return createDate;
}
public void setCreateDate(Timestamp createDate) {
this.createDate = createDate;
}
public Timestamp getLastUpdateDate() {
return lastUpdateDate;
}
public void setLastUpdateDate(Timestamp lastUpdateDate) {
this.lastUpdateDate = lastUpdateDate;
}
public boolean isFederalFunding() {
return federalFunding;
}
public void setFederalFunding(boolean federalFunding) {
this.federalFunding = federalFunding;
}
public String getDisplayString()
{
StringBuilder displayString = new StringBuilder();
if(!StringUtils.isBlank(getUwbudgetNumber()))
{
displayString.append("UW: ").append(getUwbudgetNumber());
}
else if(!StringUtils.isBlank(getPonumber()))
{
displayString.append("PO: ").append(getPonumber());
}
else
{
return "BUDGET NUMBER OR PO NUMBER NOT FOUND";
}
String name = getName50Chars();
if(!StringUtils.isBlank(name))
{
displayString.append(", ").append(name);
}
return displayString.toString();
}
public String getName50Chars()
{
if(!StringUtils.isBlank(paymentMethodName))
{
// Truncate if necessary
return paymentMethodName.length() > 50 ? paymentMethodName.substring(0,46) + "..." : paymentMethodName;
}
return "";
}
} |
/**
* @author starchmd
* @version $Revision$
*
* A monitor to monitor the multiple monitors.
*/
public class QueueMuxMonitor implements Monitor {
private static final Logger LOG = Logger.getLogger(QueueMuxMonitor.class.getName());
private BackendManager backend;
private QueueManager qManager;
/**
* ctor
* @param backend - backend manager
* @param qManager - queue manager
*/
public QueueMuxMonitor(BackendManager backend, QueueManager qManager) {
setBackendManager(backend,qManager);
}
/**
* Set the backend manager.
* @param backend - backend manager effectively mapping queue's to sets of backends.
*/
public void setBackendManager(BackendManager backend, QueueManager qManager) {
this.backend = backend;
this.qManager = qManager;
}
/* (non-Javadoc)
* @see org.apache.oodt.cas.resource.monitor.Monitor#getLoad(org.apache.oodt.cas.resource.structs.ResourceNode)
*/
@Override
public int getLoad(ResourceNode node) throws MonitorException {
//Unclear what to do here.
//Assuming we should never be more than "Max"
List<String> queues = queuesForNode(node);
int max = 0;
for (String queue : queues) {
try {
max = Math.max(max,backend.getMonitor(queue).getLoad(node));
} catch (QueueManagerException e) {
LOG.log(Level.WARNING,"Queue '"+queue+"' has dissappeared.");
}
}
return max;
}
/* (non-Javadoc)
* @see org.apache.oodt.cas.resource.monitor.Monitor#getNodes()
*/
@Override
public List<ResourceNode> getNodes() throws MonitorException {
Set<ResourceNode> set = new LinkedHashSet<ResourceNode>();
for (Monitor mon:this.backend.getMonitors()) {
for (Object res:mon.getNodes()) {
set.add((ResourceNode)res);
}
}
return new LinkedList<ResourceNode>(set);
}
/* (non-Javadoc)
* @see org.apache.oodt.cas.resource.monitor.Monitor#getNodeById(java.lang.String)
*/
@Override
public ResourceNode getNodeById(String nodeId) throws MonitorException {
ResourceNode node = null;
Iterator<Monitor> imon = this.backend.getMonitors().iterator();
while(imon.hasNext() && (node = imon.next().getNodeById(nodeId)) == null) {}
return node;
}
/* (non-Javadoc)
* @see org.apache.oodt.cas.resource.monitor.Monitor#getNodeByURL(java.net.URL)
*/
@Override
public ResourceNode getNodeByURL(URL ipAddr) throws MonitorException {
ResourceNode node = null;
Iterator<Monitor> imon = this.backend.getMonitors().iterator();
while(imon.hasNext() && (node = imon.next().getNodeByURL(ipAddr)) == null) {}
return node;
}
/* (non-Javadoc)
* @see org.apache.oodt.cas.resource.monitor.Monitor#reduceLoad(org.apache.oodt.cas.resource.structs.ResourceNode, int)
*/
@Override
public boolean reduceLoad(ResourceNode node, int loadValue)
throws MonitorException {
List<String> queues = queuesForNode(node);
boolean ret = true;
for (String queue:queues) {
try {
ret &= backend.getMonitor(queue).reduceLoad(node, loadValue);
} catch (QueueManagerException e) {
LOG.log(Level.SEVERE,"Queue '"+queue+"' has dissappeared.");
throw new MonitorException(e);
}
}
return ret;
}
/* (non-Javadoc)
* @see org.apache.oodt.cas.resource.monitor.Monitor#assignLoad(org.apache.oodt.cas.resource.structs.ResourceNode, int)
*/
@Override
public boolean assignLoad(ResourceNode node, int loadValue)
throws MonitorException {
List<String> queues = queuesForNode(node);
boolean ret = true;
for (String queue:queues) {
try {
ret &= backend.getMonitor(queue).assignLoad(node, loadValue);
} catch (QueueManagerException e) {
LOG.log(Level.SEVERE,"Queue '"+queue+"' has dissappeared.");
throw new MonitorException(e);
}
}
return ret;
}
/* (non-Javadoc)
* @see org.apache.oodt.cas.resource.monitor.Monitor#addNode(org.apache.oodt.cas.resource.structs.ResourceNode)
*/
@Override
public void addNode(ResourceNode node) throws MonitorException {
List<String> queues = queuesForNode(node);
for (String queue:queues) {
try {
backend.getMonitor(queue).addNode(node);
} catch (QueueManagerException e) {
LOG.log(Level.SEVERE,"Queue '"+queue+"' has dissappeared.");
throw new MonitorException(e);
}
}
}
/* (non-Javadoc)
* @see org.apache.oodt.cas.resource.monitor.Monitor#removeNodeById(java.lang.String)
*/
@Override
public void removeNodeById(String nodeId) throws MonitorException {
for (Monitor mon:this.backend.getMonitors()) {
mon.removeNodeById(nodeId);
}
}
/**
* Gets the queues that are associated with a particular node.
* @param node - node which queues are needed for
* @return list of queue names on that node
*/
private List<String> queuesForNode(ResourceNode node) {
List<String> ret = new LinkedList<String>();
//Get list of queues
List<String> queues = null;
queues = qManager.getQueues();
//Search each queu to see if it contains given node
for (String queue : queues) {
try
{
if (qManager.getNodes(queue).contains(node.getNodeId())) {
ret.add(queue);
}
} catch(QueueManagerException e) {
LOG.log(Level.SEVERE, "Queue '"+queue+"' has dissappeared.");
}
}
return ret;
}
} |
/**
* Ensures the truth of an condition involving the a parameter to the
* calling method, but not involving the state of the calling instance.
*
* @param condition a boolean expression
* @param errorMessage error message
* @throws IllegalArgumentException if {@code condition} is false
*/
public static void checkArgument(boolean condition, Object errorMessage) {
if (!condition) {
throw new IllegalArgumentException("" + errorMessage);
}
} |
<reponame>TomoyukiAota/photo-data-viewer
interface Stringable {
toString(): string;
}
export function formatArray(array?: Array<Stringable>): string {
if (!array) return '';
const content = array.map(element => element.toString?.() ?? '').join(', ');
return `[${content}]`;
}
|
<filename>inicu-client/src/app/nutrition/oralfeedDetail.ts
export class OralfeedDetail {
oralfeedid : any;
babyfeedid : any;
creationtime : any;
feedvolume : any;
totalFeedVolume : any;
feedtypeId : any;
modificationtime : any;
uhid : any;
} |
import tkinter as tk
from pathlib import Path
import random
from numpy import array_equal, copy, zeros, any
_GRID_SIZE = 4
class Application(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.wm_iconbitmap('2048.ico')
self.title("2048")
self.minsize(272, 350)
self.tab = []
self.old_tab = []
self.random_color = random.randrange(16777215)
# Score frame
self.score_frame = tk.Frame(self)
self.score_frame.pack()
# Score label
self.score = 0
self.old_score = 0
self.score_text = tk.StringVar()
self.score_text.set('Score\n' + str(self.score))
self.score_label = tk.Label(self.score_frame, textvariable=self.score_text, font=("Arial", 16),
width=11, borderwidth=1, relief="ridge")
self.score_label.pack(side=tk.LEFT)
# Best score label
self.best = 0
try:
self.best = int(Path('score.txt').read_text())
except FileNotFoundError:
pass
self.best_text = tk.StringVar()
self.best_text.set('Best\n' + str(self.best))
self.best_label = tk.Label(self.score_frame, textvariable=self.best_text, font=("Arial", 16),
width=11, borderwidth=1, relief="ridge")
self.best_label.pack(side=tk.RIGHT)
# Button frame
self.button_frame = tk.Frame(self)
self.button_frame.pack()
# Restart button
restart_button = tk.Button(self.button_frame, text="Restart", command=self.restart, font=("Arial", 10),
width=16, borderwidth=1, relief="ridge")
restart_button.pack(side=tk.LEFT)
# Undo button
self.undo_button = tk.Button(self.button_frame, text="Undo", command=self.undo, font=("Arial", 10),
width=16, borderwidth=1, relief="ridge", state=tk.DISABLED)
self.undo_button.pack(side=tk.RIGHT)
# Game grid
self.grid = tk.Frame(self)
self.grid.pack()
# You win label
self.win_label = tk.Label(self, text="You win!", font=("Arial", 16))
self.win_label.pack_forget()
# Continue button
self.continue_button = tk.Button(self, text="Continue", command=self.continue_game, font=("Arial", 10),
width=33, borderwidth=1, relief="ridge")
self.continue_button.pack_forget()
# Game over label
self.defeat_label = tk.Label(self, text="Game over!", font=("Arial", 16))
self.defeat_label.pack_forget()
self.start()
def start(self):
self.tab = zeros((_GRID_SIZE, _GRID_SIZE), dtype=int)
self.old_tab = zeros((_GRID_SIZE, _GRID_SIZE), dtype=int)
self.score = 0
self.old_score = 0
self.update_score()
self.random_tile()
self.random_tile()
self.bind_key()
def random_tile(self):
random_row = random.randrange(_GRID_SIZE)
random_column = random.randrange(_GRID_SIZE)
while self.tab[random_row][random_column] != 0:
random_row = random.randrange(_GRID_SIZE)
random_column = random.randrange(_GRID_SIZE)
if random.randrange(10) < 8:
self.tab[random_row][random_column] = 2 # 8% chance
else:
self.tab[random_row][random_column] = 4 # 2% chance
self.display_tab()
def bind_key(self):
self.bind("<Up>", lambda e: self.key_up_pressed())
self.bind("<Down>", lambda e: self.key_down_pressed())
self.bind("<Right>", lambda e: self.key_right_pressed())
self.bind("<Left>", lambda e: self.key_left_pressed())
def unbind_key(self):
self.unbind("<Up>")
self.unbind("<Down>")
self.unbind("<Right>")
self.unbind("<Left>")
def restart(self):
self.random_color = random.randrange(16777215)
self.start()
# You win label
self.win_label.destroy()
self.win_label = tk.Label(self, text="You win!", font=("Arial", 16))
# Continue button
self.continue_button.destroy()
self.continue_button = tk.Button(self, text="Continue", command=self.continue_game, font=("Arial", 10),
width=33, borderwidth=1, relief="ridge")
# Game over label
self.defeat_label.destroy()
self.defeat_label = tk.Label(self, text="Game over!", font=("Arial", 16))
self.undo_button['state'] = tk.DISABLED
def undo(self):
if any(self.old_tab) and not array_equal(self.tab, self.old_tab):
self.tab = self.old_tab.copy()
self.display_tab()
self.score = self.old_score
self.score_text.set('Score\n' + str(self.score))
self.undo_button['state'] = tk.DISABLED
def continue_game(self):
self.win_label.destroy()
self.continue_button.destroy()
self.bind_key()
self.undo_button['state'] = tk.NORMAL
def update_score(self):
self.score_text.set('Score\n' + str(self.score))
if self.best < self.score:
self.best = self.score
self.best_text.set('Best\n' + str(self.best))
Path('score.txt').write_text(str(self.best))
def display_tab(self):
for label in self.grid.winfo_children():
label.destroy()
for x in range(_GRID_SIZE):
for y in range(_GRID_SIZE):
if self.tab[x][y] == 0:
label = tk.Label(self.grid, text=None, font=("Arial", 20),
width=4, height=2, borderwidth=1, relief="ridge")
elif self.tab[x][y] % 2 != 0:
self.tab[x][y] += 1
label = tk.Label(self.grid, text=self.tab[x][y], font=("Arial", 20),
width=4, height=2, borderwidth=1, relief="ridge", underline=0)
else:
label = tk.Label(self.grid, text=self.tab[x][y], font=("Arial", 20),
width=4, height=2, borderwidth=1, relief="ridge")
# Colors
if self.tab[x][y] != 0:
label.config(bg="#" + '{0:06X}'.format(self.tab[x][y] * 20 + self.random_color))
label.grid(row=x, column=y)
def update_tab(self):
self.undo_button['state'] = tk.NORMAL
defeat = 1
for x in range(_GRID_SIZE):
for y in range(_GRID_SIZE):
if self.win_label.winfo_exists():
# check win
if self.tab[x][y] == 2048:
self.win_label.pack()
self.continue_button.pack()
self.unbind_key()
self.undo_button['state'] = tk.DISABLED
# defeat
if self.tab[x][y] == 0:
defeat = 0
else:
# check x
if 0 <= x < _GRID_SIZE - 1:
if self.tab[x][y] == self.tab[x + 1][y]:
defeat = 0
# check y
if 0 <= y < _GRID_SIZE - 1:
if self.tab[x][y] == self.tab[x][y + 1]:
defeat = 0
if defeat == 1:
self.defeat_label.pack()
self.unbind_key()
self.undo_button['state'] = tk.DISABLED
def move_up(self):
move = 0
self.old_tab = copy(self.tab)
self.old_score = self.score
for row in range(_GRID_SIZE):
for column in range(_GRID_SIZE):
# merge
if self.tab[column][row] != 0:
i = 1
while column + i < _GRID_SIZE and self.tab[column + i][row] != self.tab[column][row] \
and self.tab[column + i][row] == 0:
i += 1
if column + i < _GRID_SIZE and self.tab[column + i][row] == self.tab[column][row]:
self.tab[column][row] *= 2
self.score += self.tab[column][row]
self.update_score()
self.tab[column][row] -= 1
self.tab[column + i][row] = 0
move = 1
# move
if self.tab[column][row] != 0 and column != 0:
i = 0
while i < _GRID_SIZE and self.tab[i][row] != 0:
i += 1
if i < column and self.tab[i][row] == 0:
self.tab[i][row] = self.tab[column][row]
self.tab[column][row] = 0
move = 1
return move
def move_down(self):
move = 0
self.old_tab = copy(self.tab)
self.old_score = self.score
for row in range(_GRID_SIZE - 1, -1, -1):
for column in range(_GRID_SIZE - 1, -1, -1):
# merge
if self.tab[column][row] != 0:
i = 1
while i < _GRID_SIZE and self.tab[column - i][row] != self.tab[column][row] \
and self.tab[column - i][row] == 0:
i += 1
if i <= column and self.tab[column - i][row] == self.tab[column][row]:
self.tab[column][row] *= 2
self.score += self.tab[column][row]
self.update_score()
self.tab[column][row] -= 1
self.tab[column - i][row] = 0
move = 1
# move
if self.tab[column][row] != 0 and column != _GRID_SIZE - 1:
i = _GRID_SIZE - 1
while i >= 0 and self.tab[i][row] != 0:
i -= 1
if i > column and self.tab[i][row] == 0:
self.tab[i][row] = self.tab[column][row]
self.tab[column][row] = 0
move = 1
return move
def move_right(self):
move = 0
self.old_tab = copy(self.tab)
self.old_score = self.score
for row in range(_GRID_SIZE - 1, -1, -1):
for column in range(_GRID_SIZE - 1, -1, -1):
# merge
if self.tab[column][row] != 0:
i = 1
while i < _GRID_SIZE and self.tab[column][row - i] != self.tab[column][row] \
and self.tab[column][row - i] == 0:
i += 1
if i <= row and self.tab[column][row - i] == self.tab[column][row]:
self.tab[column][row] *= 2
self.score += self.tab[column][row]
self.update_score()
self.tab[column][row] -= 1
self.tab[column][row - i] = 0
move = 1
# move
if self.tab[column][row] != 0 and row != _GRID_SIZE - 1:
i = _GRID_SIZE - 1
while i >= 0 and self.tab[column][i] != 0:
i -= 1
if i > row and self.tab[column][i] == 0:
self.tab[column][i] = self.tab[column][row]
self.tab[column][row] = 0
move = 1
return move
def move_left(self):
move = 0
self.old_tab = copy(self.tab)
self.old_score = self.score
for row in range(_GRID_SIZE):
for column in range(_GRID_SIZE):
# merge
if self.tab[column][row] != 0:
i = 1
while row + i < _GRID_SIZE and self.tab[column][row + i] != self.tab[column][row] \
and self.tab[column][row + i] == 0:
i += 1
if row + i < _GRID_SIZE and self.tab[column][row + i] == self.tab[column][row]:
self.tab[column][row] *= 2
self.score += self.tab[column][row]
self.update_score()
self.tab[column][row] -= 1
self.tab[column][row + i] = 0
move = 1
# move
if self.tab[column][row] != 0 and row != 0:
i = 0
while i < _GRID_SIZE and self.tab[column][i] != 0:
i += 1
if i < row and self.tab[column][i] == 0:
self.tab[column][i] = self.tab[column][row]
self.tab[column][row] = 0
move = 1
return move
def key_up_pressed(self):
if self.move_up() == 1:
self.random_tile()
self.update_tab()
def key_down_pressed(self):
if self.move_down() == 1:
self.random_tile()
self.update_tab()
def key_right_pressed(self):
if self.move_right() == 1:
self.random_tile()
self.update_tab()
def key_left_pressed(self):
if self.move_left() == 1:
self.random_tile()
self.update_tab()
if __name__ == "__main__":
app = Application()
app.mainloop()
|
The price is (almost always) right. (Brent Lewin/Bloomberg News)
Two years ago, the Washington state began an unprecedented policy experiment by allowing large-scale production and sale of recreational marijuana to the public. The effects on public health and safety and on the relationship of law enforcement to minority communities will take years to manifest fully, but one impact has become abundantly clear: Legalized marijuana is getting very cheap very quickly.
Marijuana price data from Washington’s Liquor and Cannabis Board was aggregated by Steve Davenport of the Pardee RAND Graduate School and Jonathan Caulkins, a professor at Carnegie Mellon University. After a transitory rise in the first few months, which Davenport attributes to supply shortages as the system came on line, both retail prices and wholesale prices have plummeted. Davenport said that prices “are now steadily falling at about 2 percent per month. If that trend holds, prices may fall 25 percent each year going forward.”
Although some observers will be surprised by these sharp price declines – perhaps particularly some investors in the emerging legal marijuana industry – seasoned drug policy analysts have long predicted this effect. As noted by Caulkins and his colleagues in the book "Marijuana Legalization: What Everyone Needs to Know," prohibition imposes many costs on drug producers. They must operate covertly, forgo advertising, pay higher wages to compensate for the risk of arrest, and lack recourse to civil courts for resolving contract disputes. Legal companies in contrast endure none of these costs and also can benefit from economies of scale that push production costs down.
Falling pot prices create winners and losers. Because state taxes are based on a percentage of the sales price, declining prices mean each sale puts less money in the public purse. On the other hand, bargain-basement prices undercut the black market, bringing the public reduced law enforcement costs, both in terms of tax dollars spent on jail and the damage done to individuals who are arrested.
For consumers who enjoy pot occasionally while suffering no adverse effects from it, low prices will be a welcome but minor benefit; precisely because they consume modest amounts, the price declines are only a modest win. On the downside, young people tend to be price-sensitive consumers, and their use of inexpensive pot may rise over time, as might that of problematic marijuana users.
1 of 14 Full Screen Autoplay Close Skip Ad × An insider’s look at pot farming around the world View Photos A few places where cannabis is farmed for medical or recreational use. Caption A few places where cannabis is farmed for medical or recreational use. July 1, 2014 Bob Leeds, a recreational pot grower in Seattle and owner of Sea of Green Farms, inspects “clone” plants growing under lights. The clones will develop into plants that produce the "flower" required to make potent recreational marijuana. Ted S. Warren/AP Buy Photo Wait 1 second to continue.
How cheap can legal pot become? Says Caulkins, “It’s just a plant. There will always be the marijuana equivalent of organically grown specialty crops sold at premium prices to yuppies, but at the same time, no-frills generic forms could become cheap enough to give away as a loss leader – the way bars give patrons beer nuts and hotels leave chocolates on your pillow.”
Keith Humphreys is a professor of psychiatry and mental health policy director at Stanford University. |
/**
* Test with query against an empty file. Select clause has regular column reference, and an expression.
*
* regular column "key" is assigned with nullable-int
* expression "key + 100" is materialized with nullable-int as output type.
*/
@Test
public void testQueryEmptyJson() throws Exception {
final BatchSchema expectedSchema = new SchemaBuilder()
.addNullable("key", TypeProtos.MinorType.INT)
.addNullable("key2", TypeProtos.MinorType.INT)
.build();
testBuilder()
.sqlQuery("select key, key + 100 as key2 from cp.`%s`", SINGLE_EMPTY_JSON)
.schemaBaseLine(expectedSchema)
.build()
.run();
} |
def print_task(selected_id):
print("Below is the Entry selected to edit or delete\n" +
'-'*30)
selected_query = Task.select().where(Task.id == selected_id)
for task in selected_query:
print("Name: " + task.first_name,
"\nDate : " + datetime.datetime.strftime(task.date, '%m/%d/%Y'),
"\nTask Name: " + task.task,
"\nTime Spent: " + str(task.time_spent),
"\nTask Note:" + task.note)
print('-'*30) |
Integrative Genomic and Proteomic Analysis of the Response of Lactobacillus casei Zhang to Glucose Restriction.
Nutrient starvation is an important survival challenge for bacteria during industrial production of functional foods. As next-generation sequencing technology has greatly advanced, we performed proteomic and genomic analysis to investigate the response of Lactobacillus casei Zhang to a glucose-restricted environment. L. casei Zhang strains were permitted to evolve in glucose-restricted or normal medium from a common ancestor over a 3 year period, and they were sampled at 1000, 2000, 3000, 4000, 5000, 6000, 7000, and 8000 generations and subjected to proteomic and genomic analyses. Genomic resequencing data revealed different point mutations and other mutational events in each selected generation of L. casei Zhang under glucose restriction stress. The differentially expressed proteins induced by glucose restriction were mostly related to fructose and mannose metabolism, carbohydrate metabolic processes, lyase activity, and amino-acid-transporting ATPase activity. Integrative proteomic and genomic analysis revealed that the mutations protected L. casei Zhang against glucose starvation by regulating other cellular carbohydrate, fatty acid, and amino acid catabolism; phosphoenolpyruvate system pathway activation; glycogen synthesis; ATP consumption; pyruvate metabolism; and general stress-response protein expression. The results help reveal the mechanisms of adapting to glucose starvation and provide new strategies for enhancing the industrial utility of L. casei Zhang. |
/**
* Creates ids for a collection of currencies.
*
* @param securityType
* The security type string
* @param region
* The region string
* @param currencies
* The currencies
* @return The ids
*/
private static List<ExternalId> createIds(final String securityType, final String region, final Collection<Currency> currencies) {
final List<ExternalId> ids = new ArrayList<>(currencies.size());
for (final Currency currency : currencies) {
ids.add(ExternalId.of(SECURITY_IDENTIFIER, securityType + SEPARATOR + currency.getCode() + SEPARATOR + region));
}
return ids;
} |
<reponame>ibwei/kcc-homepage
import {networks, NetworkType} from '../constants/networks'
import {ChainId, getNetWorkConnect} from '../connectors/index'
import {Currency, PairInfo} from '../state/bridge/reducer'
import store from '../state'
import BN from 'bignumber.js'
import web3 from 'web3'
import {getBridgeContract, getErc20Contract} from './contract'
import {ListType} from '../pages/bridge/transfer'
import {BridgeService} from '../api/bridge'
import {usePariList} from '../state/bridge/hooks'
import {WalletList} from "../constants/wallet";
const {utils} = new web3()
export const web3Utils = utils
export function getNetworkInfo(networkId: ChainId): NetworkType {
return networks[networkId]
}
export function getPairInfo(pairId: number): PairInfo | undefined {
const pairList = store.getState().bridge.pairList
for (let i = 0; i < pairList.length; i++) {
if (pairList[i].id === pairId) {
return pairList[i]
}
}
}
export function getWalletInfo(walletId: number) {
for (let i = 0; i < WalletList.length; i++) {
if (WalletList[i].id === walletId) {
return WalletList[i]
}
}
}
export async function getApproveStatus(account: string, tokenAddress: string, bridgeAddress: string, library: any) {
const tokenContract = getErc20Contract(tokenAddress, library)
const allowance = await tokenContract.methods.allowance(account, bridgeAddress).call()
console.log('allowance', allowance)
return allowance > 0
}
/**
* @description check address status
*/
export const checkAddress = async (address: string, type: ListType): Promise<boolean> => {
const checkApi = type === ListType.BLACK ? BridgeService.inBlackList : BridgeService.inWhiteList
try {
const res = await checkApi(address)
console.log(res.data.data)
if (res.data.data.status) {
return Boolean(res.data?.data?.status)
}
return false
} catch {
return false
}
}
export async function getSwapFee(selectedChainInfo: PairInfo, library: any, isSelectedNetwork: boolean) {
const networkInfo = getNetworkInfo(selectedChainInfo.srcChainInfo.chainId)
const distNetworkInfo = getNetworkInfo(selectedChainInfo.dstChainInfo.chainId)
const lib = isSelectedNetwork ? library : getNetWorkConnect(networkInfo.chain_id as any)
const address = isSelectedNetwork ? networkInfo.bridgeCoreAddress : distNetworkInfo.bridgeCoreAddress
const contract = getBridgeContract(address, lib)
const swapFee = await contract.methods.swapFee().call()
return swapFee
}
/**
* getDecimals
*/
export function getDecimals(amount: string) {
if (!amount.includes('.')) {
return 0
} else {
const [interger, decimal] = amount.split('.')
return decimal.length ?? 0
}
}
export function formatNumber(number: any, precision = 6) {
return new BN(new BN(number).toFixed(precision)).toNumber().toString()
}
export function findPair(srcChainId: any, distChainId: any, currency: Currency) {
if (!(srcChainId && distChainId && currency.symbol)) {
return -1
}
const pairList = store.getState().bridge.pairList
for (let i = 0; i < pairList?.length; i++) {
const chain = pairList[i]
const srcChainInfo = chain.srcChainInfo
const distChainInfo = chain.dstChainInfo
if (
srcChainInfo.currency === currency.symbol &&
srcChainInfo.chainId === srcChainId &&
distChainInfo.chainId === distChainId
) {
return chain.id
}
}
return -1
}
export function findPairBySrcChain(srcChainId: any, currency: Currency) {
if (!(srcChainId && currency.symbol)) {
return -1
}
const pairList = store.getState().bridge.pairList
for (let i = 0; i < pairList?.length; i++) {
const chain = pairList[i]
const srcChainInfo = chain.srcChainInfo
if (srcChainInfo.currency === currency.symbol && srcChainInfo.chainId === srcChainId) {
return chain.id
}
}
return -1
}
|
GAS-TO-PARTICLE HEAT TRANSFER IN THE DRAFT TUBE OF A SPOUTED BED
The gas-to-particle heat transfer coefficients in the spout region of draft tube spouting beds of 2.6 mm glass beads were determined during continuous operation with particle fed through the base. For this purpose, detailed profiles of the gas temperature were measured in both spout and annular regions, as well as the temperature of the particles in the annulus. Fluid dynamic data were used to determine the volumetric solids concentration in the spout region. The effects of the spouting air flow rate, the particles feed rate, the height of the bed and the solids volumetric concentration, β v , on the heat transfer coefficients were also determined. The data obtained was compared with the predictions of equations for spouted beds and vertical pneumatic conveying. |
/**
* @param groupCreationRequest - contains Group Name and Description of new group.
* @param owner - Currently logged in user gets set as owner.
*/
public GroupResponse createGroup(GroupCreationRequest groupCreationRequest, User owner) {
if (!notNullOrEmpty.test(groupCreationRequest.getName()))
throw new InvalidRequestException("Invalid group name entered");
if (groupRepository.findGroupByName(groupCreationRequest.getName()).isPresent())
throw new DuplicateGroupNameException();
Group newGroup = new Group();
newGroup.setOwner(owner);
newGroup.setName(groupCreationRequest.getName().trim());
newGroup.setDescription(groupCreationRequest.getDescription());
List<User> list = new ArrayList<>();
list.add(userRepository.findUserByEmail(owner.getEmail()).get());
newGroup.setUsers(list);
return new GroupResponse(groupRepository.save(newGroup));
} |
// Command handling thread
class CommandHandler extends BlockingCommandHandlingThread {
public CommandHandler(int queueCapacity) {
super(queueCapacity);
}
// @Override
public String getClassName() {
return "MainService$CommandHandler";
}
// @Override
public void handle(BaseCommand cmd) {
if (null == cmd) {
if (mPrepareToStop) {
// If no command is left to handle, and currently service is
// waiting to stop, stop service.
mMsgHandler.sendEmptyMessage(MSG_FORCE_STOP);
this.terminate();
}
return;
}
Debugger.logI(this.getClassName(), "handle", new Object[] { cmd },
"FeatureID=" + cmd.getFeatureID() + ", Token="
+ cmd.getToken());
boolean handled = false;
if (BaseCommand.FEATURE_MAIN == cmd.getFeatureID()) {
handled = handleMainFrameFeatures(cmd);
} else if (BaseCommand.FEATURE_CONTACTS == cmd.getFeatureID()) {
handled = handleContactsFeatures(cmd);
} else if (BaseCommand.FEATURE_MESSAGE == cmd.getFeatureID()) {
handled = handleMessageFeatures(cmd);
} else if (BaseCommand.FEATURE_APPLICATION == cmd.getFeatureID()) {
handled = handleApplicationFeatures(cmd);
} else if (BaseCommand.FEATURE_SYNC == cmd.getFeatureID()) {
handled = handleSyncFeatures(cmd);
} else if (BaseCommand.FEATURE_MEDIA == cmd.getFeatureID()) {
handled = handleMediaFeatures(cmd);
} else if (BaseCommand.FEATURE_CALENDAR == cmd.getFeatureID()) {
handled = handleCalendarFeatures(cmd);
} else if (BaseCommand.FEATURE_CALENDAR_SYNC == cmd.getFeatureID()) {
handled = handleCalendarSyncFeatures(cmd);
} else if (BaseCommand.FEATURE_BOOKMARK == cmd.getFeatureID()) {
handled = handleBookmarkFeatures(cmd);
} else if (BaseCommand.FEATURE_BACKUP == cmd.getFeatureID()) {
handled = handleBackupFeatures(cmd);
} else {
Debugger.logE(this.getClassName(), "handle",
new Object[] { cmd }, "Unsupported feature.");
}
if (!handled) {
Debugger.logE(this.getClassName(), "handle",
new Object[] { cmd }, "): Unsupported command.");
onRespond(new UnsupportedRequestResponse(cmd.getFeatureID(),
cmd.getToken()));
}
}
/**
* Handle commands of main frame feature.
*
* @param cmd
* Command to handle.
* @return True if command is handled, false if not.
*/
public boolean handleMainFrameFeatures(BaseCommand cmd) {
final int reqToken = cmd.getToken();
if (cmd instanceof GreetingReq) {
GreetingRsp rsp = new GreetingRsp(reqToken);
// Get data and fill them in response command
rsp.setVersionCode(Config.VERSION_CODE);
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof SysInfoBatchReq) {
mCommandBatch = new SysInfoBatchRsp(reqToken);
SysInfoBatchReq reqSysInfoBatch = (SysInfoBatchReq) cmd;
int i = 0;
mResponseState = RSP_ST_APPEND_BATCH;
// Get data and fill them in response command
for (BaseCommand innerCmd : reqSysInfoBatch.getCommands()) {
if (++i == reqSysInfoBatch.getCommands().size()) {
// It's the last command in batch, we can send out
// the response batch now
mResponseState = RSP_ST_SEND_BATCH;
}
handle(innerCmd);
}
mResponseState = RSP_ST_SEND_SINGLE;
} else if (cmd instanceof GetSysInfoReq) {
GetSysInfoRsp rsp = new GetSysInfoRsp(reqToken);
// Get data and fill them in response command
// Device & Firmware
rsp.setDevice(SystemInfoProxy.getDevice());
rsp.setManufacturer(SystemInfoProxy.getManufacturer());
rsp.setFirmwareVersion(SystemInfoProxy.getFirmwareVersion());
rsp.setModel(SystemInfoProxy.getModel());
// Get feature option 2012-5-15 mtk54043
rsp.setFeatureOptionList(FeatureOptionControl.getFeatureList());
// Storage
if (SystemInfoProxy.isSdMounted()) {
rsp.setSdMounted(true);
rsp.setSdWriteable(SystemInfoProxy.isSdWriteable());
rsp.setSdCardPath(SystemInfoProxy.getSdPath());
rsp.setSdCardTotalSpace(SystemInfoProxy.getSdTotalSpace());
rsp.setSdCardAvailableSpace(SystemInfoProxy
.getSdAvailableSpace());
} else {
rsp.setSdMounted(false);
rsp.setSdWriteable(false);
rsp.setSdCardPath(null);
rsp.setSdCardTotalSpace(-1);
rsp.setSdCardAvailableSpace(-1);
}
rsp.setSDCardAndEmmcState(mSysInfoProxy.checkSDCardState());
rsp.setInternalTotalSpace(SystemInfoProxy
.getInternalTotalSpace());
rsp.setInternalAvailableSpace(SystemInfoProxy
.getInternalAvailableSpace());
// Applications & Data
rsp.setContactsCount(mContactsProxy
.getAvailableContactsCount());
// rsp.setSimContactsCount(mContactsProxy.getSimContactsCount());
rsp.setMessagesCount(mMessageProxy.getMessagesCount());
rsp.setApplicationsCount(mApplicationProxy
.getApplicationsCount());
// SIM
if (Config.MTK_GEMINI_SUPPORT) {
rsp.setGemini(true);
rsp.setGemini3Sim(Config.MTK_3SIM_SUPPORT);
rsp.setGemini4Sim(Config.MTK_4SIM_SUPPORT);
rsp.setSim1Accessible(SystemInfoProxy.isSim1Accessible());
rsp.setSim2Accessible(SystemInfoProxy.isSim2Accessible());
rsp.setSim3Accessible(SystemInfoProxy.isSim3Accessible());
rsp.setSim4Accessible(SystemInfoProxy.isSim4Accessible());
rsp.setSim1Info(Global
.getSimInfoBySlot(SimDetailInfo.SLOT_ID_ONE));
rsp.setSim2Info(Global
.getSimInfoBySlot(SimDetailInfo.SLOT_ID_TWO));
rsp.setSim3Info(Global
.getSimInfoBySlot(SimDetailInfo.SLOT_ID_THREE));
rsp.setSim4Info(Global
.getSimInfoBySlot(SimDetailInfo.SLOT_ID_FOUR));
//2013-01-30 for Gemini plus 2.0
rsp.getSlotInfoList().add(Global
.getSimInfoBySlot(SimDetailInfo.SLOT_ID_ONE));
rsp.getSlotInfoList().add(Global
.getSimInfoBySlot(SimDetailInfo.SLOT_ID_TWO));
if (Config.MTK_3SIM_SUPPORT)
{
rsp.getSlotInfoList().add(Global
.getSimInfoBySlot(SimDetailInfo.SLOT_ID_THREE));
}
if (Config.MTK_4SIM_SUPPORT)
{
rsp.getSlotInfoList().add(Global
.getSimInfoBySlot(SimDetailInfo.SLOT_ID_FOUR));
}
Debugger.logD(this.getClassName(), "handle",
new Object[] { cmd }, "Dual-SIM | SIM:"
+ rsp.isSimAccessible() + " | SIM1:"
+ rsp.isSim1Accessible() + " | SIM2:"
+ rsp.isSim2Accessible() + " | SIM3:"
+ rsp.isSim3Accessible() + " | SIM4:"
+ rsp.isSim4Accessible());
} else {
rsp.setGemini(false);
rsp.setSimAccessible(mSysInfoProxy.isSimAccessible());
rsp.setSimInfo(Global
.getSimInfoBySlot(SimDetailInfo.SLOT_ID_SINGLE));
//2013-01-30 for Gemini plus 2.0
SimDetailInfo detailInfo = Global.getSimInfoBySlot(SimDetailInfo.SLOT_ID_SINGLE);
detailInfo.setAccessible(mSysInfoProxy.isSimAccessible());
rsp.getSlotInfoList().add(detailInfo);
Debugger.logD(this.getClassName(), "handle",
new Object[] { cmd }, "SINGLE_SIM | SIM:"
+ rsp.isSimAccessible() + " | SIM1:"
+ rsp.isSim1Accessible() + " | SIM2:"
+ rsp.isSim2Accessible());
}
rsp.setSimInfoList(Global.getAllSIMList());
// Battery
if (mBR != null) {
rsp.setBatteryLevel(mBR.getBatteryLevel());
rsp.setBatteryScale(mBR.getBatteryScale());
} else {
rsp.setBatteryLevel(0);
rsp.setBatteryScale(0);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof GetStorageReq) {
GetStorageRsp rsp = new GetStorageRsp(reqToken);
// Get data and fill them in response command
// Storage
if (SystemInfoProxy.isSdMounted()) {
rsp.setSdMounted(true);
rsp.setSdWriteable(SystemInfoProxy.isSdWriteable());
rsp.setSdCardPath(SystemInfoProxy.getSdPath());
rsp.setSdCardTotalSpace(SystemInfoProxy.getSdTotalSpace());
rsp.setSdCardAvailableSpace(SystemInfoProxy
.getSdAvailableSpace());
} else {
rsp.setSdMounted(false);
rsp.setSdWriteable(false);
rsp.setSdCardPath(null);
rsp.setSdCardTotalSpace(-1);
rsp.setSdCardAvailableSpace(-1);
}
rsp.setInternalTotalSpace(SystemInfoProxy
.getInternalTotalSpace());
rsp.setInternalAvailableSpace(SystemInfoProxy
.getInternalAvailableSpace());
// Send response command or append it to batch
onRespond(rsp);
} else {
return false;
}
return true;
}
/**
* Handle commands of 'Contacts' feature.
*
* @param cmd
* Command to handle.
* @return True if command is handled, false if not.
*/
public boolean handleContactsFeatures(BaseCommand cmd) {
final int reqToken = cmd.getToken();
if (cmd instanceof ContactsBatchReq) {
mCommandBatch = new ContactsBatchRsp(reqToken);
ContactsBatchReq reqContactsBatch = (ContactsBatchReq) cmd;
int i = 0;
mResponseState = RSP_ST_APPEND_BATCH;
// Get data and fill them in response command
for (BaseCommand innerCmd : reqContactsBatch.getCommands()) {
if (++i == reqContactsBatch.getCommands().size()) {
// It's the last command in batch, we can send out
// the response batch now
mResponseState = RSP_ST_SEND_BATCH;
}
handle(innerCmd);
}
mResponseState = RSP_ST_SEND_SINGLE;
} else if (cmd instanceof GetDetailedContactReq) {
GetDetailedContactRsp rsp = new GetDetailedContactRsp(reqToken);
// Get data and fill them in response command
GetDetailedContactReq req = (GetDetailedContactReq) cmd;
RawContact detailedContact = mContactsProxy.getContact(req
.getContactId(), true);
if (null != detailedContact) {
rsp.setDetailedContact(detailedContact, Global
.getByteBuffer(), Config.VERSION_CODE);
} else {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof AddGroupReq) {
AddGroupRsp rsp = new AddGroupRsp(reqToken);
// Get data and fill them in response command
AddGroupReq req = (AddGroupReq) cmd;
Group group = req.getGroup();
long insertedGroupId = mContactsProxy.insertGroup(group);
rsp.setInsertedId(insertedGroupId);
if (insertedGroupId == DatabaseRecordEntity.ID_NULL) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
rsp.setResult(group);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof AddContactReq) {
AddContactRsp rsp = new AddContactRsp(reqToken);
// Get data and fill them in response command
AddContactReq req = (AddContactReq) cmd;
// For PC side
rsp.setFromFeature(req.getFromFeature());
RawContact contact = req.getContact();
long result = mContactsProxy.insertContact(contact, true);
if (result < 0) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
rsp.setInsertedId(result);
} else {
rsp.setStatusCode(ResponseCommand.SC_OK);
rsp.setInsertedId(result);
rsp.setResult(mContactsProxy.getContact(result, true));
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof AddSimContactReq) {
AddSimContactRsp rsp = new AddSimContactRsp(reqToken);
// Get data and fill them in response command
AddSimContactReq req = (AddSimContactReq) cmd;
BaseContact contact = req.getContact();
long insertedSimContactId = mContactsProxy.insertSimContact(
contact.getDisplayName(), contact.getPrimaryNumber(),
contact.getStoreLocation());
if (insertedSimContactId == DatabaseRecordEntity.ID_NULL) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof AddContactDataReq) {
AddContactDataRsp rsp = new AddContactDataRsp(reqToken);
// Get data and fill them in response command
AddContactDataReq req = (AddContactDataReq) cmd;
ContactData contactData = req.getData();
long insertedContactDataId = mContactsProxy.insertContactData(
contactData, true);
rsp.setInsertedId(insertedContactDataId);
if (insertedContactDataId == DatabaseRecordEntity.ID_NULL) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
rsp.setResult(contactData);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof AddGroupMembershipReq) {
AddGroupMembershipRsp rsp = new AddGroupMembershipRsp(reqToken);
// Get data and fill them in response command
AddGroupMembershipReq req = (AddGroupMembershipReq) cmd;
Group group = req.getGroupEntry();
int[] simIndex = null;
if (FeatureOptionControl.CONTACT_N_USIMGROUP != 0) {
simIndex = req.getSimIndexes();
}
if (simIndex == null
|| FeatureOptionControl.CONTACT_N_USIMGROUP == 0) {
rsp.setInsertedIds(mContactsProxy.insertGroupMembership(req
.getContactIds(), req.getGroupId()));
} else {
rsp.setInsertedIds(mContactsProxy
.insertGroupMembership(req.getContactIds(), req
.getGroupId(), group, simIndex));
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof UpdateGroupReq) {
UpdateGroupRsp rsp = new UpdateGroupRsp(reqToken);
// Get data and fill them in response command
UpdateGroupReq req = (UpdateGroupReq) cmd;
Group group = req.getNewOne();
String oldName = null;
if (FeatureOptionControl.CONTACT_N_USIMGROUP != 0) {
oldName = req.getOldName();
}
int updateGroupCount = 0;
if (oldName == null
|| FeatureOptionControl.CONTACT_N_USIMGROUP == 0) {
updateGroupCount = mContactsProxy.updateGroup(req
.getUpdateId(), group);
} else {
updateGroupCount = mContactsProxy.updateGroup(req
.getUpdateId(), group, oldName);
}
if (updateGroupCount < 1) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof UpdateRawContactReq) {
UpdateRawContactRsp rsp = new UpdateRawContactRsp(reqToken);
// Get data and fill them in response command
UpdateRawContactReq req = (UpdateRawContactReq) cmd;
RawContact contact = req.getNewOne();
int updateRawContactCount = mContactsProxy.updateContact(req
.getUpdateId(), RawContact.SOURCE_NONE, null, null,
contact, false/* Do not update PIM */);
if (updateRawContactCount < 1) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof UpdateDetailedContactReq) {
UpdateDetailedContactRsp rsp = new UpdateDetailedContactRsp(
reqToken);
// Get data and fill them in response command
UpdateDetailedContactReq req = (UpdateDetailedContactReq) cmd;
RawContact contact = req.getNewOne();
// int updateDetailedContactCount =
// mContactsProxy.updateContact(
// req.getUpdateId(), req.getSourceLocation(),
// req.getSimName(), req.getSimNumber(), contact,
// true/*Update PIM data*/);
int updateDetailedContactCount = mContactsProxy
.updateContact(req.getUpdateId(), req
.getSourceLocation(), req.getSimName(), req
.getSimNumber(), req.getSimEmail(), contact,
true/* Update PIM data */);
if (updateDetailedContactCount < 1) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
rsp.setResult(mContactsProxy.getContact(req.getUpdateId(),
true));
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof UpdateSimContactReq) {
UpdateSimContactRsp rsp = new UpdateSimContactRsp(reqToken);
// Get data and fill them in response command
UpdateSimContactReq req = (UpdateSimContactReq) cmd;
int updateSimContactCount = mContactsProxy.updateSimContact(req
.getOldName(), req.getOldNumber(), req.getNewOne()
.getDisplayName(), req.getNewOne().getPrimaryNumber(),
req.getSimId());
if (updateSimContactCount < 1) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof UpdateContactDataReq) {
UpdateContactDataRsp rsp = new UpdateContactDataRsp(reqToken);
// Get data and fill them in response command
UpdateContactDataReq req = (UpdateContactDataReq) cmd;
ContactData contactData = req.getNewOne();
int updateContactDataCount = mContactsProxy.updateContactData(
req.getUpdateId(), contactData, true);
if (updateContactDataCount < 1) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof DeleteGroupReq) {
DeleteGroupRsp rsp = new DeleteGroupRsp(reqToken);
// Get data and fill them in response command
DeleteGroupReq req = (DeleteGroupReq) cmd;
ArrayList<Group> groups = null;
if (FeatureOptionControl.CONTACT_N_USIMGROUP != 0) {
groups = req.getGroups();
}
if (groups == null
|| FeatureOptionControl.CONTACT_N_USIMGROUP == 0) {
rsp.setDeleteResults(mContactsProxy.deleteGroup(req
.getDeleteIds()));
} else {
rsp.setDeleteResults(mContactsProxy.deleteGroup(req
.getDeleteIds(), groups));
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof DeleteContactReq) {
DeleteContactRsp rsp = new DeleteContactRsp(reqToken);
// Get data and fill them in response command
DeleteContactReq req = (DeleteContactReq) cmd;
// rsp.setDeleteResults(mContactsProxy.deleteContacts(
// req.getDeleteIds(), false, req.getSourceLocation(),
// req.getSimNames(), req.getSimNumbers()));
rsp.setDeleteResults(mContactsProxy
.deleteContacts(req.getDeleteIds(), false, req
.getSourceLocation(), req.getSimNames(), req
.getSimNumbers(), req.getSimEmails()));
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof DeleteAllContactsReq) {
DeleteAllContactsRsp rsp = new DeleteAllContactsRsp(reqToken);
// Get data and fill them in response command
rsp.setDeleteCount(mContactsProxy.deleteAllContacts(true));
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof DeleteSimContactReq) {
DeleteSimContactRsp rsp = new DeleteSimContactRsp(reqToken);
// Get data and fill them in response command
DeleteSimContactReq req = (DeleteSimContactReq) cmd;
rsp.setDeleteResults(mContactsProxy.deleteSimContacts(req
.getNames(), req.getNumbers(), req.getSimId()));
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof DeleteContactDataReq) {
DeleteContactDataRsp rsp = new DeleteContactDataRsp(reqToken);
// Get data and fill them in response command
DeleteContactDataReq req = (DeleteContactDataReq) cmd;
Group group = req.getGroupEntry();
int[] simIndex = null;
simIndex = req.getSimIndexes();
if (simIndex == null || FeatureOptionControl.CONTACT_N_USIMGROUP == 0) {
rsp.setDeleteResults(mContactsProxy.deleteContactData(req
.getDeleteIds()));
} else {
rsp.setDeleteResults(mContactsProxy.deleteContactData(
req.getDeleteIds(), req.getGroupId(),
group, simIndex));
}
// rsp.setDeleteResults(mContactsProxy.deleteContactData(
// req.getDeleteIds()));
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof AsyncGetAllGroupsReq) {
mContactsProxy.asyncGetAllGroups(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
AsyncGetAllGroupsRsp rsp = new AsyncGetAllGroupsRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof AsyncGetAllSimContactsReq) {
final boolean simAccesible = mSysInfoProxy.isSimAccessible();
if (simAccesible) {
mContactsProxy.asyncGetAllSimContacts(
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
AsyncGetAllSimContactsRsp rsp = new AsyncGetAllSimContactsRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to
// batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else {
AsyncGetAllSimContactsRsp rsp = new AsyncGetAllSimContactsRsp(
reqToken);
rsp.setRaw(null);
rsp.setProgress(0);
rsp.setTotal(0);
// Send response command or append it to batch
onRespond(rsp);
}
} else if (cmd instanceof AsyncGetAllRawContactsReq) {
mContactsProxy.asyncGetAllRawContacts(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
AsyncGetAllRawContactsRsp rsp = new AsyncGetAllRawContactsRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof AsyncGetAllContactDataReq) {
mContactsProxy.asyncGetAllContactData(
((AsyncGetAllContactDataReq) cmd)
.getRequestingDataTypes(),
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
AsyncGetAllContactDataRsp rsp = new AsyncGetAllContactDataRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof ImportDetailedContactsReq) {
ImportDetailedContactsReq req = (ImportDetailedContactsReq) cmd;
mContactsProxy.fastImportDetailedContacts(
// raw bytes of importing detailed contacts
req.getRaw(),
// Raw contact consumer
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
ImportDetailedContactsRsp rsp = new ImportDetailedContactsRsp(
reqToken);
rsp
.setPhase(ImportDetailedContactsRsp.PHASE_RAW_CONTACT);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
},
// Contact data consumer
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
ImportDetailedContactsRsp rsp = new ImportDetailedContactsRsp(
reqToken);
rsp
.setPhase(ImportDetailedContactsRsp.PHASE_CONTACT_DATA);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
},
// output byte buffer
Global.getByteBuffer());
} else {
return false;
}
return true;
}
/**
* Handle commands of 'Messages' feature.
*
* @param cmd
* Command to handle.
* @return True if command is handled, false if not.
*/
public boolean handleMessageFeatures(BaseCommand cmd) {
final int reqToken = cmd.getToken();
if (cmd instanceof MessageBatchReq) {
mCommandBatch = new MessageBatchRsp(reqToken);
MessageBatchReq reqMessageBatch = (MessageBatchReq) cmd;
int i = 0;
mResponseState = RSP_ST_APPEND_BATCH;
// Get data and fill them in response command
for (BaseCommand innerCmd : reqMessageBatch.getCommands()) {
if (++i == reqMessageBatch.getCommands().size()) {
// It's the last command in batch, we can send out
// the response batch now
mResponseState = RSP_ST_SEND_BATCH;
}
handle(innerCmd);
}
mResponseState = RSP_ST_SEND_SINGLE;
} else if (cmd instanceof AsyncGetPhoneListReq) {
mMessageProxy.asyncGetPhoneList(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
AsyncGetPhoneListRsp rsp = new AsyncGetPhoneListRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof AsyncGetAllSmsReq) {
mMessageProxy.asyncGetAllSms(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
AsyncGetAllSmsRsp rsp = new AsyncGetAllSmsRsp(reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof AsyncGetAllMmsReq) {
mMessageProxy.asyncGetAllMms(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
AsyncGetAllMmsRsp rsp = new AsyncGetAllMmsRsp(reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
// get MMS resource
} else if (cmd instanceof GetMmsResourceReq) {
final long id = ((GetMmsResourceReq) cmd).getMmsId();
mMessageProxy.getOneMmsResource(new IRawBlockConsumer() {
public void consume(byte[] block, int blockNo, int totalNo) {
GetMmsResourceRsp rsp = new GetMmsResourceRsp(reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
rsp.setMmsId(id);
onRespond(rsp);
}
}, Global.getByteBuffer(), id);
} else if (cmd instanceof GetMmsDataReq) {
final boolean isBackup = ((GetMmsDataReq) cmd).getIsBackup();
LinkedList<Long> list = ((GetMmsDataReq) cmd).getImportList();
mMessageProxy.getMmsData(new IRawBlockConsumer() {
public void consume(byte[] block, int blockNo, int totalNo) {
GetMmsDataRsp rsp = new GetMmsDataRsp(reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
rsp.setIsBackup(isBackup);
onRespond(rsp);
}
}, Global.getByteBuffer(), isBackup, list);
} else if (cmd instanceof ImportSmsReq) {
ImportSmsRsp rsp = new ImportSmsRsp(reqToken);
// Get data and fill them in response command
ImportSmsReq req = (ImportSmsReq) cmd;
ArrayList<Long> temp = new ArrayList<Long>();
mMulMessageOb.stop();
long[] insertedIds = mMessageProxy
.importSms(req.getRaw(), temp);
if (null == insertedIds) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
if (null != temp) {
long[] threadIds = new long[temp.size()];
for (int i = 0; i < threadIds.length; i++) {
threadIds[i] = temp.get(i);
}
rsp.setThreadIds(threadIds);
}
rsp.setInsertedIds(insertedIds);
}
// Send response command or append it to batch
onRespond(rsp);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mMulMessageOb.start();
} else if (cmd instanceof ImportMmsReq) {
ImportMmsRsp rsp = new ImportMmsRsp(reqToken);
// Get data and fill them in response command
ImportMmsReq req = (ImportMmsReq) cmd;
ArrayList<Long> temp = new ArrayList<Long>();
if (mMulMessageOb.getMaxMmsId() == 0) {
/** No mms in db, get mms id thought insert */
Debugger.logW(new Object[] { cmd }, ">>pdu table is null");
mMulMessageOb.onSelfChangeStart();
long maxMmsId = mMessageProxy.getMaxMmsIdByInsert();
/** Wait 1s to make sure MulMessageob get the right max mms id */
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mMulMessageOb.onSelfChangeDone();
mMulMessageOb.setMaxMmsId(maxMmsId);
}
long[] insertedIds = mMessageProxy.importMms(req.getRaw(), temp);
if (null == insertedIds) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
if (null != temp) {
long[] threadIds = new long[temp.size()];
for (int i = 0; i < threadIds.length; i++) {
threadIds[i] = temp.get(i);
}
rsp.setThreadIds(threadIds);
}
rsp.setInsertedIds(insertedIds);
}
// Send response command or append it to batch
if (req.isIsLastImport()) {
onRespond(rsp);
}
} else if (cmd instanceof ClearMessageBoxReq) {
ClearMessageBoxRsp rsp = new ClearMessageBoxRsp(reqToken);
// Get data and fill them in response command
ClearMessageBoxReq req = (ClearMessageBoxReq) cmd;
rsp.setDeletedCount(mMessageProxy.clearMessageBox(req.getBox(),
req.isKeepLockedMessage()));
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof DeleteAllMessagesReq) {
DeleteAllMessagesRsp rsp = new DeleteAllMessagesRsp(reqToken);
// Get data and fill them in response command
DeleteAllMessagesReq req = (DeleteAllMessagesReq) cmd;
rsp.setDeletedCount(mMessageProxy.deleteAllMessages(req
.isKeepLockedMessage()));
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof DeleteMessageReq) {
DeleteMessageRsp rsp = new DeleteMessageRsp(reqToken);
// Get data and fill them in response command
DeleteMessageReq req = (DeleteMessageReq) cmd;
rsp.setDeleteSmsCount(mMessageProxy.deleteSms(req
.getDeleteSmsIds(), true, req.getDeleteSmsDates()));
rsp.setDeleteMmsCount(mMessageProxy.deleteMms(req
.getDeleteMmsIds(), true, req.getDeleteMmsDates()));
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof MarkMessageAsReadReq) {
MarkMessageAsReadRsp rsp = new MarkMessageAsReadRsp(reqToken);
// Get data and fill them in response command
MarkMessageAsReadReq req = (MarkMessageAsReadReq) cmd;
rsp.setUpdateSmsCount(mMessageProxy.markSmsAsRead(req
.getUpdateSmsIds(), req.isRead()));
rsp.setUpdateMmsCount(mMessageProxy.markMmsAsRead(req
.getUpdateMmsIds(), req.isRead()));
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof LockMessageReq) {
LockMessageRsp rsp = new LockMessageRsp(reqToken);
// Get data and fill them in response command
LockMessageReq req = (LockMessageReq) cmd;
rsp.setUpdateSmsCount(mMessageProxy.lockSms(req
.getUpdateSmsIds(), req.isLocked()));
rsp.setUpdateMmsCount(mMessageProxy.lockMms(req
.getUpdateMmsIds(), req.isLocked()));
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof SaveSmsDraftReq) {
SaveSmsDraftRsp rsp = new SaveSmsDraftRsp(reqToken);
// Get data and fill them in response command
SaveSmsDraftReq req = (SaveSmsDraftReq) cmd;
Sms result = mMessageProxy.saveSmsDraft(req.getBody(), req
.getRecipients());
if (null != result) {
rsp.setInsertedId(result.getId());
rsp.setThreadId(result.getThreadId());
rsp.setDate(result.getDate());
} else {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof SendSmsReq) {
SendSmsRsp rsp = new SendSmsRsp(reqToken);
// Get data and fill them in response command
SendSmsReq req = (SendSmsReq) cmd;
rsp.setSimId(req.getSimId());
mSmsSender.pause();
Sms[] results = mMessageProxy.sendSms(req.getBody(), req
.getRecipients(), mSmsSender, req.getSimId());
if (null == results) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
long[] insertedIds = new long[results.length];
long threadId = DatabaseRecordEntity.ID_NULL;
long[] dates = new long[results.length];
for (int i = 0; i < results.length; i++) {
insertedIds[i] = results[i].getId();
threadId = results[i].getThreadId();
dates[i] = results[i].getDate();
}
rsp.setInsertedIds(insertedIds);
rsp.setThreadId(threadId);
rsp.setDates(dates);
}
// Send response command or append it to batch
onRespond(rsp);
mSmsSender.resume();
} else if (cmd instanceof MoveMessageToBoxReq) {
MoveMessageToBoxRsp rsp = new MoveMessageToBoxRsp(reqToken);
// Get data and fill them in response command
MoveMessageToBoxReq req = (MoveMessageToBoxReq) cmd;
int smsCount = mMessageProxy.moveSmsToBox(
req.getUpdateSmsIds(), true, req.getUpdateSmsDates(),
req.getBox());
rsp.setUpdateSmsCount(smsCount);
int mmsCount = mMessageProxy.moveMmsToBox(
req.getUpdateSmsIds(), true, req.getUpdateSmsDates(),
req.getBox());
rsp.setUpdateMmsCount(mmsCount);
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof ResendSmsReq) {
ResendSmsRsp rsp = new ResendSmsRsp(reqToken);
// Get data and fill them in response command
ResendSmsReq req = (ResendSmsReq) cmd;
rsp.setSimId(req.getSimId());
mSmsSender.pause();
Sms result = mMessageProxy.resendSms(req.getId(),
req.getDate(), req.getBody(), req.getRecipient(),
mSmsSender, req.getSimId());
if (null == result) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
rsp.setErrorMessage(ResendSmsRsp.ERR_SMS_NOT_EXIST);
} else {
rsp.setDate(result.getDate());
}
// Send response command or append it to batch
onRespond(rsp);
mSmsSender.resume();
} else if (cmd instanceof BeforeImportMmsReq) {
BeforeImportMmsRsp rsp = new BeforeImportMmsRsp(reqToken);
// Send response command or append it to batch
onRespond(rsp);
} else {
return false;
}
return true;
}
/**
* Handle commands of 'Application' feature.
*
* @param cmd
* Command to handle.
* @return True if command is handled, false if not.
*/
public boolean handleApplicationFeatures(BaseCommand cmd) {
final int reqToken = cmd.getToken();
if (cmd instanceof AsyncGetAllAppInfoReq) {
mApplicationProxy.fastGetAllApplications(
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
AsyncGetAllAppInfoRsp rsp = new AsyncGetAllAppInfoRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer(),
((AsyncGetAllAppInfoReq) cmd).getDestIconWidth(),
((AsyncGetAllAppInfoReq) cmd).getDestIconHeight());
} else {
return false;
}
return true;
}
/**
* Handle commands of 'Outlook Sync' feature.
*
* @param cmd
* Command to handle.
* @return True if command is handled, false if not.
*/
public boolean handleSyncFeatures(BaseCommand cmd) {
final int reqToken = cmd.getToken();
if (cmd instanceof ContactsSyncStartReq) {
ContactsSyncStartRsp rsp = new ContactsSyncStartRsp(reqToken);
// Get data and fill them in response command
rsp.setSyncNeedReinit(mContactsProxy.isSyncNeedReinit());
rsp.setLastSyncDate(mContactsProxy.getLastSyncDate());
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof ContactsSyncOverReq) {
ContactsSyncOverRsp rsp = new ContactsSyncOverRsp(reqToken);
// Get data and fill them in response command
ContactsSyncOverReq req = (ContactsSyncOverReq) cmd;
mContactsProxy.updateSyncDate(req.getSyncDate());
rsp
.setContactsCount(mContactsProxy
.getAvailableContactsCount());
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof ContactsSlowSyncInitReq) {
ContactsSlowSyncInitRsp rsp = new ContactsSlowSyncInitRsp(
reqToken);
// Get data and fill them in response command
rsp.setCurrentMaxId(mContactsProxy.getMaxRawContactsId());
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof ContactsSlowSyncAddDetailedContactsReq) {
ContactsSlowSyncAddDetailedContactsRsp rsp = new ContactsSlowSyncAddDetailedContactsRsp(
reqToken);
// Get data and fill them in response command
// Insert new raw contacts and get their sync flags after
byte[] detailedContactsInRaw = ((ContactsSlowSyncAddDetailedContactsReq) cmd)
.getRaw();
byte[] results = mContactsProxy
.slowSyncAddDetailedContacts(detailedContactsInRaw);
if (null == results) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
rsp.setRaw(results);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof ContactsSlowSyncGetAllRawContactsReq) {
long contactIdLimit = ((ContactsSlowSyncGetAllRawContactsReq) cmd)
.getContactIdLimit();
mContactsProxy.slowSyncGetAllRawContacts(contactIdLimit,
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
ContactsSlowSyncGetAllRawContactsRsp rsp = new ContactsSlowSyncGetAllRawContactsRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof ContactsSlowSyncGetAllContactDataReq) {
long contactIdLimit = ((ContactsSlowSyncGetAllContactDataReq) cmd)
.getContactIdLimit();
mContactsProxy.slowSyncGetAllContactData(contactIdLimit,
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
ContactsSlowSyncGetAllContactDataRsp rsp = new ContactsSlowSyncGetAllContactDataRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof ContactsFastSyncInitReq) {
mContactsProxy.fastSyncGetAllSyncFlags(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
ContactsFastSyncInitRsp rsp = new ContactsFastSyncInitRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof ContactsFastSyncGetRawContactsReq) {
long[] requestedContactsIds = ((ContactsFastSyncGetRawContactsReq) cmd)
.getRequestedContactIds();
mContactsProxy.fastSyncGetRawContacts(requestedContactsIds,
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
ContactsFastSyncGetRawContactsRsp rsp = new ContactsFastSyncGetRawContactsRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof ContactsFastSyncGetContactDataReq) {
long[] requestedContactsIds = ((ContactsFastSyncGetContactDataReq) cmd)
.getRequestedContactIds();
mContactsProxy.fastSyncGetContactData(requestedContactsIds,
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
ContactsFastSyncGetContactDataRsp rsp = new ContactsFastSyncGetContactDataRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof ContactsFastSyncAddDetailedContactsReq) {
ContactsFastSyncAddDetailedContactsRsp rsp = new ContactsFastSyncAddDetailedContactsRsp(
reqToken);
// Get data and fill them in response command
// Insert new raw contacts and get their sync flags after
byte[] detailedContactsInRaw = ((ContactsFastSyncAddDetailedContactsReq) cmd)
.getRaw();
byte[] results = mContactsProxy
.fastSyncAddDetailedContacts(detailedContactsInRaw);
if (null == results) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
rsp.setRaw(results);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof ContactsFastSyncUpdateDetailedContactsReq) {
ContactsFastSyncUpdateDetailedContactsRsp rsp = new ContactsFastSyncUpdateDetailedContactsRsp(
reqToken);
// Get data and fill them in response command
// Insert new raw contacts and get their sync flags after
byte[] detailedContactsInRaw = ((ContactsFastSyncUpdateDetailedContactsReq) cmd)
.getRaw();
byte[] results = mContactsProxy
.fastSyncUpdateDetailedContacts(detailedContactsInRaw);
if (null == results) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
rsp.setRaw(results);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof ContactsFastSyncDeleteContactsReq) {
ContactsFastSyncDeleteContactsRsp rsp = new ContactsFastSyncDeleteContactsRsp(
reqToken);
// Get data and fill them in response command
ContactsFastSyncDeleteContactsReq req = (ContactsFastSyncDeleteContactsReq) cmd;
rsp.setDeleteCount(mContactsProxy
.fastDeleteContactsSourcedOnPhone(req.getDeleteIds(),
false));
// Send response command or append it to batch
onRespond(rsp);
} else {
return false;
}
return true;
}
/**
* Handle commands of 'Calendar' feature.
*
* @param cmd
* Command to handle.
* @return True if command is handled, false if not.
*/
public boolean handleCalendarFeatures(BaseCommand cmd) {
final int reqToken = cmd.getToken();
if (cmd instanceof CalendarBatchReq) {
mCommandBatch = new CalendarBatchRsp(reqToken);
CalendarBatchReq reqCalendarBatch = (CalendarBatchReq) cmd;
int i = 0;
mResponseState = RSP_ST_APPEND_BATCH;
// Get data and fill them in response command
for (BaseCommand innerCmd : reqCalendarBatch.getCommands()) {
if (++i == reqCalendarBatch.getCommands().size()) {
// It's the last command in batch, we can send out
// the response batch now
mResponseState = RSP_ST_SEND_BATCH;
}
handle(innerCmd);
}
mResponseState = RSP_ST_SEND_SINGLE;
}
if (cmd instanceof AddEventReq) {
AddEventRsp rsp = new AddEventRsp(reqToken);
AddEventReq req = (AddEventReq) cmd;
rsp.setFromFeature(req.getFromFeature());
CalendarEvent event = req.getEvent();
long insertedEventId = mCalendarProxy.insertEvent(event);
rsp.setInsertedId(insertedEventId);
if (insertedEventId == DatabaseRecordEntity.ID_NULL) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
rsp.setResult(mCalendarProxy.getEvent(insertedEventId,
true, true));
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof DeleteEventReq) {
DeleteEventRsp rsp = new DeleteEventRsp(reqToken);
// Get data and fill them in response command
DeleteEventReq req = (DeleteEventReq) cmd;
rsp.setDeleteResults(mCalendarProxy.deleteEvents(req
.getDeleteIds()));
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof GetCalendarsReq) {
mCalendarProxy.getCalendars(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
GetCalendarsRsp rsp = new GetCalendarsRsp(reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof GetEventsReq) {
mCalendarProxy.getEvents(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
GetEventsRsp rsp = new GetEventsRsp(reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof UpdateEventReq) {
UpdateEventRsp rsp = new UpdateEventRsp(reqToken);
// Get data and fill them in response command
UpdateEventReq req = (UpdateEventReq) cmd;
CalendarEvent event = req.getNewOne();
int updateGroupCount = mCalendarProxy.updateEvent(req
.getUpdateId(), event);
if (updateGroupCount < 1) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof GetRemindersReq) {
mCalendarProxy.getReminders(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
GetRemindersRsp rsp = new GetRemindersRsp(reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof GetAttendeesReq) {
mCalendarProxy.getAttendees(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
GetAttendeesRsp rsp = new GetAttendeesRsp(reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else {
return false;
}
return true;
}
/**
* Handle commands of 'Outlook Calendar Sync' feature.
*
* @param cmd
* Command to handle.
* @return True if command is handled, false if not.
*/
public boolean handleCalendarSyncFeatures(BaseCommand cmd) {
final int reqToken = cmd.getToken();
if (cmd instanceof CalendarSyncStartReq) {
CalendarSyncStartRsp rsp = new CalendarSyncStartRsp(reqToken);
// Get data and fill them in response command
rsp.setSyncNeedReinit(mCalendarProxy.isSyncNeedReinit());
rsp.setLastSyncDate(mCalendarProxy.getLastSyncDate());
rsp.setLocalAccountId(mCalendarProxy.getLocalAccountId());
rsp.setSyncAble(mCalendarProxy.isSyncAble());
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof CalendarSyncOverReq) {
CalendarSyncOverRsp rsp = new CalendarSyncOverRsp(reqToken);
// Get data and fill them in response command
CalendarSyncOverReq req = (CalendarSyncOverReq) cmd;
mCalendarProxy.updateSyncDate(req.getSyncDate());
rsp.setEventsCount(mCalendarProxy.getPcSyncEventsCount());
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof CalendarSlowSyncInitReq) {
CalendarSlowSyncInitRsp rsp = new CalendarSlowSyncInitRsp(
reqToken);
// Get data and fill them in response command
rsp.setCurrentMaxId(mCalendarProxy.getMaxEventId());
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof CalendarSlowSyncGetAllEventsReq) {
long eventIdLimit = ((CalendarSlowSyncGetAllEventsReq) cmd)
.getEventIdLimit();
mCalendarProxy.slowSyncGetAllEvents(eventIdLimit,
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
CalendarSlowSyncGetAllEventsRsp rsp = new CalendarSlowSyncGetAllEventsRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof CalendarSlowSyncGetAllRemindersReq) {
long eventIdLimit = ((CalendarSlowSyncGetAllRemindersReq) cmd)
.getEventIdLimit();
mCalendarProxy.slowSyncGetAllReminders(eventIdLimit,
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
CalendarSlowSyncGetAllRemindersRsp rsp = new CalendarSlowSyncGetAllRemindersRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof CalendarSlowSyncGetAllAttendeesReq) {
long eventIdLimit = ((CalendarSlowSyncGetAllAttendeesReq) cmd)
.getEventIdLimit();
mCalendarProxy.slowSyncGetAllAttendees(eventIdLimit,
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
CalendarSlowSyncGetAllAttendeesRsp rsp = new CalendarSlowSyncGetAllAttendeesRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof CalendarSlowSyncAddEventsReq) {
CalendarSlowSyncAddEventsRsp rsp = new CalendarSlowSyncAddEventsRsp(
reqToken);
// Get data and fill them in response command
// Insert new raw contacts and get their sync flags after
byte[] detailedEventsInRaw = ((CalendarSlowSyncAddEventsReq) cmd)
.getRaw();
byte[] results = mCalendarProxy
.slowSyncAddEvents(detailedEventsInRaw);
if (null == results) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
rsp.setRaw(results);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof CalendarFastSyncInitReq) {
mCalendarProxy.fastSyncGetAllSyncFlags(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
CalendarFastSyncInitRsp rsp = new CalendarFastSyncInitRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof CalendarFastSyncGetEventsReq) {
long[] requestedEventsIds = ((CalendarFastSyncGetEventsReq) cmd)
.getRequestedEventIds();
mCalendarProxy.fastSyncGetEvents(requestedEventsIds,
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
CalendarFastSyncGetEventsRsp rsp = new CalendarFastSyncGetEventsRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof CalendarFastSyncGetRemindersReq) {
long[] requestedEventsIds = ((CalendarFastSyncGetRemindersReq) cmd)
.getRequestedEventIds();
mCalendarProxy.fastSyncGetReminders(requestedEventsIds,
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
CalendarFastSyncGetRemindersRsp rsp = new CalendarFastSyncGetRemindersRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof CalendarFastSyncGetAttendeesReq) {
long[] requestedEventsIds = ((CalendarFastSyncGetAttendeesReq) cmd)
.getRequestedEventIds();
mCalendarProxy.fastSyncGetAttendees(requestedEventsIds,
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
CalendarFastSyncGetAttendeesRsp rsp = new CalendarFastSyncGetAttendeesRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof CalendarFastSyncAddEventsReq) {
CalendarFastSyncAddEventsRsp rsp = new CalendarFastSyncAddEventsRsp(
reqToken);
// Get data and fill them in response command
// Insert new events and get their sync flags after
byte[] eventsInRaw = ((CalendarFastSyncAddEventsReq) cmd)
.getRaw();
byte[] results = mCalendarProxy.fastSyncAddEvents(eventsInRaw);
if (null == results) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
rsp.setRaw(results);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof CalendarFastSyncDeleteEventsReq) {
CalendarFastSyncDeleteEventsRsp rsp = new CalendarFastSyncDeleteEventsRsp(
reqToken);
// Get data and fill them in response command
CalendarFastSyncDeleteEventsReq req = (CalendarFastSyncDeleteEventsReq) cmd;
rsp.setDeleteCount(mCalendarProxy.fastDeleteEvents(req
.getDeleteIds()));
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof CalendarFastSyncUpdateEventsReq) {
CalendarFastSyncUpdateEventsRsp rsp = new CalendarFastSyncUpdateEventsRsp(
reqToken);
// Get data and fill them in response command
// Insert new events and get their sync flags after
byte[] eventsInRaw = ((CalendarFastSyncUpdateEventsReq) cmd)
.getRaw();
byte[] results = mCalendarProxy
.fastSyncUpdateEvents(eventsInRaw);
if (null == results) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
rsp.setRaw(results);
}
// Send response command or append it to batch
onRespond(rsp);
} else {
return false;
}
return true;
}
/**
* Handle commands of 'Media Sync' feature.
*
* @param cmd
* Command to handle.
* @return True if command is handled, false if not.
*/
public boolean handleMediaFeatures(BaseCommand cmd) {
final int reqToken = cmd.getToken();
if (cmd instanceof GetContentDirectoriesReq) {
GetContentDirectoriesRsp rsp = new GetContentDirectoriesRsp(
reqToken);
// Get data and fill them in response command
MediaInfo[] result = mMediaProxy.getContentDirectories();
if (null == result) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
rsp.setDirectories(result);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof GetAllMediaFilesReq) {
GetAllMediaFilesRsp rsp = new GetAllMediaFilesRsp(reqToken);
// Get data and fill them in response command
GetAllMediaFilesReq req = (GetAllMediaFilesReq) cmd;
MediaInfo[] result = mMediaProxy.getFiles(req
.getRequestedContentTypes());
if (null == result) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
rsp.setFiles(result);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof RenameFilesReq) {
RenameFilesRsp rsp = new RenameFilesRsp(reqToken);
// Get data and fill them in response command
RenameFilesReq req = (RenameFilesReq) cmd;
boolean[] result = mMediaProxy.renameFiles(req.getOldPaths(),
req.getNewPaths());
if (null == result) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
rsp.setResults(result);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof MediaSyncOverReq) {
mMediaProxy.scan(MainService.this);
MediaSyncOverRsp rsp = new MediaSyncOverRsp(reqToken);
onRespond(rsp);
} else {
return false;
}
return true;
}
/**
* Handle commands of 'Bookmark Sync' feature.
*
* @param cmd
* Command to handle.
* @return True if command is handled, false if not.
*
* add by mtk54043 Yu.Chen
*/
public boolean handleBookmarkFeatures(BaseCommand cmd) {
final int reqToken = cmd.getToken();
if (cmd instanceof AsyncGetAllBookmarkInfoReq) {
AsyncGetAllBookmarkInfoRsp rspCmd = new AsyncGetAllBookmarkInfoRsp(
reqToken);
ArrayList<BookmarkData> mBookmarkDataList = new ArrayList<BookmarkData>();
ArrayList<BookmarkFolder> mBookmarkFolderList = new ArrayList<BookmarkFolder>();
mBookmarkProxy.asynGetAllBookmarks(mBookmarkDataList,
mBookmarkFolderList);
rspCmd.setmBookmarkDataList(mBookmarkDataList);
rspCmd.setmBookmarkFolderList(mBookmarkFolderList);
onRespond(rspCmd);
} else if (cmd instanceof AsyncInsertBookmarkReq) {
ArrayList<BookmarkData> mBookmarkDataList = ((AsyncInsertBookmarkReq) cmd)
.getBookmarkDataList();
ArrayList<BookmarkFolder> mBookmarkFolderList = ((AsyncInsertBookmarkReq) cmd)
.getBookmarkFolderList();
AsyncInsertBookmarkRsp rspCmd = new AsyncInsertBookmarkRsp(
reqToken);
// mBookmarkProxy.handleHistoryData(mBookmarkDataList);
mBookmarkProxy.insertBookmark(mBookmarkDataList,
mBookmarkFolderList);
// mBookmarkProxy.sendBroadcastToBrowser(MainService.this);
// MainService.this.sendBroadcast(new
// Intent("com.mediatek.apst.target.data.proxy.bookmark.sync"));
// Debugger.logI(new
// Object[]{cmd},"InsertBookmark_____SendBroadcastToBrowser");
onRespond(rspCmd);
} else if (cmd instanceof AsyncDeleteBookmarkReq) {
AsyncDeleteBookmarkRsp rspCmd = new AsyncDeleteBookmarkRsp(
reqToken);
mBookmarkProxy.deleteAll();
// mBookmarkProxy.sendBroadcastToBrowser(MainService.this);
// MainService.this.sendBroadcast(new
// Intent("com.mediatek.apst.target.data.proxy.bookmark.sync"));
// Debugger.logI(new
// Object[]{cmd},"DeleteBookmark_____SendBroadcastToBrowser");
onRespond(rspCmd);
} else {
return false;
}
return true;
}
/**
* Handle commands of 'Backup/Retore' feature.
*
* @param cmd
* Command to handle.
* @return True if command is handled, false if not.
*/
public boolean handleBackupFeatures(BaseCommand cmd) {
final int reqToken = cmd.getToken();
if (cmd instanceof GetAllGroupsForBackupReq) {
mContactsProxy.asyncGetAllGroups(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
GetAllGroupsForBackupRsp rsp = new GetAllGroupsForBackupRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof GetAllContsForBackupReq) {
mContactsProxy.asyncGetAllRawContactsForBackup(
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
GetAllContsForBackupRsp rsp = new GetAllContsForBackupRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer(), null, null);
} else if (cmd instanceof GetAllContsDataForBackupReq) {
mContactsProxy.asyncGetAllContactData(
((GetAllContsDataForBackupReq) cmd)
.getRequestingDataTypes(),
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
GetAllContsDataForBackupRsp rsp = new GetAllContsDataForBackupRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof GetPhoneListReq) {
mMessageProxy.asyncGetPhoneList(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
GetPhoneListRsp rsp = new GetPhoneListRsp(reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof DelAllContactsReq) {
DelAllContactsRsp rsp = new DelAllContactsRsp(reqToken);
// Delete all groups
mContactsProxy.deleteAllGroups();
// Get data and fill them in response command
rsp.setDeleteCount(mContactsProxy.deleteContactForBackup());
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof RestoreGroupReq) {
RestoreGroupReq req = (RestoreGroupReq) cmd;
RestoreGroupRsp rsp = new RestoreGroupRsp(reqToken);
rsp.setCount(mContactsProxy.updateGroupForRestore(req
.getGroupList()));
onRespond(rsp);
} else if (cmd instanceof RestoreContactsReq) {
RestoreContactsReq req = (RestoreContactsReq) cmd;
mContactsProxy.restoreDetailedContacts(
// raw bytes of importing detailed contacts
req.getRaw(),
// Raw contact consumer
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
RestoreContactsRsp rsp = new RestoreContactsRsp(
reqToken);
rsp
.setPhase(RestoreContactsRsp.PHASE_RAW_CONTACT);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
},
// Contact data consumer
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
RestoreContactsRsp rsp = new RestoreContactsRsp(
reqToken);
rsp
.setPhase(RestoreContactsRsp.PHASE_CONTACT_DATA);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
},
// output byte buffer
Global.getByteBuffer());
} else if (cmd instanceof GetAllSmsForBackupReq) {
mMessageProxy.asyncGetAllSms(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
GetAllSmsForBackupRsp rsp = new GetAllSmsForBackupRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof GetMmsDataForBackupReq) {
mMessageProxy.getMmsData(new IRawBlockConsumer() {
public void consume(byte[] block, int blockNo, int totalNo) {
GetMmsDataForBackupRsp rsp = new GetMmsDataForBackupRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
onRespond(rsp);
}
}, Global.getByteBuffer(), true, null);
} else if (cmd instanceof DelAllMsgsForBackupReq) {
DelAllMsgsForBackupRsp rsp = new DelAllMsgsForBackupRsp(
reqToken);
// Get data and fill them in response command
rsp.setDeletedCount(mMessageProxy.deleteAllMessages(false));
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof RestoreSmsReq) {
RestoreSmsRsp rsp = new RestoreSmsRsp(reqToken);
// Get data and fill them in response command
RestoreSmsReq req = (RestoreSmsReq) cmd;
ArrayList<Long> temp = new ArrayList<Long>();
mMulMessageOb.stop();
long[] insertedIds = mMessageProxy
.importSms(req.getRaw(), temp);
mMulMessageOb.start();
if (null == insertedIds) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
if (null != temp) {
long[] threadIds = new long[temp.size()];
for (int i = 0; i < threadIds.length; i++) {
threadIds[i] = temp.get(i);
}
rsp.setThreadIds(threadIds);
}
rsp.setInsertedIds(insertedIds);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof RestoreMmsReq) {
RestoreMmsRsp rsp = new RestoreMmsRsp(reqToken);
// Get data and fill them in response command
RestoreMmsReq req = (RestoreMmsReq) cmd;
ArrayList<Long> temp = new ArrayList<Long>();
mMulMessageOb.onSelfChangeStart();
if (mMulMessageOb.getMaxMmsId() == 0) {
/** No mms in db, get mms id thought insert */
Debugger.logW(new Object[] { cmd }, ">>restore start ,pdu table is null");
long maxMmsId = mMessageProxy.getMaxMmsIdByInsert();
/** Wait 1s to make sure MulMessageob get the right max mms id */
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mMulMessageOb.setMaxMmsId(maxMmsId);
}
long[] insertedIds = mMessageProxy.importMms(req.getRaw(), temp);
mMulMessageOb.onSelfChangeDone();
if (null == insertedIds) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
if (null != temp) {
long[] threadIds = new long[temp.size()];
for (int i = 0; i < threadIds.length; i++) {
threadIds[i] = temp.get(i);
}
rsp.setThreadIds(threadIds);
}
rsp.setInsertedIds(insertedIds);
}
// Send response command or append it to batch
if (req.isIsLastImport()) {
onRespond(rsp);
}
} else if (cmd instanceof GetEventsForBackupReq) {
mCalendarProxy.getEvents(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
GetEventsForBackupRsp rsp = new GetEventsForBackupRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof GetAttendeesForBackupReq) {
mCalendarProxy.getAttendees(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
GetAttendeesForBackupRsp rsp = new GetAttendeesForBackupRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof GetRemindersForBackupReq) {
mCalendarProxy.getReminders(new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo, int totalNo) {
GetRemindersForBackupRsp rsp = new GetRemindersForBackupRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer());
} else if (cmd instanceof DelAllCalendarReq) {
DelAllCalendarRsp rsp = new DelAllCalendarRsp(reqToken);
// Get data and fill them in response command
mCalendarProxy.deleteAll();
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof RestoreCalendarReq) {
RestoreCalendarReq req = (RestoreCalendarReq) cmd;
RestoreCalendarRsp rsp = new RestoreCalendarRsp(reqToken);
// Get data and fill them in response command
rsp.setInsertedCount(mCalendarProxy.insertAllEvents(req
.getEvent()));
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof GetAllBookmarkForBackupReq) {
GetAllBookmarkForBackupRsp rspCmd = new GetAllBookmarkForBackupRsp(
reqToken);
ArrayList<BookmarkData> mBookmarkDataList = new ArrayList<BookmarkData>();
ArrayList<BookmarkFolder> mBookmarkFolderList = new ArrayList<BookmarkFolder>();
mBookmarkProxy.asynGetAllBookmarks(mBookmarkDataList,
mBookmarkFolderList);
rspCmd.setmBookmarkDataList(mBookmarkDataList);
rspCmd.setmBookmarkFolderList(mBookmarkFolderList);
onRespond(rspCmd);
} else if (cmd instanceof DelAllBookmarkReq) {
DelAllBookmarkRsp rspCmd = new DelAllBookmarkRsp(reqToken);
mBookmarkProxy.deleteAll();
// mBookmarkProxy.sendBroadcastToBrowser(MainService.this);
// MainService.this.sendBroadcast(new
// Intent("com.mediatek.apst.target.data.proxy.bookmark.sync"));
// Debugger.logI(new Object[] { cmd },
// "DeleteBookmark_____SendBroadcastToBrowser");
onRespond(rspCmd);
} else if (cmd instanceof RestoreBookmarkReq) {
ArrayList<BookmarkData> mBookmarkDataList = ((RestoreBookmarkReq) cmd)
.getmBookmarkDataList();
ArrayList<BookmarkFolder> mBookmarkFolderList = ((RestoreBookmarkReq) cmd)
.getmBookmarkFolderList();
RestoreBookmarkRsp rspCmd = new RestoreBookmarkRsp(reqToken);
// mBookmarkProxy.handleHistoryData(mBookmarkDataList);
mBookmarkProxy.insertBookmark(mBookmarkDataList,
mBookmarkFolderList);
// mBookmarkProxy.sendBroadcastToBrowser(MainService.this);
// MainService.this.sendBroadcast(new
// Intent("com.mediatek.apst.target.data.proxy.bookmark.sync"));
// Debugger.logI(new Object[] { cmd },
// "InsertBookmark_____SendBroadcastToBrowser");
onRespond(rspCmd);
} else if (cmd instanceof MediaGetStorageStateReq) {
MediaGetStorageStateRsp rsp = new MediaGetStorageStateRsp(
reqToken);
boolean[] state = mSysInfoProxy.checkSDCardState();
Debugger.logI("SDCard1 state :" + state[0]);
Debugger.logI("SDCard2 state :" + state[1]);
rsp.setStorageState(state);
rsp.setmSdSwap(SystemInfoProxy.isSdSwap());
rsp.setmInternalStoragePath(SystemInfoProxy.getInternalStoragePathSD());
rsp.setmExternalStoragePath(SystemInfoProxy.getExternalStoragePath());
onRespond(rsp);
} else if (cmd instanceof MediaBackupReq) {
MediaBackupReq req = (MediaBackupReq) cmd;
MediaBackupRsp rsp = new MediaBackupRsp(reqToken);
ArrayList<String> oldPathsArray = new ArrayList<String>();
ArrayList<String> newPathsArray = new ArrayList<String>();
mMediaProxy.getFilesUnderDirs(req.getBackupPaths(),
oldPathsArray, newPathsArray);
Debugger.logI("oldPaths count: " + oldPathsArray.size());
Debugger.logI("newPaths count: " + newPathsArray.size());
String[] oldPaths = new String[oldPathsArray.size()];
String[] newPaths = new String[newPathsArray.size()];
for (int i = 0; i < oldPathsArray.size(); i++) {
oldPaths[i] = oldPathsArray.get(i);
newPaths[i] = newPathsArray.get(i) + "/APST_BACKUP0" + i;
Debugger.logI("oldPaths[" + i + "]: " + oldPaths[i]);
Debugger.logI("newPaths[" + i + "]: " + newPaths[i]);
}
rsp.setOldPaths(oldPaths);
rsp.setNewPaths(newPaths);
boolean[] resultRe = mMediaProxy.renameFiles(rsp.getOldPaths(),
rsp.getNewPaths());
if (null == resultRe) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
Debugger.logI("resultRe is not null");
}
// ArrayList<String> oldPathsArrayTest = new
// ArrayList<String>();
// ArrayList<String> newPathsArrayTest = new
// ArrayList<String>();
// mMediaProxy.getFilesEndWith("/mnt/sdcard", ".jpg",
// oldPathsArrayTest, newPathsArrayTest);
// String[] oldPaths = new String[oldPathsArrayTest.size()];
// String[] newPaths = new String[newPathsArrayTest.size()];
// for (int i = 0; i < oldPathsArrayTest.size(); i++) {
// oldPaths[i] = oldPathsArrayTest.get(i);
// newPaths[i] = newPathsArrayTest.get(i) + "/APST_BACKUP0" + i;
// Debugger.logI("oldPaths[" + i + "]: " + oldPaths[i]);
// Debugger.logI("newPaths[" + i + "]: " + newPaths[i]);
// }
// rsp.setOldPaths(oldPaths);
// rsp.setNewPaths(newPaths);
//
// boolean[] resultRe = mMediaProxy.renameFiles(rsp
// .getOldPaths(), rsp.getNewPaths());
// if (null == resultRe) {
// rsp.setStatusCode(ResponseCommand.SC_FAILED);
// } else {
//
// }
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof MediaFileRenameReq) {
MediaFileRenameRsp rsp = new MediaFileRenameRsp(reqToken);
MediaFileRenameReq req = (MediaFileRenameReq) cmd;
boolean[] result = mMediaProxy.renameFiles(req.getOldPaths(),
req.getNewPaths());
if (null == result) {
rsp.setStatusCode(ResponseCommand.SC_FAILED);
} else {
rsp.setResults(result);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof MediaRestoreReq) {
MediaRestoreRsp rsp = new MediaRestoreRsp(reqToken);
MediaRestoreReq req = (MediaRestoreReq) cmd;
String restorePath = req.getRestorePath();
if (null != restorePath) {
mMediaProxy.deleteAllFileUnder(restorePath);
mMediaProxy.deleteDirectory(restorePath);
mMediaProxy.createDirectory(restorePath);
}
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof MediaRestoreOverReq) {
MediaRestoreOverRsp rsp = new MediaRestoreOverRsp(reqToken);
MediaRestoreOverReq req = (MediaRestoreOverReq) cmd;
mMediaProxy.scan(MainService.this, req.getRestoreFilePath());
// Send response command or append it to batch
onRespond(rsp);
} else if (cmd instanceof GetAppForBackupReq) {
mApplicationProxy.fastGetAllApps2Backup(
new IRawBlockConsumer() {
// @Override
public void consume(byte[] block, int blockNo,
int totalNo) {
GetAppForBackupRsp rsp = new GetAppForBackupRsp(
reqToken);
rsp.setRaw(block);
rsp.setProgress(blockNo);
rsp.setTotal(totalNo);
// Send response command or append it to batch
onRespond(rsp);
}
}, Global.getByteBuffer(), ((GetAppForBackupReq) cmd)
.getDestIconWidth(), ((GetAppForBackupReq) cmd)
.getDestIconHeight());
} else {
return false;
}
return true;
}
} |
The Pentagon is floating a controversial plan to close all U.S.-based commissaries in 2015 as part of a massive cost-saving effort after more than a decade of war.
The commissaries are grocery stores that offer food and other necessities at a discount to members of the military, their families and veterans. But as Congress tightens the purse strings, the stores could get caught in the budget battle.
Budget cutters say they don't yet know how much money the plan would save, but there are 178 commissaries in the United States -- and 70 overseas -- which receive a total of $1.4 billion in government funds.
The Defense Commissary Agency, responsible for administering all commissaries worldwide, says military families and retirees save an average of more than 30 percent on their grocery bills compared with those who shop at regular retail stores. The agency says those savings amount to thousands of dollars annually per family.
But families could also lose jobs if the stores close. Thirty percent of the employees at the commissaries are military spouses. The director of the Defense Commissary Agency says that they have already cut their budget by $700 million since 1993.
More On This...
Other military services -- including the Pentagon Channel and Stars and Stripes newspaper -- may also face cuts, along with Armed Forces Radio and Television, which broadcasts football games and news for service members overseas. Stars and Stripes, an independently edited military newspaper, has been around since the Civil War and has over 200,000 daily readers. It collects just $7.8 million a year in government subsidies. To put this number in perspective, the U.S. spent $135 million in fuel for the Afghan military this year -- part of the $4 billion the nation budgeted to support the entire Afghan military this year.
Defense officials say none of these cuts have been made yet and no final decision has been reached. But, according to Pentagon Spokesman Col. Steve Warren, "everything has to be on the table."
Still, Warren said: "No commissaries have closed. No commissaries are about to close. As with every other program that's out there, we're taking a look at how we can save money. We're just taking a look. No one's decided to do anything."
Any cuts to military benefits would ultimately have to be approved and passed by Congress.
Patrons offered mixed opinions about the proposed changes.
Officials at Joint Base Myer Henderson Hall in Arlington, Va., would not allow Fox News to interview shoppers at the on-post commissary, but passersby spoke to Fox News outside the Pentagon.
"I definitely think it's a bad thing to take away the commissaries, because that's a benefit that a lot of soldiers and family members utilize." said Sgt Major Steven Scott. Scott said it's not only about lower costs, but it's also a matter of convenience for families who are able to shop on post.
Others who take advantage of the benefit, like Joseph Shubert, say it's a better option for cutting than some of the alternatives.
"I don't like it, but I understand that choices have to be made," Shubert said. "So, if it's this or, say, cutting our retirement paychecks or things like that, you know one way or another I think this is one of the least bad options." |
/**
* convenience method to initialize a row - handles setting the date info,
* color of the date field, and whether the header and divider are visible
* or not.
* @param holder a subclass of QamarViewHolder, the ViewHolder
* @param date the date for the row
* @param position the position of the row
*/
public void initializeRow(QamarViewHolder holder, Date date, int position){
Resources res = mContext.getResources();
if (DateUtils.isToday(date.getTime())){
holder.dateAreaView.setBackgroundResource(R.color.today_bg_color);
holder.dayOfWeek.setTextColor(
res.getColor(R.color.today_weekday_color));
holder.dayNumber.setTextColor(
res.getColor(R.color.today_day_color));
}
else {
holder.dateAreaView.setBackgroundResource(
R.color.normal_day_bg_color);
holder.dayOfWeek.setTextColor(
res.getColor(R.color.normal_weekday_color));
holder.dayNumber.setTextColor(
res.getColor(R.color.normal_day_color));
}
if (mDayOfWeekStyle != -1){
holder.dayOfWeek.setTextAppearance(mContext, mDayOfWeekStyle);
}
holder.dayOfWeek.setText(mDayOfWeekFormatter.format(date));
holder.dayNumber.setText(mDayFormatter.format(date));
final int section = getSectionForPosition(position);
if (getPositionForSection(section) == position) {
holder.headerMonth.setText(mMonthFormatter.format(date));
holder.headerView.setVisibility(View.VISIBLE);
}
else {
holder.headerView.setVisibility(View.GONE);
}
} |
package com.javapatterns.abstractfactory;
public class ProductB1 implements ProductB
{
public ProductB1()
{
}
}
|
package object_test
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/Nivl/git-go"
"github.com/Nivl/git-go/ginternals"
"github.com/Nivl/git-go/ginternals/object"
"github.com/Nivl/git-go/internal/testhelper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTree(t *testing.T) {
t.Parallel()
t.Run("o.AsTree().ToObject() should return the same object", func(t *testing.T) {
t.Parallel()
treeSHA := "e5b9e846e1b468bc9597ff95d71dfacda8bd54e3"
treeID, err := ginternals.NewOidFromStr(treeSHA)
require.NoError(t, err)
testFile := fmt.Sprintf("tree_%s", treeSHA)
content, err := os.ReadFile(filepath.Join(testhelper.TestdataPath(t), testFile))
require.NoError(t, err)
o := object.New(object.TypeTree, content)
tree, err := o.AsTree()
require.NoError(t, err)
newO := tree.ToObject()
require.Equal(t, o.ID(), newO.ID())
require.Equal(t, treeID, newO.ID())
require.Equal(t, o.Bytes(), newO.Bytes())
})
t.Run("Entries should be immutable", func(t *testing.T) {
t.Parallel()
blobSHA := "0343d67ca3d80a531d0d163f0078a81c95c9085a"
blobID, err := ginternals.NewOidFromStr(blobSHA)
require.NoError(t, err)
tree := object.NewTree([]object.TreeEntry{
{
Mode: object.ModeFile,
ID: blobID,
Path: "blob",
},
})
tree.Entries()[0].ID[0] = 0xe5
assert.Equal(t, byte(0x03), tree.Entries()[0].ID[0], "should not update entry ID")
tree.Entries()[0].Path = "nope"
assert.Equal(t, "blob", tree.Entries()[0].Path, "should not update entry Path")
})
}
func TestTreeObjectMode(t *testing.T) {
t.Parallel()
t.Run("ObjectType()", func(t *testing.T) {
t.Parallel()
testCases := []struct {
desc string
mode object.TreeObjectMode
expected object.Type
}{
{
desc: "unknown object should be blob",
mode: 0o644,
expected: object.TypeBlob,
},
{
desc: "ModeFile should be a blob",
mode: object.ModeFile,
expected: object.TypeBlob,
},
{
desc: "ModeExecutable should be a blob",
mode: object.ModeExecutable,
expected: object.TypeBlob,
},
{
desc: "ModeSymLink should be a blob",
mode: object.ModeSymLink,
expected: object.TypeBlob,
},
{
desc: "ModeDirectory should be a tree",
mode: object.ModeDirectory,
expected: object.TypeTree,
},
{
desc: "ModeGitLink should be a commit",
mode: object.ModeGitLink,
expected: object.TypeCommit,
},
}
for i, tc := range testCases {
tc := tc
t.Run(fmt.Sprintf("%d/%s", i, tc.desc), func(t *testing.T) {
t.Parallel()
assert.Equal(t, tc.expected, tc.mode.ObjectType())
})
}
})
t.Run("IsValid()", func(t *testing.T) {
t.Parallel()
testCases := []struct {
desc string
mode object.TreeObjectMode
isValid bool
}{
{
desc: "0o644 should not be valid",
mode: 0o644,
isValid: false,
},
{
desc: "ModeFile should be valid",
mode: object.ModeFile,
isValid: true,
},
{
desc: "0o100755 should be valid",
mode: 0o100755,
isValid: true,
},
}
for i, tc := range testCases {
tc := tc
t.Run(fmt.Sprintf("%d/%s", i, tc.desc), func(t *testing.T) {
t.Parallel()
out := tc.mode.IsValid()
assert.Equal(t, tc.isValid, out)
})
}
})
}
func TestNewTreeFromObject(t *testing.T) {
t.Parallel()
t.Run("should work on a valid tree", func(t *testing.T) {
t.Parallel()
// Find a tree
repoPath, cleanup := testhelper.UnTar(t, testhelper.RepoSmall)
t.Cleanup(cleanup)
r, err := git.OpenRepository(repoPath)
require.NoError(t, err, "failed loading a repo")
require.NotNil(t, r, "repository should not be nil")
t.Cleanup(func() {
require.NoError(t, r.Close())
})
treeID, err := ginternals.NewOidFromStr("e5b9e846e1b468bc9597ff95d71dfacda8bd54e3")
require.NoError(t, err)
o, err := r.GetObject(treeID)
require.NoError(t, err, "failed getting the tree")
_, err = object.NewTreeFromObject(o)
require.NoError(t, err)
})
t.Run("should fail if the object is not a tree", func(t *testing.T) {
t.Parallel()
o := object.New(object.TypeCommit, []byte{})
_, err := object.NewTreeFromObject(o)
require.Error(t, err)
assert.ErrorIs(t, err, object.ErrObjectInvalid)
assert.Contains(t, err.Error(), "is not a tree")
})
t.Run("should work on an empty tree", func(t *testing.T) {
t.Parallel()
o := object.New(object.TypeTree, []byte{})
tree, err := object.NewTreeFromObject(o)
require.NoError(t, err)
assert.Len(t, tree.Entries(), 0)
})
t.Run("parsing failures", func(t *testing.T) {
t.Parallel()
testCases := []struct {
desc string
data string
expectedErrorMatch string
expectedError error
}{
{
desc: "should fail if the tree has invalid content",
data: "mode",
expectedError: object.ErrTreeInvalid,
expectedErrorMatch: "could not retrieve the mode",
},
{
desc: "should fail if the tree has an invalid mode",
data: "mode ",
expectedError: object.ErrTreeInvalid,
expectedErrorMatch: "could not parse mode",
},
{
desc: "should fail if the tree ends after the mode",
data: "644 ",
expectedError: object.ErrTreeInvalid,
expectedErrorMatch: "could not retrieve the path of entry",
},
{
desc: "should fail if the tree has an invalid ID",
data: "644 file.go\x00invalid",
expectedError: object.ErrTreeInvalid,
expectedErrorMatch: "not enough space to retrieve the ID of entry",
},
}
for i, tc := range testCases {
tc := tc
i := i
t.Run(fmt.Sprintf("%d/%s", i, tc.desc), func(t *testing.T) {
t.Parallel()
o := object.New(object.TypeTree, []byte(tc.data))
_, err := object.NewTreeFromObject(o)
require.Error(t, err)
if tc.expectedError != nil {
assert.ErrorIs(t, err, tc.expectedError)
}
if tc.expectedErrorMatch != "" {
assert.Contains(t, err.Error(), tc.expectedErrorMatch)
}
})
}
})
}
|
// Estrutura de dados 2
public class AppHuff {
public static void main (String[] args) {
try
{
Huff.compactar("teste.txt", "novo.huf");
//Huff.descompactar("novo.huf", "descompactado.txt");
}
catch (Exception e)
{
System.out.println (e.getMessage());
}
}
} |
<filename>internal/webdavmount/webdavmount.go<gh_stars>1000+
// Package webdavmount implements webdav filesystem for serving snapshots.
package webdavmount
import (
"os"
"strings"
"sync"
"sync/atomic"
"github.com/pkg/errors"
"golang.org/x/net/context"
"golang.org/x/net/webdav"
"github.com/kopia/kopia/fs"
"github.com/kopia/kopia/repo/logging"
)
var log = logging.Module("kopia/webdavmount")
var (
_ os.FileInfo = webdavFileInfo{}
_ webdav.File = (*webdavFile)(nil)
_ webdav.File = (*webdavDir)(nil)
)
type webdavFile struct {
ctx context.Context
entry fs.File
mu sync.Mutex
r fs.Reader
}
func (f *webdavFile) Readdir(n int) ([]os.FileInfo, error) {
return nil, errors.New("not a directory")
}
func (f *webdavFile) Stat() (os.FileInfo, error) {
return webdavFileInfo{f.entry}, nil
}
func (f *webdavFile) getReader() (fs.Reader, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.r == nil {
r, err := f.entry.Open(f.ctx)
if err != nil {
return nil, errors.Wrap(err, "error opening webdav file")
}
f.r = r
}
return f.r, nil
}
func (f *webdavFile) Read(b []byte) (int, error) {
r, err := f.getReader()
if err != nil {
return 0, err
}
// nolint:wrapcheck
return r.Read(b)
}
func (f *webdavFile) Seek(offset int64, whence int) (int64, error) {
r, err := f.getReader()
if err != nil {
return 0, err
}
// nolint:wrapcheck
return r.Seek(offset, whence)
}
func (f *webdavFile) Write(b []byte) (int, error) {
return 0, errors.New("read-only filesystem")
}
func (f *webdavFile) Close() error {
f.mu.Lock()
r := f.r
f.r = nil
f.mu.Unlock()
if r != nil {
// nolint:wrapcheck
return r.Close()
}
return nil
}
type webdavDir struct {
ctx context.Context
w *webdavFS
entry fs.Directory
}
var symlinksAreUnsupportedLogged = new(int32)
func (d *webdavDir) Readdir(n int) ([]os.FileInfo, error) {
entries, err := d.entry.Readdir(d.ctx)
if err != nil {
return nil, errors.Wrap(err, "error reading directory")
}
if n > 0 && n < len(entries) {
entries = entries[0:n]
}
var fis []os.FileInfo
for _, e := range entries {
if _, isSymlink := e.(fs.Symlink); isSymlink {
if atomic.AddInt32(symlinksAreUnsupportedLogged, 1) == 1 {
log(d.ctx).Errorf("Mounting directories containing symbolic links using WebDAV is not supported. The link entries will be skipped.")
}
continue
}
fis = append(fis, &webdavFileInfo{e})
}
return fis, nil
}
func (d *webdavDir) Stat() (os.FileInfo, error) {
return webdavFileInfo{d.entry}, nil
}
func (d *webdavDir) Write(b []byte) (int, error) {
return 0, errors.New("read-only filesystem")
}
func (d *webdavDir) Close() error {
return nil
}
func (d *webdavDir) Read(b []byte) (int, error) {
return 0, errors.New("not supported")
}
func (d *webdavDir) Seek(int64, int) (int64, error) {
return 0, errors.New("not supported")
}
type webdavFileInfo struct {
fs.Entry
}
type webdavFS struct {
dir fs.Directory
}
func (w *webdavFS) Mkdir(ctx context.Context, path string, mode os.FileMode) error {
return errors.Errorf("can't create %q: read-only filesystem", path)
}
func (w *webdavFS) RemoveAll(ctx context.Context, path string) error {
return errors.Errorf("can't remove %q: read-only filesystem", path)
}
func (w *webdavFS) Rename(ctx context.Context, oldPath, newPath string) error {
return errors.Errorf("can't rename %q to %q: read-only filesystem", oldPath, newPath)
}
func (w *webdavFS) OpenFile(ctx context.Context, path string, flags int, mode os.FileMode) (webdav.File, error) {
f, err := w.findEntry(ctx, path)
if err != nil {
log(ctx).Errorf("OpenFile(%q) failed with %v", path, err)
return nil, err
}
switch f := f.(type) {
case fs.Directory:
return &webdavDir{ctx, w, f}, nil
case fs.File:
return &webdavFile{ctx: ctx, entry: f}, nil
}
return nil, errors.Errorf("can't open %q: not implemented", path)
}
func (w *webdavFS) Stat(ctx context.Context, path string) (os.FileInfo, error) {
e, err := w.findEntry(ctx, path)
if err != nil {
return nil, err
}
return webdavFileInfo{e}, nil
}
func (w *webdavFS) findEntry(ctx context.Context, path string) (fs.Entry, error) {
parts := removeEmpty(strings.Split(path, "/"))
var e fs.Entry = w.dir
for i, p := range parts {
d, ok := e.(fs.Directory)
if !ok {
return nil, errors.Errorf("%q not found in %q (not a directory)", p, strings.Join(parts[0:i], "/"))
}
entries, err := d.Readdir(ctx)
if err != nil {
return nil, errors.Wrap(err, "error reading directory")
}
e = entries.FindByName(p)
if e == nil {
return nil, errors.Errorf("%q not found in %q (not found)", p, strings.Join(parts[0:i], "/"))
}
}
return e, nil
}
func removeEmpty(s []string) []string {
result := s[:0]
for _, e := range s {
if e == "" {
continue
}
result = append(result, e)
}
return result
}
// WebDAVFS returns a webdav.FileSystem implementation for a given directory.
func WebDAVFS(entry fs.Directory) webdav.FileSystem {
return &webdavFS{entry}
}
|
def lookup_generic(self, obj, as_of_date, country_code):
matches = []
missing = []
if isinstance(obj, (AssetConvertible, ContinuousFuture)):
self._lookup_generic_scalar(
obj=obj,
as_of_date=as_of_date,
country_code=country_code,
matches=matches,
missing=missing,
)
try:
return matches[0], missing
except IndexError:
if hasattr(obj, '__int__'):
raise SidsNotFound(sids=[obj])
else:
raise SymbolNotFound(symbol=obj)
try:
iterator = iter(obj)
except TypeError:
raise NotAssetConvertible(
"Input was not a AssetConvertible "
"or iterable of AssetConvertible."
)
for obj in iterator:
self._lookup_generic_scalar(
obj=obj,
as_of_date=as_of_date,
country_code=country_code,
matches=matches,
missing=missing,
)
return matches, missing |
import { Component, OnInit } from '@angular/core';
import { Router, NavigationExtras } from '@angular/router';
@Component({
selector: 'app-your-rides',
templateUrl: './your-rides.page.html',
styleUrls: ['./your-rides.page.scss'],
})
export class YourRidesPage implements OnInit {
seg_id = 1;
constructor(private router: Router) { }
ngOnInit() {
}
segmentChange(val) {
this.seg_id = val;
}
goToOfferRides() {
this.router.navigate(['/offer-rides']);
}
goToFindRides() {
this.router.navigate(['/find-rides']);
}
goToDetail(ids) {
const navData: NavigationExtras = {
queryParams: {
id: ids
}
};
this.router.navigate(['/history-detail'], navData);
}
}
|
Shooting children and the elderly: is it even a good idea on paper? An American law enforcement supply company thinks so and is letting police departments purchase some rather unusual products for target practice.
For only 99 cents per sheet, Law Enforcement Targets Inc. lets customers order life-like posters that show that people of all walks of life could be potential threats to police officers. Among the targets available in their "No More Hesitation" series for shooting practice are enlarged photographs of a pregnant woman, children holding hands and a high-school aged girl.
In every image, the suspect is showing holding a gun, meant to force officers of the law to act without hesitation in even the most unusual life-or-death scenarios. In a statement emailed to Reason on Tuesday afternoon, the marketing team at Law Enforcement Targets explains the thought process involved in selling realistic targets that let people open fire on young children and the elderly alike.
"The subjects in NMH targets were chosen in order to give officers the experience of dealing with deadly force shooting scenarios with subjects that are not the norm during training,”
the statement begins.
Image from reason.com
“I found while speaking with officers and trainers in the law enforcement community that there is a hesitation on the part of cops when deadly force is required on subjects with atypical age, frailty or condition.”
According to the author of the statement, one officer interviewed by LET claims he enlarged images of his own children for target practice “so that he would not be caught off guard with such a drastically new experience while on duty.” Law Enforcement Targets Inc. has come to the rescue, however, and now the officer in question doesn’t have to bother emptying clips into his own kids’ craniums. For just a dollar plus shipping, he can order product number NMH-7, “Little Boy With Real Gun.”
“Non-traditional threat dipicting [sic] a very young boy holding a real gun,” reads the description. “Designed to prepare officers for worst possible situation.” All of the targets available are roughly two-feet-wide by three-feet-tall.
“This hesitation time may be only seconds but that is not acceptable when officers are losing their lives in these same situations,” continues the statement obtained by Reason, who first profiled the NMH series in an article published Tuesday by Mike Riggs. “The goal of NMH is to break that stereotype on the range, regardless of how slim the chances are of encountering a real life scenario that involves a child, pregnant woman, etc. If that initial hesitation time can be cut down due to range experience, the officer and community are better served."
Also available through the No More Hesitation series are “Older Man With Shotgun,” “Young Mother on Playground” and “Pregnant Woman Threat.” |
Corporeality and Emotion in Goethe's Die Wahlverwandtschaften
Abstract This article explores the connection between corporeality and emotion in Goethe's Die Wahlverwandtschaften, with special emphasis on tableaux vivants. It focuses on the dilemma of a newly emerging concept of love based on physical attraction, which partly comports and partly collides with the contemporary conception of morality. At Ottilie's death, the incongruous expectations manifest themselves: her transformation into an undecomposed corpse responds to the events unfolding in the wake of her relationship with Eduard. As an incorporeal body, she ultimately presents the only conceivable, yet paradoxical solution to the diverging bourgeois requirements of physical restraint and committed love. |
/// \par parameters: a type
/// \return Boolean telling whether the type is that of java string builder
bool refined_string_typet::is_java_string_builder_type(const typet &type)
{
if(type.id()==ID_pointer)
{
const pointer_typet &pt=to_pointer_type(type);
const typet &subtype=pt.subtype();
if(subtype.id()==ID_struct)
{
irep_idt tag=to_struct_type(subtype).get_tag();
return tag=="java.lang.StringBuilder";
}
}
return false;
} |
The Optimal Time Typing to Identifying Users at the Keyboard Handwriting
This article deals with the problem of ensuring protection against unauthorized access to data by identifying users according to biometric characteristics. The article deals with the issue of choosing the optimal time of typing. This question is relevant when identifying the user by keyboard handwriting. Typing too long can be tiring for the user. Too short a time can lead to incorrect identification and errors of the first and second kind. The article presents the results of experiments in which users type text 10, 20, 30 seconds. The results show that the optimal set time is 20 seconds. This time does not cause significant fatigue, at the same time in 20 seconds the handwriting becomes stable enough to identify the user. |
<reponame>luite/jsaddle-dom<gh_stars>10-100
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.XPathResult
(iterateNext, iterateNext_, snapshotItem, snapshotItem_,
pattern ANY_TYPE, pattern NUMBER_TYPE, pattern STRING_TYPE,
pattern BOOLEAN_TYPE, pattern UNORDERED_NODE_ITERATOR_TYPE,
pattern ORDERED_NODE_ITERATOR_TYPE,
pattern UNORDERED_NODE_SNAPSHOT_TYPE,
pattern ORDERED_NODE_SNAPSHOT_TYPE,
pattern ANY_UNORDERED_NODE_TYPE, pattern FIRST_ORDERED_NODE_TYPE,
getResultType, getNumberValue, getStringValue, getBooleanValue,
getSingleNodeValue, getInvalidIteratorState, getSnapshotLength,
XPathResult(..), gTypeXPathResult)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.iterateNext Mozilla XPathResult.iterateNext documentation>
iterateNext :: (MonadDOM m) => XPathResult -> m Node
iterateNext self
= liftDOM ((self ^. jsf "iterateNext" ()) >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.iterateNext Mozilla XPathResult.iterateNext documentation>
iterateNext_ :: (MonadDOM m) => XPathResult -> m ()
iterateNext_ self = liftDOM (void (self ^. jsf "iterateNext" ()))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.snapshotItem Mozilla XPathResult.snapshotItem documentation>
snapshotItem :: (MonadDOM m) => XPathResult -> Maybe Word -> m Node
snapshotItem self index
= liftDOM
((self ^. jsf "snapshotItem" [toJSVal index]) >>=
fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.snapshotItem Mozilla XPathResult.snapshotItem documentation>
snapshotItem_ :: (MonadDOM m) => XPathResult -> Maybe Word -> m ()
snapshotItem_ self index
= liftDOM (void (self ^. jsf "snapshotItem" [toJSVal index]))
pattern ANY_TYPE = 0
pattern NUMBER_TYPE = 1
pattern STRING_TYPE = 2
pattern BOOLEAN_TYPE = 3
pattern UNORDERED_NODE_ITERATOR_TYPE = 4
pattern ORDERED_NODE_ITERATOR_TYPE = 5
pattern UNORDERED_NODE_SNAPSHOT_TYPE = 6
pattern ORDERED_NODE_SNAPSHOT_TYPE = 7
pattern ANY_UNORDERED_NODE_TYPE = 8
pattern FIRST_ORDERED_NODE_TYPE = 9
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.resultType Mozilla XPathResult.resultType documentation>
getResultType :: (MonadDOM m) => XPathResult -> m Word
getResultType self
= liftDOM (round <$> ((self ^. js "resultType") >>= valToNumber))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.numberValue Mozilla XPathResult.numberValue documentation>
getNumberValue :: (MonadDOM m) => XPathResult -> m Double
getNumberValue self
= liftDOM ((self ^. js "numberValue") >>= valToNumber)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.stringValue Mozilla XPathResult.stringValue documentation>
getStringValue ::
(MonadDOM m, FromJSString result) => XPathResult -> m result
getStringValue self
= liftDOM ((self ^. js "stringValue") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.booleanValue Mozilla XPathResult.booleanValue documentation>
getBooleanValue :: (MonadDOM m) => XPathResult -> m Bool
getBooleanValue self
= liftDOM ((self ^. js "booleanValue") >>= valToBool)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.singleNodeValue Mozilla XPathResult.singleNodeValue documentation>
getSingleNodeValue :: (MonadDOM m) => XPathResult -> m Node
getSingleNodeValue self
= liftDOM ((self ^. js "singleNodeValue") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.invalidIteratorState Mozilla XPathResult.invalidIteratorState documentation>
getInvalidIteratorState :: (MonadDOM m) => XPathResult -> m Bool
getInvalidIteratorState self
= liftDOM ((self ^. js "invalidIteratorState") >>= valToBool)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.snapshotLength Mozilla XPathResult.snapshotLength documentation>
getSnapshotLength :: (MonadDOM m) => XPathResult -> m Word
getSnapshotLength self
= liftDOM
(round <$> ((self ^. js "snapshotLength") >>= valToNumber))
|
def board_to_state_array(board, cur_team_id):
size = board.configuration["size"]
state = np.zeros((size, size, 9), dtype=np.float32)
opp_team_id = (cur_team_id + 1) % 2
for cell in board.cells.values():
j, i = point_to_ji(cell.position, size)
state[j, i, 0] = cell.halite
if cell.ship is not None:
if cell.ship.player_id == cur_team_id:
state[j, i, 1] = 1.0
elif cell.ship.player_id == opp_team_id:
state[j, i, 3] = 1.0
else:
raise ValueError("Unexpected player_id")
state[j, i, 5] = cell.ship.halite
if cell.shipyard is not None:
if cell.shipyard.player_id == cur_team_id:
state[j, i, 2] = 1.0
elif cell.shipyard.player_id == opp_team_id:
state[j, i, 4] = 1.0
else:
raise ValueError("Unexpected player_id")
cur_player = board.players[cur_team_id]
state[:, :, 6] = cur_player.halite
opp_player = board.players[opp_team_id]
state[:, :, 7] = opp_player.halite
num_steps = board.configuration['episodeSteps']
remaining_steps = num_steps - board.step - 2
state[:, :, 8] = remaining_steps
return state |
// GetAll returns a paginated list of resources.
// An empty list of resources will be represented as `null` in the JSON response if `nil` is assigned to the
// Page.Resources. Otherwise, is an empty slice is assigned, an empty list will be represented as `[]`.
func (h *groupHandler) GetAll(r *http.Request, params scim.ListRequestParams) (scim.Page, error) {
logDebug(h.log, r)
roleCount := len(roles.AvailableRoles)
if params.Count < 1 {
return scim.Page{
TotalResults: roleCount,
}, nil
}
resources := make([]scim.Resource, 0)
i := 1
for {
if i > roleCount || i > (params.StartIndex+params.Count-1) {
break
}
role := roles.AvailableRoles[i-1]
if i >= params.StartIndex {
resources = append(resources, toScimGroup(role))
}
i++
}
return scim.Page{
TotalResults: int(roleCount),
Resources: resources,
}, nil
} |
<reponame>ricardozanini/jackson-jq<filename>jackson-jq/src/main/java/net/thisptr/jackson/jq/internal/functions/AbstractMaxByFunction.java
package net.thisptr.jackson.jq.internal.functions;
import java.util.List;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.fasterxml.jackson.databind.node.NullNode;
import net.thisptr.jackson.jq.Expression;
import net.thisptr.jackson.jq.Function;
import net.thisptr.jackson.jq.PathOutput;
import net.thisptr.jackson.jq.Scope;
import net.thisptr.jackson.jq.Version;
import net.thisptr.jackson.jq.exception.JsonQueryException;
import net.thisptr.jackson.jq.internal.misc.JsonNodeComparator;
import net.thisptr.jackson.jq.internal.misc.Preconditions;
import net.thisptr.jackson.jq.path.Path;
public abstract class AbstractMaxByFunction implements Function {
protected static final JsonNodeComparator comparator = JsonNodeComparator.getInstance();
private String fname;
public AbstractMaxByFunction(final String fname) {
this.fname = fname;
}
@Override
public void apply(final Scope scope, final List<Expression> args, final JsonNode in, final Path ipath, final PathOutput output, final Version version) throws JsonQueryException {
Preconditions.checkInputType(fname, in, JsonNodeType.ARRAY);
JsonNode maxItem = NullNode.getInstance();
JsonNode maxValue = null;
for (final JsonNode i : in) {
final ArrayNode value = scope.getObjectMapper().createArrayNode();
args.get(0).apply(scope, i, value::add);
if (maxValue == null || !isLarger(maxValue, value)) {
maxValue = value;
maxItem = i;
}
}
output.emit(maxItem, null);
}
protected abstract boolean isLarger(final JsonNode criteria, final JsonNode value);
}
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index.seqno;
import org.apache.lucene.util.FixedBitSet;
import org.elasticsearch.test.ESTestCase;
import java.util.List;
import java.util.stream.IntStream;
import static org.hamcrest.Matchers.equalTo;
public class CountedBitSetTests extends ESTestCase {
public void testCompareToFixedBitset() {
int numBits = (short) randomIntBetween(8, 4096);
final FixedBitSet fixedBitSet = new FixedBitSet(numBits);
final CountedBitSet countedBitSet = new CountedBitSet((short) numBits);
for (int i = 0; i < numBits; i++) {
if (randomBoolean()) {
fixedBitSet.set(i);
countedBitSet.set(i);
}
assertThat(countedBitSet.cardinality(), equalTo(fixedBitSet.cardinality()));
assertThat(countedBitSet.length(), equalTo(fixedBitSet.length()));
}
for (int i = 0; i < numBits; i++) {
assertThat(countedBitSet.get(i), equalTo(fixedBitSet.get(i)));
}
}
public void testReleaseInternalBitSet() {
int numBits = (short) randomIntBetween(8, 4096);
final CountedBitSet countedBitSet = new CountedBitSet((short) numBits);
final List<Integer> values = IntStream.range(0, numBits).boxed().toList();
for (int i = 1; i < numBits; i++) {
final int value = values.get(i);
assertThat(countedBitSet.get(value), equalTo(false));
assertThat(countedBitSet.isInternalBitsetReleased(), equalTo(false));
countedBitSet.set(value);
assertThat(countedBitSet.get(value), equalTo(true));
assertThat(countedBitSet.isInternalBitsetReleased(), equalTo(false));
assertThat(countedBitSet.length(), equalTo(numBits));
assertThat(countedBitSet.cardinality(), equalTo(i));
}
// The missing piece to fill all bits.
{
final int value = values.get(0);
assertThat(countedBitSet.get(value), equalTo(false));
assertThat(countedBitSet.isInternalBitsetReleased(), equalTo(false));
countedBitSet.set(value);
assertThat(countedBitSet.get(value), equalTo(true));
assertThat(countedBitSet.isInternalBitsetReleased(), equalTo(true));
assertThat(countedBitSet.length(), equalTo(numBits));
assertThat(countedBitSet.cardinality(), equalTo(numBits));
}
// Tests with released internal bitset.
final int iterations = iterations(1000, 10000);
for (int i = 0; i < iterations; i++) {
final int value = randomInt(numBits - 1);
assertThat(countedBitSet.get(value), equalTo(true));
assertThat(countedBitSet.isInternalBitsetReleased(), equalTo(true));
assertThat(countedBitSet.length(), equalTo(numBits));
assertThat(countedBitSet.cardinality(), equalTo(numBits));
if (frequently()) {
assertThat(countedBitSet.get(value), equalTo(true));
}
}
}
}
|
def transposeBelowTarget(
self: _T,
target,
*,
minimize=False,
inPlace=False
) -> _T:
if inPlace:
src = self
else:
src = copy.deepcopy(self)
while True:
if src.ps - target.ps <= 0:
break
src.octave -= 1
if minimize:
while True:
if target.ps - src.ps < 12:
break
else:
src.octave += 1
if not inPlace:
return src |
The Effect of Naloxone on the Hemodynamics of the Newborn Piglet with Septic Shock
ABSTRACT. Naloxone has been shown to reverse the hemodynamic sequelae of experimental septic shock in adult animal models. Its effectiveness in the newborn has not been studied. To further investigate the efficacy of naloxone, we instrumented 18 piglets for continuous measurement of mean arterial pressure, mean pulmonary arterial pressure, central venous pressure, heart rate, left ventricular pressure, contractility, cardiac output, and O2. Oxygen consumption, systemic vascular resistance, and pulmonary vascular resistance were calculated. Following a stabilization period, group B β-hemolytic Streptococci were infused over 30 min. Following the infusion, naloxone (1 mg/kg) was given followed by a continuous infusion of 1 mg/kg/h in nine treatment animals. Nine control animals were given an equal volume of saline. Both groups developed significant increases in mean pulmonary arterial pressure followed by a return to baseline. Oxygen consumption, cardiac output, contractility and mean arterial pressure decreased in both groups. Treatment with naloxone was associated with a cessation in the fall in the mean arterial pressure and the contractility. The difference in mean arterial pressure and contractility between groups was significant. The naloxone group had significantly improved 5–h survival. We speculate that naloxone may reverse some of the hemodynamic sequelae and improve survival in newborns with septic shock. |
class REG_Data:
"""Data Container for regression problem
Parameters
----------
tstart : float
Start of the TRF in seconds.
tstop : float
Stop of the TRF in seconds.
nlevel : int
Decides the density of Gabor atoms. Bigger nlevel -> less dense basis.
By default it is set to 1. ``nlevel > 2`` should be used with caution.
baseline: list | None
Mean that will be subtracted from ``stim``.
scaling: list | None
Scale by which ``stim`` was divided.
"""
_n_predictor_variables = 1
_prewhitened = None
def __init__(self, tstart, tstop, nlevel=1, baseline=None, scaling=None, stim_is_single=None):
if tstart != 0:
raise NotImplementedError("tstart != 0 is not implemented")
self.tstart = tstart
self.tstop = tstop
self.nlevel = nlevel
self.s_baseline = baseline
self.s_scaling = scaling
self.meg = []
self.covariates = []
self.tstep = None
self.filter_length = None
self.basis = None
self._norm_factor = None
self._stim_is_single = stim_is_single
self._stim_dims = None
self._stim_names = None
self.sensor_dim = None
def add_data(self, meg, stim):
"""Add sensor measurements and predictor variables for one trial
Call this function repeatedly to add data for multiple trials/recordings
Parameters
----------
meg : NDVar (sensor, UTS)
MEG Measurements.
stim : list of NDVar ([...,] UTS)
One or more predictor variable. The time axis needs to match ``y``.
"""
if self.sensor_dim is None:
self.sensor_dim = meg.get_dim('sensor')
elif meg.get_dim('sensor') != self.sensor_dim:
raise NotImplementedError('combining data segments with different sensors is not supported')
# check stim dimensions
meg_time = meg.get_dim('time')
stims = (stim,) if isinstance(stim, NDVar) else stim
stim_dims = []
for x in stims:
if x.get_dim('time') != meg_time:
raise ValueError(f"stim={stim!r}: time axis incompatible with meg")
elif x.ndim == 1:
stim_dims.append(None)
elif x.ndim == 2:
dim, _ = x.get_dims((None, 'time'))
stim_dims.append(dim)
else:
raise ValueError(f"stim={stim}: stimulus with more than 2 dimensions")
# stim normalization
if self.s_baseline is not None:
if len(self.s_baseline) != len(stims):
raise ValueError(f"stim={stim!r}: incompatible with baseline={self.s_baseline!r}")
for s, m in zip(stims, self.s_baseline):
s -= m
if self.s_scaling is not None:
if len(self.s_scaling) != len(stims):
raise ValueError(f"stim={stim!r}: incompatible with scaling={self.s_scaling!r}")
for s, scale in zip(stims, self.s_scaling):
s /= scale
if self.tstep is None:
# initialize time axis
self.tstep = meg_time.tstep
start = int(round(self.tstart / self.tstep))
stop = int(round(self.tstop / self.tstep))
self.filter_length = stop - start + 1
# basis
x = np.linspace(int(round(1000*self.tstart)), int(round(1000*self.tstop)), self.filter_length)
self.basis = gaussian_basis(int(round((self.filter_length-1)/self.nlevel)), x)
# stimuli
self._stim_dims = stim_dims
self._stim_names = [x.name for x in stims]
elif meg_time.tstep != self.tstep:
raise ValueError(f"meg={meg!r}: incompatible time-step with previously added data")
else:
# check stimuli dimensions
if stim_dims != self._stim_dims:
raise ValueError(f"stim={stim!r}: dimensions incompatible with previously added data")
# add meg data
y = meg.get_data(('sensor', 'time'))
y = y[:, self.basis.shape[0]-1:].astype(np.float64)
self.meg.append(y / sqrt(y.shape[1])) # Mind the normalization
if self._norm_factor is None:
self._norm_factor = sqrt(y.shape[1])
# add corresponding covariate matrix
covariates = np.dot(covariate_from_stim(stims, self.filter_length),
self.basis) / sqrt(y.shape[1]) # Mind the normalization
if covariates.ndim > 2:
self._n_predictor_variables = covariates.shape[0]
covariates = covariates.swapaxes(1, 0)
first_dim = covariates.shape[0]
x = covariates.reshape(first_dim, -1).astype(np.float64)
self.covariates.append(x)
def _prewhiten(self, whitening_filter):
"""Called by ncRF instance"""
if self._prewhitened is None:
for i, (meg, _) in enumerate(self):
self.meg[i] = np.dot(whitening_filter, meg)
self._prewhitened = True
def _precompute(self):
"""Called by ncRF instance"""
self._bbt = []
self._bE = []
self._EtE = []
for b, E in self:
self._bbt.append(np.matmul(b, b.T))
self._bE.append(np.matmul(b, E))
self._EtE.append(np.matmul(E.T, E))
def __iter__(self):
return zip(self.meg, self.covariates)
def __len__(self):
return len(self.meg)
def __repr__(self):
return 'Regression data'
def timeslice(self, idx):
"""gets a time slice (used for cross-validation)
Parameters
----------
idx : kfold splits
Returns
-------
REG_Data instance
"""
obj = type(self).__new__(self.__class__)
# take care of the copied values from the old_obj
copy_keys = ['_n_predictor_variables', 'basis', 'filter_length', 'tstart', 'tstep', 'tstop', '_stim_is_single',
'_stim_dims', '_stim_names', 's_baseline', 's_scaling', '_prewhitened']
obj.__dict__.update({key: self.__dict__[key] for key in copy_keys})
# keep track of the normalization
obj._norm_factor = sqrt(len(idx))
# add splitted data
obj.meg = []
obj.covariates = []
# Dont forget to take care of the normalization here
mul = self._norm_factor / obj._norm_factor # multiplier to take care of the time normalization
for meg, covariate in self:
obj.meg.append(meg[:, idx] * mul)
obj.covariates.append(covariate[idx, :] * mul)
return obj |
/* Generate the predefined rules into the corresponding session */
int predef_rules_generate(struct session_t *sess, char *predef_name)
{
predefined_pdr_entry *pdr_entry;
uint8_t cnt;
session_emd_response resp;
pdr_entry = predef_rules_search(predef_name);
if (NULL == pdr_entry) {
LOG(SESSION, ERR, "Activate pre-defined rules failed, no such name: %s",
predef_name);
return -1;
}
if (pdr_entry->pdr_cfg.member_flag.d.far_id_present) {
predefined_far_entry *far_entry;
far_entry = predef_far_search(pdr_entry->pdr_cfg.far_id);
if (NULL == far_entry) {
LOG(SESSION, ERR, "Pre-defined FAR ID: %u does not exist", pdr_entry->pdr_cfg.far_id);
goto cleanup;
}
if (0 > far_insert(sess, &far_entry->far_cfg, 1, &resp.failed_rule_id.rule_id)) {
LOG(SESSION, ERR, "Create FAR failed.");
goto cleanup;
}
}
for (cnt = 0; cnt < pdr_entry->pdr_cfg.qer_id_number; ++cnt) {
predefined_qer_entry *qer_entry;
qer_entry = predef_qer_search(pdr_entry->pdr_cfg.qer_id_array[cnt]);
if (NULL == qer_entry) {
LOG(SESSION, ERR, "Pre-defined QER ID: %u does not exist", pdr_entry->pdr_cfg.qer_id_array[cnt]);
goto cleanup;
}
if (0 > qer_insert(sess, &qer_entry->qer_cfg, 1, &resp.failed_rule_id.rule_id)) {
LOG(SESSION, ERR, "Create QER failed.");
goto cleanup;
}
}
for (cnt = 0; cnt < pdr_entry->pdr_cfg.urr_id_number; ++cnt) {
predefined_urr_entry *urr_entry;
urr_entry = predef_urr_search(pdr_entry->pdr_cfg.urr_id_array[cnt]);
if (NULL == urr_entry) {
LOG(SESSION, ERR, "Pre-defined URR ID: %u does not exist", pdr_entry->pdr_cfg.urr_id_array[cnt]);
goto cleanup;
}
if (0 > urr_insert(sess, &urr_entry->urr_cfg, 1, &resp.failed_rule_id.rule_id)) {
LOG(SESSION, ERR, "Create URR failed.");
goto cleanup;
}
}
return 0;
cleanup:
predef_rules_erase(sess, predef_name);
return -1;
} |
import sys, itertools
input = sys.stdin.readline
def main():
# d[i][j]は2頂点間i, j間の移動コストを格納, Vは頂点数
def warshall_floyd(d, V):
for k in range(V):
for i in range(V):
for j in range(V):
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
return d # d[i][j]に頂点i, j間の最短距離を格納
n,m,r = map(int,input().split())
R = list(map(int,input().split()))
for i in range(r):
R[i] -= 1
d = [[10**10] * n for _ in range(n)]
for _ in range(m):
a,b,c = map(int,input().split())
d[a-1][b-1] = c
d[b-1][a-1] = c
d = warshall_floyd(d, n)
ans = 10**10
ptr = list(itertools.permutations(R, len(R))) # 順列列挙 5P3
for i in ptr:
tmp = 0
for j in range(len(i)-1):
tmp += d[i[j]][i[j+1]]
ans = min(ans, tmp)
print(ans)
if __name__ == '__main__':
main()
|
<filename>src/jmh/java/com/thekirschners/emplacements/column/EnvObsevationsProcessor.java
package com.thekirschners.emplacements.column;
import java.util.Calendar;
import java.util.Iterator;
import java.util.OptionalDouble;
import java.util.stream.Collectors;
public class EnvObsevationsProcessor {
public static OptionalDouble averageMonthlyTemperatureWithPrimitiveStream(EnvObsTimeSeries columnarStore, int year, int month) {
final Calendar startCalendar = Calendar.getInstance();
startCalendar.set(
year,
month,
startCalendar.getMinimum(Calendar.DAY_OF_MONTH),
startCalendar.getMinimum(Calendar.HOUR_OF_DAY),
startCalendar.getMinimum(Calendar.MINUTE),
startCalendar.getMinimum(Calendar.SECOND)
);
startCalendar.set(Calendar.MILLISECOND, startCalendar.getMinimum(Calendar.MILLISECOND));
final long startTime = startCalendar.getTimeInMillis();
final Calendar endCalendar = Calendar.getInstance();
endCalendar.set(Calendar.YEAR, year);
endCalendar.set(Calendar.MONTH, month);
endCalendar.set(Calendar.DAY_OF_MONTH, endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
endCalendar.set(Calendar.HOUR_OF_DAY, endCalendar.getMaximum(Calendar.HOUR_OF_DAY));
endCalendar.set(Calendar.MINUTE, endCalendar.getMaximum(Calendar.HOUR_OF_DAY));
endCalendar.set(Calendar.SECOND, endCalendar.getMaximum(Calendar.HOUR_OF_DAY));
endCalendar.set(Calendar.MILLISECOND, endCalendar.getMaximum(Calendar.MILLISECOND));
final long endTime = endCalendar.getTimeInMillis();
final int[] timeSliceIndexes = columnarStore.extractTimeSlice(startTime, endTime);
return columnarStore.getTemperatures(timeSliceIndexes[0], timeSliceIndexes[1]).average();
}
public static OptionalDouble averageMonthlyTemperatureWithCursor(EnvObsTimeSeries columnarStore, int year, int month) {
final Calendar startCalendar = Calendar.getInstance();
startCalendar.set(
year,
month,
startCalendar.getMinimum(Calendar.DAY_OF_MONTH),
startCalendar.getMinimum(Calendar.HOUR_OF_DAY),
startCalendar.getMinimum(Calendar.MINUTE),
startCalendar.getMinimum(Calendar.SECOND)
);
startCalendar.set(Calendar.MILLISECOND, startCalendar.getMinimum(Calendar.MILLISECOND));
final long startTime = startCalendar.getTimeInMillis();
final Calendar endCalendar = Calendar.getInstance();
endCalendar.set(Calendar.YEAR, year);
endCalendar.set(Calendar.MONTH, month);
endCalendar.set(Calendar.DAY_OF_MONTH, endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
endCalendar.set(Calendar.HOUR_OF_DAY, endCalendar.getMaximum(Calendar.HOUR_OF_DAY));
endCalendar.set(Calendar.MINUTE, endCalendar.getMaximum(Calendar.HOUR_OF_DAY));
endCalendar.set(Calendar.SECOND, endCalendar.getMaximum(Calendar.HOUR_OF_DAY));
endCalendar.set(Calendar.MILLISECOND, endCalendar.getMaximum(Calendar.MILLISECOND));
final long endTime = endCalendar.getTimeInMillis();
final int[] timeSliceIndexes = columnarStore.extractTimeSlice(startTime, endTime);
double average = 0;
double count = timeSliceIndexes[1] - timeSliceIndexes[0];
final EnvObsTimeSeries.ArbitraryAccessCursor cursor = columnarStore.get(0);
final int start = timeSliceIndexes[0];
final int end = timeSliceIndexes[1];
for (int i = start; i <= end; i ++)
average += (cursor.at(i).getTemperature() / count);
return OptionalDouble.of(average);
}
public static OptionalDouble averageMonthlyTemperatureWithObjectItertor(EnvObsTimeSeries columnarStore, int year, int month) {
final Calendar startCalendar = Calendar.getInstance();
startCalendar.set(
year,
month,
startCalendar.getMinimum(Calendar.DAY_OF_MONTH),
startCalendar.getMinimum(Calendar.HOUR_OF_DAY),
startCalendar.getMinimum(Calendar.MINUTE),
startCalendar.getMinimum(Calendar.SECOND)
);
startCalendar.set(Calendar.MILLISECOND, startCalendar.getMinimum(Calendar.MILLISECOND));
final long startTime = startCalendar.getTimeInMillis();
final Calendar endCalendar = Calendar.getInstance();
endCalendar.set(Calendar.YEAR, year);
endCalendar.set(Calendar.MONTH, month);
endCalendar.set(Calendar.DAY_OF_MONTH, endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
endCalendar.set(Calendar.HOUR_OF_DAY, endCalendar.getMaximum(Calendar.HOUR_OF_DAY));
endCalendar.set(Calendar.MINUTE, endCalendar.getMaximum(Calendar.HOUR_OF_DAY));
endCalendar.set(Calendar.SECOND, endCalendar.getMaximum(Calendar.HOUR_OF_DAY));
endCalendar.set(Calendar.MILLISECOND, endCalendar.getMaximum(Calendar.MILLISECOND));
final long endTime = endCalendar.getTimeInMillis();
final int[] timeSliceIndexes = columnarStore.extractTimeSlice(startTime, endTime);
double average = 0;
double count = timeSliceIndexes[1] - timeSliceIndexes[0];
final int start = timeSliceIndexes[0];
final int end = timeSliceIndexes[1];
for (Iterator<EnvObservation> it = columnarStore.iterator(start, end); it.hasNext(); /* NOP */)
average += (it.next().getTemperature() / count);
return OptionalDouble.of(average);
}
public static OptionalDouble averageMonthlyTemperatureWithObjectStream(EnvObsTimeSeries columnarStore, int year, int month) {
final Calendar startCalendar = Calendar.getInstance();
startCalendar.set(
year,
month,
startCalendar.getMinimum(Calendar.DAY_OF_MONTH),
startCalendar.getMinimum(Calendar.HOUR_OF_DAY),
startCalendar.getMinimum(Calendar.MINUTE),
startCalendar.getMinimum(Calendar.SECOND)
);
startCalendar.set(Calendar.MILLISECOND, startCalendar.getMinimum(Calendar.MILLISECOND));
final long startTime = startCalendar.getTimeInMillis();
final Calendar endCalendar = Calendar.getInstance();
endCalendar.set(Calendar.YEAR, year);
endCalendar.set(Calendar.MONTH, month);
endCalendar.set(Calendar.DAY_OF_MONTH, endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
endCalendar.set(Calendar.HOUR_OF_DAY, endCalendar.getMaximum(Calendar.HOUR_OF_DAY));
endCalendar.set(Calendar.MINUTE, endCalendar.getMaximum(Calendar.HOUR_OF_DAY));
endCalendar.set(Calendar.SECOND, endCalendar.getMaximum(Calendar.HOUR_OF_DAY));
endCalendar.set(Calendar.MILLISECOND, endCalendar.getMaximum(Calendar.MILLISECOND));
final long endTime = endCalendar.getTimeInMillis();
final int[] timeSliceIndexes = columnarStore.extractTimeSlice(startTime, endTime);
return columnarStore.stream(timeSliceIndexes[0], timeSliceIndexes[1]).mapToDouble(EnvObservation::getTemperature).average();
}
}
|
<gh_stars>0
public class Solution {
public int numIslands(char[][] grid) {
int row = grid.length;
if (row == 0) {
return 0;
}
int col = grid[0].length;
boolean[][] visited = new boolean[row][col];
int count = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (!visited[i][j] && grid[i][j] == '1') {
visit(grid, visited, i, j);
count++;
}
}
}
return count;
}
public void visit(char[][] grid, boolean[][] visited, int row, int col) {
// index validation
if (row < 0 || col < 0 || row == grid.length || col == grid[0].length) {
return;
}
if (visited[row][col]) {
return;
} else {
visited[row][col] = true;
}
if (grid[row][col] == '0') {
return;
}
visit(grid, visited, row + 1, col);
visit(grid, visited, row - 1, col);
visit(grid, visited, row, col + 1);
visit(grid, visited, row, col - 1);
}
} |
<gh_stars>1-10
import { DBDriver } from '../driver/abstract'
import { cachedObj, delProperty, dispatch, Keys, options, reactCache, setProperty } from '../shared'
export function set(
cache: reactCache,
driver: DBDriver,
recordData: Record<string, cachedObj['data']>,
recordMeta?: Record<string, cachedObj['meta'] | null>,
options?: options,
): Promise<void>;
export function set(
cache: reactCache,
driver: DBDriver,
key: string,
data: cachedObj['data'],
meta?: cachedObj['meta'],
options?: options,
): Promise<void>;
export async function set(
cache: reactCache,
driver: DBDriver,
...args: unknown[]
): Promise<void> {
if (typeof args[0] == 'string') {
return _set(
cache,
driver,
{ [args[0]]: { data: args[1], meta: args[2] } } as Record<string, cachedObj>,
args[3] as options,
)
} else {
return _set(
cache,
driver,
Object.assign({}, ...Object
.entries(args[0] as Record<string, cachedObj['data']>)
.map(([key, data]) => {
const meta = (args[1] as Record<string, cachedObj['meta']> ?? {})[key]
return meta === null
? { [key]: undefined }
: { [key]: { data, meta } }
}),
),
args[2] as options,
)
}
}
async function _set(
cache: reactCache,
driver: DBDriver,
record: Record<string, { data: cachedObj['data'], meta?: cachedObj['meta'] } | undefined>,
options: options = {},
): Promise<void> {
const entries = Object.entries(record).map(([key, obj]): [string, cachedObj | undefined] => {
if (typeof obj === 'object') {
const {data, meta} = obj
return [key, {
data,
meta: {
date: new Date(),
...meta,
},
}]
}
return [key, undefined]
})
if (!options.skipIdb) {
await driver.setMany(entries)
}
const updateKeys: (keyof reactCache)[] = []
for (const [key, obj] of entries) {
if (obj) {
updateKeys.push(key)
setProperty(cache, [key, 'obj'], obj)
if (options.skipIdb) {
cache[key].isVolatile = true
}
} else if(cache[key]?.obj) {
updateKeys.push(key)
delProperty(cache, [key, 'obj'])
delProperty(cache, [key, 'isVolatile'])
}
}
if (updateKeys.length) {
updateKeys.push(Keys)
dispatch(cache, updateKeys)
}
}
|
// Copyright 2018 The Oppia Authors. 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.
/**
* @fileoverview Directive for the skill prerequisite skills editor.
*/
require('components/skill-selector/select-skill-modal.controller.ts');
require(
'components/skill-selector/skill-selector.directive.ts');
require('domain/skill/skill-update.service.ts');
require('domain/utilities/url-interpolation.service.ts');
require('pages/skill-editor-page/services/skill-editor-state.service.ts');
require('services/alerts.service.ts');
require(
'domain/topics_and_skills_dashboard/' +
'topics-and-skills-dashboard-backend-api.service.ts');
require('pages/skill-editor-page/skill-editor-page.constants.ajs.ts');
require('services/contextual/window-dimensions.service.ts');
angular.module('oppia').directive('skillPrerequisiteSkillsEditor', [
'SkillEditorStateService', 'SkillUpdateService',
'TopicsAndSkillsDashboardBackendApiService', 'UrlInterpolationService',
'WindowDimensionsService',
function(
SkillEditorStateService, SkillUpdateService,
TopicsAndSkillsDashboardBackendApiService, UrlInterpolationService,
WindowDimensionsService) {
return {
restrict: 'E',
scope: {},
templateUrl: UrlInterpolationService.getDirectiveTemplateUrl(
'/pages/skill-editor-page/editor-tab/' +
'skill-prerequisite-skills-editor/' +
'skill-prerequisite-skills-editor.directive.html'),
controller: [
'$scope', '$uibModal', 'AlertsService',
function(
$scope, $uibModal, AlertsService) {
var ctrl = this;
var categorizedSkills = null;
var untriagedSkillSummaries = null;
TopicsAndSkillsDashboardBackendApiService.fetchDashboardData().then(
function(response) {
categorizedSkills = response.categorizedSkillsDict;
untriagedSkillSummaries = response.untriagedSkillSummaries;
});
var groupedSkillSummaries =
SkillEditorStateService.getGroupedSkillSummaries();
$scope.removeSkillId = function(skillId) {
SkillUpdateService.deletePrerequisiteSkill($scope.skill, skillId);
};
$scope.getSkillEditorUrl = function(skillId) {
return '/skill_editor/' + skillId;
};
$scope.addSkill = function() {
// This contains the summaries of skill in the same topic as
// the current skill as the initial entries followed by the others.
var skillsInSameTopicCount =
groupedSkillSummaries.current.length;
var sortedSkillSummaries = groupedSkillSummaries.current.concat(
groupedSkillSummaries.others);
var allowSkillsFromOtherTopics = true;
$uibModal.open({
templateUrl: UrlInterpolationService.getDirectiveTemplateUrl(
'/components/skill-selector/select-skill-modal.template.html'),
backdrop: 'static',
resolve: {
skillsInSameTopicCount: () => skillsInSameTopicCount,
sortedSkillSummaries: () => sortedSkillSummaries,
categorizedSkills: () => categorizedSkills,
allowSkillsFromOtherTopics: () => allowSkillsFromOtherTopics,
untriagedSkillSummaries: () => untriagedSkillSummaries
},
controller: 'SelectSkillModalController',
windowClass: 'skill-select-modal',
size: 'xl'
}).result.then(function(summary) {
var skillId = summary.id;
if (skillId === $scope.skill.getId()) {
AlertsService.addInfoMessage(
'A skill cannot be a prerequisite of itself', 5000);
return;
}
for (var idx in $scope.skill.getPrerequisiteSkillIds()) {
if ($scope.skill.getPrerequisiteSkillIds()[idx] === skillId) {
AlertsService.addInfoMessage(
'Given skill is already a prerequisite skill', 5000);
return;
}
}
SkillUpdateService.addPrerequisiteSkill($scope.skill, skillId);
}, function() {
// Note to developers:
// This callback is triggered when the Cancel button is clicked.
// No further action is needed.
});
};
$scope.togglePrerequisiteSkills = function() {
if (WindowDimensionsService.isWindowNarrow()) {
$scope.prerequisiteSkillsAreShown = (
!$scope.prerequisiteSkillsAreShown);
}
};
ctrl.$onInit = function() {
$scope.skill = SkillEditorStateService.getSkill();
$scope.prerequisiteSkillsAreShown = (
!WindowDimensionsService.isWindowNarrow());
$scope.skillIdToSummaryMap = {};
for (var name in groupedSkillSummaries) {
var skillSummaries = groupedSkillSummaries[name];
for (var idx in skillSummaries) {
$scope.skillIdToSummaryMap[skillSummaries[idx].id] =
skillSummaries[idx].description;
}
}
};
}]
};
}
]);
|
/**
* Executes {@link Job} instances from the {@link JobQueue}.
*/
private class JobQueueExecutor {
/**
* {@link JobQueue}.
*/
private final JobQueue jobQueue = new JobQueue(this);
/**
* Registered {@link ProcessState} identifier instances. Typically should only
* invoke the single {@link ProcessState}.
*/
private final Map<Object, Object> registeredProcessIdentifiers = new ConcurrentHashMap<>();
/**
* {@link Thread}.
*/
private final Thread thread;
/**
* Flag indicating if complete.
*/
private volatile boolean isComplete = false;
/**
* Instantiate.
*
* @param thread {@link Thread}.
*/
private JobQueueExecutor(Thread thread) {
this.thread = thread;
}
/**
* Registers another {@link ProcessState}.
*
* @param process {@link ProcessState}.
*/
private void registerProcess(ProcessState process) {
Object processIdentifier = process.getProcessIdentifier();
this.registeredProcessIdentifiers.put(processIdentifier, processIdentifier);
}
/**
* Indicates the {@link ProcessState} has completed.
*
* @param process {@link ProcessState} that has completed.
*/
private void processComplete(ProcessState process) {
// Unregister the completed process
Object processIdentifier = process.getProcessIdentifier();
this.registeredProcessIdentifiers.remove(processIdentifier);
// Indicate if complete
if (this.registeredProcessIdentifiers.size() == 0) {
this.isComplete = true;
// Wake up job queue (allow completion)
this.jobQueue.wakeUp();
}
}
/**
* Blocking call to execute the {@link Job} instances until completion of all
* {@link ProcessState} instances registered with this {@link JobQueueExecutor}.
*/
public void executeJobs() {
// Execute jobs until all processes complete
while (!this.isComplete) {
// Obtain the next job to execute
Job job = this.jobQueue.dequeue(100);
while (job != null) {
// Execute the job
job.run();
// Obtain the next job
job = this.jobQueue.dequeue(100);
}
}
// Complete so unregister
ThreadLocalAwareExecutorImpl.this.threadToExecutor.remove(this.thread);
}
} |
<filename>aoc-rust/src/bin/aoc-2017-10.rs
fn part1(l: &str, len: usize) -> usize {
let mut r = aoc::Rope::new(len);
for pos in aoc::uints::<usize>(l) {
r.twist(pos);
}
r.product()
}
#[test]
fn part1_works() {
assert_eq!(part1("3,4,1,5", 5), 12);
}
fn part2(l: &str) -> String {
let r = aoc::Rope::new_twisted(256, l);
r.dense_hash()
}
fn main() {
let inp = aoc::read_input_line();
aoc::benchme(|bench: bool| {
let p1 = part1(&inp, 256);
let p2 = part2(&inp);
if !bench {
println!("Part 1: {}", p1);
println!("Part 2: {}", p2);
}
});
}
#[test]
fn part2_works() {
for tc in &[
("", "a2582a3a0e66e6e86e3812dcb672a272"),
("AoC 2017", "33efeb34ea91902bb2f59c9920caa6cd"),
("1,2,3", "3efbe78a8d82f29979031a4aa0b16a9d"),
("1,2,4", "63960835bcdc130f0b66d7ff4f6a5a8e"),
] {
assert_eq!(part2(tc.0), tc.1, "{}", tc.0);
}
}
|
module BABYLON {
export interface PhysicsImpostorParameters {
mass: number;
friction?: number;
restitution?: number;
nativeOptions?: any;
}
export interface IPhysicsEnabledObject {
position: Vector3;
rotationQuaternion: Quaternion;
scaling: Vector3;
rotation?: Vector3;
parent?: any;
getBoundingInfo?(): BoundingInfo;
computeWorldMatrix?(force: boolean): void;
getChildMeshes?(): Array<AbstractMesh>;
getVerticesData?(kind: string): Array<number> | Float32Array;
getIndices?(): IndicesArray;
getScene?(): Scene;
}
export class PhysicsImpostor {
public static DEFAULT_OBJECT_SIZE: Vector3 = new BABYLON.Vector3(1, 1, 1);
private _physicsEngine: PhysicsEngine;
//The native cannon/oimo/energy physics body object.
private _physicsBody: any;
private _bodyUpdateRequired: boolean = false;
private _onBeforePhysicsStepCallbacks = new Array<(impostor: PhysicsImpostor) => void>();
private _onAfterPhysicsStepCallbacks = new Array<(impostor: PhysicsImpostor) => void>();
private _onPhysicsCollideCallbacks: Array<{ callback: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor) => void, otherImpostors: Array<PhysicsImpostor> }> = []
private _deltaPosition: Vector3 = Vector3.Zero();
private _deltaRotation: Quaternion;
private _deltaRotationConjugated: Quaternion;
//If set, this is this impostor's parent
private _parent: PhysicsImpostor;
//set by the physics engine when adding this impostor to the array.
public uniqueId: number;
private _joints: Array<{
joint: PhysicsJoint,
otherImpostor: PhysicsImpostor
}>;
constructor(public object: IPhysicsEnabledObject, public type: number, private _options: PhysicsImpostorParameters = { mass: 0 }, private _scene?: Scene) {
//sanity check!
if (!this.object) {
Tools.Error("No object was provided. A physics object is obligatory");
return;
}
//legacy support for old syntax.
if (!this._scene && object.getScene) {
this._scene = object.getScene()
}
this._physicsEngine = this._scene.getPhysicsEngine();
if (!this._physicsEngine) {
Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.")
} else {
//set the object's quaternion, if not set
if (!this.object.rotationQuaternion) {
if (this.object.rotation) {
this.object.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
} else {
this.object.rotationQuaternion = new Quaternion();
}
}
//default options params
this._options.mass = (_options.mass === void 0) ? 0 : _options.mass
this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction
this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution
this._joints = [];
//If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
if (!this.object.parent) {
this._init();
}
}
}
/**
* This function will completly initialize this impostor.
* It will create a new body - but only if this mesh has no parent.
* If it has, this impostor will not be used other than to define the impostor
* of the child mesh.
*/
public _init() {
this._physicsEngine.removeImpostor(this);
this.physicsBody = null;
this._parent = this._parent || this._getPhysicsParent();
if (!this.parent) {
this._physicsEngine.addImpostor(this);
}
}
private _getPhysicsParent(): PhysicsImpostor {
if (this.object.parent instanceof AbstractMesh) {
var parentMesh: AbstractMesh = <AbstractMesh>this.object.parent;
return parentMesh.physicsImpostor;
}
return;
}
/**
* Should a new body be generated.
*/
public isBodyInitRequired(): boolean {
return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
}
public setScalingUpdated(updated: boolean) {
this.forceUpdate();
}
/**
* Force a regeneration of this or the parent's impostor's body.
* Use under cautious - This will remove all joints already implemented.
*/
public forceUpdate() {
this._init();
if (this.parent) {
this.parent.forceUpdate();
}
}
/*public get mesh(): AbstractMesh {
return this._mesh;
}*/
/**
* Gets the body that holds this impostor. Either its own, or its parent.
*/
public get physicsBody(): any {
return this._parent ? this._parent.physicsBody : this._physicsBody;
}
public get parent(): PhysicsImpostor {
return this._parent;
}
public set parent(value: PhysicsImpostor) {
this._parent = value;
}
/**
* Set the physics body. Used mainly by the physics engine/plugin
*/
public set physicsBody(physicsBody: any) {
if (this._physicsBody) {
this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
}
this._physicsBody = physicsBody;
this.resetUpdateFlags();
}
public resetUpdateFlags() {
this._bodyUpdateRequired = false;
}
public getObjectExtendSize(): Vector3 {
if (this.object.getBoundingInfo) {
this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling)
} else {
return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
}
}
public getObjectCenter(): Vector3 {
if (this.object.getBoundingInfo) {
return this.object.getBoundingInfo().boundingBox.center;
} else {
return this.object.position;
}
}
/**
* Get a specific parametes from the options parameter.
*/
public getParam(paramName: string) {
return this._options[paramName];
}
/**
* Sets a specific parameter in the options given to the physics plugin
*/
public setParam(paramName: string, value: number) {
this._options[paramName] = value;
this._bodyUpdateRequired = true;
}
/**
* Specifically change the body's mass option. Won't recreate the physics body object
*/
public setMass(mass: number) {
if (this.getParam("mass") !== mass) {
this.setParam("mass", mass);
}
this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
}
public getLinearVelocity(): Vector3 {
return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
}
public setLinearVelocity(velocity: Vector3) {
this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
}
public getAngularVelocity(): Vector3 {
return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
}
public setAngularVelocity(velocity: Vector3) {
this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
}
/**
* Execute a function with the physics plugin native code.
* Provide a function the will have two variables - the world object and the physics body object.
*/
public executeNativeFunction(func: (world: any, physicsBody: any) => void) {
func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
}
/**
* Register a function that will be executed before the physics world is stepping forward.
*/
public registerBeforePhysicsStep(func: (impostor: PhysicsImpostor) => void): void {
this._onBeforePhysicsStepCallbacks.push(func);
}
public unregisterBeforePhysicsStep(func: (impostor: PhysicsImpostor) => void): void {
var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
if (index > -1) {
this._onBeforePhysicsStepCallbacks.splice(index, 1);
} else {
Tools.Warn("Function to remove was not found");
}
}
/**
* Register a function that will be executed after the physics step
*/
public registerAfterPhysicsStep(func: (impostor: PhysicsImpostor) => void): void {
this._onAfterPhysicsStepCallbacks.push(func);
}
public unregisterAfterPhysicsStep(func: (impostor: PhysicsImpostor) => void): void {
var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
if (index > -1) {
this._onAfterPhysicsStepCallbacks.splice(index, 1);
} else {
Tools.Warn("Function to remove was not found");
}
}
/**
* register a function that will be executed when this impostor collides against a different body.
*/
public registerOnPhysicsCollide(collideAgainst: PhysicsImpostor | Array<PhysicsImpostor>, func: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor) => void): void {
var collidedAgainstList: Array<PhysicsImpostor> = collideAgainst instanceof Array ? <Array<PhysicsImpostor>>collideAgainst : [<PhysicsImpostor>collideAgainst]
this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
}
public unregisterOnPhysicsCollide(collideAgainst: PhysicsImpostor | Array<PhysicsImpostor>, func: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor | Array<PhysicsImpostor>) => void): void {
var collidedAgainstList: Array<PhysicsImpostor> = collideAgainst instanceof Array ? <Array<PhysicsImpostor>>collideAgainst : [<PhysicsImpostor>collideAgainst]
var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
if (index > -1) {
this._onPhysicsCollideCallbacks.splice(index, 1);
} else {
Tools.Warn("Function to remove was not found");
}
}
private _tmpPositionWithDelta: Vector3 = Vector3.Zero();
private _tmpRotationWithDelta: Quaternion = new Quaternion();
/**
* this function is executed by the physics engine.
*/
public beforeStep = () => {
this.object.position.subtractToRef(this._deltaPosition, this._tmpPositionWithDelta);
//conjugate deltaRotation
if (this._deltaRotationConjugated) {
this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated, this._tmpRotationWithDelta);
} else {
this._tmpRotationWithDelta.copyFrom(this.object.rotationQuaternion);
}
this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this, this._tmpPositionWithDelta, this._tmpRotationWithDelta);
this._onBeforePhysicsStepCallbacks.forEach((func) => {
func(this);
});
}
/**
* this function is executed by the physics engine.
*/
public afterStep = () => {
this._onAfterPhysicsStepCallbacks.forEach((func) => {
func(this);
});
this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this);
this.object.position.addInPlace(this._deltaPosition)
if (this._deltaRotation) {
this.object.rotationQuaternion.multiplyInPlace(this._deltaRotation);
}
}
/**
* Legacy collision detection event support
*/
public onCollideEvent: (collider:BABYLON.PhysicsImpostor, collidedWith:BABYLON.PhysicsImpostor) => void = null;
//event and body object due to cannon's event-based architecture.
public onCollide = (e: { body: any }) => {
if (!this._onPhysicsCollideCallbacks.length && !this.onCollideEvent) return;
var otherImpostor = this._physicsEngine.getImpostorWithPhysicsBody(e.body);
if (otherImpostor) {
// Legacy collision detection event support
if (this.onCollideEvent) {
this.onCollideEvent(this, otherImpostor);
}
this._onPhysicsCollideCallbacks.filter((obj) => {
return obj.otherImpostors.indexOf(otherImpostor) !== -1
}).forEach((obj) => {
obj.callback(this, otherImpostor);
})
}
}
/**
* Apply a force
*/
public applyForce(force: Vector3, contactPoint: Vector3) {
this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
}
/**
* Apply an impulse
*/
public applyImpulse(force: Vector3, contactPoint: Vector3) {
this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
}
/**
* A help function to create a joint.
*/
public createJoint(otherImpostor: PhysicsImpostor, jointType: number, jointData: PhysicsJointData) {
var joint = new PhysicsJoint(jointType, jointData);
this.addJoint(otherImpostor, joint);
}
/**
* Add a joint to this impostor with a different impostor.
*/
public addJoint(otherImpostor: PhysicsImpostor, joint: PhysicsJoint) {
this._joints.push({
otherImpostor: otherImpostor,
joint: joint
})
this._physicsEngine.addJoint(this, otherImpostor, joint);
}
/**
* Will keep this body still, in a sleep mode.
*/
public sleep() {
this._physicsEngine.getPhysicsPlugin().sleepBody(this);
}
/**
* Wake the body up.
*/
public wakeUp() {
this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
}
public clone(newObject: IPhysicsEnabledObject) {
if (!newObject) return null;
return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
}
public dispose(/*disposeChildren: boolean = true*/) {
//no dispose if no physics engine is available.
if (!this._physicsEngine) {
return;
}
this._joints.forEach((j) => {
this._physicsEngine.removeJoint(this, j.otherImpostor, j.joint);
})
//dispose the physics body
this._physicsEngine.removeImpostor(this);
if (this.parent) {
this.parent.forceUpdate();
} else {
/*this._object.getChildMeshes().forEach(function(mesh) {
if (mesh.physicsImpostor) {
if (disposeChildren) {
mesh.physicsImpostor.dispose();
mesh.physicsImpostor = null;
}
}
})*/
}
}
public setDeltaPosition(position: Vector3) {
this._deltaPosition.copyFrom(position);
}
public setDeltaRotation(rotation: Quaternion) {
if (!this._deltaRotation) {
this._deltaRotation = new Quaternion();
}
this._deltaRotation.copyFrom(rotation);
this._deltaRotationConjugated = this._deltaRotation.conjugate();
}
//Impostor types
public static NoImpostor = 0;
public static SphereImpostor = 1;
public static BoxImpostor = 2;
public static PlaneImpostor = 3;
public static MeshImpostor = 4;
public static CylinderImpostor = 7;
public static ParticleImpostor = 8;
public static HeightmapImpostor = 9;
}
}
|
/**
* @author Artem Pronchakov <[email protected]>
*/
@ClientEndpoint
public class HelloClientEndpoint {
private static final Logger log = LoggerFactory.getLogger(HelloClientEndpoint.class);
public HelloClientEndpoint() {
log.debug("new HelloClientEndpoint()");
}
@OnOpen
public void open(Session session) {
}
@OnMessage
public void onMessage(String message) {
log.debug("HelloClientEndpoint received a message: {}", message);
}
@OnClose
public void close(CloseReason reason) {
log.debug("HelloClientEndpoint closed: Reason: ", reason.getReasonPhrase());
}
} |
def gauge(self, metric, value, delta=False, rate=1.0, tags=None):
if self.enabled:
self._statsd.gauge(self.get_metric_name(metric, tags),
value,
rate=rate,
delta=delta) |
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package applicationdiscoveryserviceiface provides an interface to enable mocking the AWS Application Discovery Service service client
// for testing your code.
//
// It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators,
// and waiters.
package applicationdiscoveryserviceiface
import (
"github.com/journeymidnight/aws-sdk-go/aws"
"github.com/journeymidnight/aws-sdk-go/aws/request"
"github.com/journeymidnight/aws-sdk-go/service/applicationdiscoveryservice"
)
// ApplicationDiscoveryServiceAPI provides an interface to enable mocking the
// applicationdiscoveryservice.ApplicationDiscoveryService service client's API operation,
// paginators, and waiters. This make unit testing your code that calls out
// to the SDK's service client's calls easier.
//
// The best way to use this interface is so the SDK's service client's calls
// can be stubbed out for unit testing your code with the SDK without needing
// to inject custom request handlers into the SDK's request pipeline.
//
// // myFunc uses an SDK service client to make a request to
// // AWS Application Discovery Service.
// func myFunc(svc applicationdiscoveryserviceiface.ApplicationDiscoveryServiceAPI) bool {
// // Make svc.AssociateConfigurationItemsToApplication request
// }
//
// func main() {
// sess := session.New()
// svc := applicationdiscoveryservice.New(sess)
//
// myFunc(svc)
// }
//
// In your _test.go file:
//
// // Define a mock struct to be used in your unit tests of myFunc.
// type mockApplicationDiscoveryServiceClient struct {
// applicationdiscoveryserviceiface.ApplicationDiscoveryServiceAPI
// }
// func (m *mockApplicationDiscoveryServiceClient) AssociateConfigurationItemsToApplication(input *applicationdiscoveryservice.AssociateConfigurationItemsToApplicationInput) (*applicationdiscoveryservice.AssociateConfigurationItemsToApplicationOutput, error) {
// // mock response/functionality
// }
//
// func TestMyFunc(t *testing.T) {
// // Setup Test
// mockSvc := &mockApplicationDiscoveryServiceClient{}
//
// myfunc(mockSvc)
//
// // Verify myFunc's functionality
// }
//
// It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators,
// and waiters. Its suggested to use the pattern above for testing, or using
// tooling to generate mocks to satisfy the interfaces.
type ApplicationDiscoveryServiceAPI interface {
AssociateConfigurationItemsToApplication(*applicationdiscoveryservice.AssociateConfigurationItemsToApplicationInput) (*applicationdiscoveryservice.AssociateConfigurationItemsToApplicationOutput, error)
AssociateConfigurationItemsToApplicationWithContext(aws.Context, *applicationdiscoveryservice.AssociateConfigurationItemsToApplicationInput, ...request.Option) (*applicationdiscoveryservice.AssociateConfigurationItemsToApplicationOutput, error)
AssociateConfigurationItemsToApplicationRequest(*applicationdiscoveryservice.AssociateConfigurationItemsToApplicationInput) (*request.Request, *applicationdiscoveryservice.AssociateConfigurationItemsToApplicationOutput)
BatchDeleteImportData(*applicationdiscoveryservice.BatchDeleteImportDataInput) (*applicationdiscoveryservice.BatchDeleteImportDataOutput, error)
BatchDeleteImportDataWithContext(aws.Context, *applicationdiscoveryservice.BatchDeleteImportDataInput, ...request.Option) (*applicationdiscoveryservice.BatchDeleteImportDataOutput, error)
BatchDeleteImportDataRequest(*applicationdiscoveryservice.BatchDeleteImportDataInput) (*request.Request, *applicationdiscoveryservice.BatchDeleteImportDataOutput)
CreateApplication(*applicationdiscoveryservice.CreateApplicationInput) (*applicationdiscoveryservice.CreateApplicationOutput, error)
CreateApplicationWithContext(aws.Context, *applicationdiscoveryservice.CreateApplicationInput, ...request.Option) (*applicationdiscoveryservice.CreateApplicationOutput, error)
CreateApplicationRequest(*applicationdiscoveryservice.CreateApplicationInput) (*request.Request, *applicationdiscoveryservice.CreateApplicationOutput)
CreateTags(*applicationdiscoveryservice.CreateTagsInput) (*applicationdiscoveryservice.CreateTagsOutput, error)
CreateTagsWithContext(aws.Context, *applicationdiscoveryservice.CreateTagsInput, ...request.Option) (*applicationdiscoveryservice.CreateTagsOutput, error)
CreateTagsRequest(*applicationdiscoveryservice.CreateTagsInput) (*request.Request, *applicationdiscoveryservice.CreateTagsOutput)
DeleteApplications(*applicationdiscoveryservice.DeleteApplicationsInput) (*applicationdiscoveryservice.DeleteApplicationsOutput, error)
DeleteApplicationsWithContext(aws.Context, *applicationdiscoveryservice.DeleteApplicationsInput, ...request.Option) (*applicationdiscoveryservice.DeleteApplicationsOutput, error)
DeleteApplicationsRequest(*applicationdiscoveryservice.DeleteApplicationsInput) (*request.Request, *applicationdiscoveryservice.DeleteApplicationsOutput)
DeleteTags(*applicationdiscoveryservice.DeleteTagsInput) (*applicationdiscoveryservice.DeleteTagsOutput, error)
DeleteTagsWithContext(aws.Context, *applicationdiscoveryservice.DeleteTagsInput, ...request.Option) (*applicationdiscoveryservice.DeleteTagsOutput, error)
DeleteTagsRequest(*applicationdiscoveryservice.DeleteTagsInput) (*request.Request, *applicationdiscoveryservice.DeleteTagsOutput)
DescribeAgents(*applicationdiscoveryservice.DescribeAgentsInput) (*applicationdiscoveryservice.DescribeAgentsOutput, error)
DescribeAgentsWithContext(aws.Context, *applicationdiscoveryservice.DescribeAgentsInput, ...request.Option) (*applicationdiscoveryservice.DescribeAgentsOutput, error)
DescribeAgentsRequest(*applicationdiscoveryservice.DescribeAgentsInput) (*request.Request, *applicationdiscoveryservice.DescribeAgentsOutput)
DescribeConfigurations(*applicationdiscoveryservice.DescribeConfigurationsInput) (*applicationdiscoveryservice.DescribeConfigurationsOutput, error)
DescribeConfigurationsWithContext(aws.Context, *applicationdiscoveryservice.DescribeConfigurationsInput, ...request.Option) (*applicationdiscoveryservice.DescribeConfigurationsOutput, error)
DescribeConfigurationsRequest(*applicationdiscoveryservice.DescribeConfigurationsInput) (*request.Request, *applicationdiscoveryservice.DescribeConfigurationsOutput)
DescribeContinuousExports(*applicationdiscoveryservice.DescribeContinuousExportsInput) (*applicationdiscoveryservice.DescribeContinuousExportsOutput, error)
DescribeContinuousExportsWithContext(aws.Context, *applicationdiscoveryservice.DescribeContinuousExportsInput, ...request.Option) (*applicationdiscoveryservice.DescribeContinuousExportsOutput, error)
DescribeContinuousExportsRequest(*applicationdiscoveryservice.DescribeContinuousExportsInput) (*request.Request, *applicationdiscoveryservice.DescribeContinuousExportsOutput)
DescribeContinuousExportsPages(*applicationdiscoveryservice.DescribeContinuousExportsInput, func(*applicationdiscoveryservice.DescribeContinuousExportsOutput, bool) bool) error
DescribeContinuousExportsPagesWithContext(aws.Context, *applicationdiscoveryservice.DescribeContinuousExportsInput, func(*applicationdiscoveryservice.DescribeContinuousExportsOutput, bool) bool, ...request.Option) error
DescribeExportConfigurations(*applicationdiscoveryservice.DescribeExportConfigurationsInput) (*applicationdiscoveryservice.DescribeExportConfigurationsOutput, error)
DescribeExportConfigurationsWithContext(aws.Context, *applicationdiscoveryservice.DescribeExportConfigurationsInput, ...request.Option) (*applicationdiscoveryservice.DescribeExportConfigurationsOutput, error)
DescribeExportConfigurationsRequest(*applicationdiscoveryservice.DescribeExportConfigurationsInput) (*request.Request, *applicationdiscoveryservice.DescribeExportConfigurationsOutput)
DescribeExportTasks(*applicationdiscoveryservice.DescribeExportTasksInput) (*applicationdiscoveryservice.DescribeExportTasksOutput, error)
DescribeExportTasksWithContext(aws.Context, *applicationdiscoveryservice.DescribeExportTasksInput, ...request.Option) (*applicationdiscoveryservice.DescribeExportTasksOutput, error)
DescribeExportTasksRequest(*applicationdiscoveryservice.DescribeExportTasksInput) (*request.Request, *applicationdiscoveryservice.DescribeExportTasksOutput)
DescribeImportTasks(*applicationdiscoveryservice.DescribeImportTasksInput) (*applicationdiscoveryservice.DescribeImportTasksOutput, error)
DescribeImportTasksWithContext(aws.Context, *applicationdiscoveryservice.DescribeImportTasksInput, ...request.Option) (*applicationdiscoveryservice.DescribeImportTasksOutput, error)
DescribeImportTasksRequest(*applicationdiscoveryservice.DescribeImportTasksInput) (*request.Request, *applicationdiscoveryservice.DescribeImportTasksOutput)
DescribeImportTasksPages(*applicationdiscoveryservice.DescribeImportTasksInput, func(*applicationdiscoveryservice.DescribeImportTasksOutput, bool) bool) error
DescribeImportTasksPagesWithContext(aws.Context, *applicationdiscoveryservice.DescribeImportTasksInput, func(*applicationdiscoveryservice.DescribeImportTasksOutput, bool) bool, ...request.Option) error
DescribeTags(*applicationdiscoveryservice.DescribeTagsInput) (*applicationdiscoveryservice.DescribeTagsOutput, error)
DescribeTagsWithContext(aws.Context, *applicationdiscoveryservice.DescribeTagsInput, ...request.Option) (*applicationdiscoveryservice.DescribeTagsOutput, error)
DescribeTagsRequest(*applicationdiscoveryservice.DescribeTagsInput) (*request.Request, *applicationdiscoveryservice.DescribeTagsOutput)
DisassociateConfigurationItemsFromApplication(*applicationdiscoveryservice.DisassociateConfigurationItemsFromApplicationInput) (*applicationdiscoveryservice.DisassociateConfigurationItemsFromApplicationOutput, error)
DisassociateConfigurationItemsFromApplicationWithContext(aws.Context, *applicationdiscoveryservice.DisassociateConfigurationItemsFromApplicationInput, ...request.Option) (*applicationdiscoveryservice.DisassociateConfigurationItemsFromApplicationOutput, error)
DisassociateConfigurationItemsFromApplicationRequest(*applicationdiscoveryservice.DisassociateConfigurationItemsFromApplicationInput) (*request.Request, *applicationdiscoveryservice.DisassociateConfigurationItemsFromApplicationOutput)
ExportConfigurations(*applicationdiscoveryservice.ExportConfigurationsInput) (*applicationdiscoveryservice.ExportConfigurationsOutput, error)
ExportConfigurationsWithContext(aws.Context, *applicationdiscoveryservice.ExportConfigurationsInput, ...request.Option) (*applicationdiscoveryservice.ExportConfigurationsOutput, error)
ExportConfigurationsRequest(*applicationdiscoveryservice.ExportConfigurationsInput) (*request.Request, *applicationdiscoveryservice.ExportConfigurationsOutput)
GetDiscoverySummary(*applicationdiscoveryservice.GetDiscoverySummaryInput) (*applicationdiscoveryservice.GetDiscoverySummaryOutput, error)
GetDiscoverySummaryWithContext(aws.Context, *applicationdiscoveryservice.GetDiscoverySummaryInput, ...request.Option) (*applicationdiscoveryservice.GetDiscoverySummaryOutput, error)
GetDiscoverySummaryRequest(*applicationdiscoveryservice.GetDiscoverySummaryInput) (*request.Request, *applicationdiscoveryservice.GetDiscoverySummaryOutput)
ListConfigurations(*applicationdiscoveryservice.ListConfigurationsInput) (*applicationdiscoveryservice.ListConfigurationsOutput, error)
ListConfigurationsWithContext(aws.Context, *applicationdiscoveryservice.ListConfigurationsInput, ...request.Option) (*applicationdiscoveryservice.ListConfigurationsOutput, error)
ListConfigurationsRequest(*applicationdiscoveryservice.ListConfigurationsInput) (*request.Request, *applicationdiscoveryservice.ListConfigurationsOutput)
ListServerNeighbors(*applicationdiscoveryservice.ListServerNeighborsInput) (*applicationdiscoveryservice.ListServerNeighborsOutput, error)
ListServerNeighborsWithContext(aws.Context, *applicationdiscoveryservice.ListServerNeighborsInput, ...request.Option) (*applicationdiscoveryservice.ListServerNeighborsOutput, error)
ListServerNeighborsRequest(*applicationdiscoveryservice.ListServerNeighborsInput) (*request.Request, *applicationdiscoveryservice.ListServerNeighborsOutput)
StartContinuousExport(*applicationdiscoveryservice.StartContinuousExportInput) (*applicationdiscoveryservice.StartContinuousExportOutput, error)
StartContinuousExportWithContext(aws.Context, *applicationdiscoveryservice.StartContinuousExportInput, ...request.Option) (*applicationdiscoveryservice.StartContinuousExportOutput, error)
StartContinuousExportRequest(*applicationdiscoveryservice.StartContinuousExportInput) (*request.Request, *applicationdiscoveryservice.StartContinuousExportOutput)
StartDataCollectionByAgentIds(*applicationdiscoveryservice.StartDataCollectionByAgentIdsInput) (*applicationdiscoveryservice.StartDataCollectionByAgentIdsOutput, error)
StartDataCollectionByAgentIdsWithContext(aws.Context, *applicationdiscoveryservice.StartDataCollectionByAgentIdsInput, ...request.Option) (*applicationdiscoveryservice.StartDataCollectionByAgentIdsOutput, error)
StartDataCollectionByAgentIdsRequest(*applicationdiscoveryservice.StartDataCollectionByAgentIdsInput) (*request.Request, *applicationdiscoveryservice.StartDataCollectionByAgentIdsOutput)
StartExportTask(*applicationdiscoveryservice.StartExportTaskInput) (*applicationdiscoveryservice.StartExportTaskOutput, error)
StartExportTaskWithContext(aws.Context, *applicationdiscoveryservice.StartExportTaskInput, ...request.Option) (*applicationdiscoveryservice.StartExportTaskOutput, error)
StartExportTaskRequest(*applicationdiscoveryservice.StartExportTaskInput) (*request.Request, *applicationdiscoveryservice.StartExportTaskOutput)
StartImportTask(*applicationdiscoveryservice.StartImportTaskInput) (*applicationdiscoveryservice.StartImportTaskOutput, error)
StartImportTaskWithContext(aws.Context, *applicationdiscoveryservice.StartImportTaskInput, ...request.Option) (*applicationdiscoveryservice.StartImportTaskOutput, error)
StartImportTaskRequest(*applicationdiscoveryservice.StartImportTaskInput) (*request.Request, *applicationdiscoveryservice.StartImportTaskOutput)
StopContinuousExport(*applicationdiscoveryservice.StopContinuousExportInput) (*applicationdiscoveryservice.StopContinuousExportOutput, error)
StopContinuousExportWithContext(aws.Context, *applicationdiscoveryservice.StopContinuousExportInput, ...request.Option) (*applicationdiscoveryservice.StopContinuousExportOutput, error)
StopContinuousExportRequest(*applicationdiscoveryservice.StopContinuousExportInput) (*request.Request, *applicationdiscoveryservice.StopContinuousExportOutput)
StopDataCollectionByAgentIds(*applicationdiscoveryservice.StopDataCollectionByAgentIdsInput) (*applicationdiscoveryservice.StopDataCollectionByAgentIdsOutput, error)
StopDataCollectionByAgentIdsWithContext(aws.Context, *applicationdiscoveryservice.StopDataCollectionByAgentIdsInput, ...request.Option) (*applicationdiscoveryservice.StopDataCollectionByAgentIdsOutput, error)
StopDataCollectionByAgentIdsRequest(*applicationdiscoveryservice.StopDataCollectionByAgentIdsInput) (*request.Request, *applicationdiscoveryservice.StopDataCollectionByAgentIdsOutput)
UpdateApplication(*applicationdiscoveryservice.UpdateApplicationInput) (*applicationdiscoveryservice.UpdateApplicationOutput, error)
UpdateApplicationWithContext(aws.Context, *applicationdiscoveryservice.UpdateApplicationInput, ...request.Option) (*applicationdiscoveryservice.UpdateApplicationOutput, error)
UpdateApplicationRequest(*applicationdiscoveryservice.UpdateApplicationInput) (*request.Request, *applicationdiscoveryservice.UpdateApplicationOutput)
}
var _ ApplicationDiscoveryServiceAPI = (*applicationdiscoveryservice.ApplicationDiscoveryService)(nil)
|
Identification and characterization of the minimal androgen-regulated kidney-specific kidney androgen-regulated protein gene promoter.
The kidney androgen-regulated protein (Kap) gene is tissue specific and regulated by androgen in mouse kidney proximal tubule cells (PTCs). In the present study, we aimed to identify the minimal PTC-specific androgen-regulated Kap promoter and analyze its androgen response elements (AREs). A deletion series of the Kap1542 promoter/luciferase constructs were assayed in opossum kidney (OK) PTCs in the presence or absence of 15 nM dihydrotestosterone (DHT). Kap1542 and Kap637 had low activity and no androgen induction; Kap224 had a basal activity that was 4- to 5-fold higher than that of Kap1542, but was only slightly induced by DHT. Kap147 had a basal activity that was 2- to 3-fold higher than that of Kap1542 and was induced by DHT 4- to 6-fold. Kap77 abolished basal promoter activity but was still induced by DHT. Results showed that, in vitro, Kap147 was a minimal androgen-regulated promoter. Transient transfection in different cells demonstrated that Kap147 specifically initiated reporter gene expression in PTCs. Sequence analysis revealed two potential AREs located at positions -124 and -39 of Kap147. Mutational assays showed that only the ARE at -124 was involved in androgen response in OK cells. Electrophoretic mobility shift assay also verified -124 ARE bound specifically to androgen receptor. In conclusion, we defined the minimal Kap147 promoter that may be a good model for the study of kidney PTC-specific expression and molecular mechanisms that lead to an androgen-specific responsiveness in vivo. |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2020 Edgewall Software
# Copyright (C) 2006 <NAME> <<EMAIL>>
# Copyright (C) 2006 <NAME> <<EMAIL>>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at https://trac.edgewall.org/log/.
"""Various classes and functions to provide some backwards-compatibility with
previous versions of Python from 2.6 onward.
"""
import errno
import math
import os
import subprocess
import time
from trac.util.text import cleandoc
# Windows doesn't have a crypt module by default.
try:
from crypt import crypt
except ImportError:
try:
from passlib.hash import des_crypt
except ImportError:
crypt = None
else:
def crypt(secret, salt):
# encrypt method deprecated in favor of hash in passlib 1.7
if hasattr(des_crypt, 'hash'):
return des_crypt.using(salt=salt).hash(secret)
else:
return des_crypt.encrypt(secret, salt=salt)
# Import symbols previously defined here, kept around so that plugins importing
# them don't suddenly stop working
all = all
any = any
frozenset = frozenset
reversed = reversed
set = set
sorted = sorted
from collections import OrderedDict
from functools import partial
from hashlib import md5, sha1
from itertools import groupby, tee
class Popen(subprocess.Popen):
"""Popen objects are supported as context managers starting in
Python 3.2. This code was taken from Python 3.5 and can be removed
when support for Python < 3.2 is dropped.
"""
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
if self.stdout:
self.stdout.close()
if self.stderr:
self.stderr.close()
try: # Flushing a BufferedWriter may raise an error
if self.stdin:
self.stdin.close()
finally:
# Wait for the process to terminate, to avoid zombies.
self.wait()
def rpartition(s, sep):
return s.rpartition(sep)
# An error is raised by subprocess if we ever pass close_fds=True on Windows.
# We want it to be True on all other platforms to not leak file descriptors.
close_fds = os.name != 'nt'
def wait_for_file_mtime_change(filename):
"""This function is typically called before a file save operation,
waiting if necessary for the file modification time to change. The
purpose is to avoid successive file updates going undetected by the
caching mechanism that depends on a change in the file modification
time to know when the file should be reparsed."""
from trac.util import touch_file
try:
mtime = os.stat(filename).st_mtime
touch_file(filename)
while mtime == os.stat(filename).st_mtime:
time.sleep(1e-3)
touch_file(filename)
except OSError as e:
if e.errno == errno.ENOENT:
pass
else:
raise
|
/**
* Send the specified shared secret to a running cloud foundry application.
*
* @param client client
* @param secret the secret to send
* @param application the application to send the secret to
*/
public void sendTo(CloudFoundryClient client, SharedSecret secret, CloudApplication application) throws CloudFoundryException {
Assert.notNull(client, "Client must not be null");
Assert.notNull(application, "Application must not be null");
if (this.logger.isDebugEnabled()) {
this.logger.debug("Propagating shared secret to " + application.getName());
}
Map<String, String> env = new HashMap<String, String>();
env.putAll(application.getEnvAsMap());
String envValue = Hex.encodeHexString(secret.getBytes());
if (!envValue.equals(env.get(ENV_KEY))) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Restarting " + application.getName() + " due to new shared secret");
}
env.put(ENV_KEY, envValue);
client.updateApplicationEnv(application.getName(), env);
client.restartApplication(application.getName());
}
} |
<filename>headers/PlaySeriesController.h
//
// PlayerController.h
// Tournament
//
// Created by <NAME> on Wed Dec 26 2001.
// Copyright (c) 2001 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import "PlaySeries.h"
@interface PlaySeriesController : NSObject<NSTableViewDataSource> {
id table;
NSMutableArray *playSeries;
}
- init;
- (void) newPlaySeriesWithSamePass:sender;
- (void) newPlaySeriesWithPass:(long)pass series:(NSString *)series;
- (void) deleteSelected:sender;
- (void) deleteWholeDatabase:sender;
-(IBAction)replaceAssignments:(id)sender;
- (void) saveAll:sender;
- (void) getPlaySeriesWithPass:(long)pass;
- (void)fixNumberFormats;
- (NSArray *) shownSeries;
/******** datasource methods for a table view ********/
- (long)numberOfRowsInTableView:(NSTableView *)aTableView;
- (id)tableView:(NSTableView *)aTableView
objectValueForTableColumn:(NSTableColumn *)aTableColumn
row:(long)rowIndex;
- (void)tableView:(NSTableView *)aTableView
setObjectValue:(id)anObject
forTableColumn:(NSTableColumn *)aTableColumn
row:(long)rowIndex;
/******** delegate methods for a table view ********/
- (void)tableViewSelectionDidChange:(NSNotification *)aNotification;
@end
|
package codec
import (
"errors"
"fmt"
"strings"
"github.com/bitmovin/bitmovin-api-sdk-go/model"
"github.com/cbsinteractive/transcode-orchestrator/client/transcoding/job"
)
var ErrUnsupportedValue = errors.New("unsupported value")
var ErrEmptyList = errors.New("empty list")
var AudioSampleRate = 48000.
type enum []string
func (e enum) Set(src string, dst interface{}) error {
if len(e) == 0 {
return ErrEmptyList
}
if src == "" && len(e) > 0 {
src = e[0]
}
for _, v := range e {
if strings.EqualFold(v, src) {
_, err := fmt.Sscan(v, dst)
return err
}
}
return ErrUnsupportedValue
}
func list(v ...interface{}) (s enum) {
for _, v := range v {
s = append(s, fmt.Sprint(v))
}
return s
}
type VideoPTR struct {
Name *string
Width, Height **int32
Bitrate **int64
MinGop, MaxGop **int32
MinKeyframeInterval, MaxKeyframeInterval **float64
EncodingMode *model.EncodingMode
Profile, Level interface{}
}
type codec struct {
Profiles enum
Levels enum
id string
err error
}
func (c *codec) setVideo(cfg VideoPTR, p job.File) bool {
*cfg.Name = strings.ToLower(p.Name)
if n := int32(p.Video.Width); n != 0 && cfg.Width != nil {
*cfg.Width = &n
}
if n := int32(p.Video.Height); n != 0 && cfg.Height != nil {
*cfg.Height = &n
}
if n := int64(p.Video.Bitrate.BPS); n != 0 && cfg.Bitrate != nil {
*cfg.Bitrate = &n
}
size := int32(p.Video.Gop.Size)
if size != 0 {
if p.Video.Gop.Seconds() {
if cfg.MinKeyframeInterval != nil && cfg.MaxKeyframeInterval != nil {
*cfg.MinKeyframeInterval = &p.Video.Gop.Size
*cfg.MaxKeyframeInterval = &p.Video.Gop.Size
}
} else {
if cfg.MinGop != nil && cfg.MaxGop != nil {
*cfg.MinGop = &size
*cfg.MaxGop = &size
}
}
}
if cfg.EncodingMode != nil {
// some of these can fail on single pass mode
// check that in the specific codecs
*cfg.EncodingMode = model.EncodingMode_SINGLE_PASS
if p.Video.Bitrate.TwoPass {
*cfg.EncodingMode = model.EncodingMode_TWO_PASS
}
}
if cfg.Profile != nil {
if err := c.Profiles.Set(p.Video.Profile, cfg.Profile); err != nil {
return c.errorf("%s: profile: %w", *cfg.Name, err)
}
}
if cfg.Level != nil {
if err := c.Levels.Set(p.Video.Level, cfg.Level); err != nil {
return c.errorf("%s: level: %w", *cfg.Name, err)
}
}
return c.ok()
}
func (c codec) ok() bool { return c.err == nil }
func (c codec) Err() error { return c.err }
func (c codec) ID() string { return c.id }
func (c *codec) error(err error) bool {
c.err = err
return c.ok()
}
func (c *codec) errorf(fm string, a ...interface{}) bool {
return c.error(fmt.Errorf(fm, a...))
}
var zero = int32(0)
func ptr(n int) *int32 {
i := int32(n)
return &i
}
|
def create_pvc_clone_resource(self, clone, source):
pvc_data = self.api.read_namespaced_persistent_volume_claim(name=source, namespace=self.namespace)
pvc_size = pvc_data.spec.resources.requests['storage']
storage_class = pvc_data.spec.storage_class_name
pvc_status = self.create_pvc_clone(clone, source, pvc_size, storage_class)
if pvc_status['code'] == 201:
phase = ""
counter = 0
while phase != 'Bound' and counter < 60:
counter += 1
sleep(1)
status = self.read_status(
"pvc", pvc_status['resource_name'])
phase = status.status.phase
pvc_status['time'] = counter
pvc_status['name'] = clone
return pvc_status |
#include <hxcpp.h>
#ifndef INCLUDED_EReg
#include <EReg.h>
#endif
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_haxe_Timer
#include <haxe/Timer.h>
#endif
#ifndef INCLUDED_haxe_io_Path
#include <haxe/io/Path.h>
#endif
#ifndef INCLUDED_hxMath
#include <hxMath.h>
#endif
#ifndef INCLUDED_lime_graphics_opengl_GLObject
#include <lime/graphics/opengl/GLObject.h>
#endif
#ifndef INCLUDED_lime_graphics_opengl_GLTexture
#include <lime/graphics/opengl/GLTexture.h>
#endif
#ifndef INCLUDED_lime_math_Vector2
#include <lime/math/Vector2.h>
#endif
#ifndef INCLUDED_lime_system_System
#include <lime/system/System.h>
#endif
#ifndef INCLUDED_lime_text_Font
#include <lime/text/Font.h>
#endif
#ifndef INCLUDED_lime_text_GlyphPosition
#include <lime/text/GlyphPosition.h>
#endif
#ifndef INCLUDED_lime_text_TextLayout
#include <lime/text/TextLayout.h>
#endif
#ifndef INCLUDED_openfl_Lib
#include <openfl/Lib.h>
#endif
#ifndef INCLUDED_openfl__internal_renderer_RenderSession
#include <openfl/_internal/renderer/RenderSession.h>
#endif
#ifndef INCLUDED_openfl__internal_renderer_opengl_GLTextField
#include <openfl/_internal/renderer/opengl/GLTextField.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObject
#include <openfl/display/DisplayObject.h>
#endif
#ifndef INCLUDED_openfl_display_IBitmapDrawable
#include <openfl/display/IBitmapDrawable.h>
#endif
#ifndef INCLUDED_openfl_display_InteractiveObject
#include <openfl/display/InteractiveObject.h>
#endif
#ifndef INCLUDED_openfl_display_Tilesheet
#include <openfl/display/Tilesheet.h>
#endif
#ifndef INCLUDED_openfl_events_EventDispatcher
#include <openfl/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_events_IEventDispatcher
#include <openfl/events/IEventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_geom_Matrix
#include <openfl/geom/Matrix.h>
#endif
#ifndef INCLUDED_openfl_geom_Point
#include <openfl/geom/Point.h>
#endif
#ifndef INCLUDED_openfl_geom_Rectangle
#include <openfl/geom/Rectangle.h>
#endif
#ifndef INCLUDED_openfl_text_AntiAliasType
#include <openfl/text/AntiAliasType.h>
#endif
#ifndef INCLUDED_openfl_text_Font
#include <openfl/text/Font.h>
#endif
#ifndef INCLUDED_openfl_text_GridFitType
#include <openfl/text/GridFitType.h>
#endif
#ifndef INCLUDED_openfl_text_TextField
#include <openfl/text/TextField.h>
#endif
#ifndef INCLUDED_openfl_text_TextFieldAutoSize
#include <openfl/text/TextFieldAutoSize.h>
#endif
#ifndef INCLUDED_openfl_text_TextFieldType
#include <openfl/text/TextFieldType.h>
#endif
#ifndef INCLUDED_openfl_text_TextFormat
#include <openfl/text/TextFormat.h>
#endif
#ifndef INCLUDED_openfl_text_TextFormatAlign
#include <openfl/text/TextFormatAlign.h>
#endif
#ifndef INCLUDED_openfl_text_TextFormatRange
#include <openfl/text/TextFormatRange.h>
#endif
#ifndef INCLUDED_openfl_text_TextLineMetrics
#include <openfl/text/TextLineMetrics.h>
#endif
namespace openfl{
namespace text{
Void TextField_obj::__construct()
{
HX_STACK_FRAME("openfl.text.TextField","new",0xbd7676bc,"openfl.text.TextField.new","openfl/text/TextField.hx",595,0xccf02094)
HX_STACK_THIS(this)
{
HX_STACK_LINE(597)
super::__construct();
HX_STACK_LINE(599)
this->__width = (int)100;
HX_STACK_LINE(600)
this->__height = (int)100;
HX_STACK_LINE(601)
this->__text = HX_CSTRING("");
HX_STACK_LINE(603)
this->set_type(::openfl::text::TextFieldType_obj::DYNAMIC);
HX_STACK_LINE(604)
this->set_autoSize(::openfl::text::TextFieldAutoSize_obj::NONE);
HX_STACK_LINE(605)
this->displayAsPassword = false;
HX_STACK_LINE(606)
this->embedFonts = false;
HX_STACK_LINE(607)
this->selectable = true;
HX_STACK_LINE(608)
this->set_borderColor((int)0);
HX_STACK_LINE(609)
this->set_border(false);
HX_STACK_LINE(610)
this->set_backgroundColor((int)16777215);
HX_STACK_LINE(611)
this->set_background(false);
HX_STACK_LINE(612)
this->gridFitType = ::openfl::text::GridFitType_obj::PIXEL;
HX_STACK_LINE(613)
this->maxChars = (int)0;
HX_STACK_LINE(614)
this->multiline = false;
HX_STACK_LINE(615)
this->sharpness = (int)0;
HX_STACK_LINE(616)
this->scrollH = (int)0;
HX_STACK_LINE(617)
this->scrollV = (int)1;
HX_STACK_LINE(618)
this->set_wordWrap(false);
HX_STACK_LINE(620)
if (((::openfl::text::TextField_obj::__defaultTextFormat == null()))){
HX_STACK_LINE(622)
::openfl::text::TextFormat _g = ::openfl::text::TextFormat_obj::__new(HX_CSTRING("Times New Roman"),(int)12,(int)0,false,false,false,HX_CSTRING(""),HX_CSTRING(""),::openfl::text::TextFormatAlign_obj::LEFT,(int)0,(int)0,(int)0,(int)0); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(622)
::openfl::text::TextField_obj::__defaultTextFormat = _g;
HX_STACK_LINE(623)
::openfl::text::TextField_obj::__defaultTextFormat->blockIndent = (int)0;
HX_STACK_LINE(624)
::openfl::text::TextField_obj::__defaultTextFormat->bullet = false;
HX_STACK_LINE(625)
::openfl::text::TextField_obj::__defaultTextFormat->letterSpacing = (int)0;
HX_STACK_LINE(626)
::openfl::text::TextField_obj::__defaultTextFormat->kerning = false;
}
HX_STACK_LINE(630)
::openfl::text::TextFormat _g1 = ::openfl::text::TextField_obj::__defaultTextFormat->clone(); HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(630)
this->__textFormat = _g1;
}
;
return null();
}
//TextField_obj::~TextField_obj() { }
Dynamic TextField_obj::__CreateEmpty() { return new TextField_obj; }
hx::ObjectPtr< TextField_obj > TextField_obj::__new()
{ hx::ObjectPtr< TextField_obj > result = new TextField_obj();
result->__construct();
return result;}
Dynamic TextField_obj::__Create(hx::DynamicArray inArgs)
{ hx::ObjectPtr< TextField_obj > result = new TextField_obj();
result->__construct();
return result;}
Void TextField_obj::appendText( ::String text){
{
HX_STACK_FRAME("openfl.text.TextField","appendText",0xaa44eccb,"openfl.text.TextField.appendText","openfl/text/TextField.hx",646,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(text,"text")
HX_STACK_LINE(646)
::openfl::text::TextField _g = hx::ObjectPtr<OBJ_>(this); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(646)
::String _g1 = _g->get_text(); HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(646)
::String _g11 = (_g1 + text); HX_STACK_VAR(_g11,"_g11");
HX_STACK_LINE(646)
_g->set_text(_g11);
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,appendText,(void))
::openfl::geom::Rectangle TextField_obj::getCharBoundaries( int a){
HX_STACK_FRAME("openfl.text.TextField","getCharBoundaries",0xf44814d0,"openfl.text.TextField.getCharBoundaries","openfl/text/TextField.hx",660,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(a,"a")
HX_STACK_LINE(662)
::openfl::Lib_obj::notImplemented(HX_CSTRING("TextField.getCharBoundaries"));
HX_STACK_LINE(664)
return null();
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,getCharBoundaries,return )
int TextField_obj::getCharIndexAtPoint( Float x,Float y){
HX_STACK_FRAME("openfl.text.TextField","getCharIndexAtPoint",0x758b0c73,"openfl.text.TextField.getCharIndexAtPoint","openfl/text/TextField.hx",679,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(x,"x")
HX_STACK_ARG(y,"y")
HX_STACK_LINE(681)
::openfl::Lib_obj::notImplemented(HX_CSTRING("TextField.getCharIndexAtPoint"));
HX_STACK_LINE(683)
return (int)0;
}
HX_DEFINE_DYNAMIC_FUNC2(TextField_obj,getCharIndexAtPoint,return )
int TextField_obj::getLineIndexAtPoint( Float x,Float y){
HX_STACK_FRAME("openfl.text.TextField","getLineIndexAtPoint",0x633efa91,"openfl.text.TextField.getLineIndexAtPoint","openfl/text/TextField.hx",698,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(x,"x")
HX_STACK_ARG(y,"y")
HX_STACK_LINE(700)
::openfl::Lib_obj::notImplemented(HX_CSTRING("TextField.getLineIndexAtPoint"));
HX_STACK_LINE(702)
return (int)0;
}
HX_DEFINE_DYNAMIC_FUNC2(TextField_obj,getLineIndexAtPoint,return )
::openfl::text::TextLineMetrics TextField_obj::getLineMetrics( int lineIndex){
HX_STACK_FRAME("openfl.text.TextField","getLineMetrics",0xa6c52add,"openfl.text.TextField.getLineMetrics","openfl/text/TextField.hx",714,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(lineIndex,"lineIndex")
HX_STACK_LINE(716)
::openfl::Lib_obj::notImplemented(HX_CSTRING("TextField.getLineMetrics"));
HX_STACK_LINE(718)
return ::openfl::text::TextLineMetrics_obj::__new((int)0,(int)0,(int)0,(int)0,(int)0,(int)0);
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,getLineMetrics,return )
int TextField_obj::getLineOffset( int lineIndex){
HX_STACK_FRAME("openfl.text.TextField","getLineOffset",0x5676a039,"openfl.text.TextField.getLineOffset","openfl/text/TextField.hx",732,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(lineIndex,"lineIndex")
HX_STACK_LINE(734)
::openfl::Lib_obj::notImplemented(HX_CSTRING("TextField.getLineOffset"));
HX_STACK_LINE(736)
return (int)0;
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,getLineOffset,return )
::String TextField_obj::getLineText( int lineIndex){
HX_STACK_FRAME("openfl.text.TextField","getLineText",0xb8113fd3,"openfl.text.TextField.getLineText","openfl/text/TextField.hx",750,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(lineIndex,"lineIndex")
HX_STACK_LINE(752)
::openfl::Lib_obj::notImplemented(HX_CSTRING("TextField.getLineText"));
HX_STACK_LINE(754)
return HX_CSTRING("");
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,getLineText,return )
::openfl::text::TextFormat TextField_obj::getTextFormat( hx::Null< int > __o_beginIndex,hx::Null< int > __o_endIndex){
int beginIndex = __o_beginIndex.Default(0);
int endIndex = __o_endIndex.Default(0);
HX_STACK_FRAME("openfl.text.TextField","getTextFormat",0x560e1d56,"openfl.text.TextField.getTextFormat","openfl/text/TextField.hx",779,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(beginIndex,"beginIndex")
HX_STACK_ARG(endIndex,"endIndex")
{
HX_STACK_LINE(779)
return this->__textFormat->clone();
}
}
HX_DEFINE_DYNAMIC_FUNC2(TextField_obj,getTextFormat,return )
Void TextField_obj::setSelection( int beginIndex,int endIndex){
{
HX_STACK_FRAME("openfl.text.TextField","setSelection",0xa586666e,"openfl.text.TextField.setSelection","openfl/text/TextField.hx",799,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(beginIndex,"beginIndex")
HX_STACK_ARG(endIndex,"endIndex")
HX_STACK_LINE(799)
::openfl::Lib_obj::notImplemented(HX_CSTRING("TextField.setSelection"));
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC2(TextField_obj,setSelection,(void))
Void TextField_obj::setTextFormat( ::openfl::text::TextFormat format,hx::Null< int > __o_beginIndex,hx::Null< int > __o_endIndex){
int beginIndex = __o_beginIndex.Default(0);
int endIndex = __o_endIndex.Default(0);
HX_STACK_FRAME("openfl.text.TextField","setTextFormat",0x9b13ff62,"openfl.text.TextField.setTextFormat","openfl/text/TextField.hx",849,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(format,"format")
HX_STACK_ARG(beginIndex,"beginIndex")
HX_STACK_ARG(endIndex,"endIndex")
{
HX_STACK_LINE(851)
if (((format->font != null()))){
HX_STACK_LINE(851)
this->__textFormat->font = format->font;
}
HX_STACK_LINE(852)
if (((format->size != null()))){
HX_STACK_LINE(852)
this->__textFormat->size = format->size;
}
HX_STACK_LINE(853)
if (((format->color != null()))){
HX_STACK_LINE(853)
this->__textFormat->color = format->color;
}
HX_STACK_LINE(854)
if (((format->bold != null()))){
HX_STACK_LINE(854)
this->__textFormat->bold = format->bold;
}
HX_STACK_LINE(855)
if (((format->italic != null()))){
HX_STACK_LINE(855)
this->__textFormat->italic = format->italic;
}
HX_STACK_LINE(856)
if (((format->underline != null()))){
HX_STACK_LINE(856)
this->__textFormat->underline = format->underline;
}
HX_STACK_LINE(857)
if (((format->url != null()))){
HX_STACK_LINE(857)
this->__textFormat->url = format->url;
}
HX_STACK_LINE(858)
if (((format->target != null()))){
HX_STACK_LINE(858)
this->__textFormat->target = format->target;
}
HX_STACK_LINE(859)
if (((format->align != null()))){
HX_STACK_LINE(859)
this->__textFormat->align = format->align;
}
HX_STACK_LINE(860)
if (((format->leftMargin != null()))){
HX_STACK_LINE(860)
this->__textFormat->leftMargin = format->leftMargin;
}
HX_STACK_LINE(861)
if (((format->rightMargin != null()))){
HX_STACK_LINE(861)
this->__textFormat->rightMargin = format->rightMargin;
}
HX_STACK_LINE(862)
if (((format->indent != null()))){
HX_STACK_LINE(862)
this->__textFormat->indent = format->indent;
}
HX_STACK_LINE(863)
if (((format->leading != null()))){
HX_STACK_LINE(863)
this->__textFormat->leading = format->leading;
}
HX_STACK_LINE(864)
if (((format->blockIndent != null()))){
HX_STACK_LINE(864)
this->__textFormat->blockIndent = format->blockIndent;
}
HX_STACK_LINE(865)
if (((format->bullet != null()))){
HX_STACK_LINE(865)
this->__textFormat->bullet = format->bullet;
}
HX_STACK_LINE(866)
if (((format->kerning != null()))){
HX_STACK_LINE(866)
this->__textFormat->kerning = format->kerning;
}
HX_STACK_LINE(867)
if (((format->letterSpacing != null()))){
HX_STACK_LINE(867)
this->__textFormat->letterSpacing = format->letterSpacing;
}
HX_STACK_LINE(868)
if (((format->tabStops != null()))){
HX_STACK_LINE(868)
this->__textFormat->tabStops = format->tabStops;
}
HX_STACK_LINE(870)
this->__dirty = true;
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC3(TextField_obj,setTextFormat,(void))
::String TextField_obj::__clipText( ::String value){
HX_STACK_FRAME("openfl.text.TextField","__clipText",0x4c349fe1,"openfl.text.TextField.__clipText","openfl/text/TextField.hx",875,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(877)
Float textWidth = this->__getTextWidth(value); HX_STACK_VAR(textWidth,"textWidth");
HX_STACK_LINE(878)
Float fillPer = (Float(textWidth) / Float(this->__width)); HX_STACK_VAR(fillPer,"fillPer");
HX_STACK_LINE(879)
::String _g2; HX_STACK_VAR(_g2,"_g2");
HX_STACK_LINE(879)
if (((fillPer > (int)1))){
HX_STACK_LINE(879)
int _g = ::Math_obj::floor((Float(this->get_text().length) / Float(fillPer))); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(879)
int _g1 = ((int)-1 * _g); HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(879)
_g2 = this->get_text().substr(_g1,null());
}
else{
HX_STACK_LINE(879)
_g2 = this->get_text();
}
HX_STACK_LINE(879)
this->set_text(_g2);
HX_STACK_LINE(880)
::String _g3 = this->get_text(); HX_STACK_VAR(_g3,"_g3");
HX_STACK_LINE(880)
return (_g3 + HX_CSTRING(""));
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,__clipText,return )
Void TextField_obj::__disableInputMode( ){
{
HX_STACK_FRAME("openfl.text.TextField","__disableInputMode",0x7854fdc9,"openfl.text.TextField.__disableInputMode","openfl/text/TextField.hx",885,0xccf02094)
HX_STACK_THIS(this)
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,__disableInputMode,(void))
Void TextField_obj::__enableInputMode( ){
{
HX_STACK_FRAME("openfl.text.TextField","__enableInputMode",0xdf8d19c6,"openfl.text.TextField.__enableInputMode","openfl/text/TextField.hx",894,0xccf02094)
HX_STACK_THIS(this)
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,__enableInputMode,(void))
Void TextField_obj::__getBounds( ::openfl::geom::Rectangle rect,::openfl::geom::Matrix matrix){
{
HX_STACK_FRAME("openfl.text.TextField","__getBounds",0x189abae7,"openfl.text.TextField.__getBounds","openfl/text/TextField.hx",940,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(rect,"rect")
HX_STACK_ARG(matrix,"matrix")
HX_STACK_LINE(942)
::openfl::geom::Rectangle bounds = ::openfl::geom::Rectangle_obj::__new((int)0,(int)0,this->__width,this->__height); HX_STACK_VAR(bounds,"bounds");
HX_STACK_LINE(943)
bounds->transform(this->__worldTransform);
HX_STACK_LINE(945)
rect->__expand(bounds->x,bounds->y,bounds->width,bounds->height);
}
return null();
}
::String TextField_obj::__getFont( ::openfl::text::TextFormat format){
HX_STACK_FRAME("openfl.text.TextField","__getFont",0xb6eb31c1,"openfl.text.TextField.__getFont","openfl/text/TextField.hx",950,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(format,"format")
HX_STACK_LINE(952)
::String font; HX_STACK_VAR(font,"font");
HX_STACK_LINE(952)
if ((format->italic)){
HX_STACK_LINE(952)
font = HX_CSTRING("italic ");
}
else{
HX_STACK_LINE(952)
font = HX_CSTRING("normal ");
}
HX_STACK_LINE(953)
hx::AddEq(font,HX_CSTRING("normal "));
HX_STACK_LINE(954)
if ((format->bold)){
HX_STACK_LINE(954)
hx::AddEq(font,HX_CSTRING("bold "));
}
else{
HX_STACK_LINE(954)
hx::AddEq(font,HX_CSTRING("normal "));
}
HX_STACK_LINE(955)
hx::AddEq(font,(format->size + HX_CSTRING("px")));
HX_STACK_LINE(956)
hx::AddEq(font,((HX_CSTRING("/") + (((format->size + format->leading) + (int)4))) + HX_CSTRING("px ")));
struct _Function_1_1{
inline static ::String Block( ::openfl::text::TextFormat &format){
HX_STACK_FRAME("*","closure",0x5bdab937,"*.closure","openfl/text/TextField.hx",958,0xccf02094)
{
HX_STACK_LINE(958)
::String _g = format->font; HX_STACK_VAR(_g,"_g");
struct _Function_2_1{
inline static ::String Block( ::openfl::text::TextFormat &format,::String &_g){
HX_STACK_FRAME("*","closure",0x5bdab937,"*.closure","openfl/text/TextField.hx",958,0xccf02094)
{
HX_STACK_LINE(958)
::String _switch_1 = (_g);
if ( ( _switch_1==HX_CSTRING("_sans"))){
HX_STACK_LINE(960)
return HX_CSTRING("sans-serif");
}
else if ( ( _switch_1==HX_CSTRING("_serif"))){
HX_STACK_LINE(961)
return HX_CSTRING("serif");
}
else if ( ( _switch_1==HX_CSTRING("_typewriter"))){
HX_STACK_LINE(962)
return HX_CSTRING("monospace");
}
else {
HX_STACK_LINE(963)
return format->font;
}
;
;
}
return null();
}
};
HX_STACK_LINE(958)
return _Function_2_1::Block(format,_g);
}
return null();
}
};
HX_STACK_LINE(958)
hx::AddEq(font,(HX_CSTRING("'") + _Function_1_1::Block(format)));
HX_STACK_LINE(967)
hx::AddEq(font,HX_CSTRING("'"));
HX_STACK_LINE(969)
return font;
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,__getFont,return )
::openfl::text::Font TextField_obj::__getFontInstance( ::openfl::text::TextFormat format){
HX_STACK_FRAME("openfl.text.TextField","__getFontInstance",0x8a973676,"openfl.text.TextField.__getFontInstance","openfl/text/TextField.hx",974,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(format,"format")
HX_STACK_LINE(978)
if (((bool((format == null())) || bool((format->font == null()))))){
HX_STACK_LINE(978)
return null();
}
HX_STACK_LINE(980)
::String systemFontDirectory = ::lime::system::System_obj::get_fontsDirectory(); HX_STACK_VAR(systemFontDirectory,"systemFontDirectory");
HX_STACK_LINE(981)
Array< ::String > fontList = null(); HX_STACK_VAR(fontList,"fontList");
HX_STACK_LINE(983)
{
HX_STACK_LINE(983)
::String _g = format->font; HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(983)
::String _switch_2 = (_g);
if ( ( _switch_2==HX_CSTRING("_sans"))){
HX_STACK_LINE(988)
fontList = Array_obj< ::String >::__new().Add((systemFontDirectory + HX_CSTRING("/arial.ttf")));
}
else if ( ( _switch_2==HX_CSTRING("_serif"))){
HX_STACK_LINE(1002)
fontList = Array_obj< ::String >::__new().Add((systemFontDirectory + HX_CSTRING("/georgia.ttf")));
}
else if ( ( _switch_2==HX_CSTRING("_typewriter"))){
HX_STACK_LINE(1016)
fontList = Array_obj< ::String >::__new().Add((systemFontDirectory + HX_CSTRING("/cour.ttf")));
}
else {
HX_STACK_LINE(1029)
fontList = Array_obj< ::String >::__new().Add(format->font).Add(((systemFontDirectory + HX_CSTRING("/")) + format->font));
}
;
;
}
HX_STACK_LINE(1033)
if (((fontList == null()))){
HX_STACK_LINE(1033)
return null();
}
HX_STACK_LINE(1035)
{
HX_STACK_LINE(1035)
int _g = (int)0; HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(1035)
Array< ::Dynamic > _g1 = ::openfl::text::Font_obj::__registeredFonts; HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(1035)
while((true)){
HX_STACK_LINE(1035)
if ((!(((_g < _g1->length))))){
HX_STACK_LINE(1035)
break;
}
HX_STACK_LINE(1035)
::openfl::text::Font registeredFont = _g1->__get(_g).StaticCast< ::openfl::text::Font >(); HX_STACK_VAR(registeredFont,"registeredFont");
HX_STACK_LINE(1035)
++(_g);
HX_STACK_LINE(1037)
{
HX_STACK_LINE(1037)
int _g2 = (int)0; HX_STACK_VAR(_g2,"_g2");
HX_STACK_LINE(1037)
while((true)){
HX_STACK_LINE(1037)
if ((!(((_g2 < fontList->length))))){
HX_STACK_LINE(1037)
break;
}
HX_STACK_LINE(1037)
::String fontName = fontList->__get(_g2); HX_STACK_VAR(fontName,"fontName");
HX_STACK_LINE(1037)
++(_g2);
struct _Function_5_1{
inline static bool Block( ::openfl::text::Font ®isteredFont,::String &fontName){
HX_STACK_FRAME("*","closure",0x5bdab937,"*.closure","openfl/text/TextField.hx",1039,0xccf02094)
{
HX_STACK_LINE(1039)
::String _g3 = ::haxe::io::Path_obj::withoutDirectory(registeredFont->__fontPath); HX_STACK_VAR(_g3,"_g3");
HX_STACK_LINE(1039)
return (_g3 == fontName);
}
return null();
}
};
HX_STACK_LINE(1039)
if ((( ((!(((bool((registeredFont->__fontPath == fontName)) || bool((registeredFont->name == fontName))))))) ? bool(_Function_5_1::Block(registeredFont,fontName)) : bool(true) ))){
HX_STACK_LINE(1041)
return registeredFont;
}
}
}
}
}
HX_STACK_LINE(1049)
{
HX_STACK_LINE(1049)
int _g = (int)0; HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(1049)
while((true)){
HX_STACK_LINE(1049)
if ((!(((_g < fontList->length))))){
HX_STACK_LINE(1049)
break;
}
HX_STACK_LINE(1049)
::String fontName = fontList->__get(_g); HX_STACK_VAR(fontName,"fontName");
HX_STACK_LINE(1049)
++(_g);
HX_STACK_LINE(1051)
::openfl::text::Font font = ::openfl::text::Font_obj::fromFile(fontName); HX_STACK_VAR(font,"font");
HX_STACK_LINE(1053)
if (((font != null()))){
HX_STACK_LINE(1055)
::openfl::text::Font_obj::__registeredFonts->push(font);
HX_STACK_LINE(1056)
return font;
}
}
}
HX_STACK_LINE(1062)
return null();
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,__getFontInstance,return )
int TextField_obj::__getPosition( Float x,Float y){
HX_STACK_FRAME("openfl.text.TextField","__getPosition",0xfe83559b,"openfl.text.TextField.__getPosition","openfl/text/TextField.hx",1073,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(x,"x")
HX_STACK_ARG(y,"y")
HX_STACK_LINE(1075)
::String value = this->get_text(); HX_STACK_VAR(value,"value");
HX_STACK_LINE(1076)
::String text = value; HX_STACK_VAR(text,"text");
HX_STACK_LINE(1077)
Float totalW = (int)0; HX_STACK_VAR(totalW,"totalW");
HX_STACK_LINE(1078)
int pos = text.length; HX_STACK_VAR(pos,"pos");
HX_STACK_LINE(1080)
Float _g = this->__getTextWidth(text); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(1080)
if (((x < _g))){
HX_STACK_LINE(1082)
int _g1 = (int)0; HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(1082)
int _g2 = text.length; HX_STACK_VAR(_g2,"_g2");
HX_STACK_LINE(1082)
while((true)){
HX_STACK_LINE(1082)
if ((!(((_g1 < _g2))))){
HX_STACK_LINE(1082)
break;
}
HX_STACK_LINE(1082)
int i = (_g1)++; HX_STACK_VAR(i,"i");
HX_STACK_LINE(1084)
::String _g11 = text.charAt(i); HX_STACK_VAR(_g11,"_g11");
HX_STACK_LINE(1084)
Float _g21 = this->__getTextWidth(_g11); HX_STACK_VAR(_g21,"_g21");
HX_STACK_LINE(1084)
hx::AddEq(totalW,_g21);
HX_STACK_LINE(1086)
if (((totalW >= x))){
HX_STACK_LINE(1088)
pos = i;
HX_STACK_LINE(1089)
break;
}
}
}
HX_STACK_LINE(1097)
return pos;
}
HX_DEFINE_DYNAMIC_FUNC2(TextField_obj,__getPosition,return )
Float TextField_obj::__getTextWidth( ::String text){
HX_STACK_FRAME("openfl.text.TextField","__getTextWidth",0x4765e4e7,"openfl.text.TextField.__getTextWidth","openfl/text/TextField.hx",1120,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(text,"text")
HX_STACK_LINE(1120)
return (int)0;
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,__getTextWidth,return )
bool TextField_obj::__hitTest( Float x,Float y,bool shapeFlag,Array< ::Dynamic > stack,bool interactiveOnly){
HX_STACK_FRAME("openfl.text.TextField","__hitTest",0x83278481,"openfl.text.TextField.__hitTest","openfl/text/TextField.hx",1127,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(x,"x")
HX_STACK_ARG(y,"y")
HX_STACK_ARG(shapeFlag,"shapeFlag")
HX_STACK_ARG(stack,"stack")
HX_STACK_ARG(interactiveOnly,"interactiveOnly")
HX_STACK_LINE(1129)
if ((( ((!((!(this->get_visible()))))) ? bool((bool(interactiveOnly) && bool(!(this->mouseEnabled)))) : bool(true) ))){
HX_STACK_LINE(1129)
return false;
}
HX_STACK_LINE(1131)
::openfl::geom::Point _g = ::openfl::geom::Point_obj::__new(x,y); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(1131)
::openfl::geom::Point point = this->globalToLocal(_g); HX_STACK_VAR(point,"point");
HX_STACK_LINE(1133)
if (((bool((bool((bool((point->x > (int)0)) && bool((point->y > (int)0)))) && bool((point->x <= this->__width)))) && bool((point->y <= this->__height))))){
HX_STACK_LINE(1135)
if (((stack != null()))){
HX_STACK_LINE(1137)
stack->push(hx::ObjectPtr<OBJ_>(this));
}
HX_STACK_LINE(1141)
return true;
}
HX_STACK_LINE(1145)
return false;
}
Array< Float > TextField_obj::__measureText( ){
HX_STACK_FRAME("openfl.text.TextField","__measureText",0x5e15ed67,"openfl.text.TextField.__measureText","openfl/text/TextField.hx",1150,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1183)
if (((this->__textLayout == null()))){
HX_STACK_LINE(1185)
::lime::text::TextLayout _g = ::lime::text::TextLayout_obj::__new(null(),null(),null(),null(),null(),null()); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(1185)
this->__textLayout = _g;
}
HX_STACK_LINE(1189)
if (((this->__ranges == null()))){
HX_STACK_LINE(1191)
::openfl::text::Font font = this->__getFontInstance(this->__textFormat); HX_STACK_VAR(font,"font");
HX_STACK_LINE(1192)
Float width = 0.0; HX_STACK_VAR(width,"width");
HX_STACK_LINE(1194)
if (((bool((font != null())) && bool((this->__textFormat->size != null()))))){
HX_STACK_LINE(1196)
this->__textLayout->set_text(null());
HX_STACK_LINE(1197)
this->__textLayout->set_font(font);
HX_STACK_LINE(1198)
int _g1 = ::Std_obj::_int(this->__textFormat->size); HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(1198)
this->__textLayout->set_size(_g1);
HX_STACK_LINE(1199)
this->__textLayout->set_text(this->__text);
HX_STACK_LINE(1201)
{
HX_STACK_LINE(1201)
int _g = (int)0; HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(1201)
Array< ::Dynamic > _g11 = this->__textLayout->positions; HX_STACK_VAR(_g11,"_g11");
HX_STACK_LINE(1201)
while((true)){
HX_STACK_LINE(1201)
if ((!(((_g < _g11->length))))){
HX_STACK_LINE(1201)
break;
}
HX_STACK_LINE(1201)
::lime::text::GlyphPosition position = _g11->__get(_g).StaticCast< ::lime::text::GlyphPosition >(); HX_STACK_VAR(position,"position");
HX_STACK_LINE(1201)
++(_g);
HX_STACK_LINE(1203)
hx::AddEq(width,position->advance->x);
}
}
}
HX_STACK_LINE(1209)
return Array_obj< Float >::__new().Add(width);
}
else{
HX_STACK_LINE(1213)
Array< Float > measurements = Array_obj< Float >::__new(); HX_STACK_VAR(measurements,"measurements");
HX_STACK_LINE(1215)
{
HX_STACK_LINE(1215)
int _g = (int)0; HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(1215)
Array< ::Dynamic > _g1 = this->__ranges; HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(1215)
while((true)){
HX_STACK_LINE(1215)
if ((!(((_g < _g1->length))))){
HX_STACK_LINE(1215)
break;
}
HX_STACK_LINE(1215)
::openfl::text::TextFormatRange range = _g1->__get(_g).StaticCast< ::openfl::text::TextFormatRange >(); HX_STACK_VAR(range,"range");
HX_STACK_LINE(1215)
++(_g);
HX_STACK_LINE(1217)
::openfl::text::Font font = this->__getFontInstance(range->format); HX_STACK_VAR(font,"font");
HX_STACK_LINE(1218)
Float width = 0.0; HX_STACK_VAR(width,"width");
HX_STACK_LINE(1220)
if (((bool((font != null())) && bool((range->format->size != null()))))){
HX_STACK_LINE(1222)
this->__textLayout->set_text(null());
HX_STACK_LINE(1223)
this->__textLayout->set_font(font);
HX_STACK_LINE(1224)
int _g2 = ::Std_obj::_int(range->format->size); HX_STACK_VAR(_g2,"_g2");
HX_STACK_LINE(1224)
this->__textLayout->set_size(_g2);
HX_STACK_LINE(1225)
::String _g3 = this->get_text().substring(range->start,range->end); HX_STACK_VAR(_g3,"_g3");
HX_STACK_LINE(1225)
this->__textLayout->set_text(_g3);
HX_STACK_LINE(1227)
{
HX_STACK_LINE(1227)
int _g21 = (int)0; HX_STACK_VAR(_g21,"_g21");
HX_STACK_LINE(1227)
Array< ::Dynamic > _g31 = this->__textLayout->positions; HX_STACK_VAR(_g31,"_g31");
HX_STACK_LINE(1227)
while((true)){
HX_STACK_LINE(1227)
if ((!(((_g21 < _g31->length))))){
HX_STACK_LINE(1227)
break;
}
HX_STACK_LINE(1227)
::lime::text::GlyphPosition position = _g31->__get(_g21).StaticCast< ::lime::text::GlyphPosition >(); HX_STACK_VAR(position,"position");
HX_STACK_LINE(1227)
++(_g21);
HX_STACK_LINE(1229)
hx::AddEq(width,position->advance->x);
}
}
}
HX_STACK_LINE(1235)
measurements->push(width);
}
}
HX_STACK_LINE(1239)
return measurements;
}
HX_STACK_LINE(1189)
return null();
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,__measureText,return )
Void TextField_obj::__measureTextWithDOM( ){
{
HX_STACK_FRAME("openfl.text.TextField","__measureTextWithDOM",0xa22f3575,"openfl.text.TextField.__measureTextWithDOM","openfl/text/TextField.hx",1252,0xccf02094)
HX_STACK_THIS(this)
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,__measureTextWithDOM,(void))
Void TextField_obj::__renderCanvas( ::openfl::_internal::renderer::RenderSession renderSession){
{
HX_STACK_FRAME("openfl.text.TextField","__renderCanvas",0xfc575b12,"openfl.text.TextField.__renderCanvas","openfl/text/TextField.hx",1294,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(renderSession,"renderSession")
HX_STACK_LINE(1294)
Dynamic();
}
return null();
}
Void TextField_obj::__renderDOM( ::openfl::_internal::renderer::RenderSession renderSession){
{
HX_STACK_FRAME("openfl.text.TextField","__renderDOM",0x037e5808,"openfl.text.TextField.__renderDOM","openfl/text/TextField.hx",1301,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(renderSession,"renderSession")
HX_STACK_LINE(1301)
Dynamic();
}
return null();
}
Void TextField_obj::__renderGL( ::openfl::_internal::renderer::RenderSession renderSession){
{
HX_STACK_FRAME("openfl.text.TextField","__renderGL",0xa5533b3f,"openfl.text.TextField.__renderGL","openfl/text/TextField.hx",1308,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(renderSession,"renderSession")
HX_STACK_LINE(1308)
::openfl::_internal::renderer::opengl::GLTextField_obj::render(hx::ObjectPtr<OBJ_>(this),renderSession);
}
return null();
}
Void TextField_obj::__startCursorTimer( ){
{
HX_STACK_FRAME("openfl.text.TextField","__startCursorTimer",0xacba2811,"openfl.text.TextField.__startCursorTimer","openfl/text/TextField.hx",1313,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1315)
::haxe::Timer _g = ::haxe::Timer_obj::delay(this->__startCursorTimer_dyn(),(int)500); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(1315)
this->__cursorTimer = _g;
HX_STACK_LINE(1316)
this->__showCursor = !(this->__showCursor);
HX_STACK_LINE(1317)
this->__dirty = true;
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,__startCursorTimer,(void))
Void TextField_obj::__stopCursorTimer( ){
{
HX_STACK_FRAME("openfl.text.TextField","__stopCursorTimer",0x8f135c69,"openfl.text.TextField.__stopCursorTimer","openfl/text/TextField.hx",1324,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1324)
if (((this->__cursorTimer != null()))){
HX_STACK_LINE(1326)
this->__cursorTimer->stop();
}
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,__stopCursorTimer,(void))
::openfl::text::TextFieldAutoSize TextField_obj::set_autoSize( ::openfl::text::TextFieldAutoSize value){
HX_STACK_FRAME("openfl.text.TextField","set_autoSize",0xeca81571,"openfl.text.TextField.set_autoSize","openfl/text/TextField.hx",1499,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(1501)
if (((value != this->autoSize))){
HX_STACK_LINE(1501)
this->__dirty = true;
}
HX_STACK_LINE(1502)
return this->autoSize = value;
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,set_autoSize,return )
bool TextField_obj::set_background( bool value){
HX_STACK_FRAME("openfl.text.TextField","set_background",0x703183cf,"openfl.text.TextField.set_background","openfl/text/TextField.hx",1507,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(1509)
if (((value != this->background))){
HX_STACK_LINE(1509)
this->__dirty = true;
}
HX_STACK_LINE(1510)
return this->background = value;
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,set_background,return )
int TextField_obj::set_backgroundColor( int value){
HX_STACK_FRAME("openfl.text.TextField","set_backgroundColor",0x9fdd2f14,"openfl.text.TextField.set_backgroundColor","openfl/text/TextField.hx",1515,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(1517)
if (((value != this->backgroundColor))){
HX_STACK_LINE(1517)
this->__dirty = true;
}
HX_STACK_LINE(1518)
return this->backgroundColor = value;
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,set_backgroundColor,return )
bool TextField_obj::set_border( bool value){
HX_STACK_FRAME("openfl.text.TextField","set_border",0xa75e784d,"openfl.text.TextField.set_border","openfl/text/TextField.hx",1523,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(1525)
if (((value != this->border))){
HX_STACK_LINE(1525)
this->__dirty = true;
}
HX_STACK_LINE(1526)
return this->border = value;
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,set_border,return )
int TextField_obj::set_borderColor( int value){
HX_STACK_FRAME("openfl.text.TextField","set_borderColor",0x5e3331d6,"openfl.text.TextField.set_borderColor","openfl/text/TextField.hx",1531,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(1533)
if (((value != this->borderColor))){
HX_STACK_LINE(1533)
this->__dirty = true;
}
HX_STACK_LINE(1534)
return this->borderColor = value;
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,set_borderColor,return )
int TextField_obj::get_bottomScrollV( ){
HX_STACK_FRAME("openfl.text.TextField","get_bottomScrollV",0xfa9e92b1,"openfl.text.TextField.get_bottomScrollV","openfl/text/TextField.hx",1543,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1543)
return this->get_numLines();
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,get_bottomScrollV,return )
int TextField_obj::get_caretPos( ){
HX_STACK_FRAME("openfl.text.TextField","get_caretPos",0x916b11fe,"openfl.text.TextField.get_caretPos","openfl/text/TextField.hx",1550,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1550)
return (int)0;
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,get_caretPos,return )
::openfl::text::TextFormat TextField_obj::get_defaultTextFormat( ){
HX_STACK_FRAME("openfl.text.TextField","get_defaultTextFormat",0x83063818,"openfl.text.TextField.get_defaultTextFormat","openfl/text/TextField.hx",1557,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1557)
return this->__textFormat->clone();
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,get_defaultTextFormat,return )
::openfl::text::TextFormat TextField_obj::set_defaultTextFormat( ::openfl::text::TextFormat value){
HX_STACK_FRAME("openfl.text.TextField","set_defaultTextFormat",0xd70f0624,"openfl.text.TextField.set_defaultTextFormat","openfl/text/TextField.hx",1562,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(1565)
this->__textFormat->__merge(value);
HX_STACK_LINE(1566)
return value;
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,set_defaultTextFormat,return )
Float TextField_obj::get_height( ){
HX_STACK_FRAME("openfl.text.TextField","get_height",0x421294d4,"openfl.text.TextField.get_height","openfl/text/TextField.hx",1571,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1573)
Float _g = this->get_scaleY(); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(1573)
return (this->__height * _g);
}
Float TextField_obj::set_height( Float value){
HX_STACK_FRAME("openfl.text.TextField","set_height",0x45903348,"openfl.text.TextField.set_height","openfl/text/TextField.hx",1578,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(1580)
Float _g = this->get_scaleY(); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(1580)
if ((( ((!(((_g != (int)1))))) ? bool((value != this->__height)) : bool(true) ))){
HX_STACK_LINE(1582)
if ((!(this->__transformDirty))){
HX_STACK_LINE(1582)
this->__transformDirty = true;
HX_STACK_LINE(1582)
(::openfl::display::DisplayObject_obj::__worldTransformDirty)++;
}
HX_STACK_LINE(1583)
this->__dirty = true;
}
HX_STACK_LINE(1587)
this->set_scaleY((int)1);
HX_STACK_LINE(1588)
return this->__height = value;
}
::String TextField_obj::get_htmlText( ){
HX_STACK_FRAME("openfl.text.TextField","get_htmlText",0xb86d81e5,"openfl.text.TextField.get_htmlText","openfl/text/TextField.hx",1595,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1595)
return this->__text;
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,get_htmlText,return )
::String TextField_obj::set_htmlText( ::String value){
HX_STACK_FRAME("openfl.text.TextField","set_htmlText",0xcd66a559,"openfl.text.TextField.set_htmlText","openfl/text/TextField.hx",1602,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(1604)
if (((bool(!(this->__isHTML)) || bool((this->__text != value))))){
HX_STACK_LINE(1604)
this->__dirty = true;
}
HX_STACK_LINE(1605)
this->__ranges = null();
HX_STACK_LINE(1606)
this->__isHTML = true;
HX_STACK_LINE(1608)
{
HX_STACK_LINE(1610)
::String _g = ::EReg_obj::__new(HX_CSTRING("<br>"),HX_CSTRING("g"))->replace(value,HX_CSTRING("\n")); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(1610)
value = _g;
HX_STACK_LINE(1611)
::String _g1 = ::EReg_obj::__new(HX_CSTRING("<br/>"),HX_CSTRING("g"))->replace(value,HX_CSTRING("\n")); HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(1611)
value = _g1;
HX_STACK_LINE(1615)
Array< ::String > segments = value.split(HX_CSTRING("<font")); HX_STACK_VAR(segments,"segments");
HX_STACK_LINE(1617)
if (((segments->length == (int)1))){
HX_STACK_LINE(1619)
::String _g2 = ::EReg_obj::__new(HX_CSTRING("<.*?>"),HX_CSTRING("g"))->replace(value,HX_CSTRING("")); HX_STACK_VAR(_g2,"_g2");
HX_STACK_LINE(1619)
value = _g2;
HX_STACK_LINE(1621)
return this->__text = value;
}
else{
HX_STACK_LINE(1625)
value = HX_CSTRING("");
HX_STACK_LINE(1626)
this->__ranges = Array_obj< ::Dynamic >::__new();
HX_STACK_LINE(1630)
{
HX_STACK_LINE(1630)
int _g2 = (int)0; HX_STACK_VAR(_g2,"_g2");
HX_STACK_LINE(1630)
while((true)){
HX_STACK_LINE(1630)
if ((!(((_g2 < segments->length))))){
HX_STACK_LINE(1630)
break;
}
HX_STACK_LINE(1630)
::String segment = segments->__get(_g2); HX_STACK_VAR(segment,"segment");
HX_STACK_LINE(1630)
++(_g2);
HX_STACK_LINE(1632)
if (((segment == HX_CSTRING("")))){
HX_STACK_LINE(1632)
continue;
}
HX_STACK_LINE(1634)
int closeFontIndex = segment.indexOf(HX_CSTRING("</font>"),null()); HX_STACK_VAR(closeFontIndex,"closeFontIndex");
HX_STACK_LINE(1636)
if (((closeFontIndex > (int)-1))){
HX_STACK_LINE(1638)
int _g3 = segment.indexOf(HX_CSTRING(">"),null()); HX_STACK_VAR(_g3,"_g3");
HX_STACK_LINE(1638)
int start = (_g3 + (int)1); HX_STACK_VAR(start,"start");
HX_STACK_LINE(1639)
int end = closeFontIndex; HX_STACK_VAR(end,"end");
HX_STACK_LINE(1640)
::openfl::text::TextFormat format = this->__textFormat->clone(); HX_STACK_VAR(format,"format");
HX_STACK_LINE(1642)
int faceIndex = segment.indexOf(HX_CSTRING("face="),null()); HX_STACK_VAR(faceIndex,"faceIndex");
HX_STACK_LINE(1643)
int colorIndex = segment.indexOf(HX_CSTRING("color="),null()); HX_STACK_VAR(colorIndex,"colorIndex");
HX_STACK_LINE(1644)
int sizeIndex = segment.indexOf(HX_CSTRING("size="),null()); HX_STACK_VAR(sizeIndex,"sizeIndex");
HX_STACK_LINE(1646)
if (((bool((faceIndex > (int)-1)) && bool((faceIndex < start))))){
HX_STACK_LINE(1648)
int _g4 = segment.indexOf(HX_CSTRING("\""),faceIndex); HX_STACK_VAR(_g4,"_g4");
HX_STACK_LINE(1648)
::String _g5 = segment.substr((faceIndex + (int)6),_g4); HX_STACK_VAR(_g5,"_g5");
HX_STACK_LINE(1648)
format->font = _g5;
}
HX_STACK_LINE(1652)
if (((bool((colorIndex > (int)-1)) && bool((colorIndex < start))))){
HX_STACK_LINE(1654)
::String _g6 = segment.substr((colorIndex + (int)8),(int)6); HX_STACK_VAR(_g6,"_g6");
HX_STACK_LINE(1654)
::String _g7 = (HX_CSTRING("0x") + _g6); HX_STACK_VAR(_g7,"_g7");
HX_STACK_LINE(1654)
Dynamic _g8 = ::Std_obj::parseInt(_g7); HX_STACK_VAR(_g8,"_g8");
HX_STACK_LINE(1654)
format->color = _g8;
}
HX_STACK_LINE(1658)
if (((bool((sizeIndex > (int)-1)) && bool((sizeIndex < start))))){
HX_STACK_LINE(1660)
int _g9 = segment.indexOf(HX_CSTRING("\""),sizeIndex); HX_STACK_VAR(_g9,"_g9");
HX_STACK_LINE(1660)
::String _g10 = segment.substr((sizeIndex + (int)6),_g9); HX_STACK_VAR(_g10,"_g10");
HX_STACK_LINE(1660)
Dynamic _g11 = ::Std_obj::parseInt(_g10); HX_STACK_VAR(_g11,"_g11");
HX_STACK_LINE(1660)
format->size = _g11;
}
HX_STACK_LINE(1664)
::String sub = segment.substring(start,end); HX_STACK_VAR(sub,"sub");
HX_STACK_LINE(1665)
::String _g12 = ::EReg_obj::__new(HX_CSTRING("<.*?>"),HX_CSTRING("g"))->replace(sub,HX_CSTRING("")); HX_STACK_VAR(_g12,"_g12");
HX_STACK_LINE(1665)
sub = _g12;
HX_STACK_LINE(1667)
::openfl::text::TextFormatRange _g13 = ::openfl::text::TextFormatRange_obj::__new(format,value.length,(value.length + sub.length)); HX_STACK_VAR(_g13,"_g13");
HX_STACK_LINE(1667)
this->__ranges->push(_g13);
HX_STACK_LINE(1668)
hx::AddEq(value,sub);
HX_STACK_LINE(1670)
if ((((closeFontIndex + (int)7) < segment.length))){
HX_STACK_LINE(1672)
::String _g14 = segment.substr((closeFontIndex + (int)7),null()); HX_STACK_VAR(_g14,"_g14");
HX_STACK_LINE(1672)
sub = _g14;
HX_STACK_LINE(1673)
::openfl::text::TextFormatRange _g15 = ::openfl::text::TextFormatRange_obj::__new(this->__textFormat,value.length,(value.length + sub.length)); HX_STACK_VAR(_g15,"_g15");
HX_STACK_LINE(1673)
this->__ranges->push(_g15);
HX_STACK_LINE(1674)
hx::AddEq(value,sub);
}
}
else{
HX_STACK_LINE(1680)
::openfl::text::TextFormatRange _g16 = ::openfl::text::TextFormatRange_obj::__new(this->__textFormat,value.length,(value.length + segment.length)); HX_STACK_VAR(_g16,"_g16");
HX_STACK_LINE(1680)
this->__ranges->push(_g16);
HX_STACK_LINE(1681)
hx::AddEq(value,segment);
}
}
}
}
}
HX_STACK_LINE(1692)
return this->__text = value;
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,set_htmlText,return )
int TextField_obj::get_maxScrollH( ){
HX_STACK_FRAME("openfl.text.TextField","get_maxScrollH",0xc4f0b4c4,"openfl.text.TextField.get_maxScrollH","openfl/text/TextField.hx",1697,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1697)
return (int)0;
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,get_maxScrollH,return )
int TextField_obj::get_maxScrollV( ){
HX_STACK_FRAME("openfl.text.TextField","get_maxScrollV",0xc4f0b4d2,"openfl.text.TextField.get_maxScrollV","openfl/text/TextField.hx",1698,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1698)
return (int)1;
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,get_maxScrollV,return )
int TextField_obj::get_numLines( ){
HX_STACK_FRAME("openfl.text.TextField","get_numLines",0xda475406,"openfl.text.TextField.get_numLines","openfl/text/TextField.hx",1701,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1703)
::String _g = this->get_text(); HX_STACK_VAR(_g,"_g");
struct _Function_1_1{
inline static bool Block( hx::ObjectPtr< ::openfl::text::TextField_obj > __this){
HX_STACK_FRAME("*","closure",0x5bdab937,"*.closure","openfl/text/TextField.hx",1703,0xccf02094)
{
HX_STACK_LINE(1703)
::String _g1 = __this->get_text(); HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(1703)
return (_g1 != null());
}
return null();
}
};
HX_STACK_LINE(1703)
if ((( (((_g != HX_CSTRING("")))) ? bool(_Function_1_1::Block(this)) : bool(false) ))){
HX_STACK_LINE(1705)
int count = this->get_text().split(HX_CSTRING("\n"))->length; HX_STACK_VAR(count,"count");
HX_STACK_LINE(1707)
if ((this->__isHTML)){
HX_STACK_LINE(1709)
hx::AddEq(count,(this->get_text().split(HX_CSTRING("<br>"))->length - (int)1));
}
HX_STACK_LINE(1713)
return count;
}
HX_STACK_LINE(1717)
return (int)1;
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,get_numLines,return )
::String TextField_obj::get_text( ){
HX_STACK_FRAME("openfl.text.TextField","get_text",0x3b0d545a,"openfl.text.TextField.get_text","openfl/text/TextField.hx",1722,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1724)
if ((this->__isHTML)){
}
HX_STACK_LINE(1730)
return this->__text;
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,get_text,return )
::String TextField_obj::set_text( ::String value){
HX_STACK_FRAME("openfl.text.TextField","set_text",0xe96aadce,"openfl.text.TextField.set_text","openfl/text/TextField.hx",1735,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(1738)
if (((bool(this->__isHTML) || bool((this->__text != value))))){
HX_STACK_LINE(1738)
this->__dirty = true;
}
HX_STACK_LINE(1739)
this->__ranges = null();
HX_STACK_LINE(1740)
this->__isHTML = false;
HX_STACK_LINE(1741)
return this->__text = value;
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,set_text,return )
int TextField_obj::get_textColor( ){
HX_STACK_FRAME("openfl.text.TextField","get_textColor",0x69ca86a9,"openfl.text.TextField.get_textColor","openfl/text/TextField.hx",1748,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1748)
return this->__textFormat->color;
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,get_textColor,return )
int TextField_obj::set_textColor( int value){
HX_STACK_FRAME("openfl.text.TextField","set_textColor",0xaed068b5,"openfl.text.TextField.set_textColor","openfl/text/TextField.hx",1753,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(1755)
if (((value != this->__textFormat->color))){
HX_STACK_LINE(1755)
this->__dirty = true;
}
HX_STACK_LINE(1757)
if (((this->__ranges != null()))){
HX_STACK_LINE(1759)
int _g = (int)0; HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(1759)
Array< ::Dynamic > _g1 = this->__ranges; HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(1759)
while((true)){
HX_STACK_LINE(1759)
if ((!(((_g < _g1->length))))){
HX_STACK_LINE(1759)
break;
}
HX_STACK_LINE(1759)
::openfl::text::TextFormatRange range = _g1->__get(_g).StaticCast< ::openfl::text::TextFormatRange >(); HX_STACK_VAR(range,"range");
HX_STACK_LINE(1759)
++(_g);
HX_STACK_LINE(1761)
range->format->color = value;
}
}
HX_STACK_LINE(1767)
return this->__textFormat->color = value;
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,set_textColor,return )
Float TextField_obj::get_textWidth( ){
HX_STACK_FRAME("openfl.text.TextField","get_textWidth",0xe9d0cb4c,"openfl.text.TextField.get_textWidth","openfl/text/TextField.hx",1802,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1802)
return (int)0;
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,get_textWidth,return )
Float TextField_obj::get_textHeight( ){
HX_STACK_FRAME("openfl.text.TextField","get_textHeight",0x63308fe1,"openfl.text.TextField.get_textHeight","openfl/text/TextField.hx",1833,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1833)
return (int)0;
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,get_textHeight,return )
::openfl::text::TextFieldType TextField_obj::set_type( ::openfl::text::TextFieldType value){
HX_STACK_FRAME("openfl.text.TextField","set_type",0xe979d3db,"openfl.text.TextField.set_type","openfl/text/TextField.hx",1840,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(1842)
if (((value != this->type))){
HX_STACK_LINE(1845)
if (((value == ::openfl::text::TextFieldType_obj::INPUT))){
HX_STACK_LINE(1847)
this->__enableInputMode();
}
else{
HX_STACK_LINE(1851)
this->__disableInputMode();
}
HX_STACK_LINE(1856)
this->__dirty = true;
}
HX_STACK_LINE(1860)
return this->type = value;
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,set_type,return )
Float TextField_obj::get_width( ){
HX_STACK_FRAME("openfl.text.TextField","get_width",0x2d65e5b9,"openfl.text.TextField.get_width","openfl/text/TextField.hx",1867,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1867)
if (((this->autoSize == ::openfl::text::TextFieldAutoSize_obj::LEFT))){
HX_STACK_LINE(1870)
Float _g = this->get_textWidth(); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(1870)
Float _g1 = (_g + (int)4); HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(1870)
Float _g2 = this->get_scaleX(); HX_STACK_VAR(_g2,"_g2");
HX_STACK_LINE(1870)
return (_g1 * _g2);
}
else{
HX_STACK_LINE(1874)
Float _g3 = this->get_scaleX(); HX_STACK_VAR(_g3,"_g3");
HX_STACK_LINE(1874)
return (this->__width * _g3);
}
HX_STACK_LINE(1867)
return 0.;
}
Float TextField_obj::set_width( Float value){
HX_STACK_FRAME("openfl.text.TextField","set_width",0x10b6d1c5,"openfl.text.TextField.set_width","openfl/text/TextField.hx",1881,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(1883)
Float _g = this->get_scaleX(); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(1883)
if ((( ((!(((_g != (int)1))))) ? bool((this->__width != value)) : bool(true) ))){
HX_STACK_LINE(1885)
if ((!(this->__transformDirty))){
HX_STACK_LINE(1885)
this->__transformDirty = true;
HX_STACK_LINE(1885)
(::openfl::display::DisplayObject_obj::__worldTransformDirty)++;
}
HX_STACK_LINE(1886)
this->__dirty = true;
}
HX_STACK_LINE(1890)
this->set_scaleX((int)1);
HX_STACK_LINE(1891)
return this->__width = value;
}
bool TextField_obj::get_wordWrap( ){
HX_STACK_FRAME("openfl.text.TextField","get_wordWrap",0xa91076e1,"openfl.text.TextField.get_wordWrap","openfl/text/TextField.hx",1898,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_LINE(1898)
return this->wordWrap;
}
HX_DEFINE_DYNAMIC_FUNC0(TextField_obj,get_wordWrap,return )
bool TextField_obj::set_wordWrap( bool value){
HX_STACK_FRAME("openfl.text.TextField","set_wordWrap",0xbe099a55,"openfl.text.TextField.set_wordWrap","openfl/text/TextField.hx",1906,0xccf02094)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(1906)
return this->wordWrap = value;
}
HX_DEFINE_DYNAMIC_FUNC1(TextField_obj,set_wordWrap,return )
::openfl::text::TextFormat TextField_obj::__defaultTextFormat;
TextField_obj::TextField_obj()
{
}
void TextField_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(TextField);
HX_MARK_MEMBER_NAME(antiAliasType,"antiAliasType");
HX_MARK_MEMBER_NAME(autoSize,"autoSize");
HX_MARK_MEMBER_NAME(background,"background");
HX_MARK_MEMBER_NAME(backgroundColor,"backgroundColor");
HX_MARK_MEMBER_NAME(border,"border");
HX_MARK_MEMBER_NAME(borderColor,"borderColor");
HX_MARK_MEMBER_NAME(bottomScrollV,"bottomScrollV");
HX_MARK_MEMBER_NAME(caretIndex,"caretIndex");
HX_MARK_MEMBER_NAME(caretPos,"caretPos");
HX_MARK_MEMBER_NAME(displayAsPassword,"displayAsPassword");
HX_MARK_MEMBER_NAME(embedFonts,"embedFonts");
HX_MARK_MEMBER_NAME(gridFitType,"gridFitType");
HX_MARK_MEMBER_NAME(length,"length");
HX_MARK_MEMBER_NAME(maxChars,"maxChars");
HX_MARK_MEMBER_NAME(maxScrollH,"maxScrollH");
HX_MARK_MEMBER_NAME(maxScrollV,"maxScrollV");
HX_MARK_MEMBER_NAME(multiline,"multiline");
HX_MARK_MEMBER_NAME(numLines,"numLines");
HX_MARK_MEMBER_NAME(restrict,"restrict");
HX_MARK_MEMBER_NAME(scrollH,"scrollH");
HX_MARK_MEMBER_NAME(scrollV,"scrollV");
HX_MARK_MEMBER_NAME(selectable,"selectable");
HX_MARK_MEMBER_NAME(selectionBeginIndex,"selectionBeginIndex");
HX_MARK_MEMBER_NAME(selectionEndIndex,"selectionEndIndex");
HX_MARK_MEMBER_NAME(sharpness,"sharpness");
HX_MARK_MEMBER_NAME(textHeight,"textHeight");
HX_MARK_MEMBER_NAME(textWidth,"textWidth");
HX_MARK_MEMBER_NAME(type,"type");
HX_MARK_MEMBER_NAME(wordWrap,"wordWrap");
HX_MARK_MEMBER_NAME(__cursorPosition,"__cursorPosition");
HX_MARK_MEMBER_NAME(__cursorTimer,"__cursorTimer");
HX_MARK_MEMBER_NAME(__dirty,"__dirty");
HX_MARK_MEMBER_NAME(__hasFocus,"__hasFocus");
HX_MARK_MEMBER_NAME(__height,"__height");
HX_MARK_MEMBER_NAME(__isHTML,"__isHTML");
HX_MARK_MEMBER_NAME(__isKeyDown,"__isKeyDown");
HX_MARK_MEMBER_NAME(__measuredHeight,"__measuredHeight");
HX_MARK_MEMBER_NAME(__measuredWidth,"__measuredWidth");
HX_MARK_MEMBER_NAME(__ranges,"__ranges");
HX_MARK_MEMBER_NAME(__selectionStart,"__selectionStart");
HX_MARK_MEMBER_NAME(__showCursor,"__showCursor");
HX_MARK_MEMBER_NAME(__text,"__text");
HX_MARK_MEMBER_NAME(__textFormat,"__textFormat");
HX_MARK_MEMBER_NAME(__textLayout,"__textLayout");
HX_MARK_MEMBER_NAME(__texture,"__texture");
HX_MARK_MEMBER_NAME(__tileData,"__tileData");
HX_MARK_MEMBER_NAME(__tilesheets,"__tilesheets");
HX_MARK_MEMBER_NAME(__width,"__width");
::openfl::display::InteractiveObject_obj::__Mark(HX_MARK_ARG);
HX_MARK_END_CLASS();
}
void TextField_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(antiAliasType,"antiAliasType");
HX_VISIT_MEMBER_NAME(autoSize,"autoSize");
HX_VISIT_MEMBER_NAME(background,"background");
HX_VISIT_MEMBER_NAME(backgroundColor,"backgroundColor");
HX_VISIT_MEMBER_NAME(border,"border");
HX_VISIT_MEMBER_NAME(borderColor,"borderColor");
HX_VISIT_MEMBER_NAME(bottomScrollV,"bottomScrollV");
HX_VISIT_MEMBER_NAME(caretIndex,"caretIndex");
HX_VISIT_MEMBER_NAME(caretPos,"caretPos");
HX_VISIT_MEMBER_NAME(displayAsPassword,"displayAsPassword");
HX_VISIT_MEMBER_NAME(embedFonts,"embedFonts");
HX_VISIT_MEMBER_NAME(gridFitType,"gridFitType");
HX_VISIT_MEMBER_NAME(length,"length");
HX_VISIT_MEMBER_NAME(maxChars,"maxChars");
HX_VISIT_MEMBER_NAME(maxScrollH,"maxScrollH");
HX_VISIT_MEMBER_NAME(maxScrollV,"maxScrollV");
HX_VISIT_MEMBER_NAME(multiline,"multiline");
HX_VISIT_MEMBER_NAME(numLines,"numLines");
HX_VISIT_MEMBER_NAME(restrict,"restrict");
HX_VISIT_MEMBER_NAME(scrollH,"scrollH");
HX_VISIT_MEMBER_NAME(scrollV,"scrollV");
HX_VISIT_MEMBER_NAME(selectable,"selectable");
HX_VISIT_MEMBER_NAME(selectionBeginIndex,"selectionBeginIndex");
HX_VISIT_MEMBER_NAME(selectionEndIndex,"selectionEndIndex");
HX_VISIT_MEMBER_NAME(sharpness,"sharpness");
HX_VISIT_MEMBER_NAME(textHeight,"textHeight");
HX_VISIT_MEMBER_NAME(textWidth,"textWidth");
HX_VISIT_MEMBER_NAME(type,"type");
HX_VISIT_MEMBER_NAME(wordWrap,"wordWrap");
HX_VISIT_MEMBER_NAME(__cursorPosition,"__cursorPosition");
HX_VISIT_MEMBER_NAME(__cursorTimer,"__cursorTimer");
HX_VISIT_MEMBER_NAME(__dirty,"__dirty");
HX_VISIT_MEMBER_NAME(__hasFocus,"__hasFocus");
HX_VISIT_MEMBER_NAME(__height,"__height");
HX_VISIT_MEMBER_NAME(__isHTML,"__isHTML");
HX_VISIT_MEMBER_NAME(__isKeyDown,"__isKeyDown");
HX_VISIT_MEMBER_NAME(__measuredHeight,"__measuredHeight");
HX_VISIT_MEMBER_NAME(__measuredWidth,"__measuredWidth");
HX_VISIT_MEMBER_NAME(__ranges,"__ranges");
HX_VISIT_MEMBER_NAME(__selectionStart,"__selectionStart");
HX_VISIT_MEMBER_NAME(__showCursor,"__showCursor");
HX_VISIT_MEMBER_NAME(__text,"__text");
HX_VISIT_MEMBER_NAME(__textFormat,"__textFormat");
HX_VISIT_MEMBER_NAME(__textLayout,"__textLayout");
HX_VISIT_MEMBER_NAME(__texture,"__texture");
HX_VISIT_MEMBER_NAME(__tileData,"__tileData");
HX_VISIT_MEMBER_NAME(__tilesheets,"__tilesheets");
HX_VISIT_MEMBER_NAME(__width,"__width");
::openfl::display::InteractiveObject_obj::__Visit(HX_VISIT_ARG);
}
Dynamic TextField_obj::__Field(const ::String &inName,bool inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"text") ) { return get_text(); }
if (HX_FIELD_EQ(inName,"type") ) { return type; }
break;
case 6:
if (HX_FIELD_EQ(inName,"border") ) { return border; }
if (HX_FIELD_EQ(inName,"length") ) { return length; }
if (HX_FIELD_EQ(inName,"__text") ) { return __text; }
break;
case 7:
if (HX_FIELD_EQ(inName,"scrollH") ) { return scrollH; }
if (HX_FIELD_EQ(inName,"scrollV") ) { return scrollV; }
if (HX_FIELD_EQ(inName,"__dirty") ) { return __dirty; }
if (HX_FIELD_EQ(inName,"__width") ) { return __width; }
break;
case 8:
if (HX_FIELD_EQ(inName,"autoSize") ) { return autoSize; }
if (HX_FIELD_EQ(inName,"caretPos") ) { return inCallProp ? get_caretPos() : caretPos; }
if (HX_FIELD_EQ(inName,"htmlText") ) { return get_htmlText(); }
if (HX_FIELD_EQ(inName,"maxChars") ) { return maxChars; }
if (HX_FIELD_EQ(inName,"numLines") ) { return inCallProp ? get_numLines() : numLines; }
if (HX_FIELD_EQ(inName,"restrict") ) { return restrict; }
if (HX_FIELD_EQ(inName,"wordWrap") ) { return inCallProp ? get_wordWrap() : wordWrap; }
if (HX_FIELD_EQ(inName,"__height") ) { return __height; }
if (HX_FIELD_EQ(inName,"__isHTML") ) { return __isHTML; }
if (HX_FIELD_EQ(inName,"__ranges") ) { return __ranges; }
if (HX_FIELD_EQ(inName,"get_text") ) { return get_text_dyn(); }
if (HX_FIELD_EQ(inName,"set_text") ) { return set_text_dyn(); }
if (HX_FIELD_EQ(inName,"set_type") ) { return set_type_dyn(); }
break;
case 9:
if (HX_FIELD_EQ(inName,"multiline") ) { return multiline; }
if (HX_FIELD_EQ(inName,"sharpness") ) { return sharpness; }
if (HX_FIELD_EQ(inName,"textColor") ) { return get_textColor(); }
if (HX_FIELD_EQ(inName,"textWidth") ) { return inCallProp ? get_textWidth() : textWidth; }
if (HX_FIELD_EQ(inName,"__texture") ) { return __texture; }
if (HX_FIELD_EQ(inName,"__getFont") ) { return __getFont_dyn(); }
if (HX_FIELD_EQ(inName,"__hitTest") ) { return __hitTest_dyn(); }
if (HX_FIELD_EQ(inName,"get_width") ) { return get_width_dyn(); }
if (HX_FIELD_EQ(inName,"set_width") ) { return set_width_dyn(); }
break;
case 10:
if (HX_FIELD_EQ(inName,"background") ) { return background; }
if (HX_FIELD_EQ(inName,"caretIndex") ) { return caretIndex; }
if (HX_FIELD_EQ(inName,"embedFonts") ) { return embedFonts; }
if (HX_FIELD_EQ(inName,"maxScrollH") ) { return inCallProp ? get_maxScrollH() : maxScrollH; }
if (HX_FIELD_EQ(inName,"maxScrollV") ) { return inCallProp ? get_maxScrollV() : maxScrollV; }
if (HX_FIELD_EQ(inName,"selectable") ) { return selectable; }
if (HX_FIELD_EQ(inName,"textHeight") ) { return inCallProp ? get_textHeight() : textHeight; }
if (HX_FIELD_EQ(inName,"__hasFocus") ) { return __hasFocus; }
if (HX_FIELD_EQ(inName,"__tileData") ) { return __tileData; }
if (HX_FIELD_EQ(inName,"appendText") ) { return appendText_dyn(); }
if (HX_FIELD_EQ(inName,"__clipText") ) { return __clipText_dyn(); }
if (HX_FIELD_EQ(inName,"__renderGL") ) { return __renderGL_dyn(); }
if (HX_FIELD_EQ(inName,"set_border") ) { return set_border_dyn(); }
if (HX_FIELD_EQ(inName,"get_height") ) { return get_height_dyn(); }
if (HX_FIELD_EQ(inName,"set_height") ) { return set_height_dyn(); }
break;
case 11:
if (HX_FIELD_EQ(inName,"borderColor") ) { return borderColor; }
if (HX_FIELD_EQ(inName,"gridFitType") ) { return gridFitType; }
if (HX_FIELD_EQ(inName,"__isKeyDown") ) { return __isKeyDown; }
if (HX_FIELD_EQ(inName,"getLineText") ) { return getLineText_dyn(); }
if (HX_FIELD_EQ(inName,"__getBounds") ) { return __getBounds_dyn(); }
if (HX_FIELD_EQ(inName,"__renderDOM") ) { return __renderDOM_dyn(); }
break;
case 12:
if (HX_FIELD_EQ(inName,"__showCursor") ) { return __showCursor; }
if (HX_FIELD_EQ(inName,"__textFormat") ) { return __textFormat; }
if (HX_FIELD_EQ(inName,"__textLayout") ) { return __textLayout; }
if (HX_FIELD_EQ(inName,"__tilesheets") ) { return __tilesheets; }
if (HX_FIELD_EQ(inName,"setSelection") ) { return setSelection_dyn(); }
if (HX_FIELD_EQ(inName,"set_autoSize") ) { return set_autoSize_dyn(); }
if (HX_FIELD_EQ(inName,"get_caretPos") ) { return get_caretPos_dyn(); }
if (HX_FIELD_EQ(inName,"get_htmlText") ) { return get_htmlText_dyn(); }
if (HX_FIELD_EQ(inName,"set_htmlText") ) { return set_htmlText_dyn(); }
if (HX_FIELD_EQ(inName,"get_numLines") ) { return get_numLines_dyn(); }
if (HX_FIELD_EQ(inName,"get_wordWrap") ) { return get_wordWrap_dyn(); }
if (HX_FIELD_EQ(inName,"set_wordWrap") ) { return set_wordWrap_dyn(); }
break;
case 13:
if (HX_FIELD_EQ(inName,"antiAliasType") ) { return antiAliasType; }
if (HX_FIELD_EQ(inName,"bottomScrollV") ) { return inCallProp ? get_bottomScrollV() : bottomScrollV; }
if (HX_FIELD_EQ(inName,"__cursorTimer") ) { return __cursorTimer; }
if (HX_FIELD_EQ(inName,"getLineOffset") ) { return getLineOffset_dyn(); }
if (HX_FIELD_EQ(inName,"getTextFormat") ) { return getTextFormat_dyn(); }
if (HX_FIELD_EQ(inName,"setTextFormat") ) { return setTextFormat_dyn(); }
if (HX_FIELD_EQ(inName,"__getPosition") ) { return __getPosition_dyn(); }
if (HX_FIELD_EQ(inName,"__measureText") ) { return __measureText_dyn(); }
if (HX_FIELD_EQ(inName,"get_textColor") ) { return get_textColor_dyn(); }
if (HX_FIELD_EQ(inName,"set_textColor") ) { return set_textColor_dyn(); }
if (HX_FIELD_EQ(inName,"get_textWidth") ) { return get_textWidth_dyn(); }
break;
case 14:
if (HX_FIELD_EQ(inName,"getLineMetrics") ) { return getLineMetrics_dyn(); }
if (HX_FIELD_EQ(inName,"__getTextWidth") ) { return __getTextWidth_dyn(); }
if (HX_FIELD_EQ(inName,"__renderCanvas") ) { return __renderCanvas_dyn(); }
if (HX_FIELD_EQ(inName,"set_background") ) { return set_background_dyn(); }
if (HX_FIELD_EQ(inName,"get_maxScrollH") ) { return get_maxScrollH_dyn(); }
if (HX_FIELD_EQ(inName,"get_maxScrollV") ) { return get_maxScrollV_dyn(); }
if (HX_FIELD_EQ(inName,"get_textHeight") ) { return get_textHeight_dyn(); }
break;
case 15:
if (HX_FIELD_EQ(inName,"backgroundColor") ) { return backgroundColor; }
if (HX_FIELD_EQ(inName,"__measuredWidth") ) { return __measuredWidth; }
if (HX_FIELD_EQ(inName,"set_borderColor") ) { return set_borderColor_dyn(); }
break;
case 16:
if (HX_FIELD_EQ(inName,"__cursorPosition") ) { return __cursorPosition; }
if (HX_FIELD_EQ(inName,"__measuredHeight") ) { return __measuredHeight; }
if (HX_FIELD_EQ(inName,"__selectionStart") ) { return __selectionStart; }
break;
case 17:
if (HX_FIELD_EQ(inName,"defaultTextFormat") ) { return get_defaultTextFormat(); }
if (HX_FIELD_EQ(inName,"displayAsPassword") ) { return displayAsPassword; }
if (HX_FIELD_EQ(inName,"selectionEndIndex") ) { return selectionEndIndex; }
if (HX_FIELD_EQ(inName,"getCharBoundaries") ) { return getCharBoundaries_dyn(); }
if (HX_FIELD_EQ(inName,"__enableInputMode") ) { return __enableInputMode_dyn(); }
if (HX_FIELD_EQ(inName,"__getFontInstance") ) { return __getFontInstance_dyn(); }
if (HX_FIELD_EQ(inName,"__stopCursorTimer") ) { return __stopCursorTimer_dyn(); }
if (HX_FIELD_EQ(inName,"get_bottomScrollV") ) { return get_bottomScrollV_dyn(); }
break;
case 18:
if (HX_FIELD_EQ(inName,"__disableInputMode") ) { return __disableInputMode_dyn(); }
if (HX_FIELD_EQ(inName,"__startCursorTimer") ) { return __startCursorTimer_dyn(); }
break;
case 19:
if (HX_FIELD_EQ(inName,"__defaultTextFormat") ) { return __defaultTextFormat; }
if (HX_FIELD_EQ(inName,"selectionBeginIndex") ) { return selectionBeginIndex; }
if (HX_FIELD_EQ(inName,"getCharIndexAtPoint") ) { return getCharIndexAtPoint_dyn(); }
if (HX_FIELD_EQ(inName,"getLineIndexAtPoint") ) { return getLineIndexAtPoint_dyn(); }
if (HX_FIELD_EQ(inName,"set_backgroundColor") ) { return set_backgroundColor_dyn(); }
break;
case 20:
if (HX_FIELD_EQ(inName,"__measureTextWithDOM") ) { return __measureTextWithDOM_dyn(); }
break;
case 21:
if (HX_FIELD_EQ(inName,"get_defaultTextFormat") ) { return get_defaultTextFormat_dyn(); }
if (HX_FIELD_EQ(inName,"set_defaultTextFormat") ) { return set_defaultTextFormat_dyn(); }
}
return super::__Field(inName,inCallProp);
}
Dynamic TextField_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"text") ) { return set_text(inValue); }
if (HX_FIELD_EQ(inName,"type") ) { if (inCallProp) return set_type(inValue);type=inValue.Cast< ::openfl::text::TextFieldType >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"border") ) { if (inCallProp) return set_border(inValue);border=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"length") ) { length=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"__text") ) { __text=inValue.Cast< ::String >(); return inValue; }
break;
case 7:
if (HX_FIELD_EQ(inName,"scrollH") ) { scrollH=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"scrollV") ) { scrollV=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"__dirty") ) { __dirty=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"__width") ) { __width=inValue.Cast< Float >(); return inValue; }
break;
case 8:
if (HX_FIELD_EQ(inName,"autoSize") ) { if (inCallProp) return set_autoSize(inValue);autoSize=inValue.Cast< ::openfl::text::TextFieldAutoSize >(); return inValue; }
if (HX_FIELD_EQ(inName,"caretPos") ) { caretPos=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"htmlText") ) { return set_htmlText(inValue); }
if (HX_FIELD_EQ(inName,"maxChars") ) { maxChars=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"numLines") ) { numLines=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"restrict") ) { restrict=inValue.Cast< ::String >(); return inValue; }
if (HX_FIELD_EQ(inName,"wordWrap") ) { if (inCallProp) return set_wordWrap(inValue);wordWrap=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"__height") ) { __height=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"__isHTML") ) { __isHTML=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"__ranges") ) { __ranges=inValue.Cast< Array< ::Dynamic > >(); return inValue; }
break;
case 9:
if (HX_FIELD_EQ(inName,"multiline") ) { multiline=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"sharpness") ) { sharpness=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"textColor") ) { return set_textColor(inValue); }
if (HX_FIELD_EQ(inName,"textWidth") ) { textWidth=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"__texture") ) { __texture=inValue.Cast< ::lime::graphics::opengl::GLTexture >(); return inValue; }
break;
case 10:
if (HX_FIELD_EQ(inName,"background") ) { if (inCallProp) return set_background(inValue);background=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"caretIndex") ) { caretIndex=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"embedFonts") ) { embedFonts=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"maxScrollH") ) { maxScrollH=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"maxScrollV") ) { maxScrollV=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"selectable") ) { selectable=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"textHeight") ) { textHeight=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"__hasFocus") ) { __hasFocus=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"__tileData") ) { __tileData=inValue.Cast< Array< ::Dynamic > >(); return inValue; }
break;
case 11:
if (HX_FIELD_EQ(inName,"borderColor") ) { if (inCallProp) return set_borderColor(inValue);borderColor=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"gridFitType") ) { gridFitType=inValue.Cast< ::openfl::text::GridFitType >(); return inValue; }
if (HX_FIELD_EQ(inName,"__isKeyDown") ) { __isKeyDown=inValue.Cast< bool >(); return inValue; }
break;
case 12:
if (HX_FIELD_EQ(inName,"__showCursor") ) { __showCursor=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"__textFormat") ) { __textFormat=inValue.Cast< ::openfl::text::TextFormat >(); return inValue; }
if (HX_FIELD_EQ(inName,"__textLayout") ) { __textLayout=inValue.Cast< ::lime::text::TextLayout >(); return inValue; }
if (HX_FIELD_EQ(inName,"__tilesheets") ) { __tilesheets=inValue.Cast< Array< ::Dynamic > >(); return inValue; }
break;
case 13:
if (HX_FIELD_EQ(inName,"antiAliasType") ) { antiAliasType=inValue.Cast< ::openfl::text::AntiAliasType >(); return inValue; }
if (HX_FIELD_EQ(inName,"bottomScrollV") ) { bottomScrollV=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"__cursorTimer") ) { __cursorTimer=inValue.Cast< ::haxe::Timer >(); return inValue; }
break;
case 15:
if (HX_FIELD_EQ(inName,"backgroundColor") ) { if (inCallProp) return set_backgroundColor(inValue);backgroundColor=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"__measuredWidth") ) { __measuredWidth=inValue.Cast< int >(); return inValue; }
break;
case 16:
if (HX_FIELD_EQ(inName,"__cursorPosition") ) { __cursorPosition=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"__measuredHeight") ) { __measuredHeight=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"__selectionStart") ) { __selectionStart=inValue.Cast< int >(); return inValue; }
break;
case 17:
if (HX_FIELD_EQ(inName,"defaultTextFormat") ) { return set_defaultTextFormat(inValue); }
if (HX_FIELD_EQ(inName,"displayAsPassword") ) { displayAsPassword=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"selectionEndIndex") ) { selectionEndIndex=inValue.Cast< int >(); return inValue; }
break;
case 19:
if (HX_FIELD_EQ(inName,"__defaultTextFormat") ) { __defaultTextFormat=inValue.Cast< ::openfl::text::TextFormat >(); return inValue; }
if (HX_FIELD_EQ(inName,"selectionBeginIndex") ) { selectionBeginIndex=inValue.Cast< int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void TextField_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_CSTRING("antiAliasType"));
outFields->push(HX_CSTRING("autoSize"));
outFields->push(HX_CSTRING("background"));
outFields->push(HX_CSTRING("backgroundColor"));
outFields->push(HX_CSTRING("border"));
outFields->push(HX_CSTRING("borderColor"));
outFields->push(HX_CSTRING("bottomScrollV"));
outFields->push(HX_CSTRING("caretIndex"));
outFields->push(HX_CSTRING("caretPos"));
outFields->push(HX_CSTRING("defaultTextFormat"));
outFields->push(HX_CSTRING("displayAsPassword"));
outFields->push(HX_CSTRING("embedFonts"));
outFields->push(HX_CSTRING("gridFitType"));
outFields->push(HX_CSTRING("htmlText"));
outFields->push(HX_CSTRING("length"));
outFields->push(HX_CSTRING("maxChars"));
outFields->push(HX_CSTRING("maxScrollH"));
outFields->push(HX_CSTRING("maxScrollV"));
outFields->push(HX_CSTRING("multiline"));
outFields->push(HX_CSTRING("numLines"));
outFields->push(HX_CSTRING("restrict"));
outFields->push(HX_CSTRING("scrollH"));
outFields->push(HX_CSTRING("scrollV"));
outFields->push(HX_CSTRING("selectable"));
outFields->push(HX_CSTRING("selectionBeginIndex"));
outFields->push(HX_CSTRING("selectionEndIndex"));
outFields->push(HX_CSTRING("sharpness"));
outFields->push(HX_CSTRING("text"));
outFields->push(HX_CSTRING("textColor"));
outFields->push(HX_CSTRING("textHeight"));
outFields->push(HX_CSTRING("textWidth"));
outFields->push(HX_CSTRING("type"));
outFields->push(HX_CSTRING("wordWrap"));
outFields->push(HX_CSTRING("__cursorPosition"));
outFields->push(HX_CSTRING("__cursorTimer"));
outFields->push(HX_CSTRING("__dirty"));
outFields->push(HX_CSTRING("__hasFocus"));
outFields->push(HX_CSTRING("__height"));
outFields->push(HX_CSTRING("__isHTML"));
outFields->push(HX_CSTRING("__isKeyDown"));
outFields->push(HX_CSTRING("__measuredHeight"));
outFields->push(HX_CSTRING("__measuredWidth"));
outFields->push(HX_CSTRING("__ranges"));
outFields->push(HX_CSTRING("__selectionStart"));
outFields->push(HX_CSTRING("__showCursor"));
outFields->push(HX_CSTRING("__text"));
outFields->push(HX_CSTRING("__textFormat"));
outFields->push(HX_CSTRING("__textLayout"));
outFields->push(HX_CSTRING("__texture"));
outFields->push(HX_CSTRING("__tileData"));
outFields->push(HX_CSTRING("__tilesheets"));
outFields->push(HX_CSTRING("__width"));
super::__GetFields(outFields);
};
static ::String sStaticFields[] = {
HX_CSTRING("__defaultTextFormat"),
String(null()) };
#if HXCPP_SCRIPTABLE
static hx::StorageInfo sMemberStorageInfo[] = {
{hx::fsObject /*::openfl::text::AntiAliasType*/ ,(int)offsetof(TextField_obj,antiAliasType),HX_CSTRING("antiAliasType")},
{hx::fsObject /*::openfl::text::TextFieldAutoSize*/ ,(int)offsetof(TextField_obj,autoSize),HX_CSTRING("autoSize")},
{hx::fsBool,(int)offsetof(TextField_obj,background),HX_CSTRING("background")},
{hx::fsInt,(int)offsetof(TextField_obj,backgroundColor),HX_CSTRING("backgroundColor")},
{hx::fsBool,(int)offsetof(TextField_obj,border),HX_CSTRING("border")},
{hx::fsInt,(int)offsetof(TextField_obj,borderColor),HX_CSTRING("borderColor")},
{hx::fsInt,(int)offsetof(TextField_obj,bottomScrollV),HX_CSTRING("bottomScrollV")},
{hx::fsInt,(int)offsetof(TextField_obj,caretIndex),HX_CSTRING("caretIndex")},
{hx::fsInt,(int)offsetof(TextField_obj,caretPos),HX_CSTRING("caretPos")},
{hx::fsBool,(int)offsetof(TextField_obj,displayAsPassword),HX_CSTRING("displayAsPassword")},
{hx::fsBool,(int)offsetof(TextField_obj,embedFonts),HX_CSTRING("embedFonts")},
{hx::fsObject /*::openfl::text::GridFitType*/ ,(int)offsetof(TextField_obj,gridFitType),HX_CSTRING("gridFitType")},
{hx::fsInt,(int)offsetof(TextField_obj,length),HX_CSTRING("length")},
{hx::fsInt,(int)offsetof(TextField_obj,maxChars),HX_CSTRING("maxChars")},
{hx::fsInt,(int)offsetof(TextField_obj,maxScrollH),HX_CSTRING("maxScrollH")},
{hx::fsInt,(int)offsetof(TextField_obj,maxScrollV),HX_CSTRING("maxScrollV")},
{hx::fsBool,(int)offsetof(TextField_obj,multiline),HX_CSTRING("multiline")},
{hx::fsInt,(int)offsetof(TextField_obj,numLines),HX_CSTRING("numLines")},
{hx::fsString,(int)offsetof(TextField_obj,restrict),HX_CSTRING("restrict")},
{hx::fsInt,(int)offsetof(TextField_obj,scrollH),HX_CSTRING("scrollH")},
{hx::fsInt,(int)offsetof(TextField_obj,scrollV),HX_CSTRING("scrollV")},
{hx::fsBool,(int)offsetof(TextField_obj,selectable),HX_CSTRING("selectable")},
{hx::fsInt,(int)offsetof(TextField_obj,selectionBeginIndex),HX_CSTRING("selectionBeginIndex")},
{hx::fsInt,(int)offsetof(TextField_obj,selectionEndIndex),HX_CSTRING("selectionEndIndex")},
{hx::fsFloat,(int)offsetof(TextField_obj,sharpness),HX_CSTRING("sharpness")},
{hx::fsFloat,(int)offsetof(TextField_obj,textHeight),HX_CSTRING("textHeight")},
{hx::fsFloat,(int)offsetof(TextField_obj,textWidth),HX_CSTRING("textWidth")},
{hx::fsObject /*::openfl::text::TextFieldType*/ ,(int)offsetof(TextField_obj,type),HX_CSTRING("type")},
{hx::fsBool,(int)offsetof(TextField_obj,wordWrap),HX_CSTRING("wordWrap")},
{hx::fsInt,(int)offsetof(TextField_obj,__cursorPosition),HX_CSTRING("__cursorPosition")},
{hx::fsObject /*::haxe::Timer*/ ,(int)offsetof(TextField_obj,__cursorTimer),HX_CSTRING("__cursorTimer")},
{hx::fsBool,(int)offsetof(TextField_obj,__dirty),HX_CSTRING("__dirty")},
{hx::fsBool,(int)offsetof(TextField_obj,__hasFocus),HX_CSTRING("__hasFocus")},
{hx::fsFloat,(int)offsetof(TextField_obj,__height),HX_CSTRING("__height")},
{hx::fsBool,(int)offsetof(TextField_obj,__isHTML),HX_CSTRING("__isHTML")},
{hx::fsBool,(int)offsetof(TextField_obj,__isKeyDown),HX_CSTRING("__isKeyDown")},
{hx::fsInt,(int)offsetof(TextField_obj,__measuredHeight),HX_CSTRING("__measuredHeight")},
{hx::fsInt,(int)offsetof(TextField_obj,__measuredWidth),HX_CSTRING("__measuredWidth")},
{hx::fsObject /*Array< ::Dynamic >*/ ,(int)offsetof(TextField_obj,__ranges),HX_CSTRING("__ranges")},
{hx::fsInt,(int)offsetof(TextField_obj,__selectionStart),HX_CSTRING("__selectionStart")},
{hx::fsBool,(int)offsetof(TextField_obj,__showCursor),HX_CSTRING("__showCursor")},
{hx::fsString,(int)offsetof(TextField_obj,__text),HX_CSTRING("__text")},
{hx::fsObject /*::openfl::text::TextFormat*/ ,(int)offsetof(TextField_obj,__textFormat),HX_CSTRING("__textFormat")},
{hx::fsObject /*::lime::text::TextLayout*/ ,(int)offsetof(TextField_obj,__textLayout),HX_CSTRING("__textLayout")},
{hx::fsObject /*::lime::graphics::opengl::GLTexture*/ ,(int)offsetof(TextField_obj,__texture),HX_CSTRING("__texture")},
{hx::fsObject /*Array< ::Dynamic >*/ ,(int)offsetof(TextField_obj,__tileData),HX_CSTRING("__tileData")},
{hx::fsObject /*Array< ::Dynamic >*/ ,(int)offsetof(TextField_obj,__tilesheets),HX_CSTRING("__tilesheets")},
{hx::fsFloat,(int)offsetof(TextField_obj,__width),HX_CSTRING("__width")},
{ hx::fsUnknown, 0, null()}
};
#endif
static ::String sMemberFields[] = {
HX_CSTRING("antiAliasType"),
HX_CSTRING("autoSize"),
HX_CSTRING("background"),
HX_CSTRING("backgroundColor"),
HX_CSTRING("border"),
HX_CSTRING("borderColor"),
HX_CSTRING("bottomScrollV"),
HX_CSTRING("caretIndex"),
HX_CSTRING("caretPos"),
HX_CSTRING("displayAsPassword"),
HX_CSTRING("embedFonts"),
HX_CSTRING("gridFitType"),
HX_CSTRING("length"),
HX_CSTRING("maxChars"),
HX_CSTRING("maxScrollH"),
HX_CSTRING("maxScrollV"),
HX_CSTRING("multiline"),
HX_CSTRING("numLines"),
HX_CSTRING("restrict"),
HX_CSTRING("scrollH"),
HX_CSTRING("scrollV"),
HX_CSTRING("selectable"),
HX_CSTRING("selectionBeginIndex"),
HX_CSTRING("selectionEndIndex"),
HX_CSTRING("sharpness"),
HX_CSTRING("textHeight"),
HX_CSTRING("textWidth"),
HX_CSTRING("type"),
HX_CSTRING("wordWrap"),
HX_CSTRING("__cursorPosition"),
HX_CSTRING("__cursorTimer"),
HX_CSTRING("__dirty"),
HX_CSTRING("__hasFocus"),
HX_CSTRING("__height"),
HX_CSTRING("__isHTML"),
HX_CSTRING("__isKeyDown"),
HX_CSTRING("__measuredHeight"),
HX_CSTRING("__measuredWidth"),
HX_CSTRING("__ranges"),
HX_CSTRING("__selectionStart"),
HX_CSTRING("__showCursor"),
HX_CSTRING("__text"),
HX_CSTRING("__textFormat"),
HX_CSTRING("__textLayout"),
HX_CSTRING("__texture"),
HX_CSTRING("__tileData"),
HX_CSTRING("__tilesheets"),
HX_CSTRING("__width"),
HX_CSTRING("appendText"),
HX_CSTRING("getCharBoundaries"),
HX_CSTRING("getCharIndexAtPoint"),
HX_CSTRING("getLineIndexAtPoint"),
HX_CSTRING("getLineMetrics"),
HX_CSTRING("getLineOffset"),
HX_CSTRING("getLineText"),
HX_CSTRING("getTextFormat"),
HX_CSTRING("setSelection"),
HX_CSTRING("setTextFormat"),
HX_CSTRING("__clipText"),
HX_CSTRING("__disableInputMode"),
HX_CSTRING("__enableInputMode"),
HX_CSTRING("__getBounds"),
HX_CSTRING("__getFont"),
HX_CSTRING("__getFontInstance"),
HX_CSTRING("__getPosition"),
HX_CSTRING("__getTextWidth"),
HX_CSTRING("__hitTest"),
HX_CSTRING("__measureText"),
HX_CSTRING("__measureTextWithDOM"),
HX_CSTRING("__renderCanvas"),
HX_CSTRING("__renderDOM"),
HX_CSTRING("__renderGL"),
HX_CSTRING("__startCursorTimer"),
HX_CSTRING("__stopCursorTimer"),
HX_CSTRING("set_autoSize"),
HX_CSTRING("set_background"),
HX_CSTRING("set_backgroundColor"),
HX_CSTRING("set_border"),
HX_CSTRING("set_borderColor"),
HX_CSTRING("get_bottomScrollV"),
HX_CSTRING("get_caretPos"),
HX_CSTRING("get_defaultTextFormat"),
HX_CSTRING("set_defaultTextFormat"),
HX_CSTRING("get_height"),
HX_CSTRING("set_height"),
HX_CSTRING("get_htmlText"),
HX_CSTRING("set_htmlText"),
HX_CSTRING("get_maxScrollH"),
HX_CSTRING("get_maxScrollV"),
HX_CSTRING("get_numLines"),
HX_CSTRING("get_text"),
HX_CSTRING("set_text"),
HX_CSTRING("get_textColor"),
HX_CSTRING("set_textColor"),
HX_CSTRING("get_textWidth"),
HX_CSTRING("get_textHeight"),
HX_CSTRING("set_type"),
HX_CSTRING("get_width"),
HX_CSTRING("set_width"),
HX_CSTRING("get_wordWrap"),
HX_CSTRING("set_wordWrap"),
String(null()) };
static void sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(TextField_obj::__mClass,"__mClass");
HX_MARK_MEMBER_NAME(TextField_obj::__defaultTextFormat,"__defaultTextFormat");
};
#ifdef HXCPP_VISIT_ALLOCS
static void sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(TextField_obj::__mClass,"__mClass");
HX_VISIT_MEMBER_NAME(TextField_obj::__defaultTextFormat,"__defaultTextFormat");
};
#endif
Class TextField_obj::__mClass;
void TextField_obj::__register()
{
hx::Static(__mClass) = hx::RegisterClass(HX_CSTRING("openfl.text.TextField"), hx::TCanCast< TextField_obj> ,sStaticFields,sMemberFields,
&__CreateEmpty, &__Create,
&super::__SGetClass(), 0, sMarkStatics
#ifdef HXCPP_VISIT_ALLOCS
, sVisitStatics
#endif
#ifdef HXCPP_SCRIPTABLE
, sMemberStorageInfo
#endif
);
}
void TextField_obj::__boot()
{
}
} // end namespace openfl
} // end namespace text
|
<reponame>qiuwenhuifx/PolarDB-for-PostgreSQL
/*--------------------------------------------------------------------------
*
* px_hash.h
* Definitions and API functions for pxhash.c
*
* Portions Copyright (c) 2005-2008, Greenplum inc
* Portions Copyright (c) 2012-Present Pivotal Software, Inc.
* Portions Copyright (c) 2021, Alibaba Group Holding Limited
*
* IDENTIFICATION
* src/include/px/px_hash.h
*
*--------------------------------------------------------------------------
*/
#ifndef PXHASH_H
#define PXHASH_H
#include "utils/rel.h"
/* GUC */
extern bool px_use_legacy_hashops;
/*
* reduction methods.
*/
typedef enum
{
REDUCE_LAZYMOD = 1,
REDUCE_BITMASK,
REDUCE_JUMP_HASH
} PxHashReduce;
/*
* Structure that holds Greenplum Database hashing information.
*/
typedef struct PxHash
{
uint32 hash; /* The result hash value */
int numsegs; /* number of segments in Greenplum Database
* used for partitioning */
PxHashReduce reducealg; /* the algorithm used for reducing to buckets */
bool is_legacy_hash;
int natts;
FmgrInfo *hashfuncs;
} PxHash;
/*
* Create and initialize a PxHash in the current memory context.
*/
extern PxHash *makePxHash(int numsegs, int natts, Oid *typeoids);
/*
* Initialize PxHash for hashing the next tuple values.
*/
extern void pxhashinit(PxHash *h);
/*
* Add an attribute to the hash calculation.
*/
extern void pxhash(PxHash *h, int attno, Datum datum, bool isnull);
/*
* Reduce the hash to a segment number.
*/
extern unsigned int pxhashreduce(PxHash *h);
/*
* Return a random segment number, for a randomly distributed policy.
*/
extern unsigned int pxhashrandomseg(int numsegs);
extern unsigned int pxhashsegForUpdate(unsigned long long ctidHash,int numsegs);
extern Oid px_default_distribution_opfamily_for_type(Oid typid);
extern Oid px_default_distribution_opclass_for_type(Oid typid);
extern Oid px_hashproc_in_opfamily(Oid opfamily, Oid typeoid);
/* prototypes and other things, from pxlegacyhash.c */
/* 32 bit FNV-1 non-zero initial basis */
#define FNV1_32_INIT ((uint32)0x811c9dc5)
extern uint32 magic_hash_stash;
#endif /* PXHASH_H */
|
<reponame>JorgeLNJunior/animes-review-api<filename>src/http/modules/review/query/review.query.builer.ts
import { FindConditions, FindManyOptions } from 'typeorm'
import { Review } from '../entities/review.entity'
import { ReviewQuery } from './review.query.interface'
export class ReviewQueryBuilder {
private query: ReviewQuery;
constructor (query: ReviewQuery) {
this.query = query
}
build (): FindManyOptions<Review> {
const findOptions: FindManyOptions<Review> = {}
const conditions: FindConditions<Review> = {}
if (this.query.uuid) conditions.uuid = this.query.uuid
if (this.query.animeUuid) conditions.anime = { uuid: this.query.animeUuid }
if (this.query.userUuid) conditions.user = { uuid: this.query.userUuid }
if (this.query.take) {
findOptions.take = this.query.take
} else findOptions.take = 20
if (this.query.skip) findOptions.skip = this.query.skip
findOptions.where = conditions
return findOptions
}
}
|
Owner, Jeff Poppen, widely known from dozens of appearances on public television, is concerned over possible contamination from a neighboring corporate chicken farm.
One of Tennessee's oldest and largest organic farms is shutting down after a dispute with a subsidiary of Tyson Foods. The farm, operated by the "Barefoot Farmer," aka Jeff Poppen from public television, was concerned about a factory chicken farm next door and the impacts of its organic produce. (Photo11: John Partipilo, The Tennessean) Story Highlights Organic farms are increasing but face a number of challenges to establish a firmer foothold.
NASHVILLE, Tenn. -- One of the state's oldest and largest organic farms — operated by Tennessee's famed "Barefoot Farmer" — is shutting down operations in Macon County following a dispute over a corporate chicken farming operation next door.
The farm's owner, Jeff Poppen, is a widely known organic farmer who has hosted numerous workshops, made dozens of appearances on public television and grown food for some of Nashville's top restaurants, including Capitol Grille and Tayst.
Poppen says he is closing down Long Hungry Creek Farm in Red Boiling Springs because of concerns over possible contamination from a neighboring farm that is growing chickens for a Tyson Foods Inc. subsidiary.
"I can't guarantee organic production here anymore," Poppen said.
"Because of how close they built it, there will be no more gardens here, no more T.V. shows filmed here, no more church and school tours here and my family and I are moving," Poppen posted on his Facebook page.
Although Poppen's decision is a blow for the organic farming movement in Tennessee, others in the industry still see room for optimism.
College Grove farmer Hank Delvin Jr. has seen firsthand the recent growth in organic farming.
In the past two years, the number of wholesale orders at Delvin's 140-acre Delvin Farms has doubled.
"I think it's easier to get into organic produce than it was 20 years ago, because the public is seeking it and demanding it," Delvin said.
Since 2000, the number of certified organic farming operations in Tennessee has more than doubled — from 10 then to 26 in 2008, according to data compiled by the U.S. Department of Agriculture.
John Cahill, a farmer at Real Food Farms between Brentwood and Franklin, has also seen the rise in demand.
"It's going in the right direction," he said.
Still, the fledging farms face a number of challenges to establish a firmer foothold. Even with the growth, organic farms make up less than 1 percent of farmland nationwide.
And running an organic operation — especially a smaller local farm — can bring a unique set of challenges.
Large-scale organic farms, which can produce more food for less, are putting downward pressure on prices, even as costs for smaller farms are going up, Delvin said.
One of those increasing costs is labor.
"I plant an acre of carrots, and organically, I'm fighting the weeds the whole time," he said. "I have to spend a lot of labor getting rid of weeds. My friend who is not organic, he just sprays herbicide on it."
Most of Delvin's workers have been with him for several years and are good at their jobs, but they come at a price.
"I have to pay a living wage," he said. "There's a certain amount of training you have to do."
For Cahill, another challenge is convincing consumers that not only should they buy organic, but they should also buy local.
"There's still this giant wall that has to be broken down in people's minds of how they can get local food," Cahill said. "It's a lot easier to go to Publix and shop in the organics section to get produce from California."
In addition, sometimes prices are higher, he said.
"People are not willing to pay the price in terms of finances and getting themselves out there to get the food," he said.
That could slow growth of new farms.
"You can't start a farm with the main thought that you're going to make a million dollars," Cahill said. "It's not going to happen. The expenses of a farm keep you at even."
As for disputes with neighbors, Delvin said dealing with adjacent non-organic farms comes with the territory.
"I'm surrounded by non-organic farms," he said. "Most people are. I have some dairies beside us. I have people growing corn and grain."
The key is to try to maintain a buffer zone and prevent any contamination that could jeopardize organic status, he said.
Jeff Poppen, the barefoot farmer, greets the day at his farm near Red Boiling Springs, Tenn. The farm, one of Tennessee's oldest and largest organic farms, is shutting down after a dispute with a subsidiary of Tyson Foods. Poppen, known as the "Barefoot Farmer" on public television, was concerned about a factory chicken farm next door and the impacts of its organic produce. (Photo11: John Partipilo, The Tennessean)
Poppen had been embroiled in a public dispute over a neighbor's chicken farm for more than a year.
The neighbor, Lundy Russell, recently began raising 40,000 chicks under a contract with Cobb-Vantress Inc., a chicken breeding subsidiary of Tyson Foods. The chicks are kept in two long chicken houses on a steep hill overlooking Poppen's farm.
Poppen has contended the factory farm will pollute his land with excessive waste, which Lundy and Cobb-Vantress have denied.
Long Hungry Creek Farm drew hundreds of visitors each year, and served more than 200 regular customers with organic produce grown on the farm. The farm also supported a few part-time employees, along with interns.
For its part, Tyson Foods contends that its operation fully complies with state laws and is safe.
"We at Cobb-Vantress are serious about our responsibility to operate with integrity. In fact, we have been working with other family farmers in the area who have already built and are operating chickens houses and they have received no complaints from their neighbors," said Worth Sparkman, manager of public relations for Tyson Foods Inc. "We want to assure you we intend to continue to work with our contract family farmers in a responsible way."
As for his future plans, Poppen said he would likely look to start a similar farming operation about 5 miles away from his current farming site. Poppen did not give a timeline for when the new operations might be up and running.
"I can't imagine he will give up farming because it's what he likes to do," said Alan Powell, who has worked with Poppen, in an email. "Ultimately, I don't think he knows how this will all pan out in the end. He doesn't trust the land he has lived on and farmed for over 20 years, and will stop producing food there so as not to risk his customers' health."
Read or Share this story: http://usat.ly/USKXpM |
Google showed off screen casting from Android at Google I/O, and we've been seeing hints of it in KitKat for months, and now it's suddenly real. Google has thrown the switch and enabled casting on a number of Android devices, and it works with sound too.
Screen casting will require Android 4.4.2 or higher (MR1) and is currently supported on the following devices.
Nexus 4
Nexus 5
Nexus 7 (2013)
Nexus 10
Samsung Galaxy S4
Samsung Galaxy S5
Samsung Galaxy Note 3
Samsung Galaxy Note 10 (2014)
HTC One M7
LG G Pro2
LG G2
and LG G3
You should be able to access the casting menu in display options and select your Chromecast. The Quick Settings icon we've been seeing on stock devices for months seems to be live as well. It's also in the Chromecast app, which finally makes that app useful beyond setting up the dongle. The screen is beamed over without any further fiddling. Video seems okay (depending on network) with some artifacting, but audio goes over fine. Sound still works with the screen off too.
[Google, Chrome Blog] |
Research onHigh Robust Multimedia Image Encryption Based on Gyrator Transform Domain Model
(e encryption and privacy protection of multimedia image resources are of great value in the information age. (e utilization of the gyrator transform domain model in multimedia image encryption can select parameters more accurately, so it has a wider scope of utilization and further ameliorates the stability of the whole system. On account of this, this paper first analyzes the concept and connotation of gyrator transform, then studies the image encryption algorithm on account of gyrator transform, and verifies the robustness of the gyrator transform algorithm under the influence of noise interference, shear attack, and other factors through the high robust multimedia image encryption and result analysis of gyrator transform.
Introduction
With the iterative maturity and popularization of computer information technology, it has been widely and deeply applied in many fields and achieved remarkable results. However, the encryption and security of computer information have become the focus and difficulty of people's research and attention. On the one hand, many information resources represented by digital images are widely used in many fields. On the other hand, under the background of the deepening network threats and attacks faced by the Internet platform, the encryption and privacy protection of information multimedia image resources have become an unavoidable problem and the focus of attention and research by many scholars. Specific to the encryption level of multimedia images, if the encryption transmission and sharing of image information want to be more flexible and convenient, it is more and more inseparable from the support of data security protection technology.
In the process of multimedia image transmission, due to its own particularity, it is necessary to encrypt and protect the privacy information contained in it so as to avoid data tampering and interception. At present, the encryption methods of multimedia images mainly include linear canonical transform, Fourier transform, and wavelet transform. Among them, Fourier transform has expanded its utilization field with its extensive research and much visualization results and has strong utilization flexibility and utilization advantages. In contrast, linear canonical transformation has the typical advantages of flexibility and stronger processing power, but it has its own shortcomings in the amount of computation and parameter selection . erefore, the introduction of gyrator transform in the encryption process of multimedia image can better realize the organic integration of transformation efficiency and flexibility, so it has better applicability.
In addition, the utilization of gyrator transform in the field of multimedia image encryption can further ameliorate the parallelism and robustness of image processing, so it has gradually become the key direction of the research and utilization of the multimedia image encryption algorithm in the transform domain. e operation process of the multimedia image encryption algorithm integrating the gyrator transform domain model is shown in Figure 1, which fully releases the operation efficiency of the algorithm and the data conversion ability between spatial domains and transform domain. Generally speaking, multimedia image encryption under the transform domain model will lead to a significant increase in the amount of data operation and affect the calculation accuracy, resulting in the decline of image accuracy. e multimedia image encryption of the gyrator transform domain model can select parameters more accurately, has a wider range of utilization, and further ameliorate the stability of the whole system.
In short, the encryption of multimedia images needs to pay attention to the encryption efficiency, transmission efficiency, and use cost of images on the premise of paying attention to the security of cipher-text. e multimedia image encryption algorithm integrating the gyrator transform domain model uses different transforms to process different matrices, which greatly optimizes the distribution and management of multimedia image key, and has great advantages in security and sensitivity. erefore, it is of great practical value to study the robustness of the multimedia image encryption algorithm integrating the gyrator transform domain model.
e Concept of Gyrator Transformation.
As an important measure to realize image data information conversion, Fourier transform has typical advantages of convenient beam transmission and pure fractional spectrum signal . Similarly, as a linear regular integral transformation, the integral kernel matrix of gyrator transformation is a symmetrical structure, as shown in equation (1). Among them, α is the rotation angle, and a i b i is the position spatial frequency plane. e characteristic matrix of gyrator linear transformation is shown in equation (2). In addition, the mathematical definition of gyrator transformation can be obtained by substituting the transfer matrix into equation
Typical Multimedia Image Encryption Technologies.
Typical image encryption technologies include pixel scrambling based on spatial domain, encryption algorithm based on transform domain, encryption algorithm based on turbidity, DNA coding technology, encryption based on neural network and cellular automata, and algorithms based on secret segmentation and secret sharing. Among them, the security technology of pixel scrambling based on spatial domain is poor, which often needs to be combined with other encryption technologies. In addition, the security evaluation criteria for these typical image encryption algorithms include key space analysis, statistical feature analysis, adjacent pixel correlation analysis, information entropy analysis, sensitivity analysis, integrity analysis, and anticlipping analysis.
Typical Properties of Gyrator Transformation.
Multimedia image encryption on account of the gyrator transform domain model is mainly carried out with the help of the advantages and features of gyrator transform. e typical features of gyrator transform are not only limited to exponential additivity and reversibility but also have their own unique characteristics, as shown in Figure 2.
e linear expression of gyrator transformation is shown in equation (3), and b 1 and b 2 are complex constants. Exponential additivity and commutativity make gyrator transform more flexible. e typical properties of gyrator transform make its utilization in multimedia image encryption have significant advantages, such as convenient multilevel and channel image information encryption and decryption.
Implementation of Gyrator Transform.
In order to realize high robust multimedia image encryption, firstly, an efficient cascade system needs to be constructed at the optical level to realize wide-angle gyrator transform. e architecture of the efficient cascaded optical system is shown in Figure 3. Its main components include thin lens group and phase modulation system. In the system shown in Figure 3, the generalized lens T and the thin lens group on the right are covered, and the principle of phase modulation is shown in equation (4). Among them, λ is the wavelength of the light wave, f is the focal length, and is the position of the symmetry axis of the cylindrical thin lens relative to the Y axis.
In the phase modulation system shown in Figure 3, there are two identical lenses T1 in the Z axis, and their phase modulation functions are also the same. e angle of gyrator transformation is obtained by rotating the cylindrical thin lens constituting the generalized lens and plays a key and decisive role in the composition of the generalized lens in the experimental device. In addition, under a specific angle, the phase modulation system shown in Figure 3 can be considered as a typical special extension of the Fourier transform stacking system.
Multimedia image encryption with high robustness also needs to be realized at the numerical level, and its principle is shown in equation (5). Among them, the situations in the formula need to be treated differently, and different simulation forms should be selected, respectively, such as FFT or IFFT. In the implementation of the fast discrete algorithm of gyrator transform, the modulation function needs to be input first, and then it is further transformed by FFT or IFFT to verify the additivity of the order of gyrator transform . Optical transformation of the gyrator and the analysis and utilization of the fast numerical implementation algorithm are helpful to establish an effective premise for the utilization of this algorithm in highly robust multimedia images. Advances in Multimedia
Image Encryption Algorithm on account of Gyrator
Transform. Generally speaking, the encryption process of multimedia image is a hidden processing process of sensitive information . erefore, as long as the algorithm can realize the smooth conversion between the original image and the encrypted image, the image can be encrypted. With the continuous progress and amelioration of the computing power level of the computer system, its efficiency in the encryption processing of multimedia images is also improving accordingly. Gyrator transform has been widely studied and popularized in many fields because of its many utilization advantages . Secondly, the transform domain algorithm has many similarities with FFT, so it has important utilization value in the field of high robust multimedia image encryption. Image encryption on account of gyrator transform pays more attention to the visibility, selfsimilarity, and correlation of image information in the process of encryption and decryption and ameliorates the encryption and decryption efficiency of the whole system. e advantages of gyrator transform in algorithm efficiency, accuracy, and security make its utilization in the field of multimedia image encryption have a good development prospect and can greatly ameliorate the robustness of multimedia image encryption.
Principle of Multimedia Image Encryption on account of
Gyrator Transform. FFT has typical utilizations in the field of multicolor image encryption, and its efficiency is remarkable. Gyrator transform, as a changed form of FFT, further highlights the advantages of FFT transform and strengthens its adaptability and matching in the field of multimedia image encryption with the help of its unique characteristics; therefore, it has good utilization and development prospects and potential . Secondly, the N-cascade encryption process of the image encryption change fused with gyrator transform is shown in equation (6), in which the κ -order gyrator transform of image g( e image encryption process of gyrator transform is shown in Figure 4. When encrypting the multimedia image, the transformation and operation are cascaded for many times so as to flexibly use the encryption parameters to ensure the security of the encrypted image to the greatest extent. e gyrator transform multimedia image algorithm is more suitable for practical utilization scenarios . In addition, the fusion with double random phase coding technology is not conducive to practical utilization. Although this method increases the key multiplicity, it also leads to the complexity of its algorithm.
Single Image Encryption on account of Gyrator Transform.
For a single image, the κ-order gyrator transform is shown in equation (7), where Z (a, b) and X (a, b) are the amplitude and phase of gyrator transform spectrum, respectively. Secondly, through the mathematical operation of single image encryption of gyrator transform, the difficulty of decryption process can be effectively reduced, so as to effectively deal with the adverse effects of cascading and interchangeability . In addition, the real and imaginary parts of the gyrator transform spectrum are transposed or added or subtracted to obtain the encryption result of the image. In order to recover the information of the original image, the level inverse transformation is carried out, and further the inverse operation of the operator is carried out to obtain the κ-order gyrator transform spectrum of the image, and then the -κ order inverse transformation is carried out to obtain the image, so as to complete the image decryption process. y, a, b) Z(a, b)exp . Gyrator transform can be verified by optical path experiment. Secondly, in order to ameliorate the security of multimedia image encryption, it can be further realized by increasing the number of keys. With the help of computer simulation software, the effectiveness of the gyrator transformation algorithm can be verified. Gyrator transformation is performed on the specific image shown in Figure 5(a). After obtaining its map distribution, the matrix transpose and imaginary part matrix in the distribution are added, and then the calculated results are recombined to obtain a new matrix complex matrix . In addition, by performing gyrator transformation on the complex matrix, the new image is shown in Figure 5(b). It can be seen that the image after gyrator transformation has completely become a noise image and completely implies sensitive and real information, it can well realize the encryption of multimedia images.
As can be seen from Figure 5, the gyrator transformed image of the original image can not only obtain its image spectral distribution but also obtain the original image through inverse operation. rough the inverse operation of gyrator transform encryption program, the original image can be recovered, the original image can be decrypted, and its complete real information can be retained . e distribution shown in Figures 6(a) and 6(b) is the result of the failed inverse transformation, which is the result of the gyrator transformation, the primary and secondary transformation errors, and the correct t operation.
It can be seen from the inverse transformation results of Figure 6 that Figure 6(b) can better the original encrypted information, which shows that the secondary gyrator transformation is very necessary. erefore, adding double random phase coding to the multimedia algorithm integrating gyrator transformation can better realize the image encryption effect. In addition, it can be seen from the effect of change and encryption that gyrator transform is similar to FFT transform and has the typical characteristics of cascade and exchange, but its decryption process is relatively simple, and the complexity needs to be further ameliorated to ensure the security of the decryption process.
In addition, in order to verify the anti-interference ability of the encrypted image fused with gyrator transform, certain white noise interference needs to be verified. As shown in Figure 7(a), interfere with the decryption process, apply 15 dB, 10 dB, and 5 dB Gaussian noise, respectively, and ensure the correctness of the decryption process key. e decrypted image results are shown in Figures 7(b)-7(d). As can be seen from Figure 7, after the original encrypted image is disturbed by noise, the decrypted image will lose some real information, resulting in the impact on the detail restoration of the image, but the basic content of the original image can still be obtained and judged .
is shows that the algorithm integrating gyrator transform can resist the interference of dead noise to a certain extent, but with the increase in noise intensity, the image quality and content details obtained by decryption will decrease significantly, resulting in further annihilation of real information.
Multi-Image Encryption on account of Gyrator Transform.
FFT can effectively concentrate the spectrum. After the gyrator transformed image is rotated by a specific rotation angle usually π 2, the image information will be further concentrated in the low-frequency spectrum region . When the rotation angle is further reduced, after gyrator transformation, the original image content with more readable details needs to be restored with the help of the central spectrum. Figure 8 shows the recovery effect of the gyrator transform spectrum after different rotation angles. As can be seen from the figure, there is basically no interference between images in the process of multi-image encryption and decryption, which is also the advantage of this algorithm.
Similarly, the numerical simulation and optical implementation of multimedia image encryption need to be realized with the help of computer simulation software so as to further analyze the practicability of the image encryption algorithm. Generally speaking, the size of the central spectral area is negatively correlated with the number of original images but positively correlated with the spectrum information . erefore, a certain central spectral area is required to ensure the authenticity of the decrypted multimedia image and the details of the information. In addition, the concentration of spectral energy of gyrator transform is positively correlated with the rotation angle, while the central spectral size required for decryption is negatively correlated with the rotation angle. is shows that there is an upper limit on the number of encrypted images that can be realized by the multi-image encryption algorithm, and the upper limit value will vary with the difference of rotation angle.
Verification of the Encryption Effect and Security Principle in the Decryption Process.
After obtaining the different information components of the decrypted multimedia image, the original multimedia image can be restored by combining the three decrypted component information. So far, the decryption process is completed. Different chaotic initial values, different transform iteration times, and different gyrator transform rotation angles are used for encryption and decryption. ey will be used as the key information of the encryption system. e experiments show that the gyrator transform encryption algorithm in this paper has good encryption effect and security.
High Robustness Multimedia Image Encryption on account of Gyrator Transform.
e multimedia images to be encrypted are combined, and the combined multimedia image matrix is phase coded. By combining the virtual and real parts of the combined image, the numerical decomposition of the real matrix is realized. Secondly, the multimedia cipher-text image is obtained by singular value decomposition . With the help of the key, the plaintext image can be obtained by inverse transformation, which is 6 Advances in Multimedia realized by recombining the singular value decomposition through the orthogonal matrix. For the original multimedia image that needs to be encrypted, it is first necessary to combine the images, establish the corresponding virtual part image set and real part image set, and then calculate the real value of the image set. e process is shown in the following equations: Among them, g(x, y) is the original multimedia image. For n original images to be encrypted, they are combined to establish a complex matrix. Secondly, the real part and imaginary part image sets s and s′ are established, respectively, and the ameliorated mapping initial values are obtained by calculating the real values A 0 and A 1 . Z is the distribution of gray histogram of original multimedia image.
rough the iterative calculation of the above formula, the chaotic phase mask is obtained . Further, the complex matrix is transformed by gyrator to obtain the matrix, and the real part and imaginary part components in the transformation matrix are extracted and recombined to construct the real matrix. By extracting the real and imaginary components of the transformed matrix, respectively, and further combining them, the combined real matrix is obtained. In addition, the orthogonal matrix is obtained by multiresolution singular value decomposition of the combined real matrix, and the orthogonal matrix is combined to obtain the Gaussian matrix parameter key.
Decryption Process with the Help of Key Inverse Process.
Firstly, the cipher-text is solved by means of Clem's law, and the results of multiresolution singular value decomposition are obtained. Secondly, the complex matrix is obtained by inverse process operation of the multiresolution singular value decomposition results. en, the complex matrix is transformed by gyrator, and the transformation angle is the complex of the encryption process, so as to obtain the complex matrix. Finally, the imaginary and real parts of the complex matrix obtained by the inverse transformation are extracted, respectively, and then the original multimedia image is obtained.
Experimental Results and Analysis.
Firstly, the computer simulation platform and simulation software are used to randomly extract the multimedia plaintext image to be encrypted in the database, and the size of the image is optimized and adjusted. e simulation software selected in Advances in Multimedia this paper is Matlab2018Rb, the hardware is a quad core Intel (R) i7-5100U processor, the memory is 16g, and the operating system is Windows 10. At the selection level of test image, select the image shown in Figure 9 and set the mapping control parameters, and the square difference and mean value of random Gaussian matrix are 4.96, 1 and 0.5.
Multimedia Image Encryption and Decryption Results.
In order to ensure the scientificity and objectivity of multimedia image encryption and decryption results, PSNR, CC, and SSIM are used as evaluation parameters. e original multimedia image and the decrypted image are represented by G (x, y) and G′(x, y), respectively, and the calculation process of evaluation indexes PSNR, CC, and SSIM is shown in the following equations: SSIM � 2μ g μ g′ + c 1 2σ gg′ + c 2 in which μ g and μ g′ are the mean of the original multimedia images g(x, y) and g ′ (x, y), σ g and σ g′ are the standard deviation of the original multimedia images g(x, y) and g ′ (x, y), respectively, σ gg′ is the covariance of the original image, c 1 and c 2 are constants, and E is the expected value operation. According to the definition of the formula, it can be seen that the PSNR value is positively correlated with the quality of the decrypted image.
With the help of computer simulation, the effect of singular value decomposition factor on the decryption image effect is studied, and the selected images are experimentally analyzed. e displayed results are shown in Table 1. It is not difficult to see from the results in Table 1 that the decryption effect of the original multimedia image is the best when the value of the parameter (p, q) equals (2, 2). In addition, at the level of antistatistical attack performance, there are significant differences in the histogram peaks of different original multimedia images. e encrypted image is similar to Gaussian white noise by fusing gyrator changes, which effectively masks the details of the original image.
Robustness Analysis of Multimedia Image Encryption.
Some noise pollution is inevitable in the process of multimedia image encryption data transmission, and the quality of multimedia decrypted image is negatively correlated with (c) (d) Figure 9: Selected test image. the noise intensity. e algorithm used in this paper can better regional noise attack, which shows that the robustness of the algorithm is better, as shown in Figure 10(a). In addition, the multimedia image encryption algorithm fused with the gyrator transform domain model is less vulnerable to shear attack, and the data content of the original multimedia image is less vulnerable to cipher-text loss, as shown in Figure 10(b). ese experimental results show that the multimedia image encryption algorithm on account of the gyrator transform domain model has strong robustness.
Conclusions
e flexible and convenient encryption transmission and sharing of multimedia image information are more and more inseparable from the support of data security protection technology. In the process of multimedia image encryption, the introduction of gyrator transform can better realize the organic integration of transformation efficiency and flexibility, so it has better applicability. By studying the concept and connotation of gyrator transform, this paper analyzes the properties and implementation of gyrator transform. By analyzing the image encryption algorithm on account of gyrator transform, the image encryption algorithm integrating gyrator transform is studied. Finally, the robustness of the gyrator transform domain model in the multimedia image encryption algorithm is verified by analyzing the high robustness multimedia image encryption and results of gyrator transform.
Data Availability
e data used to support the findings of this study are available upon request to the author. Advances in Multimedia 9 |
<reponame>sarvex/tensorflow-runtime
/*
* Copyright 2020 The TensorFlow Runtime 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.
*/
// This file declares CreateCpuOpHandler, which creates CPU Op Handler
// responsible for executing ops on CPU.
#ifndef TFRT_BACKENDS_CPU_CORE_RUNTIME_CPU_OP_HANDLER_H_
#define TFRT_BACKENDS_CPU_CORE_RUNTIME_CPU_OP_HANDLER_H_
#include <memory>
#include "llvm/ADT/SetVector.h"
#include "tfrt/core_runtime/op_handler.h"
#include "tfrt/cpu/core_runtime/cpu_op_registry.h"
namespace tfrt {
class CoreRuntime;
class CoreRuntimeOp;
class Device;
class CpuOpHandler : public OpHandler {
public:
static const char* const kName;
~CpuOpHandler() override {}
Expected<CoreRuntimeOp> MakeOp(string_view op_name) override;
RCReference<Device> GetDeviceRef() { return device_; }
void AddImplicitConversion(TensorType src, TensorType dst);
bool AllowImplicitConversion(TensorType src, TensorType dst);
private:
const CpuOpRegistry op_registry_;
RCReference<Device> device_;
llvm::SmallSetVector<TensorConversionFnRegistry::ConversionKey, 4>
allowed_conversions;
friend llvm::Expected<CpuOpHandler*> CreateCpuOpHandler(
CoreRuntime* runtime, RCReference<Device> device, OpHandler* fallback);
explicit CpuOpHandler(CoreRuntime* runtime, OpHandler* fallback,
CpuOpRegistry op_registry, RCReference<Device> device);
};
llvm::Expected<CpuOpHandler*> CreateCpuOpHandler(CoreRuntime* runtime,
RCReference<Device> device,
OpHandler* fallback);
} // namespace tfrt
#endif // TFRT_BACKENDS_CPU_CORE_RUNTIME_CPU_OP_HANDLER_H_
|
/**
* Check if all DailyServices are after than current date.
* @param date
* @param days
* @return true if all dailyService are after than SystemDate
*/
public static boolean isValidDailyServices(List<DailyServices> days){
for(DailyServices d : days){
final LocalDate TODAY = new LocalDate();
if(!d.getDate().isAfter(TODAY)){
return false;
}
}
return true;
} |
def rotation_axes(
arr,
labels=None,
index=None,
sort_by_shape=False):
inertia = tensor_of_inertia(arr, labels, index, None).astype(np.double)
eigenvalues, eigenvectors = np.linalg.eigh(inertia)
if sort_by_shape:
tmp = [
(size, eigenvalue, eigenvector)
for size, eigenvalue, eigenvector
in zip(
sorted(arr.shape, reverse=True),
eigenvalues,
tuple(eigenvectors.transpose()))]
tmp = sorted(tmp, key=lambda x: arr.shape.index(x[0]))
axes = []
for size, eigenvalue, eigenvector in tmp:
axes.append(eigenvector)
else:
axes = [axis for axis in eigenvectors.transpose()]
return axes |
Induced by Inhibitory Ethanol Concentration
a* b a ABSTRACT. In oxygen-aerated non-growing cells a subinhibitory ethanol concentration (1 G/L) causes an H /K exchange. An inhibitory ethanol concentration (30 G/L) slows down acidification but + + has no effect on its extent. The transmembrane pH depends directly on the ethanol level in the medium and is not lowered at high ethanol concentrations. Changes in membrane potential induced by ethanol are also concentration dependent. The high ethanol level does not increase the passive permeability of cell membrane to H. + |
def initOptiTruck(self,**kwargs):
self.checkFeasibility()
self.M=pyomo.ConcreteModel()
self.M.isLP=True
self.M.weight=kwargs.get('weight', 'weightedDistance')
self.M.edgeIndex=self.edges()
self.M.edgeIndexForw=[(node1,node2) for (node1,node2) in self.M.edgeIndex]
self.M.edgeIndexBack=[(node2,node1) for (node1,node2) in self.M.edgeIndex]
self.M.edgeIndexFull = self.M.edgeIndexForw
self.M.edgeIndexFull.extend(self.M.edgeIndexBack)
self.M.edgeCapacity=pyomo.Var(self.M.edgeIndex)
self.M.edgeFlow=pyomo.Var(self.M.edgeIndexFull, within = pyomo.NonNegativeReals)
self.M.edgeLength=nx.get_edge_attributes(self, self.M.weight)
self.M.nodeIndex=self.nodes()
self.M.nodeProductionMax=nx.get_node_attributes(self,"productionMax")
self.M.nodeDemand=nx.get_node_attributes(self,"demand")
self.M.nodeNeighbour = {self.M.nodeIndex[i]: neighbours for i,neighbours in enumerate(self.adjacency_list()) }
self.M.nodeProduction=pyomo.Var(self.M.nodeIndex, within = pyomo.NonNegativeReals)
def massRule(M, n_index):
return (sum(M.edgeFlow[(n_neighbour,n_index)] - M.edgeFlow[(n_index,n_neighbour)] for n_neighbour in M.nodeNeighbour[n_index])+M.nodeProduction[n_index]-M.nodeDemand[n_index])==0
self.M.massCon = pyomo.Constraint(self.M.nodeIndex, rule=massRule)
def capacityRule(M, e_index0, e_index1):
return M.edgeFlow[(e_index0,e_index1)] + M.edgeFlow[(e_index1,e_index0)] <= M.edgeCapacity[(e_index0,e_index1)]
self.M.capacityCon = pyomo.Constraint(self.M.edgeIndex, rule=capacityRule)
def prodRule(M, n_index):
return M.nodeProduction[n_index]<=M.nodeProductionMax[n_index]
self.M.prodCon=pyomo.Constraint(self.M.nodeIndex, rule=prodRule)
if self.M.isLP:
def objRule(M):
return (sum(M.edgeCapacity[e_index]*M.edgeLength[e_index] for e_index in M.edgeIndex))
self.M.obj=pyomo.Objective(rule=objRule) |
def save(self, filename=None):
if filename is None:
filename = self._filename
if filename is None:
raise ValueError("No filename specified.")
data = {}
description = {}
for name in self.get_field_names():
data[name] = self._reduce(self._data[name], self._sequence_index + 1)
data[name][self._sequence_index] = self._reduce(self._data[name][self._sequence_index],
self._endmarker[name], axis=1)
if name in self._description:
description[name + "_descr"] = self._description[name]
if self._description:
data.update(description)
save_to_file(filename, data) |
import { Resources } from '../common'
import { Artifact } from '../enums/Artifact'
import { Disposition } from '../enums/Disposition'
import { FlaggedProp, Omit } from '../../../../helpers/types'
export interface Treasure {
resources: Resources
artifact: Artifact
}
export interface MessageAndTreasure {
message: string
treasure: Treasure
}
export type CreatureData = {
absodId: number
quantity: number
disposition: Disposition
neverFlees: boolean
doesNotGrow: boolean
} & FlaggedProp<'hasMessageAndTreasure', 'messageAndTreasure', MessageAndTreasure>
export type CreatureDataRoE = Omit<CreatureData, 'absodId'>
|
<gh_stars>0
# Print the head of airquality
print(airquality.head())
# Melt airquality: airquality_melt
airquality_melt = pd.melt(airquality, id_vars=["Month", "Day"], value_vars=["Ozone","Solar.R", "Wind", "Temp"])
# Print the head of airquality_melt
print(airquality_melt.head())
# Print the head of airquality
print(airquality.head())
# Melt airquality: airquality_melt
airquality_melt = pd.melt(airquality, id_vars = ["Month", "Day"], value_vars=["Ozone", "Solar.R", "Wind", "Temp"], var_name="measurement", value_name="reading")
# Print the head of airquality_melt
print(airquality_melt.head())
# Print the head of airquality_melt
print(airquality_melt.head())
# Pivot airquality_melt: airquality_pivot
airquality_pivot = pd.pivot_table(airquality_melt, index=["Month", "Day"], columns="measurement", values="reading")
# Print the head of airquality_pivot
print(airquality_pivot.head())
# Print the index of airquality_pivot
print(airquality_pivot.index)
# Reset the index of airquality_pivot: airquality_pivot
airquality_pivot = airquality_pivot.reset_index()
# Print the new index of airquality_pivot
print(airquality_pivot.index)
# Print the head of airquality_pivot
print(airquality_pivot.head())
# Pivot airquality_dup: airquality_pivot
airquality_pivot = airquality_dup.pivot_table(index=["Month", "Day"], columns="measurement", values="reading", aggfunc=np.mean)
# Reset the index of airquality_pivot
airquality_pivot = airquality_pivot.reset_index()
# Print the head of airquality_pivot
print(airquality_pivot.head())
# Print the head of airquality
print(airquality.head())
# Melt tb: tb_melt
tb_melt = pd.melt(tb, id_vars=["country", "year"])
# Create the 'gender' column
tb_melt['gender'] = tb_melt.variable.str[0]
# Create the 'age_group' column
tb_melt['age_group'] = tb_melt.variable.str[1:]
# Print the head of tb_melt
print(tb_melt.head())
# Melt ebola: ebola_melt
ebola_melt = pd.melt(ebola, id_vars=["Date", "Day"], var_name="type_country", value_name="counts")
# Create the 'str_split' column
ebola_melt['str_split'] = ebola_melt["type_country"].str.split("_")
# Create the 'type' column
ebola_melt['type'] = ebola_melt["str_split"].str.get(0)
# Create the 'country' column
ebola_melt['country'] = ebola_melt["str_split"].str.get(1)
# Print the head of ebola_melt
print(ebola_melt.head())
|
<filename>bcs/ledger/xledger/state/context/context_test.go
package context
import (
"io/ioutil"
"os"
"testing"
"github.com/superconsensus-chain/xupercore/bcs/ledger/xledger/ledger"
"github.com/superconsensus-chain/xupercore/kernel/mock"
"github.com/superconsensus-chain/xupercore/lib/crypto/client"
_ "github.com/superconsensus-chain/xupercore/lib/storage/kvdb/leveldb"
)
func TestNewNetCtx(t *testing.T) {
workspace, dirErr := ioutil.TempDir("/tmp", "")
if dirErr != nil {
t.Fatal(dirErr)
}
os.RemoveAll(workspace)
defer os.RemoveAll(workspace)
mock.InitLogForTest()
ecfg, err := mock.NewEnvConfForTest()
if err != nil {
t.Fatal(err)
}
lctx, err := ledger.NewLedgerCtx(ecfg, "xuper")
if err != nil {
t.Fatal(err)
}
lctx.EnvCfg.ChainDir = workspace
genesisConf := []byte(`
{
"version": "1",
"predistribution": [
{
"address": "TeyyPLpp9L7QAcxHangtcHTu7HUZ6iydY",
"quota": "100000000000000000000"
}
],
"maxblocksize": "16",
"award": "1000000",
"decimals": "8",
"award_decay": {
"height_gap": 31536000,
"ratio": 1
},
"gas_price": {
"cpu_rate": 1000,
"mem_rate": 1000000,
"disk_rate": 1,
"xfee_rate": 1
},
"new_account_resource_amount": 1000,
"genesis_consensus": {
"name": "single",
"config": {
"miner": "TeyyPLpp9L7QAcxHangtcHTu7HUZ6iydY",
"period": 3000
}
}
}
`)
ledgerIns, err := ledger.CreateLedger(lctx, genesisConf)
if err != nil {
t.Fatal(err)
}
gcc, err := client.CreateCryptoClient("gm")
if err != nil {
t.Errorf("gen crypto client fail.err:%v", err)
}
sctx, err := NewStateCtx(ecfg, "xuper", ledgerIns, gcc)
if err != nil {
t.Fatal(err)
}
sctx.XLog.Debug("test NewNetCtx succ", "sctx", sctx)
isInit := sctx.IsInit()
t.Log("is init", isInit)
}
|
a,b=list(map(int,input().split()))
c,d=list(map(int,input().split()))
print('YES' if (b-c<=1 and (c-2)/b<=2) or (a-d<=1 and (d-2)/a<=2) else 'NO') |
/*******************************************************************************
* MASH 3D simulator
*
* Copyright (c) 2014 Idiap Research Institute, http://www.idiap.ch/
* Written by Philip Abbet <[email protected]>
*
* This file is part of mash-simulator.
*
* mash-simulator is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* mash-simulator is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with mash-simulator. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
/** @file data_writer.cpp
@author Philip Abbet ([email protected])
Implementation of the 'DataWriter' class
*/
#include "data_writer.h"
#include <iostream>
#include <iomanip>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <assert.h>
using namespace std;
using namespace Mash;
/************************************ MACROS **********************************/
#define IMPLEMENT_OPERATOR(OPERATOR) \
OPERATOR \
{ \
if (_pStream) \
{ \
if ((_pStream->maximumSize < 0) || (_pStream->maximumSize > _pStream->stream.tellp())) \
{ \
_pStream->stream << val; \
_pStream->stream.flush(); \
} \
} \
\
return *this; \
}
#define IMPLEMENT_OPERATOR_FOR_TYPE(TYPE) IMPLEMENT_OPERATOR(DataWriter& DataWriter::operator<< (TYPE val))
#define IMPLEMENT_OPERATOR_FOR_MANIPULATOR(MANIPULATOR) \
DataWriter& DataWriter::operator<< (const Mash::MANIPULATOR& manip) \
{ \
if (_pStream) \
{ \
if ((_pStream->maximumSize < 0) || (_pStream->maximumSize > _pStream->stream.tellp())) \
_pStream->stream << std::MANIPULATOR(manip.val); \
} \
\
return *this; \
}
/************************* CONSTRUCTION / DESTRUCTION *************************/
DataWriter::DataWriter()
: _pStream(0)
{
}
DataWriter::DataWriter(const DataWriter& ref)
: _pStream(ref._pStream)
{
if (_pStream)
++_pStream->refCounter;
}
DataWriter::~DataWriter()
{
if (_pStream)
close();
}
/*********************************** METHODS **********************************/
bool DataWriter::open(const std::string& strFileName, int64_t maximumSize)
{
// Assertions
assert(!strFileName.empty());
if (_pStream)
close();
// Initialisations
_pStream = new tStream();
_pStream->strFileName = strFileName;
_pStream->maximumSize = maximumSize;
_pStream->refCounter = 1;
size_t offset = _pStream->strFileName.find("$TIMESTAMP");
if (offset != string::npos)
{
time_t t;
struct tm* timeinfo;
char buffer[16];
time(&t);
timeinfo = localtime(&t);
strftime(buffer, 16, "%Y%m%d-%H%M%S", timeinfo);
_pStream->strFileName = _pStream->strFileName.substr(0, offset) + buffer +
_pStream->strFileName.substr(offset + 10);
}
// Create the folders if necessary
offset = _pStream->strFileName.find_last_of("/");
if (offset != string::npos)
{
string dest = _pStream->strFileName.substr(0, offset + 1);
size_t start = dest.find("/", 0);
while (start != string::npos)
{
string dirname = dest.substr(0, start);
DIR* d = opendir(dirname.c_str());
if (!d)
mkdir(dirname.c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
else
closedir(d);
start = dest.find("/", start + 1);
}
}
// Open the file
_pStream->stream.open(_pStream->strFileName.c_str());
return _pStream->stream.is_open();
}
void DataWriter::close()
{
if (_pStream)
{
--_pStream->refCounter;
if (_pStream->refCounter == 0)
{
_pStream->stream.close();
delete _pStream;
}
_pStream = 0;
}
}
void DataWriter::deleteFile()
{
if (!_pStream)
return;
if (_pStream->refCounter > 1)
{
close();
return;
}
string strFileName = _pStream->strFileName;
close();
if (!strFileName.empty())
remove(strFileName.c_str());
}
std::string DataWriter::dump()
{
if (!_pStream || _pStream->strFileName.empty())
return "";
ifstream inFile;
inFile.open(_pStream->strFileName.c_str());
if (!inFile.is_open())
return "";
string strContent;
const unsigned int BUFFER_SIZE = 256;
char buffer[BUFFER_SIZE];
while (!inFile.eof())
{
inFile.read(buffer, BUFFER_SIZE - 1);
unsigned int nb = inFile.gcount();
buffer[nb] = '\0';
strContent += buffer;
}
inFile.close();
return strContent;
}
void DataWriter::operator=(const DataWriter& ref)
{
if (_pStream)
close();
if (ref._pStream)
{
_pStream = ref._pStream;
++_pStream->refCounter;
}
}
/**************************** METHODS TO WRITE DATA ***************************/
void DataWriter::write(const int8_t* pData, int64_t size)
{
// Assertions
assert(pData);
assert(size > 0);
int64_t currentSize = _pStream->stream.tellp();
if (_pStream && ((_pStream->maximumSize < 0) || (_pStream->maximumSize > currentSize)))
{
if (_pStream->maximumSize < 0)
_pStream->stream.write((const char*) pData, size);
else
_pStream->stream.write((const char*) pData, min(size, _pStream->maximumSize - currentSize));
_pStream->stream.flush();
}
}
IMPLEMENT_OPERATOR_FOR_TYPE(const char*);
IMPLEMENT_OPERATOR_FOR_TYPE(const signed char*);
IMPLEMENT_OPERATOR_FOR_TYPE(const unsigned char*);
IMPLEMENT_OPERATOR_FOR_TYPE(std::streambuf*);
DataWriter& DataWriter::operator<< (std::ostream& (*val)(std::ostream&))
{
if (_pStream && ((_pStream->maximumSize < 0) || (_pStream->maximumSize > _pStream->stream.tellp())))
{
_pStream->stream << val;
_pStream->stream.flush();
}
return *this;
}
IMPLEMENT_OPERATOR(DataWriter& DataWriter::operator<< (std::ios& (*val)(std::ios&)));
IMPLEMENT_OPERATOR(DataWriter& DataWriter::operator<< (std::ios_base& (*val)(std::ios_base&)));
DataWriter& DataWriter::operator<< (const std::string& s)
{
int64_t currentSize = _pStream->stream.tellp();
if (_pStream && ((_pStream->maximumSize < 0) || (_pStream->maximumSize > currentSize)))
{
if (_pStream->maximumSize < 0)
_pStream->stream << s.c_str();
else
_pStream->stream << s.substr(0, min((int64_t) s.size(), _pStream->maximumSize - currentSize));
_pStream->stream.flush();
}
return *this;
}
IMPLEMENT_OPERATOR_FOR_MANIPULATOR(resetiosflags);
IMPLEMENT_OPERATOR_FOR_MANIPULATOR(setiosflags);
IMPLEMENT_OPERATOR_FOR_MANIPULATOR(setbase);
IMPLEMENT_OPERATOR_FOR_MANIPULATOR(setfill);
IMPLEMENT_OPERATOR_FOR_MANIPULATOR(setprecision);
IMPLEMENT_OPERATOR_FOR_MANIPULATOR(setw);
|
Posted by James in Constitution, Holyrood, Parties, Westminster |
There’s been a lot of Holyrood-bubble drama around LabourForIndy recently. Who’s that in their photos? When did you join Labour? Is it even real? It might seem like the phoniest of wars, but it’s happening for a reason.
Fear. Specifically Labour fear.
As I’ve said before, if the referendum is to be won, it’ll be won from the left and centre-left. By next September let’s assume 75% of 2011 SNP voters will probably back independence. Die-hard capital-N nationalists, some fairly left-wing, some to the right. They make up about 30-33% of the electorate, and therefore 60-66% of the Yes vote required.
Add in a good slice of Greens and Socialists – not a huge number, although some SNP folk say Patrick Harvie’s messages are persuading voters who are neither nationalist nor Green – plus a fragment of Lib Dems frustrated by the absence of federalism from the ballot, and Yes is still short about a sixth of the vote. That sixth can only come from Labour voters plus increased turnout from the working class ex-Labour abstainers (or lifetime abstainers), the very people for whom Westminster has done next to nothing for generations.
Hence the fuss. LabourForIndy as an organisation may not (yet?) be that substantial, but Labour voters for independence are where the referendum can be won. And there are lots of them already. Take the May Panelbase poll for the Sunday Times, the most recent one up on UK Polling Report, which gives crossbreaks on voting intention and referendum intention.
The results for Q3 there (which should say “constituency”, not region) show that 41% of the undecided are Labour voters. Fewer than 50% of Labour’s supporters from 2011 backed Westminster rule, and 14% are voting Yes. If representative, that’s almost 90,000 people, perhaps seven or eight percent of the total Yes vote required (assuming a turnout of between 2.25m and 2.5m next year). And the Labour-backing referendum-undecideds are twice as many again.
If those undecided Labour voters break for Yes, they can ensure the referendum is won – probably no-one else can – and Labour is right to be afraid of this situation, because it threatens their position in three ways.
First, independence, and the Labour voters supporting it, jeopardises their chances of getting back into power at a UK level. Although Westminster elections aren’t commonly close enough for the Scottish block to make any difference (other than imposing Blairite reforms on the rest of the UK), it might well happen next time given the state of the polls. They want the buffer provided by right-wing MPs like Tom Harris. Pure self interest: they want him and his ilk to keep being sent to Westminster to help prop up future Labour administrations there.
Second, and this is where they should see opportunities rather than threats, it makes a return to office at Holyrood even less likely. Losing a referendum on which they have staked everything would be a massive blow to their institutional power and their credibility, especially when it’ll be clear so many of their own supporters have ignored their advice in favour of, ironically, the prospect of a Labour-led government for an independent Scotland. It’s not just their supporters and members, either. Why wouldn’t some potential Scottish Labour Ministers feel the same? One former senior Labour Minister told a friend he was privately in favour of independence so long as “the bloody Nats don’t get to run it” (no, it wasn’t Henry).
Finally, and perhaps most intriguingly, it’s an ideological threat. Labour have redefined their primary purpose as defence of the Union, in large part as self-interest. Like Scottish Lib Dem MPs, they’re amongst its main institutional beneficiaries. It’s also partly because they haven’t any other ideas. Ask yourself: what else do Labour at Holyrood want to achieve? Can you name a single radical thing? I can’t, and I follow politics pretty closely.
There’s no principled basis for boxing themselves in like this. Unless a party is established with a constitutional purpose at its heart, like the SNP, their supporters are likely to disagree on whether Holyrood or Westminster is best able to get them to their other political objectives. A third of Greens at conference regularly vote against independence, although none yet seem to want to work with the Tories as part of Better Together. It’s normal. I’m not scared by it, in the way Labour are terrified of Labour voters for independence. Rather than social justice or even Blairite aspiration, Labour have become obsessed with one arbitrary answer to this tactical question – will our objectives be better met at Westminster or at Holyrood? It’s a fragile new base to have chosen.
Their response to this trend not only threatens Labour’s future shots at governance, therefore, it also weakens their power over their voters too. That Labour Yes vote is likely to be centre-left types who find the SNP too economically right-wing, people who’ve stuck with Labour so far but who are increasingly desperate to be shot of a Tory-led Westminster. When they watch the Labour leadership line up with Tories and Lib Dems over the next year to ensure Scotland remains run by the bedroom taxing, fracking, poor-hating, immigrant-abusing Westminster they increasingly loathe, the risk has to be that that sight will put them off Labour too, and that those Labour voters for Yes will become SNP, Green or Socialist voters for Yes. I can’t be the only person who’s gone off Labour and off Westminster essentially in parallel.
It’s too late for them ever to win me back, but Labour didn’t need to be in this mess, especially if they’d put forward a credible “more powers” offer. Now, though, even as someone who still wants to see a better Labour Party, I now can’t see a way out of the uncomfortable corner they’ve painted themselves into. The harder they try to retain their grip, the weaker their position becomes. No wonder they’re afraid.
Share this: Email
Twitter
Facebook |
#include<bits/stdc++.h>
using namespace std;
int32_t main(){
ios::sync_with_stdio(0);
int t;
cin >> t;
while(t--){
int n, d;
cin >> n >> d;
vector<int> vs(n);
for(auto &x:vs) cin >> x;
int ans = vs[0];
int k=1;
while(d>0 and k<n){
int w = min(d, k*vs[k]);
w/=k;
d-=w*k;
ans += w;
++k;
}
cout << ans << endl;
}
}
|
"""
The Cluster module generates descriptive statistics for clusters
obtained from libraries such as sklearn.
Usage:
km = KMeans()
km.fit(df)
cluster = Cluster(df, km.labels_)
cluster.stats()
"""
from dataclasses import dataclass, field
from typing import List, Union
import pandas as pd
import numpy as np
@dataclass
class Cluster:
df: pd.DataFrame = field(
metadata={"help": "DataFrame or numpy array of X values"}
)
labels: Union[pd.Series, List[int], np.ndarray] = field(
metadata={"help": "Cluster labels. Must have at least 2 classes"}
)
def __post_init__(self):
self._check_input()
def stats(self, dist_metric: str = "cosine",
noise_cluster: bool = False,
silhouette: bool = False,
g3: bool = False,
wgap: bool = False,
sepindex: bool = False):
pass
def _check_input(self):
if not isinstance(self.labels, pd.Series):
self.labels = pd.Series(self.labels)
if not isinstance(self.df, pd.DataFrame):
raise ValueError("df needs to be a DataFrame or numpy array!")
if self.labels.size != self.df.shape[0]:
raise ValueError("df and labels have to be of same length!")
if self.labels.nunique() < 2:
raise ValueError("Labels need more than 1 cluster!")
if __name__ == "__main__":
from sklearn.cluster import KMeans
df = pd.read_csv("data.csv").select_dtypes("int")
km = KMeans()
km.fit(df)
cluster = Cluster(df, km.labels_)
assert cluster.df is not None and isinstance(cluster.df, pd.DataFrame)
assert cluster.labels is not None and isinstance(cluster.labels, pd.Series)
|
The way I feel about the above promo photo announcing Babymetal's 2015 touring plans, and also showcasing some new outfits, can be thoroughly summed up by this clip from The Simpsons:
Subscribe to Metal Injection on
Are Babymetal ready to unveil the next chapter of their story? It would seem so. The band has announced a new string of dates for later this year and even offered this teaser trailer:
Subscribe to Metal Injection on
Here are the dates of the tour:
May 9th – Mexico City, Mexico – Circo Volador
May 12th – Circo Volador – Danforth Music Hall
May 14th – Chicago, USA – House of Blues
May 16th – Columbus, USA – Rock on the Range Festival
May 29th – Nürburg, Germany – Nürburgring
May 29th – Munich, Germany – Olympiapark München
June 4th – Vienna, Austria – Rock In Vienna Fest
June 21st – Chiba, Japan – Makuhari Messe
Unfortunately, no NYC date but I certainly got my fill last year. As did a bunch of other metalheads.
[via MetalSucks]
Related Posts |
/** Main activity that displays three choices to user */
public class MainActivity extends Activity implements View.OnClickListener{
private static final String TAG = "MainActivity";
private AtomicBoolean isRegistrationInProgress = new AtomicBoolean(false);
private Button btnUI;
private Switch swchLanguage;
private String strLanguage = "中文";
private DJISDKManager.SDKManagerCallback registrationCallback = new DJISDKManager.SDKManagerCallback() {
// 又遇到不注册的问题,断点设在这里没有反应,我检查了网络,重启了手机,改回compileSdkVersion,没有效果。重新同步dji-uxsdk包,没有效果。Debug,
//
//我又电脑里找到前几天编译的可以正常注册的app,奇怪的是,还不注册。
// 我休息了十分钟,可以注册了。
// 结论:是网络不稳定。2019.02.18
// 结论:是大疆的服务器不稳定。2019.06.29
@Override
public void onRegister(DJIError error) {
isRegistrationInProgress.set(false);
if (error == DJISDKError.REGISTRATION_SUCCESS) {
DJISDKManager.getInstance().startConnectionToProduct();
// btnUI.setText("@string/registerring");
// Toast.makeText(getApplicationContext(), "正在注册...", Toast.LENGTH_SHORT).show();
// loginAccount();
btnUI.setText(getResources().getString( R.string.start ));
btnUI.setBackgroundColor( Color.parseColor("#60CC60"));
// btnUI.setBackground(getDrawable( R.drawable.corner_green_btn) );
} else {
Toast.makeText(getApplicationContext(),"Register error, please check the internet",
Toast.LENGTH_LONG).show();
}
}
@Override
public void onProductDisconnect() {
Log.d("TAG", "onProductDisconnect");
// notifyStatusChange();
}
@Override
public void onProductConnect(BaseProduct baseProduct) {
Log.d( "TAG", String.format( "onProductConnect newProduct:%s", baseProduct ) );
// notifyStatusChange();
}
@Override
public void onComponentChange(BaseProduct.ComponentKey componentKey, BaseComponent oldComponent,
BaseComponent newComponent) {
if (newComponent != null) {
newComponent.setComponentListener(new BaseComponent.ComponentListener() {
@Override
public void onConnectivityChange(boolean isConnected) {
Log.d("TAG", "onComponentConnectivityChanged: " + isConnected);
// notifyStatusChange();
}
});
}
Log.d("TAG",
String.format("onComponentChange key:%s, oldComponent:%s, newComponent:%s",
componentKey,
oldComponent,
newComponent));
} @Override
public void onInitProcess(DJISDKInitEvent djisdkInitEvent, int i) {
}
};
private static final String[] REQUIRED_PERMISSION_LIST = new String[] {
Manifest.permission.VIBRATE,
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.WAKE_LOCK,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE,
};
private static final int REQUEST_PERMISSION_CODE = 12345;
private List<String> missingPermission = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCollector.addActivity( this );
btnUI = (Button) findViewById(R.id.complete_ui_widgets);
btnUI.setOnClickListener(this);
swchLanguage = (Switch)findViewById(R.id.switch_language);
swchLanguage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(!isChecked) {
strLanguage = "中文";
// Log.e(TAG,"语言"+strLanguage);
LanguageUtil.updateLocale(MainActivity.this, LanguageUtil.LOCALE_CHINESE);
btnUI.setText( getResources().getString( R.string.start ) );
}else {
strLanguage = "EN";
LanguageUtil.updateLocale(MainActivity.this, LanguageUtil.LOCALE_ENGLISH);
btnUI.setText( getResources().getString( R.string.start ) );
}
}
});
checkAndRequestPermissions();
IntentFilter filter = new IntentFilter();
filter.addAction( GetProductApplication.FLAG_CONNECTION_CHANGE );
registerReceiver( mReceiver,filter );
}
protected BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
refreshSDKRelativeUI();
}
};
private void refreshSDKRelativeUI() {
BaseProduct mProduct = GetProductApplication.getProductInstance();
if (null != mProduct && mProduct.isConnected()) {
Log.v(TAG, "refreshSDK: True");
String str = mProduct instanceof Aircraft ? "DJIAircraft" : "DJIHandHeld";
Toast.makeText(getApplicationContext(),"Status: " + str + " connected",
Toast.LENGTH_LONG).show();
} else {
Log.v(TAG, "refreshSDK: False");
}
}
@Override
protected void onDestroy() {
// Prevent memory leak by releasing DJISDKManager's references to this activity
if (DJISDKManager.getInstance() != null) {
DJISDKManager.getInstance().destroy();
}
unregisterReceiver( mReceiver );
ActivityCollector.removeActivity( this );
super.onDestroy();
}
private void loginAccount(){
UserAccountManager.getInstance().logIntoDJIUserAccount(this,
new CommonCallbacks.CompletionCallbackWith<UserAccountState>() {
@Override
public void onSuccess(final UserAccountState userAccountState) {
// Toast.makeText(getApplicationContext(), "注册成功!", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(DJIError error) {
// Toast.makeText(getApplicationContext(), "注册失败…", Toast.LENGTH_LONG).show();
}
});
}
/**
* Checks if there is any missing permissions, and
* requests runtime permission if needed.
*/
private void checkAndRequestPermissions() {
// Check for permissions
for (String eachPermission : REQUIRED_PERMISSION_LIST) {
if (ContextCompat.checkSelfPermission(this, eachPermission) != PackageManager.PERMISSION_GRANTED) {
missingPermission.add(eachPermission);
}
}
// Request for missing permissions
if (missingPermission.isEmpty()) {
startSDKRegistration(); // 这一步是执行了的
} else {
ActivityCompat.requestPermissions(this,
missingPermission.toArray(new String[missingPermission.size()]),
REQUEST_PERMISSION_CODE);
}
}
/**
* Result of runtime permission request
*/
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Check for granted permission and remove from missing list
if (requestCode == REQUEST_PERMISSION_CODE) {
for (int i = grantResults.length - 1; i >= 0; i--) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
missingPermission.remove(permissions[i]);
}
}
}
else
{
Toast.makeText(getApplicationContext(), "onRequestPermissionsResult Error!", Toast.LENGTH_LONG).show();
}
// If there is enough permission, we will start the registration
if (missingPermission.isEmpty()) {
startSDKRegistration();
} else {
Toast.makeText(getApplicationContext(), " Unwarrantted!", Toast.LENGTH_LONG).show();
}
}
private void startSDKRegistration() {
if (isRegistrationInProgress.compareAndSet(false, true)) {
AsyncTask.execute(new Runnable() {
@Override
public void run() { // 这一步是正常执行
DJISDKManager.getInstance().registerApp(MainActivity.this, registrationCallback);
}
});
}
else
{
Toast.makeText(getApplicationContext(), "startSDKRegistration Error!", Toast.LENGTH_LONG).show();
}
}
@Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.complete_ui_widgets) {
Class nextActivityClass;
nextActivityClass = CompleteWidgetActivity.class;
Intent intent = new Intent(this, nextActivityClass);
intent.putExtra("app_language",strLanguage);
// intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity(intent);
}
else{
return;
}
}
} |
<reponame>yueya/pms<filename>pms-sysm/src/main/java/com/yueya/system/dao/dto/ViewDto.java
package com.yueya.system.dao.dto;
public class ViewDto {
public String name;
public int count;
}
|
// TRENTO: Reduced Thickness Event-by-event Nuclear Topology
// Copyright 2015 <NAME>, <NAME>
// MIT License
#ifndef FAST_EXP_H
#define FAST_EXP_H
#include <cmath>
#include <stdexcept>
#include <vector>
namespace trento {
/// \rst
/// Fast exponential approximation, to be used as a drop-in replacement for
/// ``std::exp`` when it will be evaluated many times within a fixed range.
/// Works by pre-tabulating exp() values and exploiting the leading-order Taylor
/// expansion; for step size `dx` the error is `\mathcal O(dx^2)`.
///
/// Example::
///
/// FastExp<double> fast_exp{0., 1., 11}; // tabulate at 0.0, 0.1, 0.2, ...
/// fast_exp(0.50); // evaluate at table point -> exact result
/// fast_exp(0.55); // midway between points -> worst-case error
///
/// \endrst
template <typename T = double>
class FastExp {
public:
/// Pre-tabulate exp() values from \c xmin to \c xmax in \c nsteps
/// evenly-spaced intervals.
FastExp(T xmin, T xmax, std::size_t nsteps);
/// Evaluate the exponential at \em x (must be within range).
T operator()(T x) const;
private:
/// Minimum and maximum.
const T xmin_, xmax_;
/// Step size.
const T dx_;
/// Tabulated exp() values.
std::vector<T> table_;
};
template <typename T>
FastExp<T>::FastExp(T xmin, T xmax, std::size_t nsteps)
: xmin_(xmin),
xmax_(xmax),
dx_((xmax-xmin)/(nsteps-1)),
table_(nsteps) {
// Tabulate evenly-spaced exp() values.
for (std::size_t i = 0; i < nsteps; ++i)
table_[i] = std::exp(xmin_ + i*dx_);
}
template <typename T>
inline T FastExp<T>::operator()(T x) const {
#ifndef NDEBUG
if (x < xmin_ || x > xmax_)
throw std::out_of_range{"argument must be within [xmin, xmax]"};
#endif
// Determine the table index of the nearest tabulated value.
auto index = static_cast<std::size_t>((x - xmin_)/dx_ + .5);
// Compute the leading-order Taylor expansion.
// exp(x) = exp(x0) * exp(x-x0) =~ exp(x0) * (1 + x - x0)
// exp(x0) = table_[index]
// x0 = xmin_ + index*dx_
return table_[index] * (1. + x - xmin_ - index*dx_);
}
} // namespace trento
#endif // FAST_EXP_H
|
/**
* Sorts the Documentos from the Expediente by Required first and Optional
* second.
*
* @param expediente
*/
private void sortDocumentos(ExpedienteFamiliaSolicitudDTO expediente) {
Collections.sort(expediente.getDocumentosList(), new Comparator<DocumentoDTO>() {
@Override
public int compare(DocumentoDTO doc1, DocumentoDTO doc2) {
return Boolean.compare(isRequired(doc2), isRequired(doc1));
}
});
} |
#include <Arduino.h>
#include <Servo.h>
// Set up the torso commands
#define TORSO_MOTOR_PIN 0
#define TORSO_POS_CMD 10
Servo myservo1; // create servo object to control a servo
Servo myservo2; // create servo object to control a servo
Servo myservo3; // create servo object to control a servo
void setup() {
Serial.begin(9600);
myservo1.attach(11); // attaches the servo on pin 9 to the servo object
myservo2.attach(12); // attaches the servo on pin 9 to the servo object
myservo3.attach(13); // attaches the servo on pin 9 to the servo object
}
int pos = 0; // variable to store the servo position
void loop() {
for (pos = 60; pos <= 160; pos += 1) { // goes from 0 degrees to 180 degrees
myservo1.write(pos);
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 120; pos >= 60; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo1.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach
}
for (pos = 60; pos <= 90; pos += 1) { // goes from 0 degrees to 180 degrees
myservo1.write(pos);
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 60; pos <= 160; pos += 1) { // goes from 0 degrees to 180 degrees
myservo2.write(pos);
myservo3.write(pos);
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 120; pos >= 60; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo2.write(pos); // tell servo to go to position in variable 'pos'
myservo3.write(pos);
delay(15); // waits 15ms for the servo to reach
}
// if ( Serial.available() ) {
// switch( Serial.read() ){
// case TORSO_POS_CMD:
// break;
// default:
// break;
// }
// }
} |
/* retreive current device category forced for a given usage */
static audio_policy_forced_cfg_t ap_get_force_use(
const struct audio_policy *pol,
audio_policy_force_use_t usage)
{
const struct legacy_audio_policy *lap = to_clap(pol);
return (audio_policy_forced_cfg_t)lap->apm->getForceUse(
(AudioSystem::force_use)usage);
} |
/**
* The rotation an object should take in the immediate future.
*
* @see RotationComponent
* @author madgaksha
*
*/
public class ShouldScaleComponent extends ScaleComponent implements Component, Poolable {
private final static IGrantStrategy DEFAULT_GRANT_STRATEGY = new ExponentialGrantStrategy();
public IGrantStrategy grantStrategy = DEFAULT_GRANT_STRATEGY;
public ShouldScaleComponent() {
}
public ShouldScaleComponent(IGrantStrategy gs) {
setup(gs);
}
public void setup(IGrantStrategy gs) {
grantStrategy = gs;
}
@Override
public void reset() {
super.reset();
grantStrategy = DEFAULT_GRANT_STRATEGY;
}
} |
def publish_table_notification(table_key, message, message_types, subject=None):
topic = get_table_option(table_key, 'sns_topic_arn')
if not topic:
return
for message_type in message_types:
if message_type in get_table_option(table_key, 'sns_message_types'):
__publish(topic, message, subject)
return |
import java.util.Scanner;
public class SoldierAndBananas {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//Given
int bananaUnitPrice = scanner.nextInt();
int soldierDollars = scanner.nextInt();
int requiredBananas = scanner.nextInt();
//Calculated
int totalPrice = 0;
//Result
int borrowedDollars = 0;
for (int i = 1; i <= requiredBananas; i++) {
totalPrice += bananaUnitPrice*i;
}
borrowedDollars = totalPrice - soldierDollars;
if (borrowedDollars > 0) System.out.println(borrowedDollars);
else System.out.println(0);
}
}
|
<filename>src/role/helpers/role.halpers.ts
import { Role } from "src/role/role.entity";
import { RoleName } from "../enums/role.enum";
export function createDefaultOwnerRole():Role {
let owner = new Role();
owner = {...owner,
...{
isBannedUsers: true,
name: RoleName.owner,
isMuteUsers: true,
isDeleteUsersMesseges: true,
isDeleteYourMesseges: true,
isSendMessage: true
}
};
return owner;
}
export function createDefaultUserRole():Role {
let user = new Role();
user = {...user,
...{
isBannedUsers: false,
name: RoleName.user,
isMuteUsers: false,
isDeleteUsersMesseges: false,
isDeleteYourMesseges: true,
isSendMessage: true
}
}
return user;
} |
def _call_batch(self, requests):
ids = []
for request in requests:
if request.has_key('id'):
ids.append(request['id'])
self._request = requests
message = json.dumps(requests)
notify = False
if len(ids) == 0:
notify = True
response_text = self._send_and_receive(
message, batch=True, notify=notify
)
responses = self._parse_response(response_text)
if responses is None:
responses = []
assert type(responses) is list
return BatchResponses(responses, ids) |
import { registerLocalizationBundle } from '@opensumi/ide-core-common';
import { createBrowserInjector } from '@opensumi/ide-dev-tool/src/injector-helper';
import { MockInjector } from '@opensumi/ide-dev-tool/src/mock-injector';
import { createBrowserApi } from '../../../src/browser/sumi-browser';
import { mockExtension } from '../../../__mocks__/extensions';
describe('activation event test', () => {
let injector: MockInjector;
let browserApi;
beforeAll(() => {
registerLocalizationBundle(
{
languageId: 'zh-CN',
languageName: 'Chinese',
localizedLanguageName: '中文(中国)',
contents: {
test: '测试',
'test.format': '测试{0}',
},
},
mockExtension.id,
);
});
beforeEach(() => {
injector = createBrowserInjector([]);
browserApi = createBrowserApi(injector, mockExtension);
});
afterEach(() => {
injector.disposeAll();
});
it('localize label', () => {
expect(browserApi.localize('test')).toBe('测试');
});
it('localize format label', () => {
expect(browserApi.formatLocalize('test.format', 'test')).toBe('测试test');
});
});
|
from collections import defaultdict
from itertools import combinations
read_many = lambda type_: list(map(type_, input().split()))
def main():
n, m = read_many(int)
relations = defaultdict(lambda: {})
d={}
for i in range(m):
w1, w2 = read_many(int)
relations[w1][w2] = 0
relations[w2][w1] = 0
# Procura 3 mosqueteiros que se conhecem e minimizam o problema
lowest_rec, know_each_other_penalty = float("inf"), 6
for w1 in range(1, n+1):
w1_k = relations[w1].keys()
w1_rec = len(w1_k)
if w1_rec >= 2:
for w2 in w1_k:
w2_k = set(relations[w2].keys())
w2_rec = len(w2_k)
common_friends = set(w1_k).intersection(w2_k)
for w3 in common_friends:
rec_group = w1_rec + w2_rec + len(relations[w3]) - know_each_other_penalty
if rec_group < lowest_rec:
lowest_rec = rec_group
print( -1 if lowest_rec == float("inf") else lowest_rec )
if __name__=="__main__":
main() |
export const storybookAvatarUrl = 'https://cdn.tree.ly/storybook/v1/avatar.jpeg';
export const storybookCoverUrl = 'https://cdn.tree.ly/storybook/v1/cover.jpeg';
|
<reponame>cloudfoundry/packit
package sbom
import (
"bytes"
"fmt"
"io"
"sync"
"github.com/anchore/syft/syft"
"github.com/anchore/syft/syft/sbom"
)
// FormattedReader outputs the SBoM in a specified format.
type FormattedReader struct {
m sync.Mutex
sbom SBOM
rawFormatID string
format sbom.Format
reader io.Reader
}
// NewFormattedReader creates an instance of FormattedReader given an SBOM and
// Format.
func NewFormattedReader(s SBOM, f Format) *FormattedReader {
// For backward compatibility, caller can pass f as a format ID like
// "cyclonedx-1.3-json" or as a media type like
// 'application/vnd.cyclonedx+json'
sbomFormat, err := sbomFormatByID(sbom.FormatID(f))
if err != nil {
sbomFormat, err = sbomFormatByMediaType(string(f))
if err != nil {
// Defer throwing an error until Read() is called
return &FormattedReader{sbom: s, rawFormatID: string(f), format: nil}
}
}
return &FormattedReader{sbom: s, rawFormatID: string(sbomFormat.ID()), format: sbomFormat}
}
// Read implements the io.Reader interface to output the contents of the
// formatted SBoM.
func (f *FormattedReader) Read(b []byte) (int, error) {
f.m.Lock()
defer f.m.Unlock()
if f.reader == nil {
if f.format == nil {
return 0, fmt.Errorf("failed to format sbom: '%s' is not a valid SBOM format identifier", f.rawFormatID)
}
output, err := syft.Encode(f.sbom.syft, f.format)
if err != nil {
// not tested
return 0, fmt.Errorf("failed to format sbom: %w", err)
}
f.reader = bytes.NewBuffer(output)
}
return f.reader.Read(b)
}
|
<filename>Data Structures and Algorithms/Binary Tree/BinaryTreeSearchUse.cpp
#include<iostream>
#include"BinarySearchTree.h"
using namespace std;
int main()
{
BST<int> t;
t.insert(20);
t.insert(10);
t.insert(12);
t.insert(14);
t.insert(13);
t.print();
cout<<t.hasData(12)<<endl;
cout<<t.hasData(15)<<endl;
t.remove(20);
cout<<t.hasData(20)<<endl;
t.remove(12);
t.print();
return 0;
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.