content
stringlengths 7
2.61M
|
---|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.oodt.cas.metadata.extractors;
// JUnit static imports
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
// JDK imports
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
// JAVAX imports
import javax.sql.DataSource;
// OODT imports
import org.apache.oodt.cas.metadata.Metadata;
import org.apache.oodt.cas.metadata.exceptions.MetExtractionException;
// JUnit imports
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
// Mockito imports
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
/**
* Test class for {@link DataSourceMetExtractor}.
*
* @author <EMAIL> (<NAME>)
*/
@RunWith(JUnit4.class)
public class TestDataSourceMetExtractor {
private static final String DB_COL_NAME_1 = "NAME";
private static final String DB_COL_VALUE_1 = "SomeName";
private static final String DB_COL_NAME_2 = "SIZE";
private static final String DB_COL_VALUE_2 = "20";
@Mock private DataSource dataSource;
@Mock private Connection conn;
@Mock private Statement statement;
@Mock private ResultSet rs;
@Mock private ResultSetMetaData rsMet;
private DataSourceMetExtractor extractor;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
when(dataSource.getConnection()).thenReturn(conn);
when(conn.createStatement()).thenReturn(statement);
when(statement.executeQuery(Mockito.<String>any())).thenReturn(rs);
when(rs.getMetaData()).thenReturn(rsMet);
when(rs.next()).thenReturn(true);
when(rs.getString(1)).thenReturn(DB_COL_VALUE_1);
when(rs.getString(2)).thenReturn(DB_COL_VALUE_2);
when(rsMet.getColumnCount()).thenReturn(2);
when(rsMet.getColumnName(1)).thenReturn(DB_COL_NAME_1);
when(rsMet.getColumnName(2)).thenReturn(DB_COL_NAME_2);
extractor = new DataSourceMetExtractor();
}
@Test
public void testGetKey() {
assertThat(extractor.getKey(new File("Test.csv")), is("Test"));
assertThat(extractor.getKey(new File("123_sdfwegd_g334g.dat")), is("123_sdfwegd_g334g"));
assertThat(extractor.getKey(new File("123qweJDKJF-3")), is("123qweJDKJF-3"));
}
@Test
public void testGetMetadata() throws MetExtractionException {
Metadata metadata = extractor.getMetadata(
dataSource, "select * from SomeTable where key = '%s'", "SomeKey");
assertThat(metadata.getAllKeys().size(), is(2));
assertThat(metadata.getMetadata(DB_COL_NAME_1), is(DB_COL_VALUE_1));
assertThat(metadata.getMetadata(DB_COL_NAME_2), is(DB_COL_VALUE_2));
}
}
|
/**
* Base class for interceptors which store incoming and outgoing payload
* into files with user-defined name patterns.
* <p>
* File name patterns can contain absolute and relative paths and must correspond to
* <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/expressions.html">SpEL</a>
* syntax, using square brackets for referencing placeholder parameters.
* In the base version, the following parameters are supported
* (this set can be extended in derived classes):
* <ul>
* <li><tt>sequenceId</tt> — internally generated sequential ID
* as a 12-digit positive long int, zero-padded.</li>
* <li><tt>processId</tt> — process ID consisting from the OS process
* number and the host name, e.g. <tt>"12345-myhostname"</tt>.</li>
* <li><tt>date('format_spec')</tt> — current date and time, formatted
* using {@link java.text.SimpleDateFormat} according to the given specification.</li>
* </ul>
* <br>
* Example of a file name pattern:<br>
* <tt>C:/IPF-LOGS/[processId]/[date('yyyyMMdd-HH00')]/[sequenceId]-server-output.txt</tt>
*
* @author Dmytro Rud
*/
abstract public class PayloadLoggerBase<T extends PayloadLoggingSpelContext> {
private static final transient Logger LOG = LoggerFactory.getLogger(PayloadLoggerBase.class);
private static final AtomicLong SEQUENCE_ID_GENERATOR = new AtomicLong(0L);
public static final String SEQUENCE_ID_PROPERTY_NAME =
PayloadLoggerBase.class.getName() + ".sequence.id";
private static final ExpressionParser SPEL_PARSER = new SpelExpressionParser();
private static final TemplateParserContext SPEL_PARSER_CONTEXT =
new TemplateParserContext("[", "]");
private final ThreadLocal<Expression> SPEL_EXPRESSIONS = new ThreadLocal<Expression>() {
@Override
protected Expression initialValue() {
return SPEL_PARSER.parseExpression(fileNamePattern, SPEL_PARSER_CONTEXT);
}
};
private static boolean globallyEnabled = true;
private String fileNamePattern = null;
private boolean locallyEnabled = true;
private int errorCountLimit = -1;
private int errorCount;
protected static Long getNextSequenceId() {
return SEQUENCE_ID_GENERATOR.getAndIncrement();
}
protected void doLogPayload(T spelContext, String charsetName, String... payloadPieces) {
// check whether we can process
if (! canProcess()) {
return;
}
if ((errorCountLimit >= 0) && (errorCount >= errorCountLimit)) {
LOG.warn("Error count limit has bean reached, reset the counter to enable further trials");
return;
}
// compute file path
String path = SPEL_EXPRESSIONS.get().getValue(spelContext, String.class);
// write payload pieces into the file
Writer writer = null;
try {
FileOutputStream outputStream = FileUtils.openOutputStream(new File(path), true);
writer = (charsetName != null) ?
new OutputStreamWriter(outputStream, charsetName) :
new OutputStreamWriter(outputStream);
for (String payloadPiece : payloadPieces) {
writer.write(payloadPiece);
}
errorCount = 0;
} catch (IOException e) {
++errorCount;
LOG.warn("Cannot write into " + path, e);
} finally {
IOUtils.closeQuietly(writer);
}
}
public boolean canProcess() {
if (! (globallyEnabled && locallyEnabled)) {
LOG.debug("File-based logging is disabled");
return false;
}
return true;
}
/**
* Resets count of occurred errors, can be used e.g. via JMX.
*/
public void resetErrorCount() {
errorCount = 0;
}
/**
* @return <code>true</code> if this logging interceptor is enabled.
* @see #isGloballyEnabled()
*/
public boolean isLocallyEnabled() {
return locallyEnabled;
}
/**
* @param locallyEnabled
* <code>true</code> when this logging interceptor instance should be enabled.
* @see #setGloballyEnabled(boolean)
*/
public void setLocallyEnabled(boolean locallyEnabled) {
this.locallyEnabled = locallyEnabled;
}
/**
* @return <code>true</code> when logging interceptors are generally enabled.
* @see #isLocallyEnabled()
*/
public static boolean isGloballyEnabled() {
return globallyEnabled;
}
/**
* @param globallyEnabled
* <code>true</code> when logging interceptor should be generally enabled.
* @see #setLocallyEnabled(boolean)
*/
public static void setGloballyEnabled(boolean globallyEnabled) {
PayloadLoggerBase.globallyEnabled = globallyEnabled;
}
/**
* @return
* file name pattern for payload logs.
*/
public String getFileNamePattern() {
return fileNamePattern;
}
/**
* Sets the file name pattern for payload logs.
* @param fileNamePattern
* file name pattern for payload logs.
*/
public void setFileNamePattern(String fileNamePattern) {
this.fileNamePattern = Validate.notEmpty(fileNamePattern, "log file path/name pattern");
}
/**
* @return maximal allowed count of file creation errors, negative value means "no limit".
*/
public int getErrorCountLimit() {
return errorCountLimit;
}
/**
* Configures maximal allowed count of file creation errors.
* @param errorCountLimit
* maximal allowed count of file creation errors, negative value means "no limit".
*/
public void setErrorCountLimit(int errorCountLimit) {
this.errorCountLimit = errorCountLimit;
}
} |
The low-slung, redbrick office building on the outskirts of Toronto looks just like its neighbours, except for the Canadian flag fluttering high above the front lawn — that, and maybe the lack of any sign bearing the company name.
Look closely and you might also notice the multiple security cameras bristling from every nook and cranny on the walls.
International Depository Services of Canada (IDS) is one of a handful of non-bank and non-government precious metals storage firms that have popped up over the last few years, with customers ranging from simple retail investors to large corporations. When you’re guarding other people’s gold, it helps to keep a low profile.
Robyn Sprott, the managing director, is an ebullient 30-year old who got her start in business a few years back as a precious metals trader, and soon figured out that with all the gold buying going on, there must also be a demand for a place to put the stuff. That’s the big thing buyers fail to consider until it becomes a problem.
“The individuals I was trading with were Americans and they were looking for storage options,” says Ms. Sprott. She knew she was on to something.
As a cousin to legendary commodities investor Eric Sprott, she was already familiar with the players in the precious metals industry and it didn’t take long to line up Dillon Gage, a U.S.-based gold trading firm, as a partner to help finance and run the venture.
“I like gold,” she says in an interview in her office, lit by a few stray beams of sunlight coming through narrow, gun slot window. But she insists she’s not one of those folks who believes that paper money is a government plot and that the only real money is bullion.
Her first piece of the yellow metal acquired many years ago was a Maple Leaf coin from the Canadian Mint and her holdings — she declines to say how much she owns — grew from there.
Ms. Sprott may not be a goldbug but she’s seen plenty come through the front door. On the retail front, they’re often affluent and mostly American, attracted by the idea of getting their assets out of the U.S. and out of reach of nosy government authorities. Some are Tea Party types who cleave to far right-wing ideologies, viewing gold as a hedge against political risk.
“You have a lot of people who aren’t [U.S. President Barack] Obama fans,” she explains. They’re fearful the country is going down the wrong road and that when “end times” come, only gold will have value.
Another key trend that’s driving the industry is soaring gold prices. In the face of a sluggish economy, investors increasingly see owning physical gold as a legitimate way to protect against inflation. According to Ms. Sprott, demand for physical gold traditionally went up when the price went up, but recently that phenomenon has been turned on its head as demand has remained strong even as gold is slumping.
Finally, there’s the matter of tax. Hit by rising debt, governments around the world are looking for ways to boost revenues, and the simplest way for many is to clamp down on tax evasion. The U.S. government is in the process of enacting its notorious FATCA legislation, under which foreign banks — including Canadian banks — will be required to report account details for all their American customers.
The rules for precious metals are far less strict. Most of Canada’s banks also offer precious metals storage — they’re the biggest players in the business — but Ms. Sprott is betting that potential customers will be a lot more wary of dealing with banks because of the heightened rules and regulatory scrutiny they face. Small, independent players such as IDS aren’t subject to the federal Office of the Superintendent of Financial Institutions, and nor are they affected by FATCA.
The industry is most visible in countries like Switzerland and Singapore where facilities known as freeports are located close to international airports, offering storage for precious metals, art, vintage cars and other valuable assets. Some also provide trading services for clients who want to swap, say, some silver bars for a few cases of rare wine.
IDS will guard whatever gold you have, but reporting is up to the customer. Often the company doesn’t even know who owns the gold in its warehouse as in many cases it’s held under the name of a broker acting on behalf of someone else.
The company launched in 2012 after having the building retrofitted (a two-year process) with the latest security. Exterior walls are reinforced concrete and the ones on the inside are covered in Kevlar, the stuff used in bullet-proof vests. Ubiquitous security cameras ensure that virtually every step taken inside the facility is captured on a hard disk. For good measure, there are motion detectors.
Doors are metal and controlled by a central locking mechanism, so no two doors can be opened at once.
American clients who drop by to check things out can’t help but be impressed by all the hardware, or the numerous oil paintings of canoes — this is Canada, after all — adorning the walls around Ms. Sprott’s office.
Still, gaining traction in the business will take time. More than a year after the company opened its doors, there’s a lot more empty space than bullion in the warehouse. But the facility is built and Ms. Sprott is confident that the customers will come. |
We’ve had a significant TV, radio and online presence in Canada for many years, and the BBC is uniquely placed to provide Canadian audiences with the global perspective on stories that matter to them.
The BBC has announced an investment plan for Canada, to include the addition of a new editorial team based in Toronto. As part of its expansion plans the BBC will launch a dedicated version of the North American edition of BBC.com for Canadian audiences, for PC and mobile devices.
The new Canada edition of BBC.com will see a range of enhancements to the BBC’s online news offer, including the curation of the international and news homepages to offer Canadian audiences better targeted, more relevant content from the BBC’s global coverage. There will also be an increased editorial focus on news and features to give Canadians better insight into the world around them and their role in it. This new localized edition of the site will launch later this year.
Jim Egan, CEO of BBC Global News Ltd, says: “We’ve had a significant TV, radio and online presence in Canada for many years, and the BBC is uniquely placed to provide Canadian audiences with the global perspective on stories that matter to them. These new investments will offer Canadian audiences an enriched and more relevant user experience, as well as enabling us to enhance our offer to partners and advertisers in Canada who want to reach our large, upscale audience both nationally and internationally.”
The investment in Canada to support this edition will include the appointment of three new editorial positions including a video journalist, an online journalist and a social media producer all based in Toronto. This news hub will be producing original stories and features, as well as curating the BBC’s homepage and main news index with the most relevant stories and features from across the BBC site. Canadian stories with global resonance, from the recent elections, to the Canadian perspective on the U.S election or the NAFTA summit have all been of interest to the BBC’s international audience, and this new investment will allow the BBC to offer more tailored, authoritative coverage of Canada to audiences outside the country.
The BBC has been part of the Canadian news landscape for many years, across TV, radio and online. The 24/7 global TV news channel BBC World News is carried on all the major pay-TV platforms in the market and the BBC already has a significant digital audience in Canada serving on average 5.6 million monthly users*, who come to the site for its trusted international news and features. These new changes will enhance the digital offer for local users, incorporating select Canadian stories with a global relevance that will also have a broader significance for the BBC’s international audiences.
Notes to editors
*Comscore market data 6 month average 2015-2016. Multiplatform inc mobile apps
BBC World News and BBC.com, the BBC's commercially funded international 24-hour English news platforms, are owned and operated by BBC Global News Ltd. BBC World News television is available in more than 200 countries and territories worldwide, and over 433 million households and 1.8 million hotel rooms. The channel's content is also available on 178 cruise ships, 53 airlines and 23 mobile phone networks. BBC.com offers up-to-the minute international news and in-depth analysis for PCs, tablets and mobile devices to more than 85 million unique browsers each month.
BBC Advertising, part of BBC Worldwide, sells advertising and sponsorship solutions on behalf of the BBC’s worldwide commercial portfolio across broadcast, online and mobile platforms globally.
HM3 |
Q:
Please guide me how to make my question clear?
One of my questions was closed yesterday. After that I've edited it multiple times. But it seems it is still not completely clear. Following is the question:
Do fixed and absolutely positioned elements not take the full width of their container like block elements? If yes then why?
I guess that what was not clear was that what I meant by block-level elements. I've clarified that in the question. The confusion arose in my mind after reading this answer. I am still not sure whether absolutely/fixed positioned elements are block-level elements or not. I am new to programming. There are many things in w3c draft which are above my level. I am also not fluent in English so sometimes I find it difficult to understand MDN reference; that is why I ask questions on stackoverflow. E.g. I still don't understood somewhat the answer given by user Chris; because I don't know why he mentioned non replaced elements. Would the rendering be different if there were a replaced element?
Please tell me what is not clear in the question; I'll edit it further.
Thank you.
A:
Based on the timeline I can see why your question was closed as unclear. I wouldn't have close voted if I knew my close vote was binding but Boltclock decided differently.
I'm not versed into the particular issue you have trouble with but I've read into the topic again and I find it hard to match the issue you describe in the text and the code you provide. If anything needs to be changed either a more detailed example or maybe a screenshot can help in that case.
In your paragraph where you ask the question you ask for why things are designed as they are. I personally think that question is on the brink of opinion based if not too broad. So that would put your question on the other end of unclear.
You also ask for links to reference documentation. Users that will try to answer will be helped if you link to docs you already read or saw. This will prevent answers to provide links to docs you already read but didn't help or it will clarify where your line of reasoning is off because you interpret the doc wrong or didn't find the correct one.
With these small changes I think your question should be able to gather enough re-open votes.
Let me end with a personal observation. I have tried to edit your question to remove noise and also to give it another push so it got some renewed attention. In the comments here and on the SO question I see you choose certain wording that makes me wonder why I should help you out at all. I'm trying to be respectful and helpful. I don't understand why that only seems to apply to me. |
/**
* This method is used to check whether the password trim is enabled.
*
* @return true if the value of <EnablePasswordTrim> is true in the carbon.xml or <EnablePasswordTrim> is not present
* in the carbon.xml
*/
public static boolean isPasswordTrimEnabled() {
boolean isPasswordTrimEnabled = true;
ServerConfiguration serverConfiguration = CarbonUtils.getServerConfiguration();
if (serverConfiguration != null && StringUtils.isNotEmpty(serverConfiguration.getFirstProperty
(CarbonConstants.IS_PASSWORD_TRIM_ENABLED))) {
isPasswordTrimEnabled = Boolean.parseBoolean(serverConfiguration.getFirstProperty
(CarbonConstants.IS_PASSWORD_TRIM_ENABLED));
}
return isPasswordTrimEnabled;
} |
package main
import (
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/namsral/flag"
"github.com/segmentio/consul-go/httpconsul"
log "github.com/sirupsen/logrus"
)
var (
port = flag.Int("port", 8080, "port to listen on")
)
func main() {
flag.Parse()
address := fmt.Sprintf(":%d", *port)
// Replace the DialContext method on the default transport to use consul for
// all host name resolutions.
// http.DefaultTransport = &http.Transport{
// Proxy: http.ProxyFromEnvironment,
// DialContext: (&consul.Dialer{
// Timeout: 30 * time.Second,
// KeepAlive: 30 * time.Second,
// DualStack: true,
// }).DialContext,
// ForceAttemptHTTP2: true,
// MaxIdleConns: 100,
// IdleConnTimeout: 90 * time.Second,
// TLSHandshakeTimeout: 10 * time.Second,
// ExpectContinueTimeout: 1 * time.Second,
// }
// Wraps the default transport so all service names are looked up in consul.
// The consul client uses its own transport so there's no risk of recursive
// loop here.
http.DefaultTransport = httpconsul.NewTransport(http.DefaultTransport)
s, err := New("web", *port, 2*time.Second)
if err != nil {
panic(err)
}
sigs := make(chan os.Signal, 1)
done := make(chan struct{}, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
select {
case done <- struct{}{}:
if err := s.Deregister(); err != nil {
log.WithError(err).Fatal("Failed to deregister from consul agent")
}
close(done)
return
case <-done:
return
}
}()
defer func() {
select {
case done <- struct{}{}:
if err := s.Deregister(); err != nil {
log.WithError(err).Fatal("Failed to deregister from consul agent")
}
close(done)
return
case <-done:
return
}
}()
r := gin.Default()
r.GET("/", s.callBackend)
r.GET("/healthcheck", s.healthcheck)
log.Infof("Starting to listen at %s...", address)
if err := http.ListenAndServe(address, r); err != nil {
log.WithError(err).Fatal("Failed to listen")
}
}
|
<gh_stars>0
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/Handle.hpp>
#include <RED4ext/ISerializable.hpp>
#include <RED4ext/Types/SimpleTypes.hpp>
#include <RED4ext/Types/generated/game/DebugPath.hpp>
#include <RED4ext/Types/generated/game/debug/FailureId.hpp>
namespace RED4ext
{
namespace game::debug { struct Failure; }
namespace game::debug {
struct Failure : ISerializable
{
static constexpr const char* NAME = "gamedebugFailure";
static constexpr const char* ALIAS = NAME;
game::debug::FailureId id; // 30
float time; // 38
uint8_t unk3C[0x48 - 0x3C]; // 3C
CString message; // 48
game::DebugPath path; // 68
Handle<game::debug::Failure> previous; // 90
Handle<game::debug::Failure> cause; // A0
};
RED4EXT_ASSERT_SIZE(Failure, 0xB0);
} // namespace game::debug
} // namespace RED4ext
|
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { ContentComponent } from './content.component';
@NgModule({
imports: [RouterModule],
declarations: [ContentComponent],
exports: [ContentComponent]
})
export class ContentModule {}
|
package direction
// ToString returns a string description of the direction.
func (d Direction) ToString() string {
switch d {
case Up:
return "up"
case Right:
return "right"
case Down:
return "down"
case Left:
return "left"
}
return ""
}
|
num = int(input())
input_data = list(map(int,input().split()))
for i in input_data:
if i == 0:
print(0)
exit()
result = 1
for i in range(num):
result = result * int(input_data[i])
if pow(10, 18) < result:
print(-1)
exit()
print(result) |
package it.util;
import com.atlassian.jwt.SigningAlgorithm;
import com.atlassian.jwt.core.TimeUtil;
import com.atlassian.jwt.core.writer.JsonSmartJwtJsonBuilder;
import com.atlassian.jwt.core.writer.JwtClaimsBuilder;
import com.atlassian.jwt.exception.JwtIssuerLacksSharedSecretException;
import com.atlassian.jwt.exception.JwtSigningException;
import com.atlassian.jwt.exception.JwtUnknownIssuerException;
import com.atlassian.jwt.httpclient.CanonicalHttpUriRequest;
import com.atlassian.jwt.writer.JwtJsonBuilder;
import com.atlassian.jwt.writer.JwtWriter;
import com.atlassian.jwt.writer.JwtWriterFactory;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicHeaderValueParser;
import org.apache.http.message.ParserCursor;
import org.apache.http.util.CharArrayBuffer;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkNotNull;
//Copied mostly from AC Play
public class JwtAuthorizationGenerator {
private static final char[] QUERY_DELIMITERS = new char[]{'&'};
/**
* Default of 3 minutes.
*/
private static final int JWT_EXPIRY_WINDOW_SECONDS_DEFAULT = 60 * 3;
private final int jwtExpiryWindowSeconds;
private final JwtWriterFactory jwtWriterFactory;
public JwtAuthorizationGenerator(JwtWriterFactory jwtWriterFactory) {
this(jwtWriterFactory, JWT_EXPIRY_WINDOW_SECONDS_DEFAULT);
}
public JwtAuthorizationGenerator(JwtWriterFactory jwtWriterFactory, int jwtExpiryWindowSeconds) {
this.jwtWriterFactory = checkNotNull(jwtWriterFactory);
this.jwtExpiryWindowSeconds = jwtExpiryWindowSeconds;
}
public String generate(String method, String productBaseUrl, URI uri, Map<String, List<String>> parameters,
Optional<String> userId, String issuer, String sharedSecret)
throws JwtIssuerLacksSharedSecretException, JwtUnknownIssuerException, URISyntaxException {
final String path = uri.getPath();
final URI baseUrl = new URI(productBaseUrl);
final String productContext = baseUrl.getPath();
final String pathWithoutProductContext = path.substring(productContext.length());
final URI uriWithoutProductContext = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(),
pathWithoutProductContext, uri.getQuery(), uri.getFragment());
return generate(method, uriWithoutProductContext, parameters, userId, issuer, sharedSecret);
}
public String generate(String httpMethod, URI url, Map<String, List<String>> parameters,
Optional<String> userId, String issuer, String sharedSecret)
throws JwtIssuerLacksSharedSecretException, JwtUnknownIssuerException {
Map<String, String[]> paramsAsArrays = Maps.transformValues(parameters, input -> checkNotNull(input).toArray(new String[input.size()]));
return encodeJwt(httpMethod, url, paramsAsArrays, userId.orElse(null), issuer, sharedSecret);
}
private String encodeJwt(String httpMethod, URI targetPath, Map<String, String[]> params, String userKeyValue, String issuer, String sharedSecret)
throws JwtUnknownIssuerException, JwtIssuerLacksSharedSecretException {
JwtJsonBuilder jsonBuilder = new JsonSmartJwtJsonBuilder()
.issuedAt(TimeUtil.currentTimeSeconds())
.expirationTime(TimeUtil.currentTimePlusNSeconds(jwtExpiryWindowSeconds))
.issuer(issuer);
if (null != userKeyValue) {
jsonBuilder = jsonBuilder.subject(userKeyValue);
}
Map<String, String[]> completeParams = params;
try {
if (!StringUtils.isEmpty(targetPath.getQuery())) {
completeParams = new HashMap<>(params);
completeParams.putAll(constructParameterMap(targetPath));
}
CanonicalHttpUriRequest canonicalHttpUriRequest = new CanonicalHttpUriRequest(httpMethod,
targetPath.getPath(), "", completeParams);
JwtClaimsBuilder.appendHttpRequestClaims(jsonBuilder, canonicalHttpUriRequest);
} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
return issueJwt(jsonBuilder.build(), sharedSecret);
}
private String issueJwt(String jsonPayload, String sharedSecret) throws JwtSigningException, JwtIssuerLacksSharedSecretException, JwtUnknownIssuerException {
return getJwtWriter(sharedSecret).jsonToJwt(jsonPayload);
}
private JwtWriter getJwtWriter(String sharedSecret) throws JwtUnknownIssuerException, JwtIssuerLacksSharedSecretException {
return jwtWriterFactory.macSigningWriter(SigningAlgorithm.HS256, sharedSecret);
}
private static Map<String, String[]> constructParameterMap(URI uri) throws UnsupportedEncodingException {
final String query = uri.getQuery();
if (query == null) {
return Collections.emptyMap();
}
Map<String, String[]> queryParams = new HashMap<>();
CharArrayBuffer buffer = new CharArrayBuffer(query.length());
buffer.append(query);
ParserCursor cursor = new ParserCursor(0, buffer.length());
while (!cursor.atEnd()) {
NameValuePair nameValuePair = BasicHeaderValueParser.DEFAULT.parseNameValuePair(buffer, cursor, QUERY_DELIMITERS);
if (!StringUtils.isEmpty(nameValuePair.getName())) {
String decodedName = urlDecode(nameValuePair.getName());
String decodedValue = urlDecode(nameValuePair.getValue());
String[] oldValues = queryParams.get(decodedName);
String[] newValues = null == oldValues ? new String[1] : Arrays.copyOf(oldValues, oldValues.length + 1);
newValues[newValues.length - 1] = decodedValue;
queryParams.put(decodedName, newValues);
}
}
return queryParams;
}
private static String urlDecode(final String content) throws UnsupportedEncodingException {
return null == content ? null : URLDecoder.decode(content, "UTF-8");
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::error;
use crate::key_bundle::KeyBundle;
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
/// A representation of an encrypted payload. Used as the payload in EncryptedBso and
/// also anywhere else the sync keys might be used to encrypt/decrypt, such as send-tab payloads.
#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct EncryptedPayload {
#[serde(rename = "IV")]
pub iv: String,
pub hmac: String,
pub ciphertext: String,
}
impl EncryptedPayload {
#[inline]
pub fn serialized_len(&self) -> usize {
(*EMPTY_ENCRYPTED_PAYLOAD_SIZE) + self.ciphertext.len() + self.hmac.len() + self.iv.len()
}
pub fn decrypt(&self, key: &KeyBundle) -> error::Result<String> {
key.decrypt(&self.ciphertext, &self.iv, &self.hmac)
}
pub fn decrypt_into<T>(&self, key: &KeyBundle) -> error::Result<T>
where
for<'a> T: Deserialize<'a>,
{
Ok(serde_json::from_str(&self.decrypt(key)?)?)
}
pub fn from_cleartext(key: &KeyBundle, cleartext: String) -> error::Result<Self> {
let (enc_base64, iv_base64, hmac_base16) =
key.encrypt_bytes_rand_iv(cleartext.as_bytes())?;
Ok(EncryptedPayload {
iv: iv_base64,
hmac: hmac_base16,
ciphertext: enc_base64,
})
}
pub fn from_cleartext_payload<T: Serialize>(
key: &KeyBundle,
cleartext_payload: &T,
) -> error::Result<Self> {
Self::from_cleartext(key, serde_json::to_string(cleartext_payload)?)
}
}
// Our "postqueue", which chunks records for upload, needs to know this value.
// It's tricky to determine at compile time, so do it once at at runtime.
lazy_static! {
// The number of bytes taken up by padding in a EncryptedPayload.
static ref EMPTY_ENCRYPTED_PAYLOAD_SIZE: usize = serde_json::to_string(
&EncryptedPayload { iv: "".into(), hmac: "".into(), ciphertext: "".into() }
).unwrap().len();
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[derive(Serialize, Deserialize, Debug)]
struct TestStruct {
id: String,
age: u32,
meta: String,
}
#[test]
fn test_roundtrip_crypt_record() {
let key = KeyBundle::new_random().unwrap();
let payload_json = json!({ "id": "aaaaaaaaaaaa", "age": 105, "meta": "data" });
let payload =
EncryptedPayload::from_cleartext(&key, serde_json::to_string(&payload_json).unwrap())
.unwrap();
let record = payload.decrypt_into::<TestStruct>(&key).unwrap();
assert_eq!(record.id, "aaaaaaaaaaaa");
assert_eq!(record.age, 105);
assert_eq!(record.meta, "data");
// While we're here, check on EncryptedPayload::serialized_len
let val_rec = serde_json::to_string(&serde_json::to_value(&payload).unwrap()).unwrap();
assert_eq!(payload.serialized_len(), val_rec.len());
}
#[test]
fn test_record_bad_hmac() {
let key1 = KeyBundle::new_random().unwrap();
let json = json!({ "id": "aaaaaaaaaaaa", "deleted": true, });
let payload =
EncryptedPayload::from_cleartext(&key1, serde_json::to_string(&json).unwrap()).unwrap();
let key2 = KeyBundle::new_random().unwrap();
let e = payload
.decrypt(&key2)
.expect_err("Should fail because wrong keybundle");
// Note: ErrorKind isn't PartialEq, so.
assert!(matches!(e, error::Error::CryptoError(_)));
}
}
|
Computing Alignments with Constraint Programming: The Acyclic Case Conformance checking confronts process models with real process executions to detect and measure deviations between modelled and observed behaviour. The core technique for conformance checking is the computation of an alignment. Current approaches for alignment computation rely on a shortest-path technique over the product of the state-space of a model and the observed trace, thus suffering from the well-known state explosion problem. This paper presents a fresh alternative for alignment computation of acyclic process models, that encodes the alignment problem as a Constraint Satisfaction Problem. Since modern solvers for this framework are capable of dealing with large instances, this contribution has a clear potential. Remarkably, our prototype implementation can handle instances that represent a real challenge for current techniques. Main advantages of using Constraint Programming paradigm lie in the possibility to adapt parameters such as the maximum search time, or the maximum misalignment allowed. Moreover, using search and propagation algorithms incorporated in Constraint Programming Solvers permits to find solutions for problems unsolvable with other techniques. |
Data Analytics and Physics-Based Simulation Enable Bit, Motor, and BHA Combination This article, written by JPT Technology Editor Chris Carpenter, contains highlights of paper OTC 29875, Combined Data Analytics and Physics-Based Simulation for Optimal Bit, Motor, and Bottomhole Assembly Combination, by Samba Ba, SPE, Dmitry Belov, SPE, and Daniel Nobre, SPE, Schlumberger, et al., prepared for the 2019 Offshore Technology Conference Brasil, Rio de Janeiro, 29-31 October. The paper has not been peer reviewed. Copyright 2020 Offshore Technology Conference. Reproduced by permission. Today, drill bits and mud motor issues can account for more than half of the reasons for pulling out of hole before total depth (TD) on directional drilling wells. The complete paper presents a methodology designed for optimally matching drill bits, mud motors, and bottomhole-assembly (BHA) components for reduced failure risks and improved drilling performance. Work Flow The overall work flow includes detailed modeling of each sophisticated component and an algorithm to combine them efficiently at the system level without losing their specific nature. Drilling-Bit Simulation. The drill-bit model is created in 4D - 3D space modeling plus the transient behavior with time. In 4D finite-element modeling, both polycrystalline-diamond-compact (PDC) and reverse-circulation bits can be modeled. The detailed cutting structure model may include specifying the number of cutters and how to place them in a 3D cutter space. The bit cutter and rock interaction must be modeled correctly to simulate the real scenario. This interaction is characterized by laboratory testing for almost all types of rocks interacting with the cutters. Motor Simulation. The mud motor consists of multiple subassemblies. The power section assembly is where the transformation of hydraulic power into mechanical power occurs; this consists of a rotor/stator pair. The rotor is the moving part and the stationary stator is a metal tube with rubber bonded inside. The authors developed a motor- optimization modeling work flow for evaluating the mud motors performance and durability for any defined drilling conditions. This model includes performance, fatigue, and hysteresis heating simulation capabilities. Within the framework of the developed work flow, the authors use three types of simulation (mechanical, thermal, and fatigue), with mutual correlations between the results. Drillstring Simulation. A proper drill-string simulation is critical for the successful evaluation of drilling performance and equipment reliability. In this study, the drillstring and BHA analysis consists of a comprehensive full-scale finite-element model that also includes a proper transient analysis of the drilling process in a 4D analysis. This finite- element model uses 3D beam elements with six degrees of freedom for each finite-element node. The described complex finite-element model incorporates all components from drill bit to surface. This model considers factors affecting the dynamic performance of the drillstring and can predict the transient response in the time domain. Detailed working mechanisms and geometries of downhole drive tools were implemented in the model to study the dynamic characteristics and directional performance of these tools. |
<reponame>lechium/tvOS130Headers
/*
* This header is generated by classdump-dyld 1.0
* on Tuesday, November 5, 2019 at 2:43:05 AM Mountain Standard Time
* Operating System: Version 13.0 (Build 17J586)
* Image Source: /System/Library/PrivateFrameworks/PassKitCore.framework/PassKitCore
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <PassKitCore/PassKitCore-Structs.h>
#import <PassKitCore/PKAccountFeatureDescriptor.h>
@class NSString;
@interface PKCreditAccountFeatureDescriptor : PKAccountFeatureDescriptor {
unsigned long long _paymentFundingSourceTypes;
unsigned long long _paymentPresets;
unsigned long long _paymentFrequencies;
NSString* _paymentTermsIdentifier;
NSString* _fundingSourceTermsIdentifier;
}
@property (assign,nonatomic) unsigned long long paymentFundingSourceTypes; //@synthesize paymentFundingSourceTypes=_paymentFundingSourceTypes - In the implementation block
@property (assign,nonatomic) unsigned long long paymentPresets; //@synthesize paymentPresets=_paymentPresets - In the implementation block
@property (assign,nonatomic) unsigned long long paymentFrequencies; //@synthesize paymentFrequencies=_paymentFrequencies - In the implementation block
@property (nonatomic,copy) NSString * paymentTermsIdentifier; //@synthesize paymentTermsIdentifier=_paymentTermsIdentifier - In the implementation block
@property (nonatomic,copy) NSString * fundingSourceTermsIdentifier; //@synthesize fundingSourceTermsIdentifier=_fundingSourceTermsIdentifier - In the implementation block
+(BOOL)supportsSecureCoding;
-(BOOL)isEqual:(id)arg1 ;
-(unsigned long long)hash;
-(id)copyWithZone:(NSZone*)arg1 ;
-(id)description;
-(void)encodeWithCoder:(id)arg1 ;
-(id)initWithCoder:(id)arg1 ;
-(id)initWithDictionary:(id)arg1 ;
-(unsigned long long)paymentFundingSourceTypes;
-(NSString *)paymentTermsIdentifier;
-(void)setPaymentTermsIdentifier:(NSString *)arg1 ;
-(NSString *)fundingSourceTermsIdentifier;
-(void)setFundingSourceTermsIdentifier:(NSString *)arg1 ;
-(BOOL)isEqualToCreditAccountFeatureDescriptor:(id)arg1 ;
-(void)setPaymentFundingSourceTypes:(unsigned long long)arg1 ;
-(unsigned long long)paymentPresets;
-(void)setPaymentPresets:(unsigned long long)arg1 ;
-(unsigned long long)paymentFrequencies;
-(void)setPaymentFrequencies:(unsigned long long)arg1 ;
@end
|
def fill_scores(self):
if self.team_change and self.match_change:
selected_team = self.team_list
scores = point_calculation.get_team_score(selected_team)
_translate = QtCore.QCoreApplication.translate
__sortingEnabled = self.point_list.isSortingEnabled()
self.point_list.setSortingEnabled(False)
for i in range(len(scores)):
if self.point_list.count() < len(scores):
item = QtWidgets.QListWidgetItem()
self.point_list.addItem(item)
item = self.point_list.item(i)
item.setText(_translate("evaluate_tean_dialog", "{}".format(scores[i])))
self.point_list.setSortingEnabled(__sortingEnabled)
total = sum(scores)
self.total_points.setText(_translate("evaluate_team_dialog", "{}".format(total)))
else:
self.dialog_box() |
<gh_stars>100-1000
/*
* Copyright 2019 Google LLC, <NAME>
*
* 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.
*/
#ifndef VISQOL_INCLUDE_SIMRESULTSWRITER_H
#define VISQOL_INCLUDE_SIMRESULTSWRITER_H
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include "absl/base/internal/raw_logging.h"
#include "google/protobuf/util/json_util.h"
#include "similarity_result.pb.h" // Generated by cc_proto_library rule
#include "conformance.h"
#include "file_path.h"
namespace Visqol {
class SimilarityResultsWriter {
public:
/**
* Write the results of a single ViSQOL comparison. Results can be written to
* console, to a JSON file or to both.
*
* @param verbose If true, write the results to console.
* @param results_output_csv If this path is not empty, the basic comparison
* results will be written here in CSV format.
* @param debug_output_path If this path is not empty, the comparison result
* will be written to this file in JSON format.
* @param sim_res_msg The comparison result to write.
*/
static void Write(const bool verbose,
const FilePath &results_output_csv,
const FilePath &debug_output_path,
const SimilarityResultMsg &sim_res_msg,
const bool use_speech_mode) {
WriteToConsole(sim_res_msg, verbose, use_speech_mode);
if (!debug_output_path.Path().empty()) {
WriteDebugJSON(debug_output_path, sim_res_msg);
}
if (!results_output_csv.Path().empty()) {
WriteResultsToCSV(results_output_csv, sim_res_msg);
}
}
private:
/**
* Write the results of the comparison, along with some basic debug info, to
* console.
*
* @param sim_res_msg The comparison result to write.
*/
static void WriteToConsole(const SimilarityResultMsg &sim_res_msg,
bool verbose,
const bool use_speech_mode) {
std::cout << "ViSQOL conformance version: " << kVisqolConformanceNumber <<
std::endl;
std::cout << (use_speech_mode ? "Speech mode" : "Audio mode") << std::endl;
if (verbose) {
std::cout << std::endl;
std::cout << "Reference Filepath:\t" << sim_res_msg.reference_filepath()
<< std::endl;
std::cout << "Degraded Filepath:\t" << sim_res_msg.degraded_filepath()
<< std::endl;
}
std::cout << "MOS-LQO:\t\t" << sim_res_msg.moslqo() << std::endl;
if (verbose) {
std::cout << std::endl << FormatFVNSIM(sim_res_msg) << std::endl;
std::cout << FormatPatchSimilarity(sim_res_msg)
<< std::endl;
}
}
/**
* Format the FVNSIM and center frequency band debug info.
*
* @param sim_res_msg The similarity result containing the relevant debug
* info.
*
* @return A string containing the formatted debug info.
*/
static std::string FormatFVNSIM(const SimilarityResultMsg &sim_res_msg) {
std::stringstream ss;
assert(sim_res_msg.fvnsim_size() == sim_res_msg.center_freq_bands_size());
ss << "--------------------------" << std::endl;
ss << "| FVNSIM | Freq Band |" << std::endl;
ss << "--------------------------" << std::endl;
for (size_t i = 0; i < sim_res_msg.fvnsim_size(); i++) {
ss << std::fixed << std::setprecision(6)
<< "| " << sim_res_msg.fvnsim(i)
<< std::fixed << std::setprecision(3)
<< " | " << std::setw(9) << std::right
<< sim_res_msg.center_freq_bands(i) << "Hz"
<< " |" << std::endl;
}
ss << "--------------------------\n" << std::endl;
return ss.str();
}
/**
* Format the per-patch similarity result debug info.
*
* @param sim_res_msg The similarity result containing the relevant debug
* info.
*
* @return A string containing the formatted debug info.
*/
static std::string FormatPatchSimilarity(
const SimilarityResultMsg &sim_res_msg) {
std::stringstream ss;
// Format the column titles.
ss << "--------------------------------------"
"--------------------------------------" << std::endl;
ss << "| Patch Idx | Similarity | Ref Patch: Start - End "
"| Deg Patch: Start - End |" << std::endl;
ss << "--------------------------------------"
"--------------------------------------" << std::endl;
// Format the rows.
for (size_t i = 0; i < sim_res_msg.patch_sims_size(); i++) {
// Format patch index.
ss << "| " << std::setw(9) << std::right << i
// PrFormatint patch similarity score.
<< " | " << std::fixed << std::setprecision(6)
<< std::setw(10) << std::right
<< sim_res_msg.patch_sims(i).similarity()
<< std::fixed << std::setprecision(3)
// Format ref patch timestamps.
<< " | " << std::setw(11) << std::right
<< sim_res_msg.patch_sims(i).ref_patch_start_time() << " - "
<< std::setw(7) << std::right
<< sim_res_msg.patch_sims(i).ref_patch_end_time()
// Format deg patch timestamps.
<< " | " << std::setw(11) << std::right
<< sim_res_msg.patch_sims(i).deg_patch_start_time() << " - "
<< std::setw(7) << std::right
<< sim_res_msg.patch_sims(i).deg_patch_end_time()
<< " |" << std::endl;
}
ss << "--------------------------------------"
"--------------------------------------\n" << std::endl;
return ss.str();
}
/**
* Write the ViSQOL comparison result, including all debug info, to the given
* file path. The data will be written in JSON format.
*
* Data will be appended to the file if the file already has contents.
*
* @param debug_output_path The file path to write the JSON results to.
* @param sim_res_msg The comparison result to write.
*/
static void WriteDebugJSON(const FilePath &debug_output_path,
const SimilarityResultMsg &sim_res_msg) {
std::string debug_json;
if (google::protobuf::util::MessageToJsonString(sim_res_msg,
&debug_json).ok()) {
std::ofstream outFile;
outFile.open(debug_output_path.Path(), std::ios_base::app);
outFile << debug_json;
outFile.close();
} else {
ABSL_RAW_LOG(ERROR, "Error writing debug JSON: %s ",
sim_res_msg.ShortDebugString().c_str());
}
}
/**
* Write the reference and degraded filepath, along with the resulting
* MOS-LQO from their comparison, to a CSV file.
*
* @param csv_res_path The path to the output CSV file. If the file already
* exists, values will be appended to it.
* @param sim_res_msg The comparison result to write.
* @param output_moslqo If true, write a column for the mean opinion score.
* @param If True, write a column with the average nsim value per frequency.
*/
static void WriteResultsToCSV(const FilePath &csv_res_path,
const SimilarityResultMsg &sim_res_msg,
const bool output_moslqo = true,
const bool output_fvnsim = true,
const bool output_stddev = true,
const bool output_fvdegenergy = true) {
// If this file does not already exist, we need to write the header.
const bool write_header = !csv_res_path.Exists();
std::ofstream out_file;
out_file.open(csv_res_path.Path(), std::ios_base::app);
if (write_header) {
out_file << "reference,degraded";
if (output_moslqo) {
out_file << ",moslqo";
}
if (output_fvnsim) {
for (size_t i = 0; i < sim_res_msg.fvnsim_size(); i++) {
out_file << ",fvnsim" << i;
}
}
if (output_stddev) {
for (size_t i = 0; i < sim_res_msg.fstdnsim_size(); i++) {
out_file << ",fstdnsim" << i;
}
}
if (output_fvdegenergy) {
for (size_t i = 0; i < sim_res_msg.fvdegenergy_size(); i++) {
out_file << ",fvdegenergy" << i;
}
}
out_file << std::endl;
}
out_file << sim_res_msg.reference_filepath() << ","
<< sim_res_msg.degraded_filepath();
if (output_moslqo) {
out_file << "," << std::setprecision(9) << sim_res_msg.moslqo();
}
if (output_fvnsim) {
for (size_t i = 0; i < sim_res_msg.fvnsim_size(); i++) {
out_file << "," << std::setprecision(9) << sim_res_msg.fvnsim(i);
}
}
if (output_stddev) {
for (size_t i = 0; i < sim_res_msg.fstdnsim_size(); i++) {
out_file << "," << std::setprecision(9) << sim_res_msg.fstdnsim(i);
}
}
if (output_fvdegenergy) {
for (size_t i = 0; i < sim_res_msg.fvdegenergy_size(); i++) {
out_file << "," << std::setprecision(9) << sim_res_msg.fvdegenergy(i);
}
}
out_file << std::endl;
out_file.close();
}
};
} // namespace Visqol
#endif // VISQOL_INCLUDE_SIMRESULTSWRITER_H
|
DNA adduct formation in target tissues of Sprague-Dawley rats, CD-1 mice and A/J mice following tumorigenic doses of 1-nitropyrene. Recent reports have indicated that 1-nitropyrene is tumorigenic in laboratory animals. Since it is generally accepted that the covalent binding of carcinogens to DNA is causally related to tumorigenesis, we used 32P-postlabeling to examine the DNA adducts present in target tissues. 1-Nitropyrene (99.85-99.98% 1-nitropyrene, 0.15-0.02% 1,3-, 1,6- and 1,8-dinitropyrene by mass spectral analyses) was administered to Sprague-Dawley rats, CD-1 mice and A/J mice according to three tumorigenesis protocols. In DNA obtained from the injection site of Sprague-Dawley rats, two major adducts were observed. Based upon their chromatographic behavior and sensitivities to treatment with nuclease P1 and hydrazine, these adducts were identified as N-(deoxyguanosin-8-yl)-1-aminopyrene (dG-C8-AP) and N-(deoxyguanosin-8-yl)-1-amino-3-, 6- and/or 8-nitropyrene (dG-C8-ANP), which are adducts derived from the nitroreduction of 1-nitropyrene and dinitropyrenes respectively. In mammary gland DNA from Sprague-Dawley rats, two adducts were found. One of these had chromatographic characteristics and hydrazine and nuclease P1 sensitivities similar to dG-C8-AP, while the identity of the other adduct is presently unknown. The only DNA adduct detected in the livers of newborn CD-1 mice and the lungs of A/J mice was dG-C8-ANP. The presence of dG-C8-AP in the injection site and mammary gland of the Sprague-Dawley rats indicates that nitroreduction is involved in the metabolic activation of 1-nitropyrene in these tissues. Since an unidentified adduct was also found in the mammary gland, other pathways are important in this tissue. The presence of only dinitropyrene DNA adducts in the livers of CD-1 mice and lungs of A/J mice indicates that dinitropyrenes are activated very efficiently to electrophilic metabolites, to an extent far better than 1-nitropyrene. |
Optical Properties of ZnO Thin Film Abstract In this work, we studied with a Matlab program, some of optical properties of zinc oxide (ZnO) deposited on glass (SiO2). The parameters studied include the refraction index, extinction coefficient, optical band gap, and complex dielectric constant versus incident photon energy, and transmittance, absorbance and reflectance spectrum of ZnO thin film deposited on glass (SiO2) for different thickness. The films were found to exhibit high transmittance (75- 95%), low absorbance and low reflectance in the visible / near infrared region up to 1000 nm. However, the absorbance of the films was found to be high in the ultra violet region with peak around 380 nm. |
1. Field of the Invention
The present invention relates to an image sensing device and an imaging system.
2. Description of the Related Art
Japanese Patent Laid-Open No. 2001-230974 discloses that the greater a signal level of an optical signal output from a pixel to each of vertical output lines V1 to V3 is, the lower a voltage of each of the vertical output lines V1 to V3 is, in a solid-state image sensing device as shown in FIG. 9 of Japanese Patent Laid-Open No. 2001-230974. In this case, in the solid-state image sensing device shown in FIG. 9 of Japanese Patent Laid-Open No. 2001-230974, in a column where a signal of a pixel on which very strong light is incident is read out to a vertical output line (any one of V1 to V3), the source-drain voltage of a load MOS (corresponding one of M51 to M53) connected to the vertical output line drops to 0 V so that the load MOS is turned OFF. When the load MOSs M51 to M53 are turned OFF, the voltage drop across a GND line 4 decreases. Because of this, output voltages of dark pixels and optical black (OB) pixels are different between a row including a pixel on which strong light is incident and a row that does not include such a pixel. As a result of this, in an image including a strong spot light, an abnormality occurs in a signal level of pixels on the right and left of the spot light, so that a luminance-incremented white band output or conversely, a darkening black band output occurs. In other words, horizontal smear occurs.
To address this, Japanese Patent Laid-Open No. 2001-230974 discloses that when an optical signal is output from a pixel, the vertical output lines V1 to V3 are clipped so that the voltage thereof will not drop so as to be equal to or lower than the drain voltage that allows the load MOSs M51 to M53 to operate in a saturation region, as shown in FIG. 1 of Japanese Patent Laid-Open No. 2001-230974. Consequently, according to Japanese Patent Laid-Open No. 2001-230974, since it is possible to prevent a load MOS from being tuned OFF, an abnormality in a signal level in a row including a pixel on which strong light is incident can be reduced. Thus, horizontal smear in the obtained image can be reduced.
Japanese Patent Laid-Open No. 2005-217158 discloses that an operational amplifier 120 amplifies a signal output from a pixel to a vertical output line 106, and the amplified signal is accumulated in an accumulation capacitance 112, as shown in FIG. 3 of Japanese Patent Laid-Open No. 2005-217158. In this operational amplifier 120, a source grounded field effect transistor of a constant current circuit is connected between an input transistor 125 and a GND wiring 132 as show in FIG. 2 of Japanese Patent Laid-Open No. 2005-217158.
Japanese Patent Laid-Open No. 2008-042679 discloses that when a noise level corresponding to a pixel reset state is output from an operational amplifier 10 to a noise transmission path NT, a first clip transistor 19 clips the potential of the noise transmission path NT, as shown in FIG. 3 of Japanese Patent Laid-Open No. 2008-042679. The drain of the first clip transistor 19 is connected to an output terminal of the operational amplifier 10, and its source is connected to a capacitance 14 for holding a noise level via a transmission transistor 12. Consequently, according to Japanese Patent Laid-Open No. 2008-042679, a voltage supplied from the operational amplifier 10 via the noise transmission path NT to and accumulated in the capacitance 14 is kept from being higher than an original reset level, thus enabling suppression of darkening.
On the other hand, in an image sensing device in which a differential amplifier in each column amplifies a signal output from a pixel in each column in a pixel array to a vertical output line and outputs the amplified signal to an output amplifier, a horizontal smear in an image corresponding to an image signal cannot be sufficiently suppressed when some of the pixels are irradiated with strong light.
For example, when some of the pixels are irradiated with strong light, an optical signal whose signal level is excessive is output from the some pixels to the vertical output lines. At this time, even though a MOS transistor is going to clip a potential of each of the vertical output lines, an optical signal whose signal level is excessive flows in the differential amplifier until the MOS transistor is turned ON. In this case, when the differential amplifier amplifies an optical signal, a constant current circuit included in the differential amplifier supplies an excessive current to a ground line. Due to an influence of this, it is impossible for a differential amplifier in another column to output an appropriate signal. Accordingly, a horizontal smear occurs in an image obtained corresponding to an image signal output from the image sensing device. |
package com.example.calculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
TextView textView;
Button button;
String sayi1="", sayi2="", islem;
Double sonuc;
Double temp;//işaret değiştirmede kullanılacak olan bir değişken
boolean islemeTiklandi=false;//birden fazla işlem yapılmasına engel olan bir kontrol
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.textView);
}
//Rakam butonları
public void bClickNumber(View view)
{
button=(Button)view;
textView.setText(textView.getText()+""+button.getText());
if(islemeTiklandi==true)//işlem sembolünden sonra sayi2 dolduruluyor;
{
sayi2+=button.getText();
}
else
{
sayi1+=button.getText();
}
}
//Clear butonu
public void bClickClear(View view)
{
Clear();
}
//değerleri temizlemek için bir metod;
private void Clear()
{
//bellekteki sayılar da dahil textView ın string i temizlendi;
textView.setText("");
sayi1="";
sayi2="";
sonuc=null;
islem="";
islemeTiklandi=false;
}
//= butonu;
public void bClickResult(View view)
{
try
{
switch (islem)
{
case "+":
sonuc=Double.parseDouble(sayi1)+Double.parseDouble(sayi2);
break;
case "-":
sonuc=Double.parseDouble(sayi1)-Double.parseDouble(sayi2);
break;
case "*":
sonuc=Double.parseDouble(sayi1)*Double.parseDouble(sayi2);
break;
case "/":
sonuc=Double.parseDouble(sayi1)/Double.parseDouble(sayi2);
break;
}
}
catch (Exception e)
{
//fazladan işlem olmaması için(toast, Clear() diğer durumlarda da kullanılacak) boş bırakıldı;
}
if(sonuc!=null && !sonuc.isNaN() && !sonuc.isInfinite())//işlem sorunsuz ise
{
textView.setText(textView.getText()+"="+sonuc);
}
else//kesin olarak bir sorun var(Exception || NaN || Infinite)
{
Clear();
Toast.makeText(getApplicationContext(),"Geçersiz işlem",Toast.LENGTH_SHORT).show();
}
islemeTiklandi=false;
}
//İşlem butonları
public void bClickOperator(View view)
{
button = (Button) view;
if(islemeTiklandi==false && !sayi1.isEmpty())//sayi1 kontrolü, başta herhangi bir operatöre basılamaması, işlemeTiklandi ise birden fazla operatörü engellemek içindir.
{
textView.setText(textView.getText() + "" + button.getText());
islemeTiklandi = true;
islem = button.getText().toString();
if (sonuc != null)
{
//Eğer işlem yapıldıktan sonra çıkan sonuç ile tekrar bir işlem yapılması gerekiyorsa;
sayi1 = sonuc.toString();
textView.setText(sayi1+button.getText());
sayi2 = "";
sonuc = null;
}
}
else if(islemeTiklandi==true && !sayi1.isEmpty() && sayi2.isEmpty())//işleme tıklandı fakat işlem başka bir işlem ile değiştirilmek isteniyor ise
{
islem=button.getText().toString();
textView.setText(sayi1+islem);
}
}
//İşaret değiştirme butonu; sayıyı tuşladıktan sonra basılıyor
public void bClickArtiEksi(View view)
{
button=(Button) view;
if(sonuc==null)//= butonuna basılmamış ise;
{
if(!sayi2.isEmpty())
{
temp=Double.parseDouble(sayi2)*(-1);
sayi2=temp.toString();
textView.setText(sayi1+" "+islem+" ("+sayi2+")");
}
else if((!sayi1.isEmpty()))
{
temp=Double.parseDouble(sayi1)*(-1);
sayi1=temp.toString();
if(islemeTiklandi)
{
textView.setText(sayi1+islem);
}
else
{
textView.setText(sayi1);
}
}
}
else//eğer sonuc hesaplanmış ise; bir sonraki işlemde sonucun ters işaretlesi ile devam edilmek istenirse;
{
sonuc=sonuc*(-1);
textView.setText(sonuc+"");
}
}
} |
def _apply_action(self, action: int):
if self.get_game().perform_sanity_checks:
assert self._is_chance and not self._is_terminal
assert (isinstance(action, int) and
0 <= action < self.get_game().max_chance_outcomes())
self._is_chance = False
self._can_vehicles_move = [
bool((action >> vehicle) % 2)
for vehicle in range(self.get_game().num_players())
] |
<gh_stars>0
#to separate number and special charecter from string
number = "9,223;372:036 854,775;807"
separators = ""
for char in number:
if not char.isnumeric():
separators = separators + char
print(separators)
values = "".join(char if char not in separators else " " for char in number).split()
print([int(val) for val in values])
print(sum([int(val) for val in values]))
print("*" * 120 )
quote = """
Alright, but apart from the Sanitation, the Medicine, Education, Wine,
Public Order, Irrigation, Roads, the Fresh-Water System,
and Public Health, what have the Romans ever done for us?
"""
# Use a for loop and an if statement to print just the capitals in the quote above.
for char in quote:
if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
print(char)
#write a program to prin out all the numbers from 0 to 100 are divisible by 7
# This solution uses a step value for the range function
for i in range(0, 101, 7):
print(i)
# This solution uses a slice
for i in range(101)[::7]:
print(i)
for i in range(0,100):
if(i % 7) == 0:
print(i) |
/* LanguageTool, a natural language style checker
* Copyright (C) 2016 <NAME> (http://www.languagetool.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules;
import org.languagetool.Language;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/*
* Adjust rule matches for some languages
*
* @since 4.6
*/
public class LanguageDependentFilter implements RuleMatchFilter {
protected Language language;
protected Set<String> enabledRules;
protected Set<CategoryId> disabledCategories;
public LanguageDependentFilter(Language lang, Set<String> enabledRules, Set<CategoryId> disabledRuleCategories) {
this.language = lang;
this.enabledRules = enabledRules;
this.disabledCategories = disabledRuleCategories;
}
@Override
public List<RuleMatch> filter(List<RuleMatch> ruleMatches) {
if (language.getShortCode() == "ca") {
// Use typographic apostrophe in suggestions
CategoryId catID = new CategoryId("DIACRITICS_TRADITIONAL");
if (this.enabledRules.contains("APOSTROF_TIPOGRAFIC")
|| this.disabledCategories.contains(catID)) {
List<RuleMatch> newRuleMatches = new ArrayList<>();
for (RuleMatch rm : ruleMatches) {
List<String> replacements = rm.getSuggestedReplacements();
List<String> newReplacements = new ArrayList<>();
for (String s: replacements) {
if (this.enabledRules.contains("APOSTROF_TIPOGRAFIC") && s.length() > 1) {
s = s.replace("'", "’");
}
if (this.disabledCategories.contains(catID) && s.matches(".*\\b([Dd]óna|[Vv]énen|[Vv]éns|[Ff]óra)\\b.*")) {
// skip this suggestion with traditional diacritics
} else {
newReplacements.add(s);
}
}
RuleMatch newrm = new RuleMatch(rm, newReplacements);
newRuleMatches.add(newrm);
}
return newRuleMatches;
}
}
return ruleMatches;
}
} |
<filename>budgeteer-web-interface/src/main/java/org/wickedsource/budgeteer/web/pages/budgets/manualRecords/overview/ManualRecordOverviewPage.java
package org.wickedsource.budgeteer.web.pages.budgets.manualRecords.overview;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.wickedsource.budgeteer.persistence.manualRecord.ManualRecordModel;
import org.wickedsource.budgeteer.service.manualRecord.ManualRecordService;
import org.wickedsource.budgeteer.web.Mount;
import org.wickedsource.budgeteer.web.pages.base.basepage.BasePage;
import org.wickedsource.budgeteer.web.pages.base.basepage.breadcrumbs.Breadcrumb;
import org.wickedsource.budgeteer.web.pages.base.basepage.breadcrumbs.BreadcrumbsModel;
import org.wickedsource.budgeteer.web.pages.budgets.BudgetNameModel;
import org.wickedsource.budgeteer.web.pages.budgets.details.BudgetDetailsPage;
import org.wickedsource.budgeteer.web.pages.budgets.manualRecords.add.AddManualRecordPage;
import org.wickedsource.budgeteer.web.pages.budgets.manualRecords.overview.table.ManualRecordOverviewTable;
import org.wickedsource.budgeteer.web.pages.budgets.overview.BudgetsOverviewPage;
import org.wickedsource.budgeteer.web.pages.dashboard.DashboardPage;
@Mount({"budgets/details/manuals/${id}", "budgets/details/manuals"})
public class ManualRecordOverviewPage extends BasePage {
@SpringBean
private ManualRecordService manualRecordService;
private ManualRecordModel model;
public ManualRecordOverviewPage(PageParameters parameters) {
super(parameters);
model = new ManualRecordModel(getPageParameters().get("id").toLong(), manualRecordService);
add(new ManualRecordOverviewTable("recordTable", model, parameters));
add(createManualRecordLink("addRecordLink"));
}
private Link createManualRecordLink(String id) {
return new Link(id) {
@Override
public void onClick() {
WebPage page = new AddManualRecordPage(ManualRecordOverviewPage.class, getPageParameters());
setResponsePage(page);
}
};
}
@SuppressWarnings("unchecked")
@Override
protected BreadcrumbsModel getBreadcrumbsModel() {
BreadcrumbsModel model = new BreadcrumbsModel(DashboardPage.class, BudgetsOverviewPage.class);
model.addBreadcrumb(new Breadcrumb(BudgetDetailsPage.class, getPageParameters(), new BudgetNameModel(getParameterId())));
model.addBreadcrumb(new Breadcrumb(ManualRecordOverviewPage.class, getPageParameters(), "Manual Records"));
return model;
}
}
|
Neurokinins induce a relaxation of the rat duodenum "in vivo" by activating postganglionic sympathetic elements in prevertebral ganglia: involvement of an NK-2 type of neurokinin receptor. In the small intestine of urethane-anesthetized rats, i.v. neurokinins (NKs) (0.043-14 nmol/kg) produce three distinct motor effects, e.g.: 1) a transient relaxation followed by 2) a phasic contraction and 3) a tonic contraction. The aim of this study was to characterize the nature of the receptor determining the transient relaxation and mechanisms involved. The transient relaxation was more evident in the distal than in the proximal duodenum or in the jejunum. The rank order of potency of NKs in producing relaxation was NKA greater than substance P greater than NKB. The heptapeptide NKA was as potent as the decapeptide NKA in determining relaxation but less potent than NKA in producing phasic or tonic contraction. NKA (0.43 nmol/kg i.v.)-induced relaxation and tonic contraction were unaffected by substance P, a compound which, in this tissue, acts as a NK-1 receptor antagonist. NKA (0.43 nmol/kg i.v.)-induced relaxation of the distal duodenum was unaffected by atropine, hexamethonium or adrenalectomy, reduced by phentolamine plus propranolol and abolished by guanethidine or acute (15 min before) removal of the celiac ganglion complex. These findings are consistent with the hypothesis that activation of a NK-2 receptor located on postganglionic sympathetic neurons in the prevertebral ganglia produces the intestinal relaxation in response to i.v. NKs. |
A Basic Study on the Analysis of Spatial Structure by Horizontal Expansion of Museums In recent years there has been a growing demand for museums due to an increase in cultural interest among visitors, and extensions are being carried out more frequently for older museums built due to an increase in the number of collections. However, not enough precedent studies regarding the extension of a museum have been carried out. Therefore, the purpose of this study is to establish preliminary data that will assist in constructing a museum in the future by analyzing the change in space composition, targeting actual museums that have been extended recently. The result of this study is as follows. The ratio of exhibition space, storage space, and common use space among the space composition ratio of museums that have been extended recently is increasing. Notably, the ratio occupied by experiential space is higher after extension, indicating that experiential space has become more important. The length of the visitor circulation path was also affected due to the increase of the area before and after the museum extension. However, an increase in the length of the visitor circulation path may result in a drop in the visitors concentration, and a rest area has become more important as an approach to addressing such issue. This study has significance as a basic study on the spatial analysis before and after the museum extension. However, this study has the limitation of not reflecting the visitors psychology in the analysis method, and future research should address this. 1 |
// Copyright 2019 <NAME>. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package frames
import (
"github.com/richardlehane/siegfried/internal/bytematcher/patterns"
"github.com/richardlehane/siegfried/internal/persist"
)
func init() {
patterns.Register(machineLoader, loadMachine)
patterns.Register(blockLoader, loadBlock)
}
const (
machineLoader byte = iota + 12 // mimeinfo patterns start at 16
blockLoader
)
func machinify(seg Signature) Signature {
seg = Blockify(seg)
switch seg.Characterise() {
case BOFZero, BOFWindow, BOFWild:
return Signature{NewFrame(BOF, Machine(seg), 0, 0)}
case EOFZero, EOFWindow, EOFWild:
return Signature{NewFrame(EOF, Machine(seg), 0, 0)}
default: //todo handle Prev and Succ wild
}
return seg
}
// A Machine is a segment of a signature that implements the patterns interface
type Machine Signature
func (m Machine) Test(b []byte) ([]int, int) {
var iter int
offs := make([]int, len(m))
for {
if iter < 0 {
return nil, 1
}
if offs[iter] >= len(b) {
iter--
continue
}
length, adv := m[iter].MatchN(b[offs[iter]:], 0)
if length < 0 {
iter--
continue
}
// success!
if iter == len(offs)-1 {
offs[iter] += length
break
}
offs[iter+1] = offs[iter] + length
offs[iter] += adv
iter++
}
return []int{offs[iter]}, 1
}
func (m Machine) TestR(b []byte) ([]int, int) {
iter := len(m) - 1
offs := make([]int, len(m))
for {
if iter >= len(m) {
return nil, 0
}
if offs[iter] >= len(b) {
iter++
continue
}
length, adv := m[iter].MatchNR(b[:len(b)-offs[iter]], 0)
if length < 0 {
iter++
continue
}
// success!
if iter == 0 {
offs[iter] += length
break
}
offs[iter-1] = offs[iter] + length
offs[iter] += adv
iter--
}
return []int{offs[iter]}, 1
}
func (m Machine) Equals(pat patterns.Pattern) bool {
m2, ok := pat.(Machine)
if !ok || len(m) != len(m2) {
return false
}
for i, f := range m {
if !f.Equals(m2[i]) {
return false
}
}
return true
}
func (m Machine) Length() (int, int) {
var min, max int
for _, f := range m {
pmin, pmax := f.Length()
min += f.Min
min += pmin
max += f.Max
max += pmax
}
return min, max
}
// Machines are used where sequence matching inefficient
func (m Machine) NumSequences() int { return 0 }
func (m Machine) Sequences() []patterns.Sequence { return nil }
func (m Machine) String() string {
var str string
for i, v := range m {
if i > 0 {
str += " | "
}
str += v.String()
}
return "m {" + str + "}"
}
func (m Machine) Save(ls *persist.LoadSaver) {
ls.SaveByte(machineLoader)
ls.SaveSmallInt(len(m))
for _, f := range m {
f.Save(ls)
}
}
func loadMachine(ls *persist.LoadSaver) patterns.Pattern {
m := make(Machine, ls.LoadSmallInt())
for i := range m {
m[i] = Load(ls)
}
return m
}
|
As mobile phones become more powerful, and unlimited data transfer plans from carriers become widespread, technologies such as streaming live video from phones are becoming feasible. One of the most hyped players in this market is Qik. Unfortunately, so far Qik has only worked on select Nokia devices such as the popular N95 phone. However, starting tomorrow Qik is rolling out support for select Windows Mobile devices.
Initially this partnership will bring Qik services to the Motorola Q and Samsung BlackJack phones. I’ve seen an early build of the service running on a BlackJack, and it seems to work more seamlessly on Windows Mobile than it does on the N95.
The Windows Mobile compatibility should help bring the Qik service to a larger audience. While the N95 is a very expensive phone (usually around $500-$600), the Q and BlackJack can be found for much more reasonable prices. Also, Microsoft says that it expects to sell 20 million Windows Mobile licenses in FY08, so there will be potential for much more growth as well.
Unfortunately, the timing is poor for Qik. This announcement comes just days before Apple’s WWDC event, where it is expected to unveil the 3G iPhone. This device will simply overshadow all other mobile announcements in the industry for quite some time.
Another potential problem for Qik are the rumors of video streaming capabilities being a central part of this new iPhone. While it’s no sure bet, there have been signs that such functionality could be a key component of an iChat application Apple is working on for the device.
When asked about Qik possibly working on the 3G iPhone, Qik co-founder Bhaskar Roy gave a non-committal answer. “We are going to evaluate it once the [3G] iPhone gets launched next week to see what capabilities it has and what we need to do in order to support it. We’ll need to evaluate it and figure out the next steps therein,” Roy told MobileCrunch.
Given how long it took Qik to move beyond support for basically one phone, this is not a good sign. With the 3G iPhone, it could be an issue of being ready to support it or being left in the dust. Especially with competitors like Flixwagon and Kyte out there. Flixwagon in particular may be poised to break out beyond the elite tech crowd that Qik is currently popular with.
We first reported back in April that Qik parent Visivo had raised a new $3 million round to expand the service. |
If changing skill mix is the answer, what is the question? Changing skill mix is often identified as a potential solution to health services staffing and resourcing problems, or is related to health sector reform. This paper discusses what is meant by skill mix, provides a typology of the different approaches to assessing skill mix and examines, by means of case studies, the contextual, political, social and economic factors that play a part in determining skill mix. These factors are examined in relation to three factors: the reasons (or drivers) for examining skill mix; the impact of contextual constraints; and the effect of varying spans of managerial control. Case studies conducted in Costa Rica, Finland, Mexico, the UK and the USA are used to explore the reality of assessing skill in different contexts and health care settings. We argue that, although skill mix may be a universal challenge, it is not a challenge that all managers or health professionals can meet in the same way, or with the same resources. Context can have a significant effect on the ability of health service managers to assess and change skill mix. The key determinant is the extent to which these factors are in the locus of control of management nationally, regionally, or locally, within different countries. We emphasise the need to evaluate the problem and examine the context, before deciding if a change in skill mix is the answer. The local managerial span of control and degree of organisational flexibility will be major factors in determining the likely impact of any attempts to change skill mix. Before embarking on a skill mix review, any organisation should ask itself the question: 'If changing skill mix is the answer, what is the question?' |
Gartner's mobile phone results from the first quarter of the year contained no big surprises: Times were bad for the overall industry, but pretty good for the smartphone segment. The consultancy said total sales dropped 8.6 percent compared to the year-ago quarter. The smartphone sector, which represents 13.5 percent of the total, rose 12.7 percent. In raw numbers, there were 269.1 million units sold overall. About 36.4 million of those were smartphones.
The vendor rankings remained fairly consistent as well, though there was some slight shifts and jostling. In the overall market, the top five were Nokia (36.2 percent), Samsung (19.1 percent), LG (9.9 percent), Motorola (6.2 percent and Sony Ericsson (5.4 percent). The major changes compared to the first quarter of 2008 were that Nokia lost 2.9 percentage points and LG and Motorola flipped positions.
The same trends were apparent on the smartphone vendor front. The top five smartphones during the first quarter were Nokia (41.2 percent), Research in Motion (19.9 percent), Apple (10.8 percent), HTC (5.4 percent) and Fujitsu (3.8 percent). During the year-ago quarter, Nokia was stronger by almost 4 percentage points and the positions of HTC and Fujitsu were switched.
The buzz no doubt will continue around smartphones, and likely extend the good news/bad news dynamic represented in Gartner's numbers. The launch of Palm's Pre, which has been set for June 6, is generating a lot of excitement. The device, the first to use the vendor's Web OS, will cost $199.99 after a $100 mail-in rebate and a two-year contract with Sprint. The iPhone 3.0, rumored to be in the pipeline for a summer launch, also will push the category.
And so it goes. The bottom line is that all the attention in the mobile phone sector is on the smart variety, and that the trend will accelerate as the applications become more sophisticated. The next step, perhaps a few years in the future, will be for smartphones to overtake traditional cell phones in total unit sales. In the shorter term, look for that 13.5 percent number to increase rather rapidly. The real competition to smartphones will not come from traditional cell phones or the slightly brighter feature phones. The battle will be between smartphones and the MIDs and netbooks that together constitute the other hot category in mobile devices. |
Mainstream media stars – end of an era?
FOX’s Glenn Beck is about to wrap up his TV show and start a paid Web network. Former MSNBC pundit Keith Olbermann has kicked off his new show on Current TV – a network with an average of only 23,000 viewers during primetime.
Will more mainstream media stars be jumping the mainstream ship?
Despised by some, loved by others – they certainly can’t stand each other. Glenn Beck versus Keith Olbermann – can these mainstream media stars shine just as bright in the scary world of alternative media? After years of mad chalkboarding, Fox News Channel’s Glenn Beck is about to step off America’s TV screens as the network shows him the door.
"It's imperative that now as responsible citizens who are awake, that we don't just sit in front of our TVs and say Yeah! Yeah," Beck has said in one of his last shows.
“Oh my gosh, Glenn beck! What an amazing broadcaster, I’m going to miss the tears, I’m going to miss all the lies! I’m going to miss the propaganda,” joked political comedian and blogger Sara Benincasa.
Beck will now take all that to his own Web network.
“You’re watching GBTV. We’re about to get started. The truth lives here,” invitingly says the promo on his website.
The access to this truth will cost cash – as Beck’s fans will have to subscribe to tune in.
"Turn the damn TV off right now if you have to,” Beck has recently said on his Fox News show.
“At one point he was up to 3.1 million viewers. How many of those 3.1 million are going to want to plunk down less than five bucks to see the guy? It’s difficult to have people pay for something they’ve been getting for free the whole time,” said media analyst TJ McCormack.
One person who won’t have trouble pocketing the big buck is former MSNBC star Keith Olbermann.
Several months after being dropped by the network, reportedly for making campaign contributions to Democrats, he is appearing on a new platform – Current TV, a network co-founded by former vice president and the face of America’s green movement establishment – Al Gore.
“The whole idea of having a broadcast for a network is to have viewers. And nobody watches Current right now, nobody watches it. I could yell out of my window, and more people would hear me probably than if I was to yell on Current,” said McCormack.
The channel hopes that will change with the liberal pundit hopping on board for a reported eye-popping 10 million dollars a year.This is a satisfying 3 million dollar raise from Olbermann’s MSNBC days – a much bigger, corporate-owned network.
“It may be the sort of thing where the first night, the first week – wow, he’s got 3 million people watching, but in week three, does it go down to 23,000? At that point, the people at Current TV start chewing their fingers down to their knuckles, saying what have we done,” said media analyst TJ Walker.
Without corporate backing from big business, will Olbermann change his tone as he takes to a new network?
“I do think that there’s actually going to be a big difference,” Seder says.
While it’ll take time to show which gambles pay off and which are a bust, old messages are likely to stick even on new platforms. What’s unlikely however, is mainstream media stars jumping the mainstream ship becoming a trend.
The warm comfort of sleeping in bed with a corporate pillow is too cozy for most others to get up and leave .
“I don’t think there are enough loofahs in the world to convince O’Reilly that he should hang it up. I think O’Reilly is in this till the bitter end,” said political comedian Sara Benincasa.
So, fans, relax – the one-sided shouting matches are not going anywhere, for now. |
SYDNEY (AFP) - It's just after morning opening at Sydney's Randwick Labor Club and already a few regulars are at the slot machines, or "pokies" as they are better known, for a quiet flutter.
Electronic poker machines are the most popular form of betting in Australia, but concerns about problem gamblers have prompted the government to introduce reforms to help keep their spending under control.
"The big picture is we're becoming a nanny state," said Peter Bell, a retiree who likes playing the machines, just like he enjoys to bet on horse races.
He insists he is not a problem gambler.
"I spend a lot more money at the racetrack than I ever do at a poker machine," the 70-year-old jokes.
There are about 200,000 electronic gaming machines in Australia, with about 600,000 Australians playing them at least weekly, according to a Productivity Commission report released in 2010.
But concerned that 15 per cent of these players are problem gamblers whose money accounts for about 40 per cent of spending, the government has moved to encourage all players to "pre-commit" to a financial limit before they start so they don't over-spend.
Under legislation passed late in 2012, while the scheme will remain voluntary, poker machine manufacturers must put the new pre-commitment technology on all new machines by the end of 2014.
Warnings will also flash up on players' screens with messages questioning them along the lines of, "How long have you been playing?" and "Have you spent beyond your limits?"
The biggest clubs will also limit daily cash withdrawals from automatic teller machines to Aus$250 (S$319), although this will not apply to casinos.
Anti-gambling campaigners say the scheme does not go far enough, since played at high intensity, it is easy to lose Aus$1,500 or more an hour on a poker machine.
"We think it's next to useless," said Erin McMallum, whose Getup! organisation has been pushing for maximum bets to be dropped to one dollar, a move that would limit losses to about Aus$120 an hour.
"People don't voluntarily restrict themselves. Half the time they don't even realise they have a problem."
McMallum said problem gambling is widespread in Australia, with many stories of people losing their homes, their relationships and even family members to suicide.
"Australia does have quite a unique problem in relation to problem gambling addiction, especially to poker machines," she said.
"The machines here are prolific, they are exceptionally high loss, and you can find them almost anywhere - every club, pub, bar, casino. They are hard to avoid if you do happen to have an addiction."
The clubs industry, which derives revenue from the pokies, is also non-plussed by voluntary pre-commitment, with the executive director of Clubs Australia, Anthony Ball, saying players would be reluctant to use it.
"Let's remember, people are playing a poker machine for the same reason they might bet on a horse or play the lotteries - they want to win. It's a feeling of freedom, it's their recreation," he said.
"To get a card, to register brings a whole different feel to it."
Australians love a gamble, with the Melbourne Cup horse race known as "the race that stops a nation" and the national day to commemorate war dead, Anzac Day, known for its "two-up" betting on the toss of a coin.
"The punt is engrained in Australian culture," explains Ball.
Club membership is around 11.6 million people out of a population of around 23 million, and the industry says it employs 96,000, making an economic contribution of some Aus$7.2 billion each year.
What concerns Ball is that the national government has for the first time ever, with the voluntary pre-commitment legislation, "involved itself in the regulation of poker machines".
Ball said the technology would not be a "silver bullet" for problem gambling, and the government's plan for pre-commitment to be mandatory in the Canberra region as part of a trial will fail dismally.
"We think that mandatory pre-commitment will not help people - you don't give a problem gambler a gambling card, that doesn't work. It's like giving an alcoholic drinking tickets. It's a crazy thing to do," he said.
"We say you need to get to those people and take them away from the gambling environment and into an effective treatment regime." |
Adaptively Optimizing the Algorithms for Adaptive Antenna Arrays for Randomly Time-Varying Mobile Communications Systems Abstract : Adaptive antenna arrays are widely used and have great promise to reduce the effects of interference and to increase capacity in mobile communications systems. Consider a single cell system with an (receiving) antenna array at the base station. The usual algorithms for obtaining the antenna weights for the adaptive array depend on parameters that are held fixed no matter what the operating situation, and the performance can strongly depend on the values of these parameters. |
.......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... ..........
Ghost is continually writing and has new music always in the works.
“I usually write a lot,” Nameless Ghoul said. “I don’t make an album and don’t write for two years and then end up with a blank paper starting over.”
ADVERTISEMENTSkip
The band’s next album, tentatively planned for release this time next year, has a darker theme than its previous album “Meliora,” released in 2015.
“Having in mind that the previous record was about the absence of God or the absence of deities, this new one is going to be about the return of God,” Nameless Ghoul said. “You know God’s wrath cast upon the suffering humans, so it will be a little bit more biblical in that sense, which in turn makes it darker, a little bit more apocalyptic, I think. That’s basically what I can tell you about it right now.”
Music for the new album has been in the works for a few years.
“I constantly work with material that could be 2 years old, 5 years old, 10 years old, as well as new things,” Nameless Ghoul said. “It’s a pick and mix of a lot of different ideas and stuff laying around, a lot of new stuff being added to the pile. Yeah, it’s a constant thinking ahead, and now, already now, I’m thinking about album No. 5, because there are songs coming out now or coming up being written that I feel like that won’t fit into the new album, so I’ll put that one onto the next one instead.”
Ghost is enjoying praise for its EP “Popestar,” which features five songs, including “Square Hammer,” which has garnered a lot of attention. The song is a good opener for Ghost’s live shows, according to Nameless Ghoul. Ghost has a shorter set as supporting act for Iron Maiden but it will still have the theatrics that Ghost is known for.
“Obviously, it’s very theatrical,” Nameless Ghoul said. “On our support shows like these, we tend to go for the more immediate material. But I think we’ve managed to jam in as much as we could in 45 minutes to sort of illustrate what we are about.” |
import { AbstractControl, ValidatorFn, Validators } from '@angular/forms';
export function requiredIfFieldHasValue(fieldName: string, values: Array<string>): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
if (!control.root) {
return null;
}
let field = control.root.get(fieldName);
if (!field) {
return null;
}
return values.indexOf(field.value) > -1 ?
Validators.required(control) : null;
};
}
|
There's already been a heated discussion on MNF as Gary Neville and Jamie Carragher discuss Louis van Gaal's 3-5-2 system. There's already been a heated discussion on MNF as Gary Neville and Jamie Carragher discuss Louis van Gaal's 3-5-2 system.
Gary Neville has warned Louis van Gaal that he must learn from the expensive mistakes of the previous Manchester United regime and not “panic buy” before the transfer window closes.
The Sky Sports pundit says his former club need to make additions to the squad if they are to compete for major honours again, but urged caution over wasting millions on the wrong type of player.
United have spent £165million on the likes of Juan Mata and Marouane Fellaini in the last five transfer windows – only PSG have spent more across Europe in that period – and Neville feels much of that money was spent unwisely
And he says Van Gaal must adopt a different transfer policy to David Moyes, despite the supporters calling for more money to be spent.
Neville told Monday Night Football: “In the last five transfer windows they have spent some money. In the previous ones to that, maybe there was under-investment because Sir Alex was happy with the squad that he had.
Man Utd signings Ander Herrera (£29m)
Luke Shaw (£27m)
Juan Mata (£37m)
Marouane Fellaini (£27.5m)
Wilfried Zaha (£15m)
Total: £135.5m
Neville's alternative signings Gareth Bale (£86m)
Toni Kroos (£24m)
Cesc Fabregas (£30m)
Filipe Luis (£20m)
Total: £160m
“I like to go back and look at things. We were sat here 12 months ago and as a Manchester United fan if you’d said to me the champions of England, who’d just beaten Swansea away from home, were going to spend £140million in the next 12 months and be where they are today I’d say you’re mad.
“Of course they need to spend because they have to; they have to bring more players in. There’s no doubt about that. But it’s critical they bring the right players in.
“They’ve spent £140million in the last 12 months and they’ve got Zaha, Herrera, Shaw, Fellaini and Mata. Last season I’d argue that some of those buys were panic buys, who didn’t fit the philosophy – and they’re paying for it now.
“For that money, or a bit more money, you could have got Gareth Bale, Toni Kroos, Cesc Fabregas and Filipe Luis. For the same level of money that they’ve spent you could have got those four players into that squad.
“Put those four players in and we’d have been saying United were favourites for the league maybe and maybe the Champions League?
“They’ve got to recruit well and they’ve got a manager now who won’t panic buy, he won’t breech his philosophy and he is strong enough to sit there if he can’t get the players.
“The key is can they get the players that they want? It’s not just spending money for the sake of it.
“Last year they brought in two players who I don’t think suited what they wanted at the time – and that’s a bigger problem.”
Van Gaal: Suffered a 2-1 defeat at home to Swansea in his first league game
Van Gaal admitted after the club’s opening-day defeat to Swansea that he would be looking to bring in new faces.
Highest net spenders in Europe (last 5 transfer windows) PSG (£165m)
Man Utd (£165m)
Barcelona (£155m)
Chelsea (£137m)
Real Madrid (£126m)
Man City (£126m)
United adopted a 3-5-2 in that game and while Neville isn’t convinced he wants to use that system in the long term, he says the transfer policy will tell us more about the Dutchman’s approach.
“He’s the type of manager who’s confident enough to come to this country and think ‘I’m going to do it a different way’,” he added.
“I think we’ll know in the next few weeks; we’ll know in the recruitment and the type of players that are brought in.
“Danny Blind has been mentioned and Thomas Vermaelen was mentioned a couple of weeks ago. That suggests he’s looking for players that fit the system.
“I believe strongly that outside centre-backs in the back three, who have to defend the wide areas and accept the ball in full-back positions, and wing-backs, who have to be equally as good at one end of the pitch as they are at the other, are specialist positions.
“We’ll see by his recruitment. At the moment I think he’s forced to play this formation because of the players he’s got and the deficiencies he has in his back two, midfield area and the fact he hasn’t got world-class wingers.” |
A federal judge ruled last week that Indiana overstepped in blocking public funding to Planned Parenthood. A lawsuit filed Monday by Planned Parenthood of Kansas and Mid-Missouri likely will reach the same conclusion.
But anti-abortion lawmakers and Gov. Sam Brownback may not care. That’s because new licensing requirements they imposed could close the state’s three remaining abortion clinics — which appears to be the goal.
U.S. District Judge Tanya Walton Pratt issued a preliminary injunction against an Indiana law that, similar to a new Kansas law, cuts off health and family planning funds to Planned Parenthood. She ruled that the law conflicts with a federal statute that allows Medicaid beneficiaries to choose their health care providers. |
ADVERTISEMENT
As long as men have written female characters, entertainment has been packed with girls whose individuality is just a means for some tiresome hero to work out his own ennui. From William Shakespeare's Juliet Capulet to Truman Capote's Holly Golightly, the characters' uniqueness was like an ideological rib-eye that the down-on-his-luck hero could feast on to thrive and prosper in his own life. These idiosyncratic muses were finally given a common name in 2007: The "Manic Pixie Dream Girl" — and now, in 2013, it's time to put the term to rest.
The term — which is often shortened to MPDGs — was originally coined by The AV Club's Nathan Rabin to describe Kirsten Dunst's character in Cameron Crowe's Elizabethtown. Rabin wrote:
No existential quandary is so great that it can't be solved by the perfect combination of pop song and dream girl, a world of giddy pop epiphanies and gentle humanism unencumbered by protective irony or sneering cynicism. […] Dunst embodies a character type I like to call The Manic Pixie Dream Girl (see Natalie Portman in Garden State for another prime example). The Manic Pixie Dream Girl exists solely in the fevered imaginations of sensitive writer-directors to teach broodingly soulful young men to embrace life and its infinite mysteries and adventures. The Manic Pixie Dream Girl is an all-or-nothing-proposition. Audiences either want to marry her instantly (despite The Manic Pixie Dream Girl being, you know, a fictional character) or they want to commit grievous bodily harm against them and their immediate family. [The AV Club, 2007]
But what, exactly, makes a character a Manic Pixie Dream Girl has always been a fluid construct. Rabin's oft-quoted definition doesn't actually describe the girl; it describes the audience's experience of watching her. But with the references to Portman and Dunst's roles in Garden State and Elizabethtown, a rough list of attributes could be inferred: The MPDG lives life "differently" than the average girl. She loves indie music, whimsy, and any number of idiosyncratic hobbies, from barefoot tap dancing to driving on "gloriously confusing" roads.
The perfect timing of Rabin's cleverly worded phrase allowed it to take off like wildfire as a kind of shorthand among film fans. After all, Zooey Deschanel, who's often cited as a real-life Manic Pixie Dream Girl, was just about to break into the mainstream. And just a few years earlier, Charlie Kaufman and Michel Gondry put themselves on the map when they collaborated to create the MPDG Clementine Kruczynski, Kate Winslet's wacky-hair-colored character in Eternal Sunshine of the Spotless Mind.
Given the term's popularity, it only took a year for the The AV Club to return to the topic, expanding the confines of the term beyond the contemporary to include the likes of Audrey Hepburn (Breakfast at Tiffany's), Katharine Hepburn (Bringing Up Baby), Shirley Maclaine (The Apartment), and Goldie Hawn (Butterflies Are Free). With each step, the MPDG designation was expanded to encompass more female characters — but the inclusion of Diane Keaton's complex, wonderfully realized Annie Hall was a tip-off that the term "Manic Pixie Dream Girl" was beginning to expand in some insidious ways.
In its expansion, the Manic Pixie Dream Girl designation moved from putting a spotlight on questionably hollow female characters to marginalizing and dismissing all manner of diverse female characters on film. Pulp Fiction's Mrs. Mia Wallace was thrown into the mix for being impulsive and having bangs, though she never teaches Vincent Vega about life. Alyssa is a kind of muse in the oft-listed Chasing Amy, but her characterization is far from superficial. Even Belle from Disney's Beauty and the Beast has received the designation.
Slate wondered recently if the archetype was dead. Many of the top "offenders" came out years ago — and in recent years, films like (500) Days of Summer and Ruby Sparks have shown the holes of the archetype; Deschanel's Summer struggled to have a relationship with a man who idealized her into quirks, and Zoe Kazan's Ruby was stuck at the whims of the male author who created her and wants to control her. But despite these subversions, the Manic Pixie Dream Girl label thrives because its boundaries continue to grow — and because the internet age thrives with a new group to snark about.
"Manic Pixie Dream Girl" was useful when it commented on the superficiality of female characterizations in male-dominated journeys, but it has since devolved into a pejorative way to deride unique women in fiction and reality. It's no longer a call to arms for more well-rounded female characters in fiction, but a way to chastise difference from the norm. MPDG is now the catch-all term for unusual interests and style — a film-related off-shoot of the Hipster designation evolving from people who wear/use things ironically to anyone with retro interests. Last week, Rookie Mag ran a piece by a girl who fears that her genuine interests have made many pigeonhole her as a real-life quirky MPDG. A woman at XOJane writes: "I was a quirky girl and on top of that, I wrote really well to the hearts and minds of other quirky girls … Could I really be the type of woman whose very existence was demeaning to other women?"
Instead of bolstering women to demand more independent and fully-realized female characters, the term has divided them, simply because the Manic Pixie Dream Girl is different. The truth is that the MPDG is just a part of a larger problem; countless female characters have been written just to teach men to embrace life and be successful. The MPDG's joie de vivre makes her stick out among female characters, but in a way that prevents more serious dialogue. She's easier to lump together and dismiss, as if the MPDG isn't part of a much bigger problem that has nothing to do with the music a character listens to or the clothing a character wears.
What makes this problem even more frustrating is that many MPDGs do break some genuine ground for female characters. These aren't women written as conforming to peer pressure, adding to the smattering of superficial female characters lacking unique personas. They're not submitting to makeovers that will turn them from outcast to queen bee. Holly Golightly isn't ashamed to be an escort in a world where women are expected to be proper; Portman's Sam takes pride in the way she finds humor in life; Deschanel's Summer doesn't care if the outside world thinks she's weird.
"Manic Pixie Dream Girl" once had its place as a clever way to describe female characters that were all quirk and no depth, existing solely for the benefit of a broody male lead — but now, it's a term more damaging than it is helpful. "Manic Pixie Dream Girl" is used too often to chastise the one thing that gives supporting women that little bit of oomph in marginalized roles — a personality that expands beyond basic gender stereotypes like boys, clothing, and gossip, seen so often in entertainment. "Manic Pixie Dream Girl" distracts us from the real problems of superficial female characters, and it inspires real-life women to question the validity and worth of each other's interests. And when a term has outlived its usefulness and become a part of the very marginalizing trend that it was designed to rally against, it's time to put it to rest for good.
Girls on Film is a weekly column focusing on women and cinema. It can be found at TheWeek.com every Friday morning. And be sure to follow the Girls on Film Twitter feed for additional femme-con. |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2018 by <NAME> : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.excelwriter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.steps.StepMockUtil;
import org.pentaho.di.trans.steps.mock.StepMockHelper;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/**
* @author <NAME>
*/
public class ExcelWriterStep_FormulaRecalculationTest {
private ExcelWriterStep step;
private ExcelWriterStepData data;
private StepMockHelper<ExcelWriterStepMeta, StepDataInterface> mockHelper;
@Before
public void setUp() throws Exception {
mockHelper =
StepMockUtil.getStepMockHelper( ExcelWriterStepMeta.class, "ExcelWriterStep_FormulaRecalculationTest" );
step = new ExcelWriterStep(
mockHelper.stepMeta, mockHelper.stepDataInterface, 0, mockHelper.transMeta, mockHelper.trans );
step = spy( step );
// ignoring to avoid useless errors in log
doNothing().when( step ).prepareNextOutputFile();
data = new ExcelWriterStepData();
step.init( mockHelper.initStepMetaInterface, data );
}
@After
public void cleanUp() {
mockHelper.cleanUp();
}
@Test
public void forcesToRecalculate_Sxssf_PropertyIsSet() throws Exception {
forcesToRecalculate_Sxssf( "Y", true );
}
@Test
public void forcesToRecalculate_Sxssf_PropertyIsCleared() throws Exception {
forcesToRecalculate_Sxssf( "N", false );
}
@Test
public void forcesToRecalculate_Sxssf_PropertyIsNotSet() throws Exception {
forcesToRecalculate_Sxssf( null, false );
}
private void forcesToRecalculate_Sxssf( String property, boolean expectedFlag ) throws Exception {
step.setVariable( ExcelWriterStep.STREAMER_FORCE_RECALC_PROP_NAME, property );
data.wb = spy( new SXSSFWorkbook() );
step.recalculateAllWorkbookFormulas();
if ( expectedFlag ) {
verify( data.wb ).setForceFormulaRecalculation( true );
} else {
verify( data.wb, never() ).setForceFormulaRecalculation( anyBoolean() );
}
}
@Test
public void forcesToRecalculate_Hssf() throws Exception {
data.wb = new HSSFWorkbook();
data.wb.createSheet( "sheet1" );
data.wb.createSheet( "sheet2" );
step.recalculateAllWorkbookFormulas();
if ( !data.wb.getForceFormulaRecalculation() ) {
int sheets = data.wb.getNumberOfSheets();
for ( int i = 0; i < sheets; i++ ) {
Sheet sheet = data.wb.getSheetAt( i );
assertTrue( "Sheet #" + i + ": " + sheet.getSheetName(), sheet.getForceFormulaRecalculation() );
}
}
}
}
|
<gh_stars>0
package seedu.address.model;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static seedu.address.testutil.Assert.assertThrows;
import org.junit.jupiter.api.Test;
public class UserPrefsTest {
public static final int VALID_MIN_FLOOR_SETTINGS = 1;
public static final int VALID_MAX_FLOOR_SETTINGS = 9;
public static final int VALID_MIN_ROOM_SETTINGS = 1;
public static final int VALID_MAX_ROOM_SETTINGS = 20;
public static final int INVALID_MIN_FLOOR_SETTINGS = -1;
public static final int INVALID_MAX_FLOOR_SETTINGS = 1000;
public static final int INVALID_MIN_ROOM_SETTINGS = 1;
public static final int INVALID_MAX_ROOM_SETTINGS = 2000;
@Test
public void setGuiSettings_nullGuiSettings_throwsNullPointerException() {
UserPrefs userPref = new UserPrefs();
assertThrows(NullPointerException.class, () -> userPref.setGuiSettings(null));
}
@Test
public void setAddressBookFilePath_nullPath_throwsNullPointerException() {
UserPrefs userPrefs = new UserPrefs();
assertThrows(NullPointerException.class, () -> userPrefs.setAddressBookFilePath(null));
}
@Test
public void setValidFloorSettings() {
UserPrefs userPrefs = new UserPrefs();
userPrefs.setMinFloorSettings(VALID_MIN_FLOOR_SETTINGS);
userPrefs.setMaxFloorSettings(VALID_MAX_FLOOR_SETTINGS);
// valid
assertEquals(VALID_MIN_FLOOR_SETTINGS, userPrefs.getMinFloorSettings());
assertEquals(VALID_MAX_FLOOR_SETTINGS, userPrefs.getMaxFloorSettings());
}
@Test
public void setInvalidFloorSettings() {
UserPrefs userPrefs = new UserPrefs();
userPrefs.setMinFloorSettings(INVALID_MIN_FLOOR_SETTINGS);
userPrefs.setMaxFloorSettings(INVALID_MAX_FLOOR_SETTINGS);
// resets to default values
assertEquals(userPrefs.DEFAULT_MIN_FLOOR_SETTINGS, userPrefs.getMinFloorSettings());
assertEquals(userPrefs.DEFAULT_MAX_FLOOR_SETTINGS, userPrefs.getMaxFloorSettings());
}
@Test
public void setValidRoomSettings() {
UserPrefs userPrefs = new UserPrefs();
userPrefs.setMinRoomSettings(VALID_MIN_ROOM_SETTINGS);
userPrefs.setMaxRoomSettings(VALID_MAX_ROOM_SETTINGS);
// valid
assertEquals(VALID_MIN_ROOM_SETTINGS, userPrefs.getMinRoomSettings());
assertEquals(VALID_MAX_ROOM_SETTINGS, userPrefs.getMaxRoomSettings());
}
@Test
public void setInvalidRoomSettings() {
UserPrefs userPrefs = new UserPrefs();
userPrefs.setMinRoomSettings(INVALID_MIN_ROOM_SETTINGS);
userPrefs.setMaxRoomSettings(INVALID_MAX_ROOM_SETTINGS);
// resets to default values
assertEquals(userPrefs.DEFAULT_MIN_ROOM_SETTINGS, userPrefs.getMinRoomSettings());
assertEquals(userPrefs.DEFAULT_MAX_ROOM_SETTINGS, userPrefs.getMaxRoomSettings());
}
}
|
/**
* Called when the build load button is clicked.
*/
@FXML
public void handleBulkPathfinderLoad()
{
DirectoryChooser fileChooser = new DirectoryChooser();
fileChooser.setTitle("Open Pathfinder File");
File choosenFile = fileChooser.showDialog(null);
if (choosenFile != null)
{
try
{
Files.walk(choosenFile.toPath()).filter(Files::isRegularFile).forEach(this::loadPathfinderFile);
}
catch (IOException ex)
{
sLOGGER.log(Level.ERROR, "Error crawling pathfinder directory", ex);
}
}
} |
// Clear the contents of this logger. Useful for reducing the event output to write more readable tests.
func (l *Logger) Clear() {
if l != nil {
l.b.Reset()
}
} |
<filename>platforms/spring-boot/components-starter/camel-hazelcast-starter/src/test/java/org/apache/camel/component/hazelcast/springboot/customizer/HazelcastInstanceCustomizerTest.java
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.hazelcast.springboot.customizer;
import java.util.List;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import org.apache.camel.component.hazelcast.HazelcastComponent;
import org.apache.camel.component.hazelcast.list.HazelcastListComponent;
import org.apache.camel.component.hazelcast.set.HazelcastSetComponent;
import org.apache.camel.component.hazelcast.topic.HazelcastTopicComponent;
import org.apache.camel.spi.ComponentCustomizer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootApplication
@SpringBootTest(
classes = {
HazelcastInstanceCustomizerTest.TestConfiguration.class
},
properties = {
"debug=false",
"camel.component.customizer.enabled=false",
"camel.component.hazelcast.customizer.enabled=true",
"camel.component.hazelcast-set.customizer.enabled=true",
"camel.component.hazelcast-topic.customizer.enabled=true"
})
public class HazelcastInstanceCustomizerTest {
@Autowired
HazelcastInstance instance;
@Autowired
HazelcastTopicComponent topicComponent;
@Autowired
List<ComponentCustomizer<HazelcastTopicComponent>> topicCustomizers;
@Autowired
HazelcastSetComponent setComponent;
@Autowired
List<ComponentCustomizer<HazelcastSetComponent>> setCustomizers;
@Autowired
HazelcastListComponent listComponent;
@Test
public void testInstanceCustomizer() throws Exception {
Assert.assertNotNull(instance);
Assert.assertNotNull(topicComponent);
Assert.assertEquals(1, topicCustomizers.size());
Assert.assertEquals(instance, topicComponent.getHazelcastInstance());
Assert.assertNotNull(setComponent);
Assert.assertEquals(1, setCustomizers.size());
Assert.assertEquals(instance, setComponent.getHazelcastInstance());
Assert.assertNotNull(listComponent);
Assert.assertNull(listComponent.getHazelcastInstance());
}
@Configuration
public static class TestConfiguration {
@Bean(destroyMethod = "shutdown")
public HazelcastInstance hazelcastInstance() {
return Hazelcast.newHazelcastInstance();
}
}
}
|
A Study on Evalution of HR Outsourcing Providers Based on Multi-Criteria Decision Making with Linguistic Preference Information In this paper, the problem of HR outsourcing providers evaluation is studied. Based on Extended Ordered Weighted Averaging (EOWA) operator, an approach of multi-criteria decision making with linguistic preference information is introduced to the problem. An illustrative numerical example is also provided to illustrate the feasibility and practicality of the proposed approach. |
import os
import sys
import tempfile
import pytest
import six
from geonotebook import config
config_paths = {
"/etc/geonotebook.ini": None,
"/usr/etc/geonotebook.ini": None,
"/usr/local/etc/geonotebook.ini": None,
os.path.join(sys.prefix, "etc/geonotebook.ini"): None,
os.path.expanduser("~/.geonotebook.ini"): None,
os.path.join(os.getcwd(), ".geonotebook.ini"): None,
os.path.expandvars("${GEONOTEBOOK_INI}"): None
}
def make_config(settings):
"""Generate a config file string from a settings object."""
s = ''
for section, defs in six.iteritems(settings):
s += '[%s]\n' % section
for key, value in six.iteritems(defs):
s += '%s = %s\n' % (key, value)
return s
def mock_file(content):
"""Generate a file like object containing the given content."""
temp = tempfile.TemporaryFile(mode='r+')
temp.write(content)
temp.seek(0)
return temp
class MockFileOpener(object):
"""Mock the builtin open object.
Takes a single object as an argument. The keys
of this object are a list of files handled by the
mocked open method. The value of each key is a string
that is passed back to the ``read`` method.
"""
def __init__(self, files=None):
if files is None:
files = {}
self.files = files
self._open = six.moves.builtins.open
def open(self, name, mode='r', **kwargs):
if name not in self.files:
return self._open(name, mode, **kwargs)
if mode != 'r':
raise Exception('Mocked files are read only')
if self.files[name] is None:
raise IOError(name)
return mock_file(self.files[name])
@pytest.fixture
def mockopen(monkeypatch):
manager = MockFileOpener()
monkeypatch.setattr(six.moves.builtins, 'open', manager.open)
return manager
@pytest.fixture
def mockconfig(mockopen):
files = {}
files.update(config_paths)
mockopen.files = files
return mockopen
def test_no_config_file(mockconfig):
with pytest.raises(RuntimeError):
config.Config()
def test_override_config(mockconfig):
mockconfig.files['/etc/geonotebook.ini'] = make_config({
'basemap': {
'url': 'url a',
'attribution': 'attribution a'
}
})
mockconfig.files['/usr/etc/geonotebook.ini'] = make_config({
'basemap': {
'url': 'url b',
'attribution': 'attribution b'
}
})
mockconfig.files['/usr/local/etc/geonotebook.ini'] = make_config({
'basemap': {
'attribution': 'attribution c'
}
})
mockconfig.files[
os.path.expanduser('~/.geonotebook.ini')
] = make_config({
'basemap': {
'attribution': 'attribution d'
}
})
c = config.Config()
assert c.basemap == {'url': 'url b', 'attribution': 'attribution d'}
def test_custom_path(mockconfig):
mockconfig.files['foo.ini'] = make_config({
'test': {
'foo': 'bar'
}
})
c = config.Config(path='foo.ini')
assert c.config.get('test', 'foo') == 'bar'
def test_vis_server_geoserver(mockconfig):
mockconfig.files['/etc/geonotebook.ini'] = make_config({
'default': {
'vis_server': 'geoserver'
},
'geoserver': {
'username': 'admin',
'password': '<PASSWORD>',
'url': 'http://localhost'
}
})
c = config.Config()
assert c.vis_server.base_url == 'http://localhost'
def test_vis_server_invalid(mockconfig):
mockconfig.files['/etc/geonotebook.ini'] = make_config({
'default': {
'vis_server': 'invalid'
}
})
c = config.Config()
with pytest.raises(NotImplementedError):
c.vis_server
|
Simulation of pulmonary O2 uptake during exercise transients in humans. Computer simulation of blood flow and O2 consumption (QO2) of leg muscles and of blood flow through other vascular compartments was made to estimate the potential effects of circulatory adjustments to moderate leg exercise on pulmonary O2 uptake (VO2) kinetics in humans. The model revealed a biphasic rise in pulmonary VO2 after the onset of constant-load exercise. The length of the first phase represented a circulatory transit time from the contracting muscles to the lung. The duration and magnitude of rise in VO2 during phase 1 were determined solely by the rate of rise in venous return and by the venous volume separating the muscle from the lung gas exchange sites. The second phase of VO2 represented increased muscle metabolism (QO2) of exercise. With the use of a single-exponential model for muscle QO2 and physiological estimates of other model parameters, phase 2 VO2 could be well described as a first-order exponential whose time constant was within 2 s of that for muscle QO2. The use of unphysiological estimates for certain parameters led to responses for VO2 during phase 2 that were qualitatively different from QO2. It is concluded that 1) the normal response of VO2 in humans to step increases in muscle work contains two components or phases, the first determined by cardiovascular phenomena and the second primarily reflecting muscle metabolism and 2) the kinetics of VO2 during phase 2 can be used to estimate the kinetics of muscle QO2. The simulation results are consistent with previously published profiles of VO2 kinetics for square-wave transients. |
Expression of mutant and wild-type gag proteins for gene therapy in HIV-1 infection. The effect of expression of defective HIV-based retroviral constructs in CD4-positive lymphocytes on subsequent infection of the cell by HIV-1 was studied. A vector containing a N terminally elongated gag protein which was noncleavable and myristoylation negative was not effective at inhibiting HIV assembly or viral replication in the culture. Expression of a wild-type HIV gag in trans led to an increase in cytopathicity within the culture such that all the cells died. A control LTR containing vector had no effect. A myristoylation negative gag would not appear to be a useful dominant negative inhibitor of HIV replication, but might be usable as a post-exposure immunogen. Post-infective immunisation with wild-type HIV-1 gag would appear to risk increasing virus-related cytopathicity. |
Liver-X-Receptors (LXRs) are members of the nuclear hormone receptor superfamily. The LXRs are activated by endogenous oxysterols and glucose and regulate the transcription of genes controlling multiple metabolic pathways. Two subtypes, LXRalpha and LXRbeta, have been described (Willy, P. J. et al., Genes Dev. 1995, 9:1033-45; Song, C. et al., Proc Natl Acad Sci USA. 1994, 91:10809-13). LXRbeta is ubiquitously expressed, while LXRalpha is predominantly expressed in cholesterol metabolizing tissues such as the liver, adipose, intestine and macrophage. The LXRs modulate a variety of physiological responses including regulation of cholesterol absorption, cholesterol elimination (bile acid synthesis), and transport of cholesterol from peripheral tissues via plasma lipoproteins to the liver. The LXRs also appear to regulate genes involved in glucose metabolism, cholesterol metabolism in the brain, cellular differentiation and apopotosis, inflammation, and infectious diseases (Geyeregger, R. et al., Cell. Mol. Life. Sci. 2006, 63:524-539.
About half of all patients with coronary artery disease have low concentrations of plasma high-density lipoprotein cholesterol (HDL-C). The atheroprotective function of HDL was first highlighted almost 25 years ago and stimulated exploration of the genetic and environmental factors that influence HDL-C levels (Miller N E., Lipids 1978, 13:914-9). The protective function of HDL derives from its role in a process termed reverse cholesterol transport (Forrester, J. S., and Shah, P. K., Am. J. Cardiol. 2006, 98:1542-49. HDL mediates the removal of cholesterol from cells in peripheral tissues, including macrophage foam cells in the atherosclerotic lesions of the arterial wall. HDL delivers its cholesterol to the liver and sterol-metabolizing organs for conversion to bile and elimination in feces. Studies have shown that HDL-C levels are predictive of coronary artery disease risk independently of low-density lipoprotein cholesterol (LDL-C) levels (Gordon, T. et al., Am J. Med. 1977, 62:707-14).
At present, the estimated age-adjusted prevalence among Americans age 20 and older who have HDL-C of less than 35 mg/dl is 16% (males) and 5.7% (females). A substantial increase of HDL-C is currently achieved by treatment with niacin in various formulations. However, the substantial unfavorable side-effects limit the therapeutic potential of this approach.
It has been observed that as many as 90% of the 14 million diagnosed type 2 diabetic patients in the United States are overweight or obese, and a high proportion of type 2 diabetic patients have abnormal concentrations of lipoproteins. Studies have shown that the prevalence of total cholesterol >240 mg/dl is 37% in diabetic men and 44% in women. The rates for LDL-C >160 mg/dl are 31% and 44%, and for HDL-C <35 mg/dl are 28% and 11%, in diabetic men and women respectively. Diabetes is a disease in which a patient's ability to control glucose levels in blood is decreased because of partial impairment in response to the action of insulin. Type II diabetes (T2D) is also called non-insulin dependent diabetes mellitus (NIDDM) and has been shown to afflict 80-90% of all diabetic patients in developed countries. In T2D, the pancreatic Islets of Langerhans continue to produce insulin. However, the target organs for insulin action, mainly muscle, liver and adipose tissue, exhibit a profound resistance to insulin stimulation. The body continues to compensate by producing unphysiologically high levels of insulin, which ultimately decreases in the later stages of the disease, due to exhaustion and failure of pancreatic insulin-producing capacity. Thus, T2D is a cardiovascular-metabolic syndrome associated with multiple co-morbidities, including insulin resistance, dyslipidemia, hypertension, endothelial dysfunction and inflammatory atherosclerosis.
The first line of treatment for dyslipidemia and diabetes at present generally involves a low-fat and low-glucose diet, exercise and weight loss. However, compliance can be moderate, and as the disease progresses, treatment of the various metabolic deficiencies becomes necessary with lipid-modulating agents such as statins and fibrates for dyslipidemia, and hypoglycemic drugs, e.g. sulfonylureas, metformin, or insulin sensitizers of the thiazolidinedione (TZD) class of PPARγ-agonists, for insulin resistance. Recent studies provide evidence that modulators of LXRs would result in compounds with enhanced therapeutic potential, and as such, modulators of LXRs should improve the plasma lipid profile, and raise HDL-C levels (Lund, E. G. et al., Arterioscler. Thromb. Vasc. Biol. 2003, 23:1169-77; Mitro, N. et al., Nature 2007, 445:219-23). LXRs are also known to control the efflux of cholesterol from the macrophage foam cell of the atherosclerotic lesion, and agonists of LXRs have been shown to be atheroprotective (Joseph, S. B. and Tontonoz, P., Curr. Opin. Pharmacol. 2003, 3:192-7). Thus, modulators of LXRs would be effective treatments for the atherosclerotic disease which underlies the cardiovascular morbidity and mortality of stroke and heart disease. Recent observations also suggest that there is an independent LXR mediated effect on insulin-sensitization in addition to its role in atheroprotection (Cao, G. et al., J Biol. Chem. 2003, 278:1131-6). Thus LXR modulators can also show superior therapeutic efficacy on HDL-raising and atheroprotection, with additional effects on diabetes, compared to current therapies.
Compounds that bind to and activate LXR alpha and LXR beta have previously been suggested (e.g.: WO 03/099769). However, there is still a need for new compounds with improved properties. The present invention provides the novel compounds of formula (I) which bind to LXR alpha and/or LXR beta. The compounds of the present invention unexpectedly exhibit improved pharmacological properties compared to the compounds known in the art, concerning e.g. metabolic stability, selectivity, bioavailability and activity. |
import json
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterable, List, Union
if TYPE_CHECKING:
from httpx import AsyncClient
E_HALL_NAME = "成绩查询"
E_HALL_ID = "4768574631264620"
GRADES_URL = ("http://ehall.xidian.edu.cn/jwapp/sys/cjcx/modules/cjcx/xscjcx.do",)
query = [
{
"name": "XNXQDM",
"value": "2019-2020-1",
"linkOpt": "and",
"builder": "m_value_equal",
},
{
"name": "SFYX",
"caption": "是否有效",
"linkOpt": "AND",
"builderList": "cbl_m_List",
"builder": "m_value_equal",
"value": "1",
"value_display": "是",
},
{
"name": "SHOWMAXCJ",
"caption": "显示最高成绩",
"linkOpt": "AND",
"builderList": "cbl_m_List",
"builder": "m_value_equal",
"value": "0",
"value_display": "否",
},
]
@dataclass
class Grade(object):
course: str
score: Union[str, int]
is_pass: bool
@classmethod
def by_data(cls, raw_data: dict):
return cls(
lesson=raw_data["KCM"],
final=raw_data["ZCJ"],
effective=bool(int(raw_data["SFYX"])),
is_pass=bool(int(raw_data["SFJG"])),
)
async def get_grades(client: "AsyncClient", term="2019-2020-1") -> List[Grade]:
query[0].update(value=term)
res = await client.post(GRADES_URL, data={"querySetting": query})
return [Grade.by_data(i) for i in res.json()["datas"]["xscjcx"]["rows"]]
def save_scores(grades: Iterable[Grade]):
with open("./scores.json", "w", encoding="utf-8") as fp:
json.dump([i for i in grades], fp, ensure_ascii=False, indent=4)
|
The Pragmatics and Sociolinguistics of Maasai Greetings The speech act of greeting is one of the most frequent linguistic interactional routines performed among the Maasai of Arusha in Tanzania. The structure of their greetings demonstrates a number of culturally specific features of Maasai society, illuminated by analysing data collected through interviews and non-participatory observations of both men and women. The structure of Maasai greetings highlights the importance of maintaining gentility and exercising deference in everyday affairs. Politeness and civility are demonstrated by acknowledging vertical ranking between those who greet each other; sustaining propriety is determined by recognition of social status and by a heightened gender sensitivity which is ever present. Good manners are performed not only by following verbal codes scrupulously, such as tone of voice and word choice; non-verbal signals are just as important in the demonstration of Maasai etiquette; these include the posture adopted when a greeting is initiated, the adjustment of spatial distance and by whom once a greeting has commenced, the manner of shaking hands, as well as the length of time spent greeting. |
<gh_stars>1-10
/*
* loc_incl.h - local include file for stdio library
*/
/* $Header: loc_incl.h,v 1.5 91/06/10 17:07:18 ceriel Exp $ */
#define io_testflag(p,x) ((p)->_flags & (x))
char *_ecvt(double value, int ndigit, int *decpt, int *sign);
char *_fcvt(double value, int ndigit, int *decpt, int *sign);
#define FL_LJUST 0x0001 /* left-justify field */
#define FL_SIGN 0x0002 /* sign in signed conversions */
#define FL_SPACE 0x0004 /* space in signed conversions */
#define FL_ALT 0x0008 /* alternate form */
#define FL_ZEROFILL 0x0010 /* fill with zero's */
#define FL_SHORT 0x0020 /* optional h */
#define FL_LONG 0x0040 /* optional l */
#define FL_LONGDOUBLE 0x0080 /* optional L */
#define FL_WIDTHSPEC 0x0100 /* field width is specified */
#define FL_PRECSPEC 0x0200 /* precision is specified */
#define FL_SIGNEDCONV 0x0400 /* may contain a sign */
#define FL_NOASSIGN 0x0800 /* do not assign (in scanf) */
#define FL_NOMORE 0x1000 /* all flags collected */
|
Colorectal cancer survivorship statistics: A Veterans Affairs Central Cancer Registry analysis. e267 Background: Our objective was to evaluate VA CRC incidence and survival and compare with the National Cancer Institute's Surveillance, Epidemiology, and End Results (SEER) data. METHODS Data were obtained from VACCR for veterans diagnosed/treated in VA for incident CRC during fiscal years (FY) 2009-2012. Using VHA Support Service Center information about the distribution of VA healthcare system enrollees for corresponding years, we adjusted incidence rates for age and gender to the underlying VA population. Survival data were available through January 2015; thus, patients in the analysis had 3-6 years of follow-up data and were censored accordingly. CRC incidence and survival among VA patients was compared to projected national 2014 CRC-specific SEER and supporting data sources. RESULTS From FY 2009-2012, 12,551 patients (2.6% women; 97.4% men) were in the analytic cohort. Among VACCR patients, the most common tumor location was proximal colon (38%), followed by rectum (31%), distal colon (26%), and other colon (5%). This is comparable to SEER, in which proximal colon and rectum are most common. Among patients in the VACCR, SEER summary stage distribution was: 44% local, 36% regional, 17% distant and 4% unknown. This also aligns with SEER, in which approximately 40% of CRC cases are diagnosed locally. Mirroring SEER, overall VA CRC incidence rate decreased from 0.22 to 0.16 cases per 1,000 veterans in FYs 2009 and 2012. Evaluating survival, median follow-up time was 3.3 years among veterans. The 3-year survival rate for VA patients was 65.9%. Overall 3-year survival is slightly higher for rectal (66.4%) than for colon (65.6%). This is comparable to 5-year SEER survival rates (66.5% and 64.2% for rectal and colon, respectively). Also consistent with SEER, VA CRC patients < 65 have higher rates of 3-year survival than patients > 65 years (74.6% vs. 58.5%, respectively). CONCLUSIONS VACCR data indicate that CRC incidence and survival in FY 2009-2012 approximated SEER projections during a similar timeframe. This suggests that, although VA patients are more complex than the general population, they are diagnosed with comparable CRC locations and stages. |
Inflammatory response to infectious pulmonary injury This review describing the inflammatory response to infectious pulmonary injury is focused on the innate immunity of the distal lung to bacterial pneumonia. The fact that the inflammatory response varies to some extent with the bacterial strain responsible for the infection is emphasised. The key cellular components present in the distal lung are described. The major role of alveolar macrophage is described, inasmuch as it responds to the usual daily challenges of bacteria entering the terminal airways and is capable of initiating an inflammatory reaction if the microbial challenge is either too large or too virulent. Under these conditions, the alveolar macrophages initiate an inflammatory response that recruits large numbers of neutrophils into the alveolar spaces. The strategy of the innate immune response may not be to recognise every possible antigen, but rather to focus on a few, highly conserved structures present in large groups of microorganisms. These structures are referred to as pathogen-associated molecular patterns and the receptors of the innate immune system that evolved to recognise them are called pattern-recognition receptors. The soluble factors in innate defence, such as cytokines, are described, and a last paragraph discusses whether a specific inflammatory response could characterise nosocomial pneumonia. |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu
"""
redis queue输入
"""
import time
from redis_queue import RedisQueue
# 新建队列名字为rq
q = RedisQueue("rq")
for i in range(5):
q.put(i)
print("input key: {} enqueue: {}".format(i, time.strftime("%c")))
time.sleep(0.5)
|
Humanisation of Childbirth 7. The Role of Critical Pedagogy in Midwifery Education In this seventh article of the 19th Midwifery Basics series on humanising birth, the authors discuss the importance of using critical pedagogy as a pathway to transforming maternity care and humanising childbirth. We have a responsibility to students in terms of what and how we teach future generations of midwives. Midwives are guardians of normal birth, and they are also teachers, passing on midwifery technology (knowledge of the art and skill of midwifery) to midwifery students. Midwifery academics in particular, as educators and researchers, are guardians of the discipline and its knowledge base. The authors of this paper, all of whom work in higher education, see education as transformational transformational on a personal level, as well as encompassing the transformation from student to midwife, the transformation of the profession itself and, ultimately, the transformation of society. |
1. Field of the Invention
The present invention relates generally to privacy protection and, more particularly, to systems and methods that protect private information provided to a third party.
2. Description of Related Art
Electronic commerce (“eCommerce”) has dramatically increased in recent years. Many server operators now have web sites on the Internet that users can access to seek out or research information, purchase or research goods and/or services, and communicate with other users, web sites, or services. In a typical commercial transaction, a user browses a vendor's catalog, selects a product, places an order for the product, and pays for the product, all electronically over the Internet.
In some conventional eCommerce systems, the server operator requests the user to provide confidential personal and/or corporate information, such as a name, address, telephone number, or account data, in order to proceed with the on-line transaction. The user transmits the confidential information to the server operator over the Internet. The server operator may then use the confidential information to complete the transaction.
In other conventional eCommerce systems, a growing number of transactions are performed across intranets and internets (including the Internet) by protocols or mechanisms other than the hypertext transfer protocol (http://). Such non-http-based transactions use a myriad of different protocols and languages to encode the information, including electronic data interchange (EDI), file transfer protocol (FTP), extensible markup language (XML) send and receive, standard generalized markup language (SGML), etc. Furthermore, transactions such as these use transport mechanisms with protocols other than, or built upon, transmission control protocol/Internet protocol (TCP/IP), such as internetwork packet exchange (IPX), Internet protocol security (IPSEC), Internet protocol version 6 (Ipv6), secure sockets layer (SSL), etc. Also, these non-Web-based transactions can occur as a result of interconnections between systems through a common language specified by a metalanguage (e.g., specified by XML) or through direct binary communication between systems (e.g., via distributed component object model (DCOM), common object request broker architecture (CORBA), or other distributed object, procedural, or client-server architectures).
Two problems that exist in conventional eCommerce systems pose a major concern to businesses and individuals. The first problem includes the risk of invasion of privacy imposed on a user (corporate or individual) seeking goods, services, and/or information. The user may provide personal information, such as a name or credit card number, corporate information, such as a corporate name or account data, or a combination of personal and corporate information to a server operator offering these goods, services, and/or information. The user, however, has no way of knowing whether the provided information will be kept secure by the server operator and not used in a manner against his wishes. For example, the user may provide his name and telephone number as part of a standard eCommerce transaction. In some cases, the server operator sells or trades the user's information to telemarketing services without the knowledge of the user or stores the information in an insecure manner that permits access by a third party.
In the case of business-to-business transactions, information on what the business is buying, what quality and quantity, from whom, and what the business is thinking of buying (as evidenced by research and browsing habits) constitutes critical confidential information to the business. The risk of interception or misuse of this information is as great or greater than that of other types of personal or corporate information.
The second problem involves the irritating, time-consuming, and generally repetitious data entry required for a user (corporate or individual) to open a new account or use an existing one. For example, to open a new account, the user must provide private information regarding the user or the business. Some server operators will store a user's private information on their server for subsequent transactions by the user. To set up the account, however, the user must enter the information manually. To use a previously-opened account, the user must go through a tedious and mistake-fraught process and recall a password which, if the user follows security doctrines, should be unique to each site the user visits.
As a result, a need has arisen for a mechanism to insure the security of private information provided to a third party. A need has also arisen for a simplified, expedited, and automated mechanism for providing such information. |
The complete Baseball America and Collegiate Baseball Newspaper polls can be found on S6.
Center fielder Whitley Gerhart’s two-run home run in the bottom of the sixth inning lifted the Mustangs to the win in the opener before the Bulldogs scored five runs in the top of the ninth inning to take the nightcap in the nonleague doubleheader at Bob Janssen Field on Monday.
In the opener, Cal Poly (12-20-1) trailed 4-3 entering the bottom of the sixth.
In the bottom of the sixth, catcher Mariah Cochiolo drew a leadoff walk and was sacrificed to second. First baseman Breana West singled home Cochiolo, and two pitches later, Gerhart hit her second homer of the season to give the Mustangs a 6-4 lead.
West, third baseman Jillian Andersen and shortstop Kim Westlund all had two hits for Cal Poly in the opener, and West and Gerhart had two RBI apiece.
Nicole Innamorato, who came on in the fourth inning, pitched three innings for the win.
Arroyo Grande High graduate Jillian Compton went the distance in the circle for the Bulldogs (19-14), allowing nine hits, six runs (five earned), three walks and three strikeouts in falling to 8-10.
In the nightcap, Fresno State scored in the top of the first, and the Mustangs answered with a run in the third when Celina Lafrades singled to score second baseman Ashley Romano.
The score remained 1-1 until the top of the ninth when the Bulldogs erupted for five runs.
Left fielder Lauren Moreno had two of Cal Poly’s five hits in the second game.
The Cal Poly A team sits 17 strokes behind Cal State Northridge, and the Cal Poly B team is 39 strokes behind the Matadors after Monday’s first two rounds at Bakersfield Country Club.
Asia Adell and Madison Hirsch are tied for fourth individually for the Mustangs with a 10-over 154 on the par-72 course.
Cal Poly’s A team has 622 strokes through 36 holes to Cal State Northridge’s 605. The Cal Poly B team is third at 644 in the five-team field.
Drew Thomas and Morgan Thomas are both at 157 and tied for seventh individually for the Cal Poly B team.
Cal State Northridge’s Elisabeth Haavardsho is the individual leader at 141 after rounds of 74 and 67, giving her an eight-stroke lead over runner-up and teammate Clariss Guce.
The tournament concludes today with the final 18 holes. |
// DejaLu
// Copyright (c) 2015 <NAME>. All rights reserved.
#ifndef __dejalu__MailDBPeopleConversationInfoOperation__
#define __dejalu__MailDBPeopleConversationInfoOperation__
#include <MailCore/MailCore.h>
#include "HMMailDBOperation.h"
#ifdef __cplusplus
namespace hermes {
class MailDBPeopleConversationInfoOperation : public MailDBOperation {
public:
MailDBPeopleConversationInfoOperation();
virtual ~MailDBPeopleConversationInfoOperation();
virtual int64_t conversationID();
virtual void setConversationID(int64_t conversationID);
virtual int64_t inboxFolderID();
virtual void setInboxFolderID(int64_t inboxFolderID);
virtual mailcore::Set * emailSet();
virtual void setEmailSet(mailcore::Set * emailSet);
virtual mailcore::HashMap * foldersScores();
virtual void setFoldersScores(mailcore::HashMap * foldersScores);
virtual mailcore::Set * foldersToExcludeFromUnread();
virtual void setFoldersToExcludeFromUnread(mailcore::Set * foldersToExcludeFromUnread);
virtual mailcore::HashMap * conversationInfo();
// Implements Operation.
virtual void main();
private:
int64_t mConversationID;
int64_t mInboxFolderID;
mailcore::Set * mEmailSet;
mailcore::HashMap * mFoldersScores;
mailcore::HashMap * mConversationInfo;
mailcore::Set * mFoldersToExcludeFromUnread;
};
}
#endif
#endif /* defined(__dejalu__MailDBPeopleConversationInfoOperation__) */
|
// Boost.Geometry
// Copyright (c) 2021, Oracle and/or its affiliates.
// Contributed and/or modified by <NAME>, on behalf of Oracle
// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html
#ifndef BOOST_GEOMETRY_GEOMETRIES_GEOMETRY_COLLECTION_HPP
#define BOOST_GEOMETRY_GEOMETRIES_GEOMETRY_COLLECTION_HPP
#include <vector>
#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tags.hpp>
namespace boost { namespace geometry
{
namespace model
{
/*!
\brief Basic geometry_collection class representing a container of DynamicGeometries.
\ingroup geometries
\tparam DynamicGeometry Type adapted to DynamicGeometry Concept.
\tparam Container \tparam_container
\tparam Allocator \tparam_allocator
*/
template
<
typename DynamicGeometry,
template <typename, typename> class Container = std::vector,
template <typename> class Allocator = std::allocator
>
class geometry_collection
: public Container<DynamicGeometry, Allocator<DynamicGeometry>>
{
typedef Container<DynamicGeometry, Allocator<DynamicGeometry>> base_type;
public:
geometry_collection() = default;
geometry_collection(std::initializer_list<DynamicGeometry> l)
: base_type(l.begin(), l.end())
{}
};
} // namespace model
#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS
namespace traits
{
template
<
typename DynamicGeometry,
template <typename, typename> class Container,
template <typename> class Allocator
>
struct tag<model::geometry_collection<DynamicGeometry, Container, Allocator>>
{
using type = geometry_collection_tag;
};
} // namespace traits
#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_GEOMETRIES_GEOMETRY_COLLECTION_HPP
|
import { TestBed } from '@angular/core/testing';
import { ApontamentosService } from './apontamentos.service';
describe('ApontamentosService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: ApontamentosService = TestBed.get(ApontamentosService);
expect(service).toBeTruthy();
});
});
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "NSImage.h"
@interface NSImage (UIImageShim)
+ (id)imageWithContentsOfFile:(id)arg1;
+ (id)imageWithCGImage:(struct CGImage *)arg1;
+ (id)imageWithCGImage:(struct CGImage *)arg1 scale:(float)arg2 orientation:(long long)arg3;
+ (id)imageWithColor:(id)arg1 andSize:(struct CGSize)arg2;
+ (id)imageWithColor:(id)arg1;
+ (struct CGAffineTransform)transformForImageOrientation:(long long)arg1 andSize:(struct CGSize)arg2;
+ (BOOL)isSizeSwappedForImageOrientation:(long long)arg1;
+ (id)stretchyImageNamed:(id)arg1;
+ (id)stretchyImageNamed:(id)arg1 hStretch:(BOOL)arg2 vStretch:(BOOL)arg3;
+ (id)stretchyVersionH:(BOOL)arg1 V:(BOOL)arg2 forImage:(id)arg3;
+ (void)saveToStretchyCache:(id)arg1 forKey:(id)arg2;
+ (id)imageFlippedIfABLocaleWithName:(id)arg1;
+ (id)imageNamed:(id)arg1 keepInCache:(BOOL)arg2;
- (long long)imageOrientation;
- (id)imageFlippedForRightToLeftLayoutDirection;
- (float)scale;
- (BOOL)_isSRGB;
- (id)extendedRangeSafeDrawInRect:(struct CGRect)arg1 opaque:(BOOL)arg2 scale:(float)arg3;
- (id)extendedRangeSafeDrawInRect:(struct CGRect)arg1;
- (id)stretchyImageWithLeftCapWidth:(int)arg1 topCapHeight:(int)arg2;
- (id)stretchyVersion;
- (id)stretchyVVersion;
- (id)stretchyHVersion;
- (id)stretchyVersionH:(BOOL)arg1 V:(BOOL)arg2;
- (id)stretchyImageViewWithLeftCap:(double)arg1 topCap:(double)arg2;
- (id)cropImage:(struct CGRect)arg1;
- (id)cropped16X9Image;
- (id)scaledImageWithMaxDimension:(double)arg1;
- (struct CGSize)scaledSizeEqualOrSmallerThanSize:(struct CGSize)arg1 maintainAspectRatio:(BOOL)arg2 normalizeOrientation:(BOOL)arg3;
- (id)drawImageIntoSize:(struct CGSize)arg1 maintainAspectRatio:(BOOL)arg2 normalizeOrientation:(BOOL)arg3;
- (id)scaledImageEqualOrSmallerThanSize:(struct CGSize)arg1 maintainAspectRatio:(BOOL)arg2 normalizeOrientation:(BOOL)arg3;
- (struct CGSize)scaledSized:(struct CGSize)arg1 maintainAspectRatio:(BOOL)arg2;
- (BOOL)adjustFitInSize:(struct CGSize *)arg1 normalizeOrientation:(BOOL)arg2;
- (void)drawInRect:(struct CGRect)arg1 fromRect:(struct CGRect)arg2 blendMode:(int)arg3 alpha:(float)arg4;
- (id)applyBlurWithRadius:(double)arg1 tintColor:(id)arg2 saturationDeltaFactor:(double)arg3 maskImage:(id)arg4 scale:(double)arg5;
- (id)applyBlurWithRadius:(double)arg1 tintColor:(id)arg2 saturationDeltaFactor:(double)arg3 maskImage:(id)arg4;
- (id)applyDarkEffect;
- (id)applyExtraLightEffect;
- (id)applyLightEffect;
@end
|
padding = 2
def dash_field(text, width):
#padding = 2
return text.ljust(len(text) + padding, ' ').ljust(width, '-')
def center_equals_field(text, width=92):
#padding = 2
if len(text) + 2 * padding >= width:
return padding * ' ' + text + padding * ' '
leftSize = (width // 2) + (len(text) // 2) + 1
return right_equals_field(left_equals_field(text, leftSize), width)
def left_equals_field(text, width):
return text.rjust(len(text) + padding, ' ').rjust(width, '=')
def right_equals_field(text, width):
return text.ljust(len(text) + padding, ' ').ljust(width, '=')
if __name__ == "__main__":
print('This is the tester for field Space')
print(center_equals_field("Perfect! This is nice", 91))
|
Whether they sweat out victories like Tuesday night's or coast to those of the blowout variety, the Celtics' mission is history.
And they don't mean any meager stuff like sweeping their first season series of the Bulls since 1986-87 (Boston's last trip to the NBA Finals) with a 106-92 triumph at the United Center. The Celtics, one victory shy of 60, are talking title.
"Our focus every day is we can get better the next day," coach Doc Rivers said. "They believe that and understand that."
The only history the Bulls are focused on is their playoff chances becoming just that. And with a five-game deficit with eight to play, that day will come soon.
Thus, the focus is on next season, both on who will be here and who won't.
Tyrus Thomas, who will be shopped, rebounded from picking up a foul 12 seconds after tipoff to fare well in a high-profile matchup against Kevin Garnett with a team-high 24 points.
Joakim Noah, who definitely will return, continued to flash moments of promise and finished with eight rebounds and three assists.
Larry Hughes, who likely will be back because of the albatross that is his contract, missed all six of his shots, scored two points without a rebound or assist and didn't play in the fourth quarter.
Interim coach Jim Boylan, who isn't expected to retain the job, knows the value of trading for a big-name player.
"When you can go out and get a so-called superstar, a guy who can bring a certain level of greatness to your team, it makes everyone else's job easier," Boylan said. "At certain times when a play needs to be made, that guy is ready to make it for you.
"That relieves the burden on a lot of people. It allows them to relax and be more efficient. If there's a way for us to go out and secure somebody like that, it would make a huge difference."
The Bulls actually were within six points early in the fourth quarter and within 95-87 late when James Posey and Ray Allen drained three-pointers on consecutive possessions.
Overall, the Celtics sank 14 of 25 (56 percent) shots from beyond the arc, an area the Bulls have struggled to defend all season.
Allen's 22 points led Boston, which also received 20 points, seven rebounds and countless focused stares from Garnett.
Garnett's energy, intensity and skill are major reasons the Celtics have rebounded from winning an Eastern-Conference-low 24 victories last season. He also has aided in setting a tone of accountability, something the Bulls used to have.
"We've gotten better as the year has gone on," Rivers said. "That's what we wanted and we're still striving to do that. "I'm happy the guys bought in. If they didn't, our record wouldn't be this. We got them at the right time.
"If they were 23 and 24 and 25, this may have happened but it would've been a tougher sell for me. It was an easier sell for me because they've won everything individually in their careers. For the rest of their lives, everything will be defined by what they do with team success." |
<filename>src/main/java/me/hink/tweaker/config/TConfig.java
/*
* Copyright (c) 2017 h1nk
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.hink.tweaker.config;
import net.minecraftforge.common.config.Configuration;
import java.io.File;
import static me.hink.tweaker.config.TConfig.Category.*;
/**
* TODO
*
* @author <a href="https://github.com/h1nk">h1nk</a>
* @since 0.0.1
*/
public class TConfig {
public static Configuration config;
public static String customScreenShotName;
public static String customScreenShotFolderNamePattern;
public static boolean isCustomScreenShotNameEnabled;
public static boolean isCustomScreenShotFolderNamePatternEnabled;
// Tweaks & Features
public static boolean isDoubleClickMechanicDisabled;
public static boolean isEnhancedSoundOptionsEnabled;
public static boolean isHurtCameraEffectEnabled = true;
public static boolean isPersistentChatEnabled;
public static boolean isPotionEffectRepositioningEnabled;
public static boolean isSearchableControlOptionsGUIEnabled;
public static boolean isAutomaticRespawnScreen;
public static boolean isRespawnButtonCooldownEnabled;
// Bug Fixes
public static boolean isHeadLookYawCalculationFixEnabled = false;
public static boolean isRightArmRidableEntityRenderFixEnabled = true;
public static boolean isToggleFullscreenResizeFixEnabled = true;
// Plugin Channel Messaging
public static boolean blockInboundMessages;
public static boolean blockOutboundMessages;
// Debug
public static boolean isPluginChannelMessageLoggingEnabled = false;
public static boolean isDebugBlockHighlightingEnabled = false;
public static boolean isGuiLoggingEnabled = false;
public enum Category {
SCREENSHOTS("screenshots", "Screenshots"),
FEATURES("features", "Features"),
BUG_FIXES("bug-fixes", "Bug Fixes"),
PLUGIN_MESSAGING("plugin-messaging", "Plugin Channel Messaging"),
DEBUG("debug", "Debug");
private final String category;
private final String name;
Category(final String category, final String name) {
this.category = category;
this.name = name;
}
public String getCategory() {
return category;
}
public String getName() {
return name;
}
}
public static void startConfig(File configFile) {
if (config == null) {
config = new Configuration(configFile);
loadConfig();
}
}
public static void loadConfig() {
config.setCategoryComment(SCREENSHOTS.category, "Screenshot settings");
config.setCategoryComment(FEATURES.category, "Feature settings");
config.setCategoryComment(BUG_FIXES.category, "Bug Fixes");
config.setCategoryComment(PLUGIN_MESSAGING.category, "Plugin Messaging");
config.setCategoryLanguageKey(SCREENSHOTS.category, "tweaker.config-gui.category.screenshots");
config.setCategoryLanguageKey(FEATURES.category, "tweaker.config-gui.category.features");
config.setCategoryLanguageKey(BUG_FIXES.category, "tweaker.config-gui.category.bug-fixes");
config.setCategoryLanguageKey(PLUGIN_MESSAGING.category, "tweaker.config-gui.category.plugin-messaging");
config.setCategoryRequiresMcRestart(BUG_FIXES.category, true);
isCustomScreenShotNameEnabled = config.getBoolean("isCustomScreenShotNameEnabled",
SCREENSHOTS.getCategory(),
true,
"Enable custom screenshot file naming",
"tweaker.config-gui.category.screenshots.is-custom-screenshot-name-enabled");
customScreenShotName = config.getString("customScreenShotName",
SCREENSHOTS.category,
"%uuid",
"Custom screenshot file naming pattern",
"tweaker.config-gui.category.screenshots.custom-screenshot-name");
// Tweaks & Features
isDoubleClickMechanicDisabled = config.getBoolean("Double Click Inventory Mechanic",
FEATURES.category,
true,
"Toggle option for the double click container inventory GUI stack mechanic",
"test");
isHurtCameraEffectEnabled = config.getBoolean("Hurt Camera Effect",
FEATURES.category,
true,
"Toggle option for the the hurt (hit punch) entity render effect",
"");
isSearchableControlOptionsGUIEnabled = config.getBoolean("Searchable Control Options GUI",
FEATURES.category,
true,
"Enabled a search bar in the controls GUI screen that enabled you to search through the available keybinds.",
"");
isEnhancedSoundOptionsEnabled = config.getBoolean("Enhanced Sound Options",
FEATURES.category,
true,
"Enhanced sound setting features, like customized sound profiles and the ability to individually" +
" scale the volume of each registered game sound individually",
"");
isPersistentChatEnabled = config.getBoolean("Persistent Chat",
FEATURES.category,
true,
"Remember the state of typed chat when dying, changing worlds, or leaving bed",
"");
isAutomaticRespawnScreen = config.getBoolean("Automatically Respawn",
FEATURES.category,
false,
"Automatically select respawn as the option respawn whenever presented a respawn/death screen",
"");
isRespawnButtonCooldownEnabled = config.getBoolean("Respawn Button Enable Delay",
FEATURES.category,
false,
"Toggle the one second wait for Game Over GUI buttons to be enabled",
"");
isPotionEffectRepositioningEnabled = config.getBoolean("Potion Effect Repositioning",
FEATURES.category,
false,
"Whether or not to reposition the player inventory GUI container when rendering potion effects " +
"on the side of the screen.",
"");
// Bug Fixes
isHeadLookYawCalculationFixEnabled = config.getBoolean("[MC-67665] Head yaw look calculation bug fix",
BUG_FIXES.category,
true,
"Fixes head yaw look vector calculation bug.",
"");
isRightArmRidableEntityRenderFixEnabled = config.getBoolean("[MC-1349] Right arm ridable entity render bug fix",
BUG_FIXES.category,
true,
"Fixes visual render glitch with how the right arm of the player model is rendered, the bug was easily" +
"reproducible when riding a rideable entity",
"");
isToggleFullscreenResizeFixEnabled = config.getBoolean("[MC-68754] Exiting fullscreen disables window resize",
BUG_FIXES.category,
true,
"",
"");
// Plugin Channel Messaging
blockInboundMessages = config.getBoolean("Block Inbound Communication",
PLUGIN_MESSAGING.category,
false,
"Enable blocking of inbound plugin channel message packet communication",
"");
blockOutboundMessages = config.getBoolean("Block Outbound Communication",
PLUGIN_MESSAGING.category,
false,
"Enable blocking of outbound plugin channel message packet communication",
"");
isPluginChannelMessageLoggingEnabled = config.getBoolean("Log Plugin Channel Messages",
DEBUG.category,
false,
"Enable logging of plugin channel messaging communication",
"");
isDebugBlockHighlightingEnabled = config.getBoolean("Block Highlighting",
DEBUG.category,
false,
"",
"");
isGuiLoggingEnabled = config.getBoolean("GUI Logging",
DEBUG.category,
false,
"",
"");
if (config.hasChanged()) {
config.save();
}
}
}
|
Facial Expression Recognition using Multiclass Ensemble Least-Square Support Vector Machine Facial expression is one of behavior characteristics of human-being. The use of biometrics technology system with facial expression characteristics makes it possible to recognize a persons mood or emotion. The basic components of facial expression analysis system are face detection, face image extraction, facial classification and facial expressions recognition. This paper uses Principal Component Analysis (PCA) algorithm to extract facial features with expression parameters, i.e., happy, sad, neutral, angry, fear, and disgusted. Then Multiclass Ensemble Least-Squares Support Vector Machine (MELS-SVM) is used for the classification process of facial expression. The result of MELS-SVM model obtained from our 185 different expression images of 10 persons showed high accuracy level of 99.998% using RBF kernel. Introduction Facial expression in everyday human life is used as a form of natural human response that describes the feelings felt by a person in interacting with a certain thing. In the interaction between fellow human, expression is use as a part of communication. On the other hand, technological developments from time to time have great leaps when a new interaction is implemented such as the use of keys, monitor screen, GUI, touch screen, to voice commands. The key to technological development lies in the user, therefore computer interaction is an important part in technological development and understanding the user's response becomes very important. One approach taken to understand the response of the user is by a facial recognition system. By understanding the expression of the user, the computer can be made as if it can understand human feelings. The research on facial expressions has been started since 1978 and was extensively researched in the computer science area of the 90s and continues to the present day. an expression recognition system of two important stages, namely facial features representation and classification design. Facial feature representation is obtained by extracting input in the form of digital image by using certain method. The method of feature extraction used by researchers to build a facial expression recognition system that is Principal Component Analysis Algorithm (PCA). Principal Component Analysis (PCA) algorithm is one method that can be used to process the image of a person's face so that the system will automatically recognize a person's face through its main features such as eyes, nose, lips, and eyebrows as identity. The identity of the person's face image by the system will be recognized through various training (training) stored in the database. The training phase is the result of extraction from different collections of different faces then collected and stored in a database. The results of facial images that have been extracted using PCA algorithm will be compared with the new face image 2 1234567890 ''"" as the face image to be tested and testing whether it has similarity or almost similar to recognizable by the system. Related Works Yubo Wang, et al., have proposed a new method of recognition of facial expressions. The facial expressions are extracted from the human face by the expression classifier learned from the Haar feature based on the LUT Weak Classifiers. The expression recognition system consists of three modules, face detection, facial feature landmark extraction and facial expression recognition. This system is applied automatically can recognize seven expressions in real time that include anger, disgust, fear, pleasure, neutrality, sadness and surprise. Reda Shbib and Shikun Zhou in studied the introduction of facial expressions using the Active Shape Model method by adopting AdaBoost classifier and Haar-Like feature to detect images. AdaBoost is a method to increase classifier accuracy gained from the component learner of the Support Vector Machine (SVM) method. Data mining is a process that uses statistical techniques, calculations, artificial intelligence and machine learning to extract and identify useful information and related knowledge from large databases. SVM initially can only classify data in two classes. However, further research SVM was developed so that it can classify data over two classes (multiclass). Classifying M-classes means predicting the class labels, = 1,, one way to solve the M-class problem by formulating it into binary L classification problems. SVM concept is simply trying to find the best hyperplane that serves as a separator of two classes in the input space. Pattern that is a member of two classes into +1 and -1, and share alternate field separators. The best dividing fields can not only separate the data but also have the largest margins. Margin is the distance between the fields of separator (hyperplane) with the closest pattern of each class. Let { 1,, } be the dataset and ∈ {+1, −1} is the class label of the data. A pair of parallel bounding plane separates the two classes. The first delimiter field limits the first class while the second delimiter field limits the second class, it is obtained therefore as follows. The best separator field has the largest margin values that can be formulated into a quadratic programming problem as follows. min,, with constraints: (. + ) ≥ 1 − and ≥ 0, where = 1,.., is a slack variable that determines the level of misclassification of the data samples. Whereas, > 0 is a parameter. Kernel method is used when the ordinary SVM classifier cannot separate the data linearly. The kernel method transforms the data into the features space dimension so that it can be linearly separated on the features space. The kernel method can be formulated as follows. LS-SVM is one of the SVM modifications that is solved linearly. If the SVM separator field is given as in, then the LS-SVM is given as follows. The above equation can be solved with Lagrangian multiplier. where the Lagrangian multiplier i can be either positive or negative. To optimize the conditions in, we decrease of w, b,, and is equal to zero. The results of the process are as follows. Using the One-Against-All (OAA) method, k binary model can be constructed (in which k is the number of classes). Each i-class model is trained by using the entire data. For example, there is a classification problem with 3 classes. Training step constructs 3 pieces of binary classification with the following objective function. min,,, Confusion matrix is a table that expresses the amount of test data that is correctly classified and misclassified. The table using the following parameters in order to calculate accuracy, sensitivity and false discovery rate. True Positive (TP) is the number of documents from class 1 is correctly classified as class 1. True Negative (TN) is the number of documents from class 0 is are correctly classified as class 0. False Positive (FP) is the number of documents from class 0 incorrectly classified as class 1. False Negative (FN) is the number of documents from class 1 that are misclassified as class 0. Performance measurements of accuracy, sensitivity and false discovery rate can be calculated using the following formulas respectively. Experimental Details The process of facial classification is explained by the following activities: Principal Component Analysis (PCA) The sequence of features extraction process using PCA is given as follows. 1. Read input data 2. Calculate the average of each column Input of all image of training data is input parameter on PCA function that is "ImageTraining" mean column image can be calculated using matlab program code: I = imread ('YM.AN1.61.tiff'); Average = mean (I); Calculate the zero mean To calculate the zero mean, the average matrix of training data must be doubled as much as the sample data, which is multiplied by 240 lines with the command: ZeroMean = bsxfun (@ minus, 256, Average); 4. Calculate the covariance To calculate the covariance matrix by multiplying the zero mean against its transpose, and the result is divided by "Amount Sample-1" with the command: CovMatric = (1 / ) * (ZeroMean * ZeroMean '); Calculate eigen value and eigen vector The dimensions resulting from the covariance matrix have 240 row dimensions and 240 column dimensions. The dimension has been significantly reduced from 10304 to 240, so the dimension number has decreased by 10064 (10304-240 = 10064). The value of the covariance matrix is used further process to determine the value of eigen value and eigen vector with the command: = eig (CovMatric); Sort the eigen value in descending order To perform a descending order of "eigen value", simply take the diagonal value followed by the sequencing process. The "eigen value" sorting result is stored in a variable, that is, the "Result" variable and the sorting index are stored in the "Index" variable with the command: eigvalue = diag (eigvalue); = sort (eigvalue, 'descend'); eigvalue = eigvalue (index); 7. Sort the eigen vector column to change as the eigen value index changes 8. Check the value of eigen value close to 0 The most non-dominant eigenvector values tend to have a correlation of the value of eigen value that is close to zero, therefore it is necessary to check the value of eigen value and the number of close to zero with the command: NotDominant = find (eigvalue <0.00000000001); Amount = length (Not Dominate); 9. Calculate the projection matrix The projection matrix can be calculated by multiplying the transpose data variable by "eigen vector". The code of the program is as follows: ProjectionMatric = ZeroMean '* eigvector; The result of the program code is used to form a diagonal matrix with the command: RootSumProjectionMatric = (1./ (sum (ProjectionMatric. ^ 2). ^ 0.5)); New projection matrix can be obtained with the command: ProjectionMatric = (bsxfun (@ times, ProjectionMatric, RootSumProjectionMatric)); 10. Throw away the eigen vector column whose position is equal to the eigen value position which has a value close to 0. If the value of eigen value is found to be close to zero, then the eigenvector column correspondingto the eigen value position need not be used for the next process with the command: eigvector = eigvector (:, 1: end-Amount); The Dataset We conducted a simulation for the proposed method; i.e., face detection, feature extraction using PCA algorithm, and facial expression classification process using Ensemble Multiclass Least-Square Support Vector Machine (LS-SVM). The data used in this simulation is data about facial expressions from the Olivetty Research Laboratory (ORL) and Jaffe Images can be downloaded, respectively, on the following URL addresses. and The type of expression is divided into six classes, i.e., angry, disgust, fear, happy, neutral, and sad. The sample data on this dataset amounts to 240 images of facial expressions. Classification Process In the process of expression classification, starting with image taking of the file, then image is processed using image processing software to get numerical data value which will be used as input data for learning process and validation. After the learning data in the next can be the result of data learning is used for the testing process. Multiclass Algorithm Method The analysis used in this multiclass classification is the One Against All classification method. The multilingas method algorithm as follows: 1. Dataset input. 2. Identify the input dataset a. The values of the training data feature (xi) b. Class of training data (yi) c. Values feature test data (xti) d. Class of test data (yti) 3. Initiate objects on LS-SVM before performing the training process with the initlssvm function a. Specify data of training data feature (xi) b. Specifies the training data class (yi), c. Choose a classifier to classify data d. Selects the kernel and its parameters to use 4. Selecting the multilingual method code used (code_OneVsAll for One Against All) 5. Conduct training process with train lssvm function 6. Calculating values w 7. Make predictions based on the model obtained and determine data feature test data (xti) with simlssvm function 8. Create a confusion matrix 9. Calculate the level of accuracy with the formula: where C is the correct total of predictions and N is the total of all data tested. Implementation Results on dataset The separator function for the one against all method with the RBF (Radial Basis Function) kernel using the parameter = 0.5 for dataset is as follows. Results and Discussion The values of w and b based on the kernel type and their parameters for the use of the One Against All method on the expression dataset can be seen in table 1: Based on table 1 and figure 1, the use of RBF kernel types and using the parameter = 0.5 has the highest accuracy on dataset has the highest accuracy of 99.99832%. Accuracy for classification with the 6 number of classes. Conclusion The facial expression recognition have been proposed using the Multiclass Ensemble Least-Squares Support Vector Machine (MELS-SVM) method. The image of the face is extracted using Principal Component Analysis (PCA) algorithm to take the value of Projection Matrix and Weight Matrix. The classification process uses the MELS-SVM to construct the classifier model from the training images. Finally, the testing images is used to measure accuracy using RBF kernel and the our result showed the accuracy level is 99.99832%. |
Solving vehicle routing problems using multiple ant colonies and deterministic approaches In the vehicle routing problem with time windows VRPTW, there arc two main objectives. The primary objective is to reduce the number of vehicles, the secondary one is to minimise the total distance travelled by all vehicles. This thesis describes some experiments with multiple ant colony and deterministic approaches. For that, it starts explaining how a double ant colony system called DACS 01 with two colonies has the advantage of using the pheromone trails and the XCHNG local search and the ability of tackling multiple objectives problems like VRPTW. Also, it shows how such DACS system lacks vital components that make the performance as comparable and competitive with that of the well-known VRPTW algorithms. Therefore, the inclusions of components, like a triple move local search, a push-forward and pushbackward strategy PFPBS, a hybrid local search HLS and a variant of a 2-0pt move, improve the results very significantly, compared to not using them. Furthermore, it draws the attention to an interesting discovery, which suggests that if a DACS system uses ants that arc more deterministic, then that system has the ability to bring performance that is better than that of another DACS system with pheromone ants. Consequently, the interesting discovery has motivated the author to investigate a number of SI1- Like deterministic approaches, which most of them depend on capturing under-constrained tours and removing them using a removing heuristic that uses the hybrid local search HLS. Some of these SI1-Like approaches show signs of the ability of improving the average, best and worst case performances of DACS systems on some problem set cases, if they are merged with such systems. Of course, this casts some doubt on whether the usc of pheromone trails, which is a distinctive feature of multiple ant-colony systems in the research literature, is really so advantageous as is sometimes claimed. Experiments are conducted on the 176 problem instances with 100, 200 and 400 customers of Solomon, Ghering and Homberger and. The results shown in this thesis are comparable and competitive to those obtained by other state-of-the-art approaches. |
#pragma once
#include <cuda_runtime.h>
#include <vector>
#include "HugeCTR/include/common.hpp"
#include "HugeCTR/include/embeddings/hybrid_embedding/data.hpp"
#include "HugeCTR/include/embeddings/hybrid_embedding/model.hpp"
#include "HugeCTR/include/embeddings/hybrid_embedding/utils.hpp"
#include "HugeCTR/include/gpu_resource.hpp"
#include "HugeCTR/include/tensor2.hpp"
namespace HugeCTR {
namespace hybrid_embedding {
// ===========================================================================================
// Frequent Compression
// ===========================================================================================
template <typename dtype>
struct FrequentEmbeddingCompressionView {
const dtype* samples;
bool* cache_masks;
uint32_t *model_cache_indices, *model_cache_indices_offsets;
uint32_t *network_cache_indices, *network_cache_indices_offsets;
uint32_t *d_num_frequent_sample_indices, *frequent_sample_indices;
};
template <typename dtype>
class FrequentEmbeddingCompression {
void calculate_frequent_sample_indices_temp_storage_bytes(const size_t local_samples_size);
void calculate_model_cache_indices_temp_storage_bytes(const size_t num_frequent);
void calculate_network_cache_indices_temp_storage_bytes(const size_t num_frequent);
const Model<dtype>& model_;
const Data<dtype>& data_;
FrequentEmbeddingCompressionView<dtype>* device_indices_view_;
public:
// Role:
// push from the locally reduced gradient buffer => update embedding vector
// pull embedding vector from the model => update local cache
//
// Def:
// 1 if frequent category is present in this network batch
// [size num_frequent]
Tensor2<bool> cache_masks_;
// model_cache_indices : list of cache indices of this frequent embedding model instance
// for each mlp deep learning network.
// Definition.
// given the frequent embedding model of frequent embedding vectors
// stored and updated by this instance, i.e. the range in
// frequent_embedding_vectors
// i * num_frequent /num_instances ... (i+1) * num_frequent /num_instances
// - 1
// for each network n, the range within model_cache_indices specified by
// model_cache_indices_offsets_[n] .. model_cache_indices_offsets_[n] - 1
// is the list of frequent cache indices that appear in network n.
//
// Role.
//
// 1. Forward-model : cache indices into the frequent_embedding_vector array
// for each send-message-buffer - per mlp network.
// 2. Backward-model : cache indices for each receive-message-buffer - mlp
//
Tensor2<uint32_t> model_cache_indices_;
Tensor2<uint32_t> model_cache_indices_offsets_;
// network_cache_indices : list of cache indices contained in this network for each
// frequent embedding model instance
// Def.
// Given the mlp deep learning network samples for this instance,
// - network n, sample_ids starting with i * batch_size / num_instances -
// For each embedding model - model_id - list its cache indices that
// are present within network n's samples. The range of these indices is
// given by network_cache_indices_offsets_[i+1] ...
// network_cache_indices_offsets_[i+1]
// Role.
// 1. Forward-network : cache indices into the frequent_embedding_vector array
// for each receive-message-buffer - per frequent embedding model
// 2. Backward-network : cache indices into the frequent_gradient_vectors_
// for each send-message-buffer - mlp
//
Tensor2<uint32_t> network_cache_indices_;
Tensor2<uint32_t> network_cache_indices_offsets_;
// Role:
// from buffer => interaction layer
// sample gradients => gradient buffer
//
// Def:
// sample id's within this network batch
// containing frequent category [network batch size]
// "Network side"
Tensor2<uint32_t> d_num_frequent_sample_indices_;
Tensor2<uint32_t> frequent_sample_indices_;
// scratch buffers for index calculations
Tensor2<char> frequent_sample_indices_temp_storage_;
Tensor2<char> model_cache_indices_temp_storage_;
Tensor2<char> network_cache_indices_temp_storage_;
size_t frequent_sample_indices_temp_storage_bytes_;
size_t model_cache_indices_temp_storage_bytes_;
size_t network_cache_indices_temp_storage_bytes_;
FrequentEmbeddingCompression(size_t max_num_frequent_categories, const Data<dtype>& data,
const Model<dtype>& model);
void calculate_frequent_sample_indices(cudaStream_t stream);
void calculate_model_cache_indices(size_t sm_count, cudaStream_t stream);
void calculate_network_cache_mask(cudaStream_t stream);
void calculate_network_cache_indices(cudaStream_t stream);
void calculate_cache_masks(cudaStream_t stream);
FrequentEmbeddingCompressionView<dtype>* get_device_view() { return device_indices_view_; };
const Data<dtype>* get_data() { return &data_; }
};
// ===========================================================================================
// Infrequent Selection
// ===========================================================================================
template <typename dtype>
struct InfrequentEmbeddingSelectionView {
const dtype* samples;
uint32_t *model_indices, *model_indices_offsets;
uint32_t *network_indices, *network_indices_offsets;
};
template <typename dtype>
class InfrequentEmbeddingSelection {
void calculate_model_indices_temp_storage_bytes(size_t max_batch_size, size_t table_size);
void calculate_network_indices_temp_storage_bytes(size_t max_batch_size, size_t table_size,
const uint32_t num_instances);
const Model<dtype>& model_;
const Data<dtype>& data_;
InfrequentEmbeddingSelectionView<dtype>* device_indices_view_;
public:
// model_indices : list of samples indices of categories for which the embedding vectors are
// stored in this infrequent embedding model instance.
// Sample-id's for entire batch, i.e. sorted by mlp deep learning network.
// Definition.
// Given the infrequent embedding model of infrequent embedding vectors
// stored and updated by this instance, sample indices for categories such
// that
// category_location[2*category] == model_id
// for each network n, the range within model_cache_indices specified by
// model_indices_offsets_[n] .. model_indices_offsets_[n+1] - 1
// is the list of infrequent sample indices in network n.
// Role.
// 1. Forward-model : indices in the samples array for each send-message-buffer
// - per mlp network.
// 2. Backward-model : indices in the samples array for each receive-message-buffer
// - per mlp network.
Tensor2<uint32_t> model_indices_;
Tensor2<uint32_t> model_indices_offsets_;
// Tensor2<size_t> model_indices_sizes_;
// Tensor2<size_t *> model_indices_sizes_ptrs_;
// network_indices : list of sample indices of infrequent categories ordered per infrequent
// embedding model - model_id - where they're stored.
// Sample-id's for local batch (i.e sub-batch of this mlp network)
// Definition.
// Given the mlp deep learning network samples for this instance,
// - network n, sample_ids starting with i * batch_size / num_instances -
// For each embedding model - model_id - list its sample indices that
// are present within network n's samples. The range of these indices is given
// by
// network_indices_offsets_[n] .. network_indices_offsets_[n+1] - 1
// Role.
// 1. Forward-network : local sample indices for each receive-message-buffer
// - per infrequent embedding model.
// 2. Backward-network : local sample indices for each send-message-buffer
// - mlp
Tensor2<uint32_t> network_indices_;
Tensor2<uint32_t> network_indices_offsets_;
// Tensor2<size_t> network_indices_sizes_;
// Tensor2<size_t *> network_indices_sizes_ptrs_;
// scratch buffers for index calculations
/// TODO: if not overlapping, we can use the same storage
Tensor2<char> model_indices_temp_storage_;
size_t model_indices_temp_storage_bytes_;
Tensor2<char> network_indices_temp_storage_;
size_t network_indices_temp_storage_bytes_;
InfrequentEmbeddingSelection(const Data<dtype>& data, const Model<dtype>& model);
void calculate_model_indices(cudaStream_t stream);
void calculate_network_indices(size_t sm_count, cudaStream_t stream);
// For now these functions stay in InfreqeuentEmbedding
// since the communications can only use one offsets tensor
// void calculate_model_indices_sizes_from_offsets( size_t embedding_vec_bytes, cudaStream_t
// stream); void calculate_network_indices_sizes_from_offsets(size_t embedding_vec_bytes,
// cudaStream_t stream);
InfrequentEmbeddingSelectionView<dtype>* get_device_view() { return device_indices_view_; }
const Data<dtype>* get_data() { return &data_; }
};
// Single-stream version
template <typename dtype>
void compute_indices(FrequentEmbeddingCompression<dtype>& compression,
InfrequentEmbeddingSelection<dtype>& selection,
CommunicationType communication_type, bool compute_network_cache_indices,
cudaStream_t main_stream, int sm_count);
} // namespace hybrid_embedding
} // namespace HugeCTR
|
Combinations or sequences of targeted agents in CLL: is the whole greater than the sum of its parts (Aristotle, 360 BC)? The treatment landscape for chronic lymphocytic leukemia (CLL) is rapidly evolving. Targeted agents (TAs) have demonstrated impressive single agent activity and therefore have been replacing chemoimmunotherapy (CIT). Despite their efficacy, the optimal use of the current TAs remains challenging. Perhaps the major dilemma is whether these drugs are best used in sequence or in combinations. Most patients tolerate TA well, notably early during treatment; however, a substantial number discontinue therapy because of toxicities. Therefore, the reasons for discontinuation and, subsequently, the preferred sequence of these agents become critical issues. Although TA monotherapy has revolutionized the treatment of CLL, residual disease, acquired resistance, suboptimal durability of response in patients with high-risk disease, indefinite treatment duration, and decreased compliance over time are issues of concern. To address these challenges, an increasing number of studies are evaluating different combinations of TAs; however, these studies have been mostly small single arm trials in heterogeneous patient populations using different methods for response assessment. A number of questions remain regarding the predictive value of minimal residual disease (MRD) status, durability of response, fixed treatment durations, and importantly, criteria for selection of patients for the optimal combinations. Medical comorbidities, performance status, prior therapies, and disease risk profile are fundamental in determining the treatment plan for each individual patient. Furthermore, utilizing prognostic and predictive markers along with monitoring MRD can guide the development of individualized, better-tolerated, time-limited, and potentially curative chemo-free treatment regimens. |
Secure communication protocol for smart transportation based on vehicular cloud The pioneering concept of connected vehicles has transformed the way of thinking for researchers and entrepreneurs by collecting relevant data from nearby objects. However, this data is useful for a specific vehicle only. Moreover, vehicles get a high amount of data (e.g., traffic, safety, and multimedia infotainment) on the road. Thus, vehicles expect adequate storage device for this data, but it is infeasible to have a large memory in each vehicle. Hence, the vehicular cloud computing (VCC) framework came into the picture to provide a storage facility by connecting a road-side-unit (RSU) with the vehicular cloud (VC). In this, data should be saved in an encrypted form to preserve security, but there is a challenge to search for information over encrypted data. Next, we understand that many of vehicular communication schemes are inefficient for data transmissions due to its poor performance results and vulnerable to different fundamental security attacks. Accordingly, on-device performance is critical, but data damages and secure on-time connectivity are also significant challenges in a public environment. Therefore, we propose reliable data transmission protocols for cutting-edge architecture to search data from the storage, to resist against various security attacks, and provide better performance results. Thus, the proposed data transmission protocol is useful in diverse smart city applications (business, safety, and entertainment) for the benefits of society. |
package leetcode;
public class Task3 {
public static void main(String[] args) {
System.out.println(new Task3().lengthOfLongestSubstring("abcabcbb"));
System.out.println(new Task3().lengthOfLongestSubstring("bbbbb"));
System.out.println(new Task3().lengthOfLongestSubstring("pwwkew"));
System.out.println(new Task3().lengthOfLongestSubstring(" "));
}
public int lengthOfLongestSubstring(String s) {
int maxSize = 0;
for (int i = 0; i < s.length(); i++) {
int[] substringCharIndex = new int[128];
substringCharIndex[s.charAt(i)]++;
for (int j = i + 1; j < s.length(); j++) {
if (substringCharIndex[s.charAt(j)] > 0) {
break;
}
substringCharIndex[s.charAt(j)]++;
}
int size = 0;
for (int c : substringCharIndex) {
if (c == 1) {
size++;
}
}
if (size > maxSize) {
maxSize = size;
}
}
return maxSize;
}
}
|
The successful treatment of mycotic infections in immunosuppressed renal transplant recipients with ketoconazole. Ketoconazole, a new broad-spectrum antimycotic drug, was administered to six renal transplant recipients with mucocutaneous and/or systemic candidosis. A beneficial clinical and microbiologic effect was seen in the treated patients. This orally administered drug was well tolerated, and side effects were not evident. Our results indicate that good treatment of mycotic infections can be expected even in patients with impaired graft function, since ketoconazole metabolism occurs mainly in the liver. |
In the field of beer, ale and malt liquors, finely divided DTE substances are used as filter aids The purpose of the filter aid is to decrease the liquor soluble multivalent cations, such as iron and aluminum The presence of such multivalent cations has a tendency to promote "chill haze" which means the formation of a cloudy fluid when the fluid is chilled. Filter aids such as DTE have been used in the past. Significant reductions in the presence of multivalent cations in the fluid has been difficult to obtain.
In the field of dilute aqueous acids, it is undesirable to have the high concentrations of molybdenum present. Dilute acidic solutions are used to extract manganese from ore. The extraction is performed by using a dilute aqueous acidic solution. The manganese that is extracted has as one of its end uses the preparation of alkaline batteries. The presence of molybdenum in such batteries is undesirable for it is believed to cause outgassing and leaking of the batteries.
It is the object of the present invention to obtain a significant reduction in the presence of multivalent cations in liquids such as beer, ale and malt liquor.
It is an object of the present invention to obtain significant reduction presence of molybdenum in dilute acidic aqueous solutions. |
import axes from '@src/store/axes';
import Store from '@src/store/store';
import { LineChartOptions, BarChartOptions, ColumnChartOptions } from '@t/options';
import { ChartState, Scale, StateFunc, Options, InitStoreState } from '@t/store/store';
import { deepMergedCopy } from '@src/helpers/utils';
import * as Calculator from '@src/helpers/calculator';
const notify = () => {};
const fontTheme = {
fontSize: 11,
fontFamily: 'Arial',
fontWeight: 'normal',
color: '#333333',
};
describe('Axes Store module', () => {
const axesStateFunc = axes.state as StateFunc;
describe('state', () => {
it('could use with options', () => {
const data = [
{ name: 'han', data: [1, 4] },
{ name: 'cho', data: [5, 2] },
];
const state = {
chart: { width: 120, height: 120 },
layout: {
plot: { width: 100, height: 150, x: 30, y: 10 },
yAxis: { x: 10, y: 10, width: 10, height: 80 },
xAxis: { x: 10, y: 10, width: 80, height: 10 },
},
scale: { yAxis: { limit: { min: 0, max: 5 }, stepSize: 1, stepCount: 1 } } as Scale,
series: { line: { data } },
axes: {
xAxis: {},
yAxis: {},
},
categories: ['A', 'B'],
options: {
xAxis: { tick: { interval: 2 }, label: { interval: 3 } },
yAxis: { tick: { interval: 4 }, label: { interval: 5 } },
},
theme: {
xAxis: { title: { ...fontTheme }, label: { ...fontTheme } },
yAxis: { title: { ...fontTheme }, label: { ...fontTheme } },
},
} as ChartState<LineChartOptions>;
jest.spyOn(Calculator, 'getTextWidth').mockReturnValue(11);
jest.spyOn(Calculator, 'getTextHeight').mockReturnValue(11);
const initStoreState = { series: { line: data } } as InitStoreState<LineChartOptions>;
const store = { state, initStoreState } as Store<Options>;
axes.action!.setAxesData.call({ notify }, store);
expect(state.axes).toEqual({
xAxis: {
isLabelAxis: true,
labelDistance: 100,
labelInterval: 3,
labels: ['A', 'B'],
viewLabels: [{ text: 'A', offsetPos: 0 }],
pointOnColumn: false,
tickCount: 2,
tickDistance: 100,
tickInterval: 2,
maxLabelWidth: 11,
maxLabelHeight: 11,
maxHeight: 26.5,
offsetY: 15.5,
needRotateLabel: false,
radian: 0,
rotationHeight: 11,
},
yAxis: {
isLabelAxis: false,
labelInterval: 5,
labels: ['0', '1', '2', '3', '4', '5'],
viewLabels: [
{ text: '5', offsetPos: 0 },
{ text: '0', offsetPos: 150 },
],
pointOnColumn: false,
tickCount: 6,
tickDistance: 25,
tickInterval: 4,
zeroPosition: 150,
maxLabelWidth: 11,
maxLabelHeight: 11,
},
});
});
it("should be stored the values, when diverging is enabled and y-axis alignment is 'center' on bar series", () => {
const data = [
{ name: 'han', data: [1, 2, 3], rawData: [1, 2, 3], color: '#aaaaaa' },
{ name: 'cho', data: [4, 5, 6], rawData: [4, 5, 6], color: '#bbbbbb' },
];
const series = { bar: { ...data } };
const options = {
yAxis: { align: 'center' },
series: { diverging: true },
} as BarChartOptions;
expect(axesStateFunc({ series, options })).toEqual({
axes: {
xAxis: {},
yAxis: {},
centerYAxis: {},
},
});
});
});
it('should be setAxesData with state values', () => {
const data = [
{ name: 'han', data: [1, 4] },
{ name: 'cho', data: [5, 2] },
];
const state = {
chart: { width: 120, height: 120 },
layout: {
plot: { width: 100, height: 150, x: 30, y: 10 },
yAxis: { x: 10, y: 10, width: 10, height: 80 },
xAxis: { x: 10, y: 10, width: 80, height: 10 },
},
scale: { yAxis: { limit: { min: 0, max: 5 }, stepSize: 1, stepCount: 1 } } as Scale,
series: { line: { data } },
axes: {
xAxis: {},
yAxis: {},
},
categories: ['A', 'B'],
options: {},
theme: {
xAxis: { title: { ...fontTheme }, label: { ...fontTheme } },
yAxis: { title: { ...fontTheme }, label: { ...fontTheme } },
},
} as ChartState<LineChartOptions>;
const initStoreState = { series: { line: data } } as InitStoreState<LineChartOptions>;
const store = { state, initStoreState } as Store<LineChartOptions>;
axes.action!.setAxesData.call({ notify }, store);
expect(state.axes).toEqual({
xAxis: {
isLabelAxis: true,
labels: ['A', 'B'],
viewLabels: [
{ text: 'A', offsetPos: 0 },
{ text: 'B', offsetPos: 100 },
],
pointOnColumn: false,
tickCount: 2,
tickDistance: 100,
labelDistance: 100,
labelInterval: 1,
tickInterval: 1,
maxLabelWidth: 11,
maxLabelHeight: 11,
maxHeight: 26.5,
offsetY: 15.5,
needRotateLabel: false,
radian: 0,
rotationHeight: 11,
},
yAxis: {
isLabelAxis: false,
labels: ['0', '1', '2', '3', '4', '5'],
viewLabels: [
{ text: '5', offsetPos: 0 },
{ text: '4', offsetPos: 30 },
{ text: '3', offsetPos: 60 },
{ text: '2', offsetPos: 90 },
{ text: '1', offsetPos: 120 },
{ text: '0', offsetPos: 150 },
],
pointOnColumn: false,
tickCount: 6,
tickDistance: 25,
zeroPosition: 150,
labelInterval: 1,
tickInterval: 1,
maxLabelWidth: 11,
maxLabelHeight: 11,
},
});
});
it('should be make properly datetime category label', () => {
const data = [
{ name: 'han', data: [1, 4] },
{ name: 'cho', data: [5, 2] },
];
const state = {
chart: { width: 120, height: 120 },
layout: {
plot: { width: 100, height: 150, x: 30, y: 10 },
yAxis: { x: 10, y: 10, width: 10, height: 80 },
xAxis: { x: 10, y: 10, width: 80, height: 10 },
},
scale: { yAxis: { limit: { min: 0, max: 5 }, stepSize: 1, stepCount: 1 } } as Scale,
series: { line: { data } },
axes: {
xAxis: {},
yAxis: {},
},
categories: ['2020/08/08', '2020/08/09'],
options: {
xAxis: {
date: {
format: 'yy-MM-DD',
},
},
},
theme: {
xAxis: { title: { ...fontTheme }, label: { ...fontTheme } },
yAxis: { title: { ...fontTheme }, label: { ...fontTheme } },
},
} as ChartState<LineChartOptions>;
const initStoreState = { series: { line: data } } as InitStoreState<LineChartOptions>;
const store = { state, initStoreState } as Store<LineChartOptions>;
axes.action!.setAxesData.call({ notify }, store);
expect(state.axes.xAxis.labels).toEqual(['20-08-08', '20-08-09']);
});
});
describe('x Axis stepSize is auto', () => {
const categories = [
'aaaaaaa',
'bbbbbbb',
'ccccccc',
'ddddddd',
'eeeeeee',
'fffffff',
'ggggggg',
'hhhhhhh',
'iiiiiii',
'jjjjjjj',
'kkkkkkk',
'lllllll',
'mmmmmmm',
'nnnnnnn',
'ooooooo',
'ppppppp',
'qqqqqqq',
'rrrrrrr',
'sssssss',
'ttttttt',
];
const data = [
{ name: 'han', data: [1, 4] },
{ name: 'cho', data: [5, 2] },
];
const state = {
chart: { width: 520, height: 120 },
layout: {
plot: { width: 500, height: 150, x: 30, y: 10 },
yAxis: { x: 10, y: 10, width: 10, height: 80 },
xAxis: { x: 10, y: 10, width: 480, height: 10 },
},
scale: { yAxis: { limit: { min: 0, max: 5 }, stepSize: 1, stepCount: 1 } } as Scale,
series: { line: { data } },
axes: {
xAxis: {},
yAxis: {},
},
rawCategories: categories,
categories,
options: {
xAxis: { scale: { stepSize: 'auto' } },
},
theme: {
xAxis: { title: { ...fontTheme }, label: { ...fontTheme } },
yAxis: { title: { ...fontTheme }, label: { ...fontTheme } },
},
} as ChartState<Options>;
it('should automatically adjusts the interval according to the width', () => {
const initStoreState = { series: { line: data } } as InitStoreState<LineChartOptions>;
const store = { state, initStoreState } as Store<Options>;
jest.spyOn(Calculator, 'getTextWidth').mockReturnValue(49);
axes.action!.setAxesData.call({ notify }, store);
expect(store.state.axes.xAxis).toMatchObject({ tickInterval: 4, labelInterval: 4 });
});
it('should ignore auto options when the interval attribute is exist', () => {
const initStoreState = { series: { line: data } } as InitStoreState<LineChartOptions>;
const changedState = deepMergedCopy(state, { options: { xAxis: { label: { interval: 3 } } } });
const store = { state: changedState, initStoreState } as Store<Options>;
axes.action!.setAxesData.call({ notify }, store);
expect(store.state.axes.xAxis).toMatchObject({ tickInterval: 1, labelInterval: 3 });
});
});
describe('pointOnColumn state is properly created', () => {
it('[bar chart] xAxis.pointOnColumn: false, yAxis.pointOnColumn: true', () => {
const data = [
{ name: 'han', data: [1, 4] },
{ name: 'cho', data: [5, 2] },
];
const state = {
chart: { width: 120, height: 120 },
layout: {
plot: { width: 100, height: 150, x: 30, y: 10 },
yAxis: { x: 10, y: 10, width: 10, height: 80 },
xAxis: { x: 10, y: 10, width: 80, height: 10 },
},
scale: { xAxis: { limit: { min: 0, max: 5 }, stepSize: 1, stepCount: 1 } } as Scale,
series: { bar: { data } },
axes: {
xAxis: {},
yAxis: {},
},
categories: ['A', 'B'],
options: {},
theme: {
xAxis: { title: { ...fontTheme }, label: { ...fontTheme } },
yAxis: { title: { ...fontTheme }, label: { ...fontTheme } },
},
} as ChartState<BarChartOptions>;
const initStoreState = { series: { bar: data } } as InitStoreState<BarChartOptions>;
const store = { state, initStoreState } as Store<BarChartOptions>;
axes.action!.setAxesData.call({ notify }, store);
expect(store.state.axes).toMatchObject({
xAxis: { pointOnColumn: false },
yAxis: { pointOnColumn: true },
});
});
it('[column chart] xAxis.pointOnColumn: true, yAxis.pointOnColumn: false', () => {
const data = [
{ name: 'han', data: [1, 4] },
{ name: 'cho', data: [5, 2] },
];
const state = {
chart: { width: 120, height: 120 },
layout: {
plot: { width: 100, height: 150, x: 30, y: 10 },
yAxis: { x: 10, y: 10, width: 10, height: 80 },
xAxis: { x: 10, y: 10, width: 80, height: 10 },
},
scale: { yAxis: { limit: { min: 0, max: 5 }, stepSize: 1, stepCount: 1 } } as Scale,
series: { column: { data } },
axes: {
xAxis: {},
yAxis: {},
},
categories: ['A', 'B'],
options: {},
theme: {
xAxis: { title: { ...fontTheme }, label: { ...fontTheme } },
yAxis: { title: { ...fontTheme }, label: { ...fontTheme } },
},
} as ChartState<ColumnChartOptions>;
const initStoreState = { series: { line: data } } as InitStoreState<BarChartOptions>;
const store = { state, initStoreState } as Store<ColumnChartOptions>;
axes.action!.setAxesData.call({ notify }, store);
expect(store.state.axes).toMatchObject({
xAxis: { pointOnColumn: true },
yAxis: { pointOnColumn: false },
});
});
});
|
<filename>src/hw/signMessage/index.ts
import invariant from "invariant";
import {
DeviceAppVerifyNotSupported,
UserRefusedAddress,
} from "@ledgerhq/errors";
import { log } from "@ledgerhq/logs";
import { Observable } from "rxjs";
import type { Resolver } from "./types";
import perFamily from "../../generated/hw-signMessage";
import { useState, useEffect, useCallback, useRef } from "react";
import { from } from "rxjs";
import { createAction as createAppAction } from "../actions/app";
import type { AppRequest, AppState } from "../actions/app";
import type { Device } from "../actions/types";
import type { ConnectAppEvent, Input as ConnectAppInput } from "../connectApp";
import { withDevice } from "../deviceAccess";
import type { MessageData, Result } from "./types";
const dispatch: Resolver = (transport, opts) => {
const { currency, verify } = opts;
const getAddress = perFamily[currency.family];
invariant(getAddress, `signMessage is not implemented for ${currency.id}`);
return getAddress(transport, opts)
.then((result) => {
log(
"hw",
`signMessage ${currency.id} on ${opts.path} with message [${opts.message}]`,
result
);
return result;
})
.catch((e) => {
log(
"hw",
`signMessage ${currency.id} on ${opts.path} FAILED ${String(e)}`
);
if (e && e.name === "TransportStatusError") {
if (e.statusCode === 0x6b00 && verify) {
throw new DeviceAppVerifyNotSupported();
}
if (e.statusCode === 0x6985 || e.statusCode === 0x5501) {
throw new UserRefusedAddress();
}
}
throw e;
});
};
type BaseState = {
signMessageRequested: MessageData | null | undefined;
signMessageError: Error | null | undefined;
signMessageResult: string | null | undefined;
};
export type State = AppState & BaseState;
export type Request = AppRequest & {
message: MessageData;
};
export type Input = {
request: Request;
deviceId: string;
};
export const signMessageExec = ({
request,
deviceId,
}: Input): Observable<Result> => {
const result: Observable<Result> = withDevice(deviceId)((t) =>
from(dispatch(t, request.message))
);
return result;
};
const initialState: BaseState = {
signMessageRequested: null,
signMessageError: null,
signMessageResult: null,
};
export const createAction = (
connectAppExec: (arg0: ConnectAppInput) => Observable<ConnectAppEvent>,
signMessage: (arg0: Input) => Observable<Result> = signMessageExec
) => {
const useHook = (
reduxDevice: Device | null | undefined,
request: Request
): State => {
const appState: AppState = createAppAction(connectAppExec).useHook(
reduxDevice,
{
account: request.account,
}
);
const { device, opened, inWrongDeviceForAccount, error } = appState;
const [state, setState] = useState<BaseState>({
...initialState,
signMessageRequested: request.message,
});
const signedFired = useRef<boolean>();
const sign = useCallback(async () => {
let result;
if (!device) {
setState({
...initialState,
signMessageError: new Error("no Device"),
});
return;
}
try {
result = await signMessage({
request,
deviceId: device.deviceId,
}).toPromise();
} catch (e: any) {
if (e.name === "UserRefusedAddress") {
e.name = "UserRefusedOnDevice";
e.message = "UserRefusedOnDevice";
}
return setState({ ...initialState, signMessageError: e });
}
setState({ ...initialState, signMessageResult: result?.signature });
}, [device, request]);
useEffect(() => {
if (!device || !opened || inWrongDeviceForAccount || error) {
return;
}
if (state.signMessageRequested && !signedFired.current) {
signedFired.current = true;
sign();
}
}, [
device,
opened,
inWrongDeviceForAccount,
error,
sign,
state.signMessageRequested,
]);
return { ...appState, ...state };
};
return {
useHook,
mapResult: (r: State) => ({
signature: r.signMessageResult,
error: r.signMessageError,
}),
};
};
export default dispatch;
|
<reponame>RostyslavFridman/metallb
# Copyright (C) 2017 Nippon Telegraph and Telephone Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
import sys
import time
import unittest
from fabric.api import local
import nose
from lib.noseplugin import OptionParser, parser_option
from lib import base
from lib.base import BGP_FSM_ESTABLISHED
from lib.gobgp import GoBGPContainer
from lib.exabgp import ExaBGPContainer
class GoBGPTestBase(unittest.TestCase):
@classmethod
def setUpClass(cls):
gobgp_ctn_image_name = parser_option.gobgp_image
base.TEST_PREFIX = parser_option.test_prefix
g1 = GoBGPContainer(name='g1', asn=65000, router_id='192.168.0.1',
ctn_image_name=gobgp_ctn_image_name,
log_level=parser_option.gobgp_log_level)
e1 = ExaBGPContainer(name='e1', asn=65001, router_id='192.168.0.2')
ctns = [g1, e1]
initial_wait_time = max(ctn.run() for ctn in ctns)
time.sleep(initial_wait_time)
g1.add_peer(e1, treat_as_withdraw=True)
e1.add_peer(g1)
cls.g1 = g1
cls.e1 = e1
# test each neighbor state is turned establish
def test_01_neighbor_established(self):
self.g1.wait_for(expected_state=BGP_FSM_ESTABLISHED, peer=self.e1)
def test_02_attribute_discard(self):
# Malformed attribute 'AGGREGATOR' should be discard, but the session should not be disconnected.
self.e1.add_route('10.0.0.0/24', attribute='0x07 0xc0 0x0000006400')
# Confirm the session is not disconnected
for _ in range(5):
state = self.g1.get_neighbor_state(self.e1)
self.assertTrue(BGP_FSM_ESTABLISHED, state)
time.sleep(1)
# Confirm the path is added
dests = self.g1.get_global_rib()
self.assertTrue(len(dests) == 1)
routes = dests[0]['paths']
self.assertTrue(len(routes) == 1)
# Confirm the attribute 'AGGREGATOR(type=7)' is discarded
for d in routes[0]['attrs']:
self.assertFalse(d['type'] == 7)
self.e1.del_route('10.0.0.0/24')
def test_03_treat_as_withdraw(self):
# Malformed attribute 'MULTI_EXIT_DESC' should be treated as withdraw,
# but the session should not be disconnected.
self.e1.add_route('172.16.17.32/24', attribute='0x04 0x80 0x00000064')
self.e1.add_route('172.16.31.10/24', attribute='0x04 0x80 0x00000064')
# Malformed
self.e1.add_route('172.16.31.10/24', attribute='0x04 0x80 0x0000000064')
# Confirm the session is not disconnected
for _ in range(5):
state = self.g1.get_neighbor_state(self.e1)
self.assertTrue(BGP_FSM_ESTABLISHED, state)
time.sleep(1)
# Confirm the number of path in RIB is only one
dests = self.g1.get_global_rib()
self.assertTrue(len(dests) == 1)
self.assertTrue(dests[0]['paths'][0]['nlri']['prefix'] == '172.16.17.32/24')
if __name__ == '__main__':
output = local("which docker 2>&1 > /dev/null ; echo $?", capture=True)
if int(output) is not 0:
print "docker not found"
sys.exit(1)
nose.main(argv=sys.argv, addplugins=[OptionParser()],
defaultTest=sys.argv[0])
|
This invention relates to structural support systems, and has particular application to top-supported steam generators.
Relatively large vapor generators, such as steam generating units used by utility companies, are usually hung from a frame in order to allow for thermal expansion of their components during their operation. Such frames include upstanding members disposed adjacent the front, rear and sides of the steam generator, and a laterally extending member disposed adjacent the roof of the steam generator. A plurality of tie rods are employed to hang the steam generator from its upper extremities, being connected between the roof of the vapor generator and the laterally extending frame member. A plurality of ties can also be used to connect the steam generator from its front, rear and sides to the upstanding frame members. When these ties are used the steam generator is spaced from the upstanding frame members, with the ties being disposed within the space therebetween. It is to be understood that steam generators possess certain characteristics which distinguish them from other type of large top-supported machines, and therefore lend themselves to the use of the present invention, whereas other large devices may not be suited for such use. Steam generators are generally large devices of great mass, often standing well over 150 ft. high. Yet the boundary walls of a steam generator are relatively flexible members. Because of these characteristics, top-supported steam generators have relatively low natural frequencies, tending to react to excitation frequencies of 1 cycle per second or lower.
The dynamic loading toward which the present invention is directed principally takes place during earthquakes and/or wind loading. The excitation frequencies associated with an earthquake usually are higher than the natural frequencies of the steam generator. Therefore, the steam generator tends to remain stationary, during an earthquake while its base moves.
It has been suggested to tie the steam generator rigidly to the upstanding support members in an attempt to transmit dynamic loads from the support system to the steam generator, and thereby relieve the support system of certain stresses. However, when this is done, the steam generator must be specially designed and constructed to withstand such loads which are transmitted from the support system.
As an alternative it has been suggested to employ ties which are designed to disconnect or break during the initial period of response by the steam generator to dynamic loading by the support system, thereby allowing the steam generator to be in a free-swinging mode. This approach virtually eliminates dynamic loading of the steam generator but can result in large displacement of the steam generator relative to the support system, thereby requiring that the support system be designed to accommodate relatively high stresses.
The present invention provides an apparatus and method for transmitting dynamic load from a structural support system to a top-supported steam generator, and for dissipating energy so as to lessen stresses on both the support system and the steam generator. The steam generator is dynamically isolated from the support system through the use of a plurality of dampers connected therebetween. A typical top-supported steam generator has a large mass and tends to serve as a "support" to a deflected support system which tends to "lean" against the steam generator; as a consequence, the support system experiences relatively little deflection and stress while the energy introduced to the support system during an earthquake is dissipated in the dampers. |
ForexNewsNow – Xogee is a leading online forex trading software provider that produces trading platforms which allow forex brokers to offer some of the most advanced services and options in today’s retail forex market.
The company Xogee has more than 10 years of experience in this market which allows it to offer some of the best services available. The platforms developed by Xogee mainly focus on mode devices and web-based interfaces. Most Xogee forex platform reviews aren’t giving enough information about this provider, so we have decided to create a full article about this company.
Xogee’s iPhone Trader is interconnected with the MetaTrader 4 server platform in order to allow online traders to access the services and options available through the MT4 platform right from their iPhones.
The iPhone Trader offers a multitude of options, such as price monitoring, creating watch lists, opening and closing instant and market orders, amends, places and others. It also gives access to an internal mailing system and can create different charts and graphs.
It also has a complete range of technical indicators and drawing objects such as Fibonacci retracement, trend lines and more. The platform can also provide the trader with the latest online trading news and developments.
The iPad Trader pretty much offers the same services as the iPhone Trader, with the only difference that this platform has been customized in order to live up to the standards of iPad users and provide the best visual effects and the most efficient navigation.
The iPad platform has a multi-panel user interface, offers dockable panels, provides advanced charts with technical analysis and offers full support for portrait-landscape orientations. It can also integrate 4 desktops into one and monitor online updating prices in real time.
The iPad Trader can likewise monitor open positions as well as equities and exposures. It can also generate activity reports and contains various advanced features. The navigation of this platform is very user friendly and intuitive.
The Android Trader developed by Xogee has the exact same features as the iPhone Trader. Despite this, the “feel” of the platform is completely different which originates from the fact that it has been customized specifically for Android devices.
It’s very easy to learn to use this platform due to the intuitive design and simple, but elegant navigational menu. Traders also have the possibility to learn using this platform by watching various instructional material provided by Xogee.
The Blackberry Trader designed and developed by Xogee contains the same features and usability as the iPhone and Android platforms. The Blackberry Trader is perhaps the most unique platform from the three smartphone platforms due to the fact that the Blackberry phone functions completely differently than the previous two devices.
WebTrader 4 is a white label online trading platform that can be used by a broker with its own logo and brand colors. It provides fully customizable trading possibilities and does not require the installing of any software whatsoever.
The platform is fully compatible with MetaTrader 4 and offers a multitude of possibilities. For example, traders will have the possibility to open a demo account right in their browsers at a broker that uses the WebTrader 4 platform. This aspect can hugely improve conversions.
The additional features provided by the WebTrader 4 platform are the same as in the case of the iPhone, Android and Blackberry platforms. Special features include a drag and drop technology that allows brokers to build their platform as they desire.
The navigation of this platform is very easy, but Xogee offers traders the possibility to learn every aspect of the platform from a total of 4 tutorials. These can be found on Xogee’s website.
The WebTrader 5 platform contains the exact same features and options as the WebTrader 4. The only difference lies in the fact that this platform is only compatible with the MetaTrader 5 system.
With the help of these two platforms, forex brokers will have the possibility to offer a large selection of services and allow players to access both the MetaTrader 4 and MetaTrader 5 services through a brand-customized software platform.
The success of Xogee is best reflected from the big number of forex brokers that employ its platforms. For example, one forex broker that uses the platforms developed by Xogee is renowned company ACFX. Other brokers include renowned names such as AXITrader, ForexClub, IronFX and FXChoice. |
<reponame>cuba-platform/workflow-thesis<filename>modules/core/src/com/haulmont/workflow/core/app/CardPropertyHandlerLoader.java<gh_stars>0
/*
* Copyright (c) 2008-2015 Haulmont. All rights reserved.
* Use is subject to license terms, see http://www.cuba-platform.com/license for details.
*/
package com.haulmont.workflow.core.app;
import com.haulmont.chile.core.datatypes.impl.EnumClass;
import com.haulmont.cuba.core.entity.BaseUuidEntity;
import com.haulmont.workflow.core.app.valuehandler.BaseCardPropertyHandler;
import com.haulmont.workflow.core.app.valuehandler.DateCardPropertyHandler;
import com.haulmont.workflow.core.app.valuehandler.EntityCardPropertyHandler;
import com.haulmont.workflow.core.app.valuehandler.EnumCardPropertyHandler;
import com.haulmont.workflow.core.entity.Card;
import com.haulmont.workflow.core.app.valuehandler.CardPropertyHandler;
import javax.annotation.ManagedBean;
import java.util.Date;
/**
* @author zaharchenko
* @version $Id$
*/
@ManagedBean(CardPropertyHandlerLoader.NAME)
public class CardPropertyHandlerLoader {
public static final String NAME = "workflow_WfCardPropertyValueHandlerLoader";
public CardPropertyHandler loadHandler(Class clazz, Card card, Boolean isExpression) {
if (BaseUuidEntity.class.isAssignableFrom(clazz)) {
return new EntityCardPropertyHandler(clazz, card, isExpression);
}
if (EnumClass.class.isAssignableFrom(clazz)) {
return new EnumCardPropertyHandler(clazz, card, isExpression);
}
if (Date.class.isAssignableFrom(clazz)) {
return new DateCardPropertyHandler(clazz, card, isExpression);
}
return new BaseCardPropertyHandler(clazz, card, isExpression);
}
}
|
Development of a new ultrasonic liquid flowmeter for very low flow rate applicable to a thin pipe A new ultrasonic liquid flowmeter has been developed to measure very low flow rate. This flow meter consists of small disk ultrasonic transducers and measuring pipe whose diameter is less than 1 mm. The measuring pipe passed through the ultrasonic transducer two times making the loop feature. A very low flow rate less than 1ml/min can be measured accurately and stably. |
Campaigning in the time of coronavirus L ast week, in the midst of lockdown, I attended a DPAC (Disabled People Against Cuts) online event for Ellen Cliffords book launch and rally (DPAC 2020a). Ellens book, The War on Disabled People, recounts DPACs struggles against the past decade of austerity in the UK, situated in the historical context of exclusionary capitalism, whilst providing a contemporary activists guide for a more socially-just alternative. Ellen said the hardest thing about writing her (brilliant) book was not the writing or the research, but the authorial demand that she put herself forward as an individual, not as a collective. The book launch, therefore, was a deliberate return to collaboration, consisting of a rapid and rousing succession of speakers, a solidarity event kick-started by a radical poem and accompanied by kick-ass live music. The event brought DPAC campaigners and supporters together, eliding space as participants connected from across the UK, Greece, the United States and Uganda. A solidarity event full of love, shared pain, remembrance and intention. This is just one example of campaigning in the time of coronavirus. Writing about a moving target is an unstable business, but we can begin to think about what new connections, concepts, practices and potentials are emerging from the technologies of lockdown and the modalities of crisis. The calm and the storms of these Covid-19 times are generating new forms of struggle, a hybrid urbanism (Leontidou 2015, 2020) combining online and on-the-streets campaigning, generating a productive dialectic. I speak from my position in London, the UK, but try to make sense of what I have heard and observed through my own campaign networks of resistance in the broader international context. It may seem ironic that while we are being contained in so many spatial, social and economic ways during the coronavirus pandemic, resistance is being |
/*
http://ozzmaker.com/compass3
The BerryIMUv1, BerryIMUv2 and BerryIMUv3 are supported.
Feel free to do whatever you like with this code.
Distributed as-is; no warranty is given.
http://ozzmaker.com/
*/
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "IMU.c"
int magXmax = -32767;
int magYmax = -32767;
int magZmax = -32767;
int magXmin = 32767;
int magYmin = 32767;
int magZmin = 32767;
int file;
//When Ctrl-C is pressed, we need to print out the high and low values which would then be copied into the main program.
void INThandler(int sig)
{
signal(sig, SIG_IGN);
printf("\n\n\nCopy the below definitions to the start of your compass program. \n");
printf("\033[01;36m#define magXmax %i\n#define magYmax %i\n#define magZmax %i\n", magXmax,magYmax,magZmax);
printf("\033[01;36m#define magXmin %i\n#define magYmin %i\n#define magZmin %i\n\n", magXmin,magYmin,magZmin);
exit(0);
}
int main(int argc, char *argv[])
{
int magRaw[3];
detectIMU();
enableIMU();
signal(SIGINT, INThandler);
while(1)
{
readMAG(magRaw);
printf("magXmax %4i magYmax %4i magZmax %4i magXmin %4i magYmin %4i magZmin %4i\n", magXmax,magYmax,magZmax,magXmin,magYmin,magZmin);
if (magRaw[0] > magXmax) magXmax = magRaw[0];
if (magRaw[1] > magYmax) magYmax = magRaw[1];
if (magRaw[2] > magZmax) magZmax = magRaw[2];
if (magRaw[0] < magXmin) magXmin = magRaw[0];
if (magRaw[1] < magYmin) magYmin = magRaw[1];
if (magRaw[2] < magZmin) magZmin = magRaw[2];
//Sleep for 0.25ms
usleep(25000);
}
}
|
// problem_660_B.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include <stdio.h>
int n, m;
int a[128][4];
int c[4];
void add(int i, int p)
{
a[c[p]][p] = i;
c[p]++;
}
void print_p(int h, int p)
{
if (h < c[p])
{
printf("%d ", a[h][p]);
}
}
int main()
{
scanf("%d %d", &n, &m);
for (int i = 1; i <= m; i++)
{
if (i <= n * 2)
{
add(i, (i - 1) % 2 * 3);
}
else
{
add(i, (i - 1) % 2 + 1);
}
}
for (int i = 0; i < n; i++)
{
print_p(i, 1);
print_p(i, 0);
print_p(i, 2);
print_p(i, 3);
}
return 0;
}
|
<reponame>neizod/problems
#!/usr/bin/env python3
import re
TAPE = { 'children': 3,
'cats': 7,
'samoyeds': 2,
'pomeranians': 3,
'akitas': 0,
'vizslas': 0,
'goldfish': 5,
'trees': 3,
'cars': 2,
'perfumes': 1 }
def is_sue(features):
for feature, amount in features.items():
if feature in {'cats', 'trees'}:
if not TAPE[feature] < amount:
return False
elif feature in {'pomeranians', 'goldfish'}:
if not TAPE[feature] > amount:
return False
else:
if not TAPE[feature] == amount:
return False
return True
def find_aunt(sues):
for number, features in sues.items():
if (is_sue(features)):
return number
def main():
try:
sues = {}
while True:
number, info = re.findall(r'^Sue (\d+): (.*)$', input().strip())[0]
sues[int(number)] = {k: int(v) for e in info.split(', ') for k, v in [e.split(': ')]}
except EOFError:
print(find_aunt(sues))
if __name__ == '__main__':
main()
|
package uk.co.downthewire.jLTE.experiments.results;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
public class EALogFileReaderTest {
@Test
public void parseEALogFile() throws IOException {
String filename = "src/test/resources/ea_log_file.log";
EALogFileReader eaLogfileReader = new EALogFileReader(filename);
List<String> results = eaLogfileReader.getResults();
assertEquals("1.1637914666526057,0.05802028405308153,0.10030674862123563,0.013285574343819448,4,0.5813194990362789,0.7503021779880691,true,0.136312832842726,0.8404454700268283", results.get(0));
}
}
|
<reponame>ythecombinator/.space<filename>src/components/common/events-listing/header/styles.ts
import styled from 'utils/styles';
interface HeaderProps {
image: string;
}
export const Header = styled.header<HeaderProps>`
height: 150px;
width: 100%;
padding: 15px;
background-size: cover;
background-image: ${(props) => `url(${props.image})`};
`;
export const Title = styled.p`
text-transform: uppercase;
margin: 0;
background: ${(props) => props.theme.colors.background};
color: ${(props) => props.theme.colors.texts};
box-sizing: border-box;
display: inline-block;
font-size: 16px;
font-weight: 600;
line-height: 16px;
padding: 0.5rem;
text-decoration: none;
`;
|
Plea Bargain In White-Collar Crimes: An Argumentative Analysis Plea bargain is a widely practiced and common characteristic in various international legal systems. However, in Pakistan it is rebuked for providing a legitimate outlet to white-collar offenders so they are not only able to clear their names from National Accountability Bureaus (NAB) investigation, but are also absolved from heavy financial penalization by submitting a meagre amount from their fraudulently acquired wealth. This article aims to study the theory of plea bargain and its origin, based on the theoretical research method of study. A critical analysis of the societal and constitutional implications of article 25 of National Accountability Bureau Ordinance (NAO), 1999 Pakistan, is also done. Coherent arguments are given in favour of retaining the provision of plea bargain while proposing specific guidelines to enhance the transparency of this process. Introduction This article intends to establish a coherent jurisprudential debate in support of the statutory option of plea bargain available to the financial/ white collar criminal given as clause 25 NAO. Additionally, the article will examine the legal intricacies and controversies regarding the moral implications as well as the legislative philosophy and efficacy connected with plea bargain. During the time this article is written, the Government of Pakistan is working to amend the NAB statute in its entirety and introduce comprehensive guidelines for the betterment of the said section in order to ensure justice and transparency in the recovery of money. These legislative amendments are taking place when Pakistan is at the juncture of economic insolvency and the hope of prosperity in future. The State has decided to recover money from white-collar offenders who have used their social stature, political power and public-office position to commit fraud, corruption or money-laundering. In this regard, the role of the National Accountability Bureau (NAB) has taken the centre stage, as major recoveries are being done via NAB. Similarly, the article of plea bargain in NAB Ordinance, 1999 (NAO) is also being widely discussed for its lack of transparency and legislative ambiguities. As stated above, this article will argue in favour of retaining the provision of plea bargain; nevertheless, it is also acknowledged that there is an urgent need to improve the mode of operation with respect to the implementation of this section, as well as to make the role of NAB credible, just and transparent. Therefore, a comprehensive argument is made through this research to enhance the legislative procedure of plea bargain for white-collar crimes. Selective portions of section 25, are reproduced herein below for the reference of the reader: "where a government officer. willingly confesses and agrees to return the gains obtained by him, the NAB Chairman has the power to accept the proposed amount the Chairman while using his discretionary authority accept the offer given by the accused on terms as he deems appropriate". In cases of civil nature plea bargaining (also referred to as 'negotiated settlements' or 'plea agreements') is described as concerting of an agreement where each party, involved in the plea bargain agrees to waive some legal entitlements, which they may have, if the case went either to the court for regular hearing or it was presented for an administrative hearing, and in both procedures the matter ends with a formal judgement. Moreover, during the procedure of plea bargaining the government body/agency would have to surrender certain rights for imposing enhanced penalizations, similarly the defendant also relinquishes certain legal safeguards which a formal trial would provide. In some cases, plea bargain also implies the waiver of any possibility from being exonerated and both parties consent to some form of a deal. In criminal law plea bargain is defined as a formal settlement that takes place between the defendant and the public prosecutor, wherein the former pleads guilty Plea Bargain in White-Collar Crimes: An Argumentative Analysis 75 to either a reduced charge or when indicted for several charges, the accused cop a plea to one or more charges, and in some cases even resulting in complete dismissal of charges. Negotiations involved in "implicit plea bargains" provide no guarantee of leniency. While the negotiations which result in normal or customary agreements are termed "explicit plea bargains". Archival traces of plea bargain became evident around 1692 in the colonial era during a series of witchcraft cases, called the Salem Witch Trials. These cases were brought before the magistrates of the Massachusetts Bay Colony's settlement named Salem. In these trials the accused witches were given the option to either confess to committing witchcraft and remain alive or be executed if they refuted the allegations against them. The magistrates of Salem encouraged confessions as they wanted the witches who confessed to testify against other women accused of witchcraft (Burr, n.d.). Many of the accused women were saved from execution due to their confessions. Subsequently, it was the Salem Witch Trials which became the persuasive contention against the concept of 'plea bargain' since this procedure visibly indicated that every so often innocent individuals could be propelled to confess to the crime which they did not commit. Plea bargaining was strongly disapproved by the Appellate Courts during the Anglo-American time, rather it was generally met with strong disapproval on part of the. However, in the post-World War II years when the societal conflict in America was beginning to emerge as a result of rapid industrialization, urbanization and immigration, it affected the political institutions and made them spare and fragmented. Amidst of significant criticism in the late 19 th century plea deals gained momentum, and the courts formally allowed plea bargaining to efficiently dispose of the cases, to promote political and economic stabilization. Henceforth, the occasional leniency offered under common law was restructured as plea bargain. Plea bargain consists of three main kinds: i) Charge-bargaining: the offender accepts the guilty plea for reduced charges, such as, being indicted for causing serious bodily injury rather than attempted murder; ii) Sentence-bargaining: in this deal the defendant receives guarantee of lesser / alternate sentencing in return of pleading guilty to the offence; iii) Count-bargaining: a defendant who is convicted for multiple charges is permitted to plead guilty to lesser offences. However, the offences committed are not necessarily analogous, and the State may reduce charges in return of a confession by the accused. It is an a periodic bargaining because it is used only in the cases of defendants who are charged with multiple offences. Plea bargaining refers to an agreement of defrayals and settlement of cases between corporations/individuals and the prosecuting authority for committing white-collar crimes like money laundering, scams, tax evasion, etc.. It comprises financial penalty and remedial measures, presented before the court for approval (Dervan, n.d.). In some cases it also involves making deferred prosecution agreements, through which companies are effectively put on probation, while also deferring full prosecution on the prerequisite that the stipulations stated in the agreement are met, thereby, preventing companies and /or individuals from convictions and allowing them to continue with their businesses, professions and occupational responsibilities. Research Questions, Objective and Scope 1. How effectively has NAB adopted the principles of plea bargain, a concept which has its roots in the US criminal justice system? 2. Is Pakistan's current judicial system equipped with the appropriate regulatory framework that is able to ensure transparency and integrity in monetary recoveries from white collar offenders? Resolving the cases of white collar crime has become an integral part of the criminal justice system in Pakistan. Notable fiduciary organs like the State Bank and Securities and Exchange Commission of Pakistan have suffered huge losses to national exchequer due to financial offences of businesspersons, public-office holders, public leaders, etc. Therefore, this article aims to propose efficacious regulatory/ legislative recommendations that could be incorporated in the NAB statute to bring transparency as well as productivity in the financial recovery procedure which significantly revolves around plea bargaining with the offenders. This research article is primarily focused on the advancement and strengthening of the plea bargaining process adopted by NAB, although references have been made to cases of foreign jurisdictions yet the area of study is limited to Pakistan only. Review of Literature Plea deal is an acknowledged element of the U.S. legal system and has been used in Britain since 2015, it allow companies to circumvent criminal prosecution in a judicially permitted deal that often consists of fine and regulatory compliances. Nonetheless, in Pakistan, plea bargain is denunciated for being an escape route for the unscrupulous to 'clean' their misappropriated wealth by offering the State a trifling amount while retaining the major portion with themselves. The practice of plea bargain in Pakistan is censured not only for benefitting the elite white-collar offenders but also for absolving them from penalisation for their illegal gains. Prima facie the provision of plea bargain in NAB Ordinance seems reasonable as it is cost-effective in utilizing the tax-payers' money and beneficial for the national exchequer, whereby, it receives the amount wrongfully acquired by a white-collar/financial offender. However, the drawback of this provision became apparent when NAB failed to receive any substantial amount in recovery from the offenders. If in a case NAB was able to make a plea bargain the money received was not only insignificant, but the investigation was always considered dubious and done for political victimization. Regrettably, this was the reality as well as a highly strong perception amongst the general public; nevertheless, in the years 2018-2019 NAB began to restore the trust of public as it conducted serious investigations of high-profile businesspersons, corporations, politicians, etc. and recovered Rs. 3349.736 million on account of plea bargain and voluntary returns and a further Rs. 21051.2 million by way of indirect recoveries with approximately 67 percent conviction rate in the courts. Yet the legal problem and the moral dilemma of Plea Bargain is quite prevalent, highlighting the key lacunae of section 25: 1) the indiscriminate powers given to the NAB Chairman to unilaterally decide the recovery amount. 2) The Chairman is under no legal obligation to consult, inform the law ministry, trial court and/or high court while he is settling the plea deal with or discharging the offender from any liability and allegation. From NAB's viewpoint, plea bargain can result in efficient utilization of its time and financial resources and could also lead to improved implementation of its policies ultimately resulting in better crime prevention mechanism. It has become a tradition to only publicly accuse or convict politicians for concealing their offshore income or illegally accumulated wealth, whereas companies, businesspersons, and public-office holders with far more greater financial crimes quietly enters into plea agreements with the NAB. Here, it is significant to mention that the Chairman NAB has unbridled powers to accept any monetary deal on behalf of the State from a white collar offender, and he has to merely inform the Court about the deal. Moreover, due to the abuse of political power, corruption, absence of judicial guidelines, lack of legislative or administrative control mechanisms regarding the modalities of plea bargain the elite offender gets superior treatment. According to financial and legal experts plea bargains may have their utility, yet applying this method as the standard operating procedure in Pakistan, to recover the misappropriated money should be discouraged. Rather, our legislature is required to make concentrated efforts in restructuring the plea bargain process in cases of financial impropriety. In general, financial culpability must be fair and transparent, and everyone who is indicted for white collar crimes must be brought to justice, irrespective of their occupational respect or financial status. There are two contrasting ends to the broad spectrum of plea bargaining (Brown & Bunnell, 2006) its opponents argue that it frustrates the process of justice by infringing the due process of civil, administrative and the criminal justice system, whereas, its exponents argue that it results in swift court proceedings along with a guaranteed conviction. The debate is advanced in the following sections, by primarily discussing the criticism against plea bargain followed by the supportive view of its proponents. Many legal scholars argue that plea bargaining permits white collar criminals to escape appropriate punishment for their crimes; it unjustifiably pressurizes gullible defendants to agree to plea agreements due to their unawareness regarding the justice system; and at times it castigates those corporations or individuals who exercise their constitutional right to opt for trial. The major flaw in plea bargaining is excessive discretion granted to NAB Chairman in comparison to the judges, who are required to adhere to precise sentencing standards. According to one study, prosecutors have applied various methods of coercion and threatened the defendants to consent to plea settlements just to get a conviction, even though the evidence against them was insufficient. Moreover, several researchers have observed that as a result of wide latitude given to the competent authority, prosecutorial preferences influence the plea bargaining process. Additionally, several other studies have found that offenders who consent to plea bargaining can also receive lighter sentences due to the prosecutorial discretion; whereas the offenders who choose to be tried in the courts tend to receive severe punishments. Various international research studies have expounded that factors such as race /caste, socioeconomic status, gender and age of defendants significantly contributes in accentuating the extrajudicial nature of plea bargain. Hence, studies also indicate that the extrajudicial characteristics of plea bargaining puts an offender belonging to ethnic minority in a vulnerable position as he/she might not be able to receive a just and reasonable plea settlement from the prosecuting authority. It has been found through strong evidence that the legal and extrajudicial nature of plea bargaining may significantly influence the legal proceedings depending on the region where the case is being investigated/ heard along with the prosecutorial discretion that is exercised. Chances of exploitation increase immensely when unilateral powers are exercised by prosecuting authorities, as innocent individuals could be incriminated and coerced to pay money. Therefore, to avoid flagrant violations of human rights, it is mandatory to have a definite mechanism of judicial control. Unfortunately, the unbridled powers of law enforcement agencies in Pakistan have the ability to threaten defendants with agglomerated charges against them if Plea Bargain in White-Collar Crimes: An Argumentative Analysis 79 they fail to give consent to or cooperate in giving the plea bargained amount, thereby effectively creating a 'threatening' atmosphere. Plea bargains can also be coercive when legal safeguards are bypassed, for instance encouraging the accused to make a deal when she/he has no access to legal advice, or there is absence of an attorney who can inform them of their rights or not to divulge any of the evidence against them. Research Methodology For this article researcher has adopted doctrinal method of research, since the material analysed herein was specifically based on the principles of law, statutes, information collected from various legal-research articles and judgements of higher courts in Pakistan. The legislative justification for incorporating the provision of plea bargain is for expediting criminal justice so authorities can avoid expensive and long trials, and succeed in recovering financially misappropriated amount. Contrariwise, due to plea-bargain many of the accused individuals are either taken into custody or in judicial remand, and compelled to give some amount of misappropriated/looted money-although the case against them is quite weak that it could have been dismissed due to lack of evidence. Results & Findings Based on Policy Justifications in Plea Bargain for White Collar Crimes This indicates that NAB investigators and prosecutors are held to lower standards of investigation-and there is always a risk for individuals who enter the investigative process of NAB that they could be forced to take plea bargain or face the potential 'criminal case as well as public denigration,' whether they actually perpetrated or not. Furthermore, plea bargain creates a two-layered criminal justice system in Pakistan, where on one hand the privileged class offenders can easily afford expensive lawyers giving them advantageous position to avoid punishments, while, on the other hand, sole proprietors, small and medium business owners who do not have access to high-profile lawyers can be unreasonably proscribed. Additionally, an indictment of a wealthy and powerful money launderer or tax evader, or an offender of varying financial crimes could quietly settle, within the office parameters of the NAB chairman, for a much less amount than what he had acquired through illegitimate means. The public would never be able to know the identity of the white-collar criminal who could have been a prominent businessman, politician, holder of a public office, a doctor or even a lawyer. This kind of secrecy during plea bargaining violates the right of every citizen to have access to information which could directly infringe their constitutional right to information thus affecting their lives and economic condition of their country. Although from several supporting studies we could infer that both the prosecutorial discretion and the extrajudicial nature of plea bargain are able to affect adversely the indictment process for the white collar criminal ("Harvard Law and Economics Discussion Paper ", 2006), completely scrapping of the provision of plea bargain could over-burden court work. In this regard, various scholars and policymakers have expounded that there is a need to reform the process by limiting the prosecutorial discretion and introducing structured policy and legislative measures that will require firm guidelines when opting for plea bargain in financial or economic crimes, thereby, mandating that both the judiciary and the prosecuting authority in-charge of the plea bargaining process practice substantial balance of power for all the parties involved. Therefore, it is imperative to mention that plea bargaining should be dealt with objectively so that the disparities within the system could be addressed effectively. Edward W. Sutherland coined the term white-collar crime in 1939 and also highlighted the multifarious aspects of this kind of financial crimes. Yet there were two main aspects of his research on the subject: 1) the socio-economic and professional status of the offender, 2) how easily the elite category of offenders can use their status in order to escape punishments and judicial/public reprimand. In order to deter the elite-offender from manipulating the process of justice it is imperative to strongly adhere to the concept and definition of white collar offences as given by Sutherland. The actual outcome of punishment should be to restrain an individual from committing of injurious and wrongful acts. The punishment meted out to a criminal should be an example for others and must serve as a warning that similar actions on their part would be dealt with similar punishment. Some schools of criminology believe in the exemplary theory of punishment according to which the punishment should be quick and harsh. The use of punishment is a means by which fear of crime can be aroused in people. It can be argued that true purpose of punishment is the welfare of society. Though the punishment is harsh, it serves as an example, excites fear of crime in general public, and thus really minimizes the occurrence of crime which in turn promotes the welfare of the society. Keeping in view the above argument, it is significant that the name and full identity of the white collar offender who agrees on plea bargain should not be kept confidential. After the approval of the plea agreement from the court, charges laid and the amount received from the financial offender should be revealed to the Plea Bargain in White-Collar Crimes: An Argumentative Analysis 81 general public by the financial authority. This measure not only satisfies the enquiry that was raised by Sutherland that a wealthy and respectful financial criminal influences the justice system, so his/her name is not shared with the general public and she/he could continue to live in the society as a respectful citizen of the country. To support my argument, I would like to discuss the punishments announced by the District Attorney of Massachusetts, on March 2019. William Rick Singer was arrested for racketeering, conspiracy, obstruction of justice and money laundering conspiracy. Singer provided the services of college counselling and entrance-test preparation through his company called "Edge College & Career Network LLC". Singer was also the CEO of an alleged charity named Key Worldwide Foundation (KWF). He was indicted for organizing nationwide bribery in SAT and ACT exams so the administrators would give permission to bogus candidates to secretly take college entrance exams in place of actual candidates. The exam administrators also corrected the answers for students after the test. Singe also bribed athletic coaches and administrators at the Yale University, Stanford and Georgetown University, UCLA, and University of Texas so they could facilitate the wrongful admission process of ineligible candidates to the elite universities as athletes. Singer used his charity KWF for money-laundering and concealing the sources of the bribes. Approximately 33 parents paid substantial amount of money so their children would be able to have guaranteed admissions in some leading schools. The District Attorney stated that the parents who were involved in the fraud and bribery were the ideal examples of wealth and societal privilege and included the CEO's of companies, prominent real estate investors, well-known actresses, a well-known fashion designer and even chairman of an international law firm. The list of convicted professionals in the scam comprises athletic coaches of elite university, SAT/ACT exam administers, college administrator, exam proctor, educational coaches at Yale, Harvard, UCLA, etc. All the above-mentioned individuals were charged on several counts of white-collar crime, wherein, many consented to different kinds of plea bargains-ranging from lessening of severity of charges & imprisonment time to paying monetary fine: 1. Charges on William Rick Singer: racketeering, money-laundering, deception of government and obstructing justice. 2. Charges on Rudolph Meredith (Aka Rudy) ex-coach of women's soccer team at the Yale University: honest services fraud and wire-fraud. 3. Charges on John Vandemoer ex-coach of sailing at the Stanford University: racketeering and conspiracy. We can conclude from the above information that it's important to publicise identity of the white collar criminal along with complete details of the offence and how the sentence was settled through plea bargain so that apprehension of public humiliation could be provoked in society, which might to a certain extent, aid in creating deterrence. Some researchers of crime and penology believe that public humiliation and judicial-moral shaming of offenders is gaining recognition in the courts resulting in authentic demonstrations of remorse and apology from the defendants. Support for this argument can be found in Fritz Heider's developed models of attribution (Theory of Attribution), as well as in Social Exchange Theory that was created by George Homans in 1958(Malle, 2011. Rationale for Plea Bargain From the above case we can further infer that plea bargaining can be costeffective for the tax-payers money as it provides an efficient mechanism for monetary recoveries. When the convicted individuals and companies accept the charges based on sound evidence through plea settlements, it effectively reduces the time of the courts to go through a detailed litigation and only a summary trial would dispose of the matter. Plea bargaining offers substantial advantage to the accused as well, by providing them the opportunity to be on-board in the disposition of their cases and produce more transparent and certain results. However, plea bargaining can gain societal and legal acceptance only if NAB is able to successfully establish its reputation for being fair, consistent and always acting in good faith. In this regard, transparent and predictable procedural guidelines governing the plea settlements should be developed that would also permit certain flexibility on case-to-case basis (Wray & Hur, 2006). Plea bargain can also become highly productive if NAB establishes an authentic, updated public record of every monetary settlement it makes. So publishing plea bargains, reviewing guidelines on regular basis can contribute to achieve the desired goals. Similarly, fair and transparent bye-laws and detailed rules are to be drafted to monitor plea bargain. It is imperative that defendants are given awareness of the rewards for cooperation along with the risks involved in case of failure to reach an agreement. The stage when the court is involved in such cases, transparency of procedures and complete information about the offence and the aptness of a proposed fine/recovery-amount will add to the credibility of plea bargaining, while effectively alleviating any apprehensions regarding the after effects of plea deal on the fundamental rights of the offender. To increase credibility in the process and lower the risk of an erroneous assessment of monetary compensation or recovery from the defendant, NAB should pursue to make deals with the offenders only in the cases where it has established all the relevant facts through unshakable evidence. So it is vital that the financial settlements should correctly estimate the loss to economy by a particular white collar offender as this can directly affect the overall deterrence impact. If conducted accurately the society at large could also benefit from plea bargains as they can play a vital role in productively utilizing limited resources and maximizing deterrence. Conclusions It is pertinent to highlight NAB's plea bargaining process before the recommendations are given. According to the plea bargain data available on NAB'S online database for the period of ( NAB since its inception has always been under severe public and media scrutiny and criticism("Increasingly controversial NAB", 2018). In numerous cases NAB authorities have been accused of harassing and blackmailing businesspersons and political rivals of the ruling parties. Although NAB has been able to recover more than Rs. 300 billion over the period yet the covert and unilateral nature of plea bargain decisions taken by NAB Chairman were always shrouded with controversies. It is the most appropriate time to ensure the trust of public in NAB is safeguarded. Therefore, in order to retain public's confidence in NAB the process of plea bargaining should be revamped-as it could prove to be a vital instrument for recovering misappropriated money provided if appropriate safeguards are in place. Furthermore, plea bargain could also result in more efficient criminal justice system for white-collar crimes (Attorney General, n.d.). The following recommendations give a framework for further legislation of guidelines and regulations: 1. NAB should act fairly, unambiguously, and in the interests of justice while making the decisions for plea-bargaining. NAB should fully ensure that the financial deal reflects the seriousness of the offence and that NAB will not consent to a lesser amount of plea bargain than which is due and correctly calculated. 2. An independent body within NAB is required to be created, which will decide the terms of plea bargain individually, on case-to-case basis. No individual should be authorized to unilaterally decide any condition for settling the recovery amount or releasing the accused from NAB's reference or investigations. 3. Rules for the modus operandi will be made comprehensively and fairly valuing the legal rights of an individual/ company being investigated for white collar offenses. 4. To initiate the negotiations for plea bargaining NAB will send an official letter to the defendant's lawyer asking the defendant's lawyer to enter into negotiation for plea bargain. 5. NAB or any of its prosecutors will not coerce an accused person during the course of plea bargain; and while adhering to the best standards of transparency NAB should ensure that: a. Comprehensive record of the entire negotiations of plea bargaining will be maintained; b. Defendants will be given proper information with respect to their cases; c. Every term of the plea bargain between NAB and a defendant will be written in a Plea Agreement, and any deal/agreement before becoming effective will be presented in the court providing an accurate description of the terms and conditions agreed upon; d. Prosecuting authority is not permitted to settle with a defendant on any additional matters that are not mentioned in the agreement of plea settlements presented before the court. 6. Finalized and signed plea agreement will be treated as the evidence of confession. 7. Finalized written plea agreement shall be signed by both parties before its presentation to the court and shall consist of: 1) complete statement of the facts and charge, 2) a signed declaration by the defendant whereby he/she accepts the stated facts and concedes to his /her guilt on the agreed charges; 8. NAB will provide the court sufficient material (including any correspondence and minutes of any meetings held between the parties) so the judge is able to assess the fairness of the plea bargain; 9. Once the plea deal is presented in the court, it would be the court's prerogative to approve or reject the plea bargain agreement; 10. Categories of updated white-collar crime, base count (that is severity of the crime), sentencing-guidelines and fast track system of prosecution for financial/economic crime cases will be introduced by NAB. 11. Any information provided by the defendant or his lawyer will only be disclosed to another party if it is required by law and will be treated with confidentiality; 12. Legal representative of the defendant will be required to give a signed affidavit in to that the information shared by the prosecutor during plea discussions shall remain confidential. Unless the matter of 'confidentiality' is satisfactorily agreed between the parties in the form of signed undertakings, the prosecuting authority will not continue with the plea bargain negotiations. 13. NAB will make available to the public complete and updated statistics of every white-collar crime it enquires, investigates, file references for and make deals of plea bargain. |
A grand jury has indicted six Cleveland police officers in the deaths of two unarmed suspects, who were killed in a spray of 137 bullets after a wild car chase that ended in a schoolyard, the Associated Press reports.
The indictment on Friday is part of a far-reaching federal investigation into “the Cleveland Police Department’s use of deadly force and its pursuit policies,” the AP reports.
Since both suspects were black, the specter of racism hovers over the case and represents a major part of a federal investigation into the department, the AP says. Timothy Russell, the driver, was shot 23 times, and Malissa Williams, the passenger, was shot 24 times. No guns were found in their possession or inside the vehicle, the AP reports.
McGinty said the shootings occurred after the suspects had been subdued and the public safety threat was over, the AP says. The incident involved five dozen cruisers and raced through residential neighborhoods, onto Interstate 90 and eventually ended in East Cleveland, the AP says. McGinty said the chase covered 20 miles over 23 minutes and reached speeds of 110 mph.
Capt. Brian Betley, the leader of the Fraternal Order of Police, which represents police supervisors, told the (Cleveland) Plain Dealer that he was disappointed in the grand jury's findings.
Read the entire story at MSN. |
<reponame>callwyat/Quiet-Firmware<gh_stars>0
/*
* File: i.h
* Author: callwyat
*
* Created on October 17, 2021, 2:41 PM
*/
#ifndef CLI_H
#define CLI_H
#ifdef __cplusplus
extern "C"
{
#endif
#include <stdint.h>
#include <stdbool.h>
#define CLI_WORD_SIZE 24
typedef enum
{
HexFormat,
DecimalFormat,
} NumberFormat_e;
typedef union CliHandle_t
{
struct
{
char LastRead;
char LastWord[CLI_WORD_SIZE];
char; // Put a null that can't be addressed at the end of the string
char (*Read)(void);
void (*Write)(char);
uint8_t (*GetReceivedCount)(void);
char *ReceivePnt;
};
} CliHandle_t;
#define DEFINE_CLI_HANDLE(getRxCount, read, write) \
{ \
.Read = read, \
.Write = write, \
.GetReceivedCount = getRxCount, \
}
typedef void (*CommandHandle)(CliHandle_t *handle, void *channel);
typedef struct CommandDefinition
{
const char Command[5]; // Needs to hold four letters and a null
struct CommandDefinition *Children;
uint8_t ChildrenCount;
CommandHandle Handle;
} CommandDefinition_t;
#define DEFINE_COMMAND(command, handle) \
{ \
.Command = command, \
.Handle = handle, \
.Children = 0x0000, \
.ChildrenCount = 0, \
}
#define DEFINE_BRANCH(command, children) \
{ \
.Command = command, \
.Handle = 0x0000, \
.Children = &children[0], \
.ChildrenCount = sizeof(children) / sizeof(children[0]), \
}
#define DEFINE_COMMAND_W_BRANCH(command, handle, children) \
{ \
.Command = command, \
.Handle = handle, \
.Children = &children[0], \
.ChildrenCount = sizeof(children) / sizeof(children[0]), \
}
bool SCPICompare(const char *reference, char *input);
void ProcessCLI(CliHandle_t *handle, CommandDefinition_t *commands);
void ProcessCommand(CliHandle_t *handle, CommandDefinition_t *commands);
void SetNumberFormat(NumberFormat_e format);
NumberFormat_e GetNumberFormat(void);
void WriteNumber(CliHandle_t *handle, uint24_t input);
char inline ReadChar(CliHandle_t *handle);
char *ReadWord(CliHandle_t *handle);
bool ReadBool(CliHandle_t *handle);
uint16_t ReadInt(CliHandle_t *handle);
uint24_t ReadInt24(CliHandle_t *handle);
uint16_t ReadIEEEHeader(CliHandle_t *handle);
void WriteIEEEHeader(CliHandle_t *handle, uint16_t dataSize);
void QueueErrorCode(uint16_t);
uint16_t DequeueErrorCode(void);
void ClearAllErrors(void);
void WriteChar(CliHandle_t *handle, char c);
void WriteString(CliHandle_t *handle, const char *word);
#ifdef __cplusplus
}
#endif
#endif /* CLI_H */
|
1. Field of the Invention
The present invention relates to a novel diphosphine compound characterized by introducing an oxygen-containing functional group bonded via an oxygen atom such as an alkoxy group to the benzene rings of an optically active diphosphine compound having two benzene rings of a biphenyl skeleton at the 4- and 4′-positions thereof, a transition metal complex containing said diphosphine compound, a catalyst for an asymmetric synthesis comprising said transition metal complex, and a method for producing an optically active compound characterized by subjecting an unsaturated compound to an asymmetric reduction in the presence of said transition metal complex.
2. Description of the Related Art
Recently, an asymmetric synthesis using a transition metal complex containing a diphosphine ligand has been desired a formulation of various diphosphine ligands so as to improve the performance of the reaction. Patent literature 1, for example, discloses various diphosphine ligands having a ((5,6),(5′,6′)-bis(methylenedioxy)biphenyl-2,2′-diyl) group, specifically ((5,6),(5′,6′)-bis(methylenedioxy)biphenyl-2,2′-diyl)bis(diphenylphosphine) (hereinafter referred to as SEGPHOS).
Patent literature 2 describes an asymmetric diphosphine compound introducing a methoxy group to a benzene ring that is different from methylenedioxybenzene, however, it does not describe an example of synthesis of the asymmetric diphosphine compound introducing a methoxy group, nor an example of synthesis of a symmetric diphosphine compound introducing a methoxy group, nor a reaction example of an asymmetric hydrogenation using the diphosphine compound as a ligand.
Non-patent literature 1 describes synthesis of a SEGPHOS derivative formed by substituting a methylene proton of methylenedioxybenzene with fluorine and its application to asymmetric hydrogenation as a ruthenium complex, but does not show any practical data thereof. Non-patent literature 2 describes synthesis of a SEGPHOS derivative formed by substituting a methylene proton of methylenedioxybenzene with an alkyl group and its application to asymmetric hydrogenation as a ruthenium complex, but hardly contributes to improvement of asymmetric recognition.
Patent literature 3 describes a ligand substituting at the 3- and 3′-positions, and patent literature 2 describes a ligand having different modes of substitution in two benzene rings, however, both ligands have a complicated synthesis route and are difficult to use industrially due to an insufficient substrate/catalyst ratio of about 100 in the symmetric hydrogenation. Patent literature 1: JP-A-10-182678 Patent literature 2: WO 02/40492 pamphlet Patent literature 3: WO 02/40491 pamphlet Non-patent literature 1: Synthesis, 2004, 326 Non-patent literature 2: Tetrahedron: Asymmetry, 2004, 15, 2185 |
Thermal Treatment Method for Synthesis and Characterization of the Octahedral Magnetic Nanostructures of Co3O4 from a New Precursor Abstract Magnetic Co3O4 nanostructures were synthesized via a facile thermal treatment method at 700°C by using trans-Na.H2O as a new precursor. In synthetic process Co-complex was prepared by the reaction of Na3 and hexamethylenetetramine (HMTA). Results show that the target Co-complex was synthesized successfully and provides good conditions for preparation of magnetic nanostructures in a facile and surfactant-free method to prepare the octahedral nanostructures. Precursors and nanostructures were characterized by scanning electron microscope (SEM), X-ray diffraction (XRD), UVvisible, Fourier transform infrared (FTIR) spectroscopy and alternating gradient force magnetometer (AGFM). It is found that the Co3O4 nanostructures exhibit a ferromagnetic behavior with a saturation magnetization of 8.69 emu/g and a coercivity of 305.3 Oe at room temperature. |
Kerosene lighting contributes to household air pollution in rural Uganda The literature on the contribution of kerosene lighting to indoor air particulate concentrations is sparse. In rural Uganda, kitchens are almost universally located outside the main home, and kerosene is often used for lighting. In this study, we obtained longitudinal measures of particulate matter 2.5 microns or smaller in size (PM2.5 ) from living rooms and kitchens of 88 households in rural Uganda. Linear mixed-effects models with a random intercept for household were used to test the hypotheses that primary reported lighting source and kitchen location (indoor vs outdoor) are associated with PM2.5 levels. During initial testing, households reported using the following sources of lighting: open-wick kerosene (19.3%), hurricane kerosene (45.5%), battery-powered (33.0%), and solar (1.1%) lamps. During follow-up testing, these proportions changed to 29.5%, 35.2%, 18.2%, and 9.1%, respectively. Average ambient, living room, and kitchen PM2.5 levels were 20.2, 35.2, and 270.0 g/m3. Living rooms using open-wick kerosene lamps had the highest PM2.5 levels (55.3 g/m3 ) compared to those using solar lighting (19.4 g/m3 ; open wick vs solar, P=.01); 27.6% of homes using open-wick kerosene lamps met World Health Organization indoor air quality standards compared to 75.0% in homes using solar lighting. |
FORT LAUDERDALE -- Fort Lauderdale was rescued from playoff elimination in gallant style Saturday night.
The Three Amigos -- Argentines Ricardo Alonso, Pedro Magallanes and Marcelo Carrera -- led the Strikers to a 5-2 thumping of the Tampa Bay Rowdies before 4,133 at Lockhart Stadium in the Strikers' final regular-season game.
Magallanes, who scored the winning goal Friday at Orlando, scored Fort Lauderdale's second, third and fifth goals for his first hat trick of the season.
Alonso, the American Soccer League's scoring leader with 27 points, scored the Strikers' first and fourth goals, and assisted each Fort Lauderdale goal he didn't score.
Carrera assisted four of Fort Lauderdale's goals, guiding the Strikers' stylish attack from his midfield position.
Facing the end of their season with a loss, the Strikers (12-8) were on a tear all night, the likes of which hadn't been seen this season in Lockhart Stadium, with the Three Amigos playing one-upsmanship the entire time.
The assists, such a Magallanes' backward kick that set up the first goal, were bettered only by the acrobatic goals.
Perhaps the amazing charge was capped by Fort Lauderdale's fourth goal, which Alonso scored while lying on his side.
"We scored some great goals today," said keeper Arnie Mausser, "especially since we needed them so much."
The Rowdies (11-8) beat Fort Lauderdale 3-0 twice this season, but collapsed Saturday after closing the game to 2-1 with nine minutes left in the first half with a 25-yard shot by Gregg Willin.
The Strikers countered with Magallanes' second goal with :51 left in the half, and Alonso scored his on-the-side goal five minutes into the second half.
"That was the killer," coach Thomas Rongen said. "You always like to score late in the first half and early in the second. It gets the other team down, and it did tonight."
Fort Lauderdale entered the night third in the ASL's Southern Division, but came out on top of the standings with 35 points -- and can still win the division.
The Washington Diplomats (11-8) lost to Albany 3-2 Saturday, and have 33 points with a game left today at New Jersey. Tampa has 32 points, and plays at Miami today.
The only way Fort Lauderdale can be kept out of the playoffs is if both the Diplomats and Rowdies win today in regulation -- amazing, considering that Fort Lauderdale started the season without a goal in its first four games and has been battling injuries and suspensions ever since.
"We are playing with confidence. We look like a team," said Carrera, who added a slightly-wide bicycle kick for good measure with eight minutes left and the Strikers leading 5-1. "I wish we had looked like this before. If we had, we'd already be in the playoffs. Now we have to wait."
Tampa ended the scoring when Perry Vanderbeck scored a goal with three minutes left.
"This has been a roller-coaster season," Rongen said. "We knew that we were far superior to Tampa technically, so we just had to go out and match their intensity.
-- The Washington Diplomats or Tampa Bay Rowdies must not win in regulation in today's games. The Diplomats play at New Jersey, and the Rowdies play at Miami. |
def sample_orientation(direction_type: DirType) -> str:
if direction_type == DirType.SLIGHT_LEFT:
return random.sample(get_direction_phrases('left', True), 1)[0]
elif direction_type == DirType.LEFT:
return random.sample(get_direction_phrases('left'), 1)[0]
elif direction_type == DirType.SLIGHT_RIGHT:
return random.sample(get_direction_phrases('right', True), 1)[0]
elif direction_type == DirType.RIGHT:
return random.sample(get_direction_phrases('right'), 1)[0]
elif direction_type == DirType.STRAIGHT:
return random.sample(AHEAD_PHRASES, 1)[0]
elif direction_type == DirType.AROUND:
return random.sample(BEHIND_PHRASES, 1)[0]
elif direction_type == DirType.UP:
return random.sample(UP_PHRASES, 1)[0]
elif direction_type == DirType.DOWN:
return random.sample(DOWN_PHRASES, 1)[0]
elif direction_type == DirType.STOP:
return 'here'
else:
raise ValueError('Unknown DirectionType:', direction_type) |
Sotos syndrome in two children from India. Sotos syndrome is one of the overgrowth syndromes, and can present with intellectual disability, behavioral problems and tall stature. In some cases, seizures, pectus deformity, cardiac and renal anomalies may be identified. Here we report two Indian children with Sotos syndrome whose initial presentation was macrocephaly and behavioral problems, respectively. The pathogenic variants in NSD1 gene were confirmed by next generation sequencing. The gene variants in the two children, one male and one female; were NSD1: c.2362C>T and NSD1: c.5474dup, respectively, leading to premature termination of protein formation. |
. A 28-year-old man with back pain visited a near hospital on October, 1987. Afterwards he was referred to our hospital on November 11 for detailed examination of the kidneys. The blood chemical analysis showed marked renal hypofunction. The abdominal USG and CT showed bilateral calcification of the cortices. Biopsy specimens of the kidneys revealed bone formation containing bone marrow tissue. Afterwards he had been treated as an outpatients, but he admitted again on June 3, 1988. He is now being hemodialyzed. |
// Returns an identical copy of the Combination. Altering the new
// Combination does not affect the old
func (c *Combination) Copy() Combination {
c2 := NewCombination()
for k, _ := range c.set {
c2.set[k] = true
}
return c2
} |
The United States on Wednesday night expressed its strong support for Egypt's call for an international donors' conference in Cairo on March 2 to facilitate Gaza recovery and strengthen the Palestinian economy. The State Department said in a statement that that the US plans to be represented at a high level and urged members of the international community to show similar support for the Egyptian initiative. The statement went on to say that the US viewed the conference as an opportunity to address the immediate humanitarian suffering in Gaza and support the Palestinian Authority's plan for the reconstruction of the Strip as an integral part of a future Palestinian state. The State Department also welcomed Egypt's Gaza cease-fire efforts and expressed hope that the United States and other members of the international community would be able to provide substantial levels of assistance to Gazans. |
<gh_stars>0
# -*- coding: utf-8 -*-
'''
<NAME>, Ph.D.
<EMAIL>
www.reubotics.com
Apache 2 License
Software Revision D, 03/13/2022
Verified working on: Python 2.7, 3.8 for Windows 8.1, 10 64-bit and Raspberry Pi Buster (no Mac testing yet).
'''
__author__ = 'reuben.brewer'
import os, sys, platform
import time, datetime
import math
import collections
import inspect #To enable 'TellWhichFileWereIn'
import threading
import traceback
###############
if sys.version_info[0] < 3:
from Tkinter import * #Python 2
import tkFont
import ttk
else:
from tkinter import * #Python 3
import tkinter.font as tkFont #Python 3
from tkinter import ttk
###############
###############
if sys.version_info[0] < 3:
import Queue # Python 2
else:
import queue as Queue # Python 3
###############
###############
if sys.version_info[0] < 3:
from builtins import raw_input as input
else:
from future.builtins import input as input
############### #"sudo pip3 install future" (Python 3) AND "sudo pip install future" (Python 2)
###############
import platform
if platform.system() == "Windows":
import ctypes
winmm = ctypes.WinDLL('winmm')
winmm.timeBeginPeriod(1) #Set minimum timer resolution to 1ms so that time.sleep(0.001) behaves properly.
###############
###########################################################
###########################################################
#To install Phidget22, enter folder "Phidget22Python_1.0.0.20190107\Phidget22Python" and type "python setup.py install"
from Phidget22.PhidgetException import *
from Phidget22.Phidget import *
from Phidget22.Devices.Log import *
from Phidget22.LogLevel import *
from Phidget22.Devices.DigitalOutput import *
###########################################################
###########################################################
class Phidgets1xRelayREL2001_ReubenPython2and3Class(Frame): #Subclass the Tkinter Frame
#######################################################################################################################
#######################################################################################################################
def __init__(self, setup_dict): #Subclass the Tkinter Frame
print("#################### Phidgets1xRelayREL2001_ReubenPython2and3Class __init__ starting. ####################")
self.EXIT_PROGRAM_FLAG = 0
self.OBJECT_CREATED_SUCCESSFULLY_FLAG = -1
self.EnableInternal_MyPrint_Flag = 0
self.MainThread_still_running_flag = 0
#########################################################
self.CurrentTime_CalculatedFromMainThread = -11111.0
self.StartingTime_CalculatedFromMainThread = -11111.0
self.LastTime_CalculatedFromMainThread = -11111.0
self.DataStreamingFrequency_CalculatedFromMainThread = -11111.0
self.DataStreamingDeltaT_CalculatedFromMainThread = -11111.0
#########################################################
#########################################################
self.DetectedDeviceName = "default"
self.DetectedDeviceID = "default"
self.DetectedDeviceVersion = "default"
self.VINT_DetectedSerialNumber = "default"
#########################################################
self.DigitalOutputsList_PhidgetsDigitalOutputObjects = list()
self.NumberOfDigitalOutputs = 1
self.DigitalOutputsList_AttachedAndOpenFlag = [-1.0]*self.NumberOfDigitalOutputs
self.DigitalOutputsList_ErrorCallbackFiredFlag = [-1.0]*self.NumberOfDigitalOutputs
self.DigitalOutputsList_State = [-1]*self.NumberOfDigitalOutputs
self.DigitalOutputsList_State_NeedsToBeChangedFlag = [1]*self.NumberOfDigitalOutputs
self.DigitalOutputsList_State_ToBeSet = [0]*self.NumberOfDigitalOutputs
self.MostRecentDataDict = dict([("DigitalOutputsList_State", self.DigitalOutputsList_State),
("DigitalOutputsList_ErrorCallbackFiredFlag", self.DigitalOutputsList_ErrorCallbackFiredFlag),
("Time", self.CurrentTime_CalculatedFromMainThread)])
##########################################
##########################################
if platform.system() == "Linux":
if "raspberrypi" in platform.uname(): #os.uname() doesn't work in windows
self.my_platform = "pi"
else:
self.my_platform = "linux"
elif platform.system() == "Windows":
self.my_platform = "windows"
elif platform.system() == "Darwin":
self.my_platform = "mac"
else:
self.my_platform = "other"
print("The OS platform is: " + self.my_platform)
##########################################
##########################################
##########################################
##########################################
if "GUIparametersDict" in setup_dict:
self.GUIparametersDict = setup_dict["GUIparametersDict"]
##########################################
if "USE_GUI_FLAG" in self.GUIparametersDict:
self.USE_GUI_FLAG = self.PassThrough0and1values_ExitProgramOtherwise("USE_GUI_FLAG", self.GUIparametersDict["USE_GUI_FLAG"])
else:
self.USE_GUI_FLAG = 0
print("USE_GUI_FLAG = " + str(self.USE_GUI_FLAG))
##########################################
##########################################
if "root" in self.GUIparametersDict:
self.root = self.GUIparametersDict["root"]
self.RootIsOwnedExternallyFlag = 1
else:
self.root = None
self.RootIsOwnedExternallyFlag = 0
print("RootIsOwnedExternallyFlag = " + str(self.RootIsOwnedExternallyFlag))
##########################################
##########################################
if "GUI_RootAfterCallbackInterval_Milliseconds" in self.GUIparametersDict:
self.GUI_RootAfterCallbackInterval_Milliseconds = int(self.PassThroughFloatValuesInRange_ExitProgramOtherwise("GUI_RootAfterCallbackInterval_Milliseconds", self.GUIparametersDict["GUI_RootAfterCallbackInterval_Milliseconds"], 0.0, 1000.0))
else:
self.GUI_RootAfterCallbackInterval_Milliseconds = 30
print("GUI_RootAfterCallbackInterval_Milliseconds = " + str(self.GUI_RootAfterCallbackInterval_Milliseconds))
##########################################
##########################################
if "EnableInternal_MyPrint_Flag" in self.GUIparametersDict:
self.EnableInternal_MyPrint_Flag = self.PassThrough0and1values_ExitProgramOtherwise("EnableInternal_MyPrint_Flag", self.GUIparametersDict["EnableInternal_MyPrint_Flag"])
else:
self.EnableInternal_MyPrint_Flag = 0
print("EnableInternal_MyPrint_Flag: " + str(self.EnableInternal_MyPrint_Flag))
##########################################
##########################################
if "PrintToConsoleFlag" in self.GUIparametersDict:
self.PrintToConsoleFlag = self.PassThrough0and1values_ExitProgramOtherwise("PrintToConsoleFlag", self.GUIparametersDict["PrintToConsoleFlag"])
else:
self.PrintToConsoleFlag = 1
print("PrintToConsoleFlag: " + str(self.PrintToConsoleFlag))
##########################################
##########################################
if "NumberOfPrintLines" in self.GUIparametersDict:
self.NumberOfPrintLines = int(self.PassThroughFloatValuesInRange_ExitProgramOtherwise("NumberOfPrintLines", self.GUIparametersDict["NumberOfPrintLines"], 0.0, 50.0))
else:
self.NumberOfPrintLines = 10
print("NumberOfPrintLines = " + str(self.NumberOfPrintLines))
##########################################
##########################################
if "UseBorderAroundThisGuiObjectFlag" in self.GUIparametersDict:
self.UseBorderAroundThisGuiObjectFlag = self.PassThrough0and1values_ExitProgramOtherwise("UseBorderAroundThisGuiObjectFlag", self.GUIparametersDict["UseBorderAroundThisGuiObjectFlag"])
else:
self.UseBorderAroundThisGuiObjectFlag = 0
print("UseBorderAroundThisGuiObjectFlag: " + str(self.UseBorderAroundThisGuiObjectFlag))
##########################################
##########################################
if "GUI_ROW" in self.GUIparametersDict:
self.GUI_ROW = int(self.PassThroughFloatValuesInRange_ExitProgramOtherwise("GUI_ROW", self.GUIparametersDict["GUI_ROW"], 0.0, 1000.0))
else:
self.GUI_ROW = 0
print("GUI_ROW = " + str(self.GUI_ROW))
##########################################
##########################################
if "GUI_COLUMN" in self.GUIparametersDict:
self.GUI_COLUMN = int(self.PassThroughFloatValuesInRange_ExitProgramOtherwise("GUI_COLUMN", self.GUIparametersDict["GUI_COLUMN"], 0.0, 1000.0))
else:
self.GUI_COLUMN = 0
print("GUI_COLUMN = " + str(self.GUI_COLUMN))
##########################################
##########################################
if "GUI_PADX" in self.GUIparametersDict:
self.GUI_PADX = int(self.PassThroughFloatValuesInRange_ExitProgramOtherwise("GUI_PADX", self.GUIparametersDict["GUI_PADX"], 0.0, 1000.0))
else:
self.GUI_PADX = 0
print("GUI_PADX = " + str(self.GUI_PADX))
##########################################
##########################################
if "GUI_PADY" in self.GUIparametersDict:
self.GUI_PADY = int(self.PassThroughFloatValuesInRange_ExitProgramOtherwise("GUI_PADY", self.GUIparametersDict["GUI_PADY"], 0.0, 1000.0))
else:
self.GUI_PADY = 0
print("GUI_PADY = " + str(self.GUI_PADY))
##########################################
##########################################
if "GUI_ROWSPAN" in self.GUIparametersDict:
self.GUI_ROWSPAN = int(self.PassThroughFloatValuesInRange_ExitProgramOtherwise("GUI_ROWSPAN", self.GUIparametersDict["GUI_ROWSPAN"], 0.0, 1000.0))
else:
self.GUI_ROWSPAN = 0
print("GUI_ROWSPAN = " + str(self.GUI_ROWSPAN))
##########################################
##########################################
if "GUI_COLUMNSPAN" in self.GUIparametersDict:
self.GUI_COLUMNSPAN = int(self.PassThroughFloatValuesInRange_ExitProgramOtherwise("GUI_COLUMNSPAN", self.GUIparametersDict["GUI_COLUMNSPAN"], 0.0, 1000.0))
else:
self.GUI_COLUMNSPAN = 0
print("GUI_COLUMNSPAN = " + str(self.GUI_COLUMNSPAN))
##########################################
##########################################
if "GUI_STICKY" in self.GUIparametersDict:
self.GUI_STICKY = str(self.GUIparametersDict["GUI_STICKY"])
else:
self.GUI_STICKY = "w"
print("GUI_STICKY = " + str(self.GUI_STICKY))
##########################################
else:
self.GUIparametersDict = dict()
self.USE_GUI_FLAG = 0
print("Phidgets1xRelayREL2001_ReubenPython2and3Class __init__: No GUIparametersDict present, setting USE_GUI_FLAG = " + str(self.USE_GUI_FLAG))
print("GUIparametersDict = " + str(self.GUIparametersDict))
##########################################
##########################################
##########################################
if "VINT_DesiredSerialNumber" in setup_dict:
try:
self.VINT_DesiredSerialNumber = int(setup_dict["VINT_DesiredSerialNumber"])
except:
print("ERROR: VINT_DesiredSerialNumber invalid.")
else:
self.OBJECT_CREATED_SUCCESSFULLY_FLAG = 0
print("PhidgetBrushlessDCmotorDCC1100controller_ReubenPython2and3Class ERROR: Must initialize object with 'VINT_DesiredSerialNumber' argument.")
return
print("VINT_DesiredSerialNumber: " + str(self.VINT_DesiredSerialNumber))
##########################################
##########################################
if "VINT_DesiredPortNumber" in setup_dict:
try:
self.VINT_DesiredPortNumber = int(setup_dict["VINT_DesiredPortNumber"])
except:
print("ERROR: VINT_DesiredPortNumber invalid.")
else:
self.OBJECT_CREATED_SUCCESSFULLY_FLAG = 0
print("PhidgetBrushlessDCmotorDCC1100controller_ReubenPython2and3Class ERROR: Must initialize object with 'VINT_DesiredPortNumber' argument.")
return
print("VINT_DesiredPortNumber: " + str(self.VINT_DesiredPortNumber))
##########################################
##########################################
if "DesiredDeviceID" in setup_dict:
try:
self.DesiredDeviceID = int(setup_dict["DesiredDeviceID"])
except:
print("ERROR: DesiredDeviceID invalid.")
else:
self.OBJECT_CREATED_SUCCESSFULLY_FLAG = 0
print("PhidgetBrushlessDCmotorDCC1100controller_ReubenPython2and3Class ERROR: Must initialize object with 'DesiredDeviceID' argument.")
return
print("DesiredDeviceID: " + str(self.DesiredDeviceID))
##########################################
##########################################
if "NameToDisplay_UserSet" in setup_dict:
self.NameToDisplay_UserSet = str(setup_dict["NameToDisplay_UserSet"])
else:
self.NameToDisplay_UserSet = ""
##########################################
##########################################
if "WaitForAttached_TimeoutDuration_Milliseconds" in setup_dict:
self.WaitForAttached_TimeoutDuration_Milliseconds = int(self.PassThroughFloatValuesInRange_ExitProgramOtherwise("WaitForAttached_TimeoutDuration_Milliseconds", setup_dict["WaitForAttached_TimeoutDuration_Milliseconds"], 0.0, 60000.0))
else:
self.WaitForAttached_TimeoutDuration_Milliseconds = 5000
print("WaitForAttached_TimeoutDuration_Milliseconds: " + str(self.WaitForAttached_TimeoutDuration_Milliseconds))
##########################################
##########################################
if "UsePhidgetsLoggingInternalToThisClassObjectFlag" in setup_dict:
self.UsePhidgetsLoggingInternalToThisClassObjectFlag = self.PassThrough0and1values_ExitProgramOtherwise("UsePhidgetsLoggingInternalToThisClassObjectFlag", setup_dict["UsePhidgetsLoggingInternalToThisClassObjectFlag"])
else:
self.UsePhidgetsLoggingInternalToThisClassObjectFlag = 1
print("UsePhidgetsLoggingInternalToThisClassObjectFlag: " + str(self.UsePhidgetsLoggingInternalToThisClassObjectFlag))
##########################################
##########################################
if "MainThread_TimeToSleepEachLoop" in setup_dict:
self.MainThread_TimeToSleepEachLoop = self.PassThroughFloatValuesInRange_ExitProgramOtherwise("MainThread_TimeToSleepEachLoop", setup_dict["MainThread_TimeToSleepEachLoop"], 0.001, 100000)
else:
self.MainThread_TimeToSleepEachLoop = 0.005
print("MainThread_TimeToSleepEachLoop: " + str(self.MainThread_TimeToSleepEachLoop))
##########################################
#########################################################
self.PrintToGui_Label_TextInputHistory_List = [" "]*self.NumberOfPrintLines
self.PrintToGui_Label_TextInput_Str = ""
self.GUI_ready_to_be_updated_flag = 0
#########################################################
#########################################################
#########################################################
#########################################################
#########################################################
try:
#########################################################
self.DigitalOutput0object = DigitalOutput()
self.DigitalOutput0object.setIsHubPortDevice(True) # $$$$ KEY LINE THAT'S DIFFERENT FROM THE Phidgets4xRelayREL1000_ReubenPython2and3Class CODE!!!!
self.DigitalOutputsList_PhidgetsDigitalOutputObjects.append(self.DigitalOutput0object)
self.DigitalOutput0object.setHubPort(self.VINT_DesiredPortNumber)
self.DigitalOutput0object.setDeviceSerialNumber(self.VINT_DesiredSerialNumber)
self.DigitalOutput0object.setOnAttachHandler(self.DigitalOutput0onAttachCallback)
self.DigitalOutput0object.setOnDetachHandler(self.DigitalOutput0onDetachCallback)
self.DigitalOutput0object.setOnErrorHandler(self.DigitalOutput0onErrorCallback)
self.DigitalOutput0object.openWaitForAttachment(self.WaitForAttached_TimeoutDuration_Milliseconds)
#########################################################
self.PhidgetsDeviceConnectedFlag = 1
except PhidgetException as e:
self.PhidgetsDeviceConnectedFlag = 0
print("Phidgets1xRelayREL2001_ReubenPython2and3Class __init__Failed to attach, Phidget Exception %i: %s" % (e.code, e.details))
#########################################################
#########################################################
#########################################################
#########################################################
if self.PhidgetsDeviceConnectedFlag == 1:
#########################################################
if self.UsePhidgetsLoggingInternalToThisClassObjectFlag == 1:
try:
Log.enable(LogLevel.PHIDGET_LOG_INFO, os.getcwd() + "\Phidgets1xRelayREL2001_ReubenPython2and3Class_PhidgetLog_INFO.txt")
print("Phidgets1xRelayREL2001_ReubenPython2and3Class __init__Enabled Phidget Logging.")
except PhidgetException as e:
print("Phidgets1xRelayREL2001_ReubenPython2and3Class __init__Failed to enable Phidget Logging, Phidget Exception %i: %s" % (e.code, e.details))
#########################################################
#########################################################
try:
self.DetectedDeviceName = self.DigitalOutput0object.getDeviceName()
print("DetectedDeviceName: " + self.DetectedDeviceName)
except PhidgetException as e:
print("Failed to call 'getDeviceName', Phidget Exception %i: %s" % (e.code, e.details))
#########################################################
#########################################################
try:
self.VINT_DetectedSerialNumber = self.DigitalOutput0object.getDeviceSerialNumber()
print("VINT_DetectedSerialNumber: " + str(self.VINT_DetectedSerialNumber))
except PhidgetException as e:
print("Failed to call 'getDeviceSerialNumber', Phidget Exception %i: %s" % (e.code, e.details))
#########################################################
#########################################################
try:
self.DetectedDeviceID = self.DigitalOutput0object.getDeviceID()
print("DetectedDeviceID: " + str(self.DetectedDeviceID))
except PhidgetException as e:
print("Failed to call 'getDesiredDeviceID', Phidget Exception %i: %s" % (e.code, e.details))
#########################################################
#########################################################
try:
self.DetectedDeviceVersion = self.DigitalOutput0object.getDeviceVersion()
print("DetectedDeviceVersion: " + str(self.DetectedDeviceVersion))
except PhidgetException as e:
print("Failed to call 'getDeviceVersion', Phidget Exception %i: %s" % (e.code, e.details))
#########################################################
#########################################################
try:
self.DetectedDeviceLibraryVersion = self.DigitalOutput0object.getLibraryVersion()
print("DetectedDeviceLibraryVersion: " + str(self.DetectedDeviceLibraryVersion))
except PhidgetException as e:
print("Failed to call 'getLibraryVersion', Phidget Exception %i: %s" % (e.code, e.details))
#########################################################
#########################################################
if self.VINT_DetectedSerialNumber != self.VINT_DesiredSerialNumber:
print("The desired Serial Number (" + str(self.VINT_DesiredSerialNumber) + ") does not match the detected serial number (" + str(self.VINT_DetectedSerialNumber) + ").")
input("Press any key (and enter) to exit.")
sys.exit()
#########################################################
#########################################################
if self.DetectedDeviceID != self.DesiredDeviceID:
print("The desired DesiredDeviceID (" + str(self.DesiredDeviceID) + ") does not match the detected Device ID (" + str(self.DetectedDeviceID) + ").")
input("Press any key (and enter) to exit.")
sys.exit()
#########################################################
##########################################
self.MainThread_ThreadingObject = threading.Thread(target=self.MainThread, args=())
self.MainThread_ThreadingObject.start()
##########################################
##########################################
if self.USE_GUI_FLAG == 1:
self.StartGUI(self.root)
##########################################
self.OBJECT_CREATED_SUCCESSFULLY_FLAG = 1
#########################################################
#########################################################
#######################################################################################################################
#######################################################################################################################
#######################################################################################################################
#######################################################################################################################
def __del__(self):
dummy_var = 0
#######################################################################################################################
#######################################################################################################################
##########################################################################################################
##########################################################################################################
def PassThrough0and1values_ExitProgramOtherwise(self, InputNameString, InputNumber):
try:
InputNumber_ConvertedToFloat = float(InputNumber)
except:
exceptions = sys.exc_info()[0]
print("PassThrough0and1values_ExitProgramOtherwise Error. InputNumber must be a float value, Exceptions: %s" % exceptions)
input("Press any key to continue")
sys.exit()
try:
if InputNumber_ConvertedToFloat == 0.0 or InputNumber_ConvertedToFloat == 1:
return InputNumber_ConvertedToFloat
else:
input("PassThrough0and1values_ExitProgramOtherwise Error. '" +
InputNameString +
"' must be 0 or 1 (value was " +
str(InputNumber_ConvertedToFloat) +
"). Press any key (and enter) to exit.")
sys.exit()
except:
exceptions = sys.exc_info()[0]
print("PassThrough0and1values_ExitProgramOtherwise Error, Exceptions: %s" % exceptions)
input("Press any key to continue")
sys.exit()
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def PassThroughFloatValuesInRange_ExitProgramOtherwise(self, InputNameString, InputNumber, RangeMinValue, RangeMaxValue):
try:
InputNumber_ConvertedToFloat = float(InputNumber)
except:
exceptions = sys.exc_info()[0]
print("PassThroughFloatValuesInRange_ExitProgramOtherwise Error. InputNumber must be a float value, Exceptions: %s" % exceptions)
input("Press any key to continue")
sys.exit()
try:
if InputNumber_ConvertedToFloat >= RangeMinValue and InputNumber_ConvertedToFloat <= RangeMaxValue:
return InputNumber_ConvertedToFloat
else:
input("PassThroughFloatValuesInRange_ExitProgramOtherwise Error. '" +
InputNameString +
"' must be in the range [" +
str(RangeMinValue) +
", " +
str(RangeMaxValue) +
"] (value was " +
str(InputNumber_ConvertedToFloat) + "). Press any key (and enter) to exit.")
sys.exit()
except:
exceptions = sys.exc_info()[0]
print("PassThroughFloatValuesInRange_ExitProgramOtherwise Error, Exceptions: %s" % exceptions)
input("Press any key to continue")
sys.exit()
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def TellWhichFileWereIn(self):
#We used to use this method, but it gave us the root calling file, not the class calling file
#absolute_file_path = os.path.dirname(os.path.realpath(sys.argv[0]))
#filename = absolute_file_path[absolute_file_path.rfind("\\") + 1:]
frame = inspect.stack()[1]
filename = frame[1][frame[1].rfind("\\") + 1:]
filename = filename.replace(".py","")
return filename
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def DigitalOutputGENERALonAttachCallback(self, DigitalOutputChannel):
try:
self.DigitalOutputsList_AttachedAndOpenFlag[DigitalOutputChannel] = 1
self.MyPrint_WithoutLogFile("$$$$$$$$$$ DigitalOutputGENERALonAttachCallback event for DigitalOutputChannel " + str(DigitalOutputChannel) + ", Attached! $$$$$$$$$$")
except PhidgetException as e:
self.DigitalOutputsList_AttachedAndOpenFlag[DigitalOutputChannel] = 0
self.MyPrint_WithoutLogFile("DigitalOutputGENERALonAttachCallback event for DigitalOutputChannel " + str(DigitalOutputChannel) + ", ERROR: Failed to attach DigitalOutput0, Phidget Exception %i: %s" % (e.code, e.details))
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def DigitalOutputGENERALonDetachCallback(self, DigitalOutputChannel):
self.DigitalOutputsList_AttachedAndOpenFlag[DigitalOutputChannel] = 0
self.MyPrint_WithoutLogFile("$$$$$$$$$$ DigitalOutputGENERALonDetachCallback event for DigitalOutputChannel " + str(DigitalOutputChannel) + ", Detatched! $$$$$$$$$$")
try:
self.DigitalOutputsList_PhidgetsDigitalOutputObjects[DigitalOutputChannel].openWaitForAttachment(self.WaitForAttached_TimeoutDuration_Milliseconds)
time.sleep(0.250)
except PhidgetException as e:
self.MyPrint_WithoutLogFile("DigitalOutputGENERALonDetachCallback event for DigitalOutput Channel " + str(DigitalOutputChannel) + ", failed to openWaitForAttachment, Phidget Exception %i: %s" % (e.code, e.details))
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def DigitalOutputGENERALonErrorCallback(self, DigitalOutputChannel, code, description):
self.DigitalOutputsList_ErrorCallbackFiredFlag[DigitalOutputChannel] = 1
self.MyPrint_WithoutLogFile("DigitalOutputGENERALonErrorCallback event for DigitalOutput Channel " + str(DigitalOutputChannel) + ", Error Code " + ErrorEventCode.getName(code) + ", description: " + str(description))
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def DigitalOutput0onAttachCallback(self, HandlerSelf):
DigitalOutputChannel = 0
self.DigitalOutputGENERALonAttachCallback(DigitalOutputChannel)
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def DigitalOutput0onDetachCallback(self, HandlerSelf):
DigitalOutputChannel = 0
self.DigitalOutputGENERALonDetachCallback(DigitalOutputChannel)
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def DigitalOutput0onErrorCallback(self, HandlerSelf, code, description):
DigitalOutputChannel = 0
self.DigitalOutputGENERALonErrorCallback(DigitalOutputChannel, code, description)
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def getPreciseSecondsTimeStampString(self):
ts = time.time()
return ts
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def SetRelayState(self, State_ToBeSet):
if State_ToBeSet in [0, 1]:
self.DigitalOutputsList_State_ToBeSet[0] = State_ToBeSet
self.DigitalOutputsList_State_NeedsToBeChangedFlag[0] = 1
else:
print("SetRelayState ERROR, State_ToBeSet must be 0 or 1.")
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def GetMostRecentDataDict(self):
self.MostRecentDataDict = dict([("DigitalOutputsList_State", self.DigitalOutputsList_State),
("DigitalOutputsList_ErrorCallbackFiredFlag", self.DigitalOutputsList_ErrorCallbackFiredFlag),
("Time", self.CurrentTime_CalculatedFromMainThread)])
return self.MostRecentDataDict
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def UpdateFrequencyCalculation_MainThread(self):
try:
self.DataStreamingDeltaT_CalculatedFromMainThread = self.CurrentTime_CalculatedFromMainThread - self.LastTime_CalculatedFromMainThread
if self.DataStreamingDeltaT_CalculatedFromMainThread != 0.0:
self.DataStreamingFrequency_CalculatedFromMainThread = 1.0/self.DataStreamingDeltaT_CalculatedFromMainThread
self.LastTime_CalculatedFromMainThread = self.CurrentTime_CalculatedFromMainThread
except:
exceptions = sys.exc_info()[0]
print("UpdateFrequencyCalculation_MainThread ERROR with Exceptions: %s" % exceptions)
traceback.print_exc()
##########################################################################################################
##########################################################################################################
##########################################################################################################
########################################################################################################## unicorn
def MainThread(self):
self.MyPrint_WithoutLogFile("Started MainThread for Phidgets1xRelayREL2001_ReubenPython2and3Class object.")
self.MainThread_still_running_flag = 1
self.StartingTime_CalculatedFromMainThread = self.getPreciseSecondsTimeStampString()
###############################################
while self.EXIT_PROGRAM_FLAG == 0:
###############################################
self.CurrentTime_CalculatedFromMainThread = self.getPreciseSecondsTimeStampString() - self.StartingTime_CalculatedFromMainThread
###############################################
###############################################
for DigitalOutputChannel in range(0, self.NumberOfDigitalOutputs):
if self.DigitalOutputsList_State_NeedsToBeChangedFlag[DigitalOutputChannel] == 1:
self.DigitalOutputsList_PhidgetsDigitalOutputObjects[DigitalOutputChannel].setState(self.DigitalOutputsList_State_ToBeSet[DigitalOutputChannel])
time.sleep(0.002)
self.DigitalOutputsList_State[DigitalOutputChannel] = self.DigitalOutputsList_PhidgetsDigitalOutputObjects[DigitalOutputChannel].getState()
if self.DigitalOutputsList_State[DigitalOutputChannel] == self.DigitalOutputsList_State_ToBeSet[DigitalOutputChannel]:
self.DigitalOutputsList_State_NeedsToBeChangedFlag[DigitalOutputChannel] = 0
###############################################
############################################### USE THE TIME.SLEEP() TO SET THE LOOP FREQUENCY
###############################################
###############################################
self.UpdateFrequencyCalculation_MainThread()
if self.MainThread_TimeToSleepEachLoop > 0.0:
time.sleep(self.MainThread_TimeToSleepEachLoop)
###############################################
###############################################
###############################################
###############################################
###############################################
for DigitalOutputChannel in range(0, self.NumberOfDigitalOutputs):
self.DigitalOutputsList_PhidgetsDigitalOutputObjects[DigitalOutputChannel].close()
###############################################
self.MyPrint_WithoutLogFile("Finished MainThread for Phidgets1xRelayREL2001_ReubenPython2and3Class object.")
self.MainThread_still_running_flag = 0
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def ExitProgram_Callback(self):
print("Exiting all threads for Phidgets1xRelayREL2001_ReubenPython2and3Class object")
self.EXIT_PROGRAM_FLAG = 1
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def StartGUI(self, GuiParent=None):
GUI_Thread_ThreadingObject = threading.Thread(target=self.GUI_Thread, args=(GuiParent,))
GUI_Thread_ThreadingObject.setDaemon(True) #Should mean that the GUI thread is destroyed automatically when the main thread is destroyed.
GUI_Thread_ThreadingObject.start()
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def GUI_Thread(self, parent=None):
print("Starting the GUI_Thread for Phidgets1xRelayREL2001_ReubenPython2and3Class object.")
###################################################
if parent == None: #This class object owns root and must handle it properly
self.root = Tk()
self.parent = self.root
################################################### SET THE DEFAULT FONT FOR ALL WIDGETS CREATED AFTTER/BELOW THIS CALL
default_font = tkFont.nametofont("TkDefaultFont")
default_font.configure(size=8)
self.root.option_add("*Font", default_font)
###################################################
else:
self.root = parent
self.parent = parent
###################################################
###################################################
self.myFrame = Frame(self.root)
if self.UseBorderAroundThisGuiObjectFlag == 1:
self.myFrame["borderwidth"] = 2
self.myFrame["relief"] = "ridge"
self.myFrame.grid(row = self.GUI_ROW,
column = self.GUI_COLUMN,
padx = self.GUI_PADX,
pady = self.GUI_PADY,
rowspan = self.GUI_ROWSPAN,
columnspan= self.GUI_COLUMNSPAN,
sticky = self.GUI_STICKY)
###################################################
###################################################
self.TKinter_LightGreenColor = '#%02x%02x%02x' % (150, 255, 150) #RGB
self.TKinter_LightRedColor = '#%02x%02x%02x' % (255, 150, 150) #RGB
self.TKinter_LightYellowColor = '#%02x%02x%02x' % (255, 255, 150) # RGB
self.TKinter_DefaultGrayColor = '#%02x%02x%02x' % (240, 240, 240) # RGB
self.TkinterScaleWidth = 10
self.TkinterScaleLength = 250
###################################################
#################################################
self.device_info_label = Label(self.myFrame, text="Device Info", width=50) #, font=("Helvetica", 16)
self.device_info_label["text"] = self.NameToDisplay_UserSet + \
"\nDevice Name: " + self.DetectedDeviceName + \
"\nDevice Serial Number: " + str(self.VINT_DetectedSerialNumber) + \
"\nDevice ID: " + str(self.DetectedDeviceID) + \
"\nDevice Version: " + str(self.DetectedDeviceVersion)
self.device_info_label.grid(row=0, column=0, padx=5, pady=1, columnspan=1, rowspan=1)
#################################################
#################################################
self.DigitalOutputs_Label = Label(self.myFrame, text="DigitalOutputs_Label", width=70)
self.DigitalOutputs_Label.grid(row=0, column=1, padx=5, pady=1, columnspan=1, rowspan=10)
#################################################
#################################################
self.DigitalOutputButtonsFrame = Frame(self.myFrame)
#if self.UseBorderAroundThisGuiObjectFlag == 1:
# self.myFrame["borderwidth"] = 2
# self.myFrame["relief"] = "ridge"
self.DigitalOutputButtonsFrame.grid(row = 1, column = 0, padx = 1, pady = 1, rowspan = 1, columnspan = 1)
self.DigitalOutputsList_ButtonObjects = []
for DigitalOutputChannel in range(0, self.NumberOfDigitalOutputs):
self.DigitalOutputsList_ButtonObjects.append(Button(self.DigitalOutputButtonsFrame, text="Relay " + str(DigitalOutputChannel), state="normal", width=8, command=lambda i=DigitalOutputChannel: self.DigitalOutputsList_ButtonObjectsResponse(i)))
self.DigitalOutputsList_ButtonObjects[DigitalOutputChannel].grid(row=1, column=DigitalOutputChannel, padx=1, pady=1)
#################################################
########################
self.PrintToGui_Label = Label(self.myFrame, text="PrintToGui_Label", width=75)
if self.EnableInternal_MyPrint_Flag == 1:
self.PrintToGui_Label.grid(row=0, column=2, padx=1, pady=1, columnspan=1, rowspan=10)
########################
########################
if self.RootIsOwnedExternallyFlag == 0: #This class object owns root and must handle it properly
self.root.protocol("WM_DELETE_WINDOW", self.ExitProgram_Callback)
self.root.after(self.GUI_RootAfterCallbackInterval_Milliseconds, self.GUI_update_clock)
self.GUI_ready_to_be_updated_flag = 1
self.root.mainloop()
else:
self.GUI_ready_to_be_updated_flag = 1
########################
########################
if self.RootIsOwnedExternallyFlag == 0: #This class object owns root and must handle it properly
self.root.quit() # Stop the GUI thread, MUST BE CALLED FROM GUI_Thread
self.root.destroy() # Close down the GUI thread, MUST BE CALLED FROM GUI_Thread
########################
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def GUI_update_clock(self):
#######################################################
#######################################################
#######################################################
#######################################################
if self.USE_GUI_FLAG == 1 and self.EXIT_PROGRAM_FLAG == 0:
#######################################################
#######################################################
#######################################################
if self.GUI_ready_to_be_updated_flag == 1:
#######################################################
#######################################################
try:
#######################################################
for DigitalOutputChannel in range(0, self.NumberOfDigitalOutputs):
if self.DigitalOutputsList_State[DigitalOutputChannel] == 1:
self.DigitalOutputsList_ButtonObjects[DigitalOutputChannel]["bg"] = self.TKinter_LightGreenColor
elif self.DigitalOutputsList_State[DigitalOutputChannel] == 0:
self.DigitalOutputsList_ButtonObjects[DigitalOutputChannel]["bg"] = self.TKinter_LightRedColor
else:
self.DigitalOutputsList_ButtonObjects[DigitalOutputChannel]["bg"] = self.TKinter_DefaultGrayColor
#######################################################
#######################################################
self.DigitalOutputs_Label["text"] = "\nDigital States: " + str(self.DigitalOutputsList_State) + \
"\nTime: " + self.ConvertFloatToStringWithNumberOfLeadingNumbersAndDecimalPlaces_NumberOrListInput(self.CurrentTime_CalculatedFromMainThread, 0, 3) + \
"\nData Frequency: " + self.ConvertFloatToStringWithNumberOfLeadingNumbersAndDecimalPlaces_NumberOrListInput(self.DataStreamingFrequency_CalculatedFromMainThread, 0, 3)
#######################################################
#######################################################
self.PrintToGui_Label.config(text=self.PrintToGui_Label_TextInput_Str)
#######################################################
except:
exceptions = sys.exc_info()[0]
print("Phidgets1xRelayREL2001_ReubenPython2and3Class GUI_update_clock ERROR: Exceptions: %s" % exceptions)
traceback.print_exc()
#######################################################
#######################################################
#######################################################
#######################################################
if self.RootIsOwnedExternallyFlag == 0: # This class object owns root and must handle it properly
self.root.after(self.GUI_RootAfterCallbackInterval_Milliseconds, self.GUI_update_clock)
#######################################################
#######################################################
#######################################################
#######################################################
#######################################################
#######################################################
#######################################################
#######################################################
#######################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def IsInputList(self, input, print_result_flag = 0):
result = isinstance(input, list)
if print_result_flag == 1:
self.MyPrint_WithoutLogFile("IsInputList: " + str(result))
return result
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def ConvertFloatToStringWithNumberOfLeadingNumbersAndDecimalPlaces_NumberOrListInput(self, input, number_of_leading_numbers=4, number_of_decimal_places=3):
IsListFlag = self.IsInputList(input)
if IsListFlag == 0:
float_number_list = [input]
else:
float_number_list = list(input)
float_number_list_as_strings = []
for element in float_number_list:
try:
element = float(element)
prefix_string = "{:." + str(number_of_decimal_places) + "f}"
element_as_string = prefix_string.format(element)
float_number_list_as_strings.append(element_as_string)
except:
self.MyPrint_WithoutLogFile(self.TellWhichFileWereIn() + ": ConvertFloatToStringWithNumberOfLeadingNumbersAndDecimalPlaces_NumberOrListInput ERROR: " + str(element) + " cannot be turned into a float")
return -1
StringToReturn = ""
if IsListFlag == 0:
StringToReturn = float_number_list_as_strings[0].zfill(number_of_leading_numbers + number_of_decimal_places + 1 + 1) # +1 for sign, +1 for decimal place
else:
StringToReturn = "["
for index, StringElement in enumerate(float_number_list_as_strings):
if float_number_list[index] >= 0:
StringElement = "+" + StringElement # So that our strings always have either + or - signs to maintain the same string length
StringElement = StringElement.zfill(number_of_leading_numbers + number_of_decimal_places + 1 + 1) # +1 for sign, +1 for decimal place
if index != len(float_number_list_as_strings) - 1:
StringToReturn = StringToReturn + StringElement + ", "
else:
StringToReturn = StringToReturn + StringElement + "]"
return StringToReturn
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def DigitalOutputsList_ButtonObjectsResponse(self, DigitalOutputChannel):
if self.DigitalOutputsList_State[DigitalOutputChannel] == 1:
self.DigitalOutputsList_State_ToBeSet[DigitalOutputChannel] = 0
else:
self.DigitalOutputsList_State_ToBeSet[DigitalOutputChannel] = 1
self.DigitalOutputsList_State_NeedsToBeChangedFlag[DigitalOutputChannel] = 1
self.MyPrint_WithoutLogFile("DigitalOutputsList_ButtonObjectsResponse: Event fired for DigitalOutputChannel " + str(DigitalOutputChannel))
##########################################################################################################
##########################################################################################################
##########################################################################################################
##########################################################################################################
def MyPrint_WithoutLogFile(self, input_string):
input_string = str(input_string)
if input_string != "":
#input_string = input_string.replace("\n", "").replace("\r", "")
################################ Write to console
# Some people said that print crashed for pyinstaller-built-applications and that sys.stdout.write fixed this.
# http://stackoverflow.com/questions/13429924/pyinstaller-packaged-application-works-fine-in-console-mode-crashes-in-window-m
if self.PrintToConsoleFlag == 1:
sys.stdout.write(input_string + "\n")
################################
################################ Write to GUI
self.PrintToGui_Label_TextInputHistory_List.append(self.PrintToGui_Label_TextInputHistory_List.pop(0)) #Shift the list
self.PrintToGui_Label_TextInputHistory_List[-1] = str(input_string) #Add the latest value
self.PrintToGui_Label_TextInput_Str = ""
for Counter, Line in enumerate(self.PrintToGui_Label_TextInputHistory_List):
self.PrintToGui_Label_TextInput_Str = self.PrintToGui_Label_TextInput_Str + Line
if Counter < len(self.PrintToGui_Label_TextInputHistory_List) - 1:
self.PrintToGui_Label_TextInput_Str = self.PrintToGui_Label_TextInput_Str + "\n"
################################
##########################################################################################################
##########################################################################################################
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.