content
stringlengths 10
4.9M
|
---|
/**
* Wrapper for the app.properties file.
*/
public class AppProperties {
private static final Logger LOG = Log.getLog();
public static final String PROPERTIES_FILE = "app.properties";
private static final String KEY_FIREFOX_DRIVER = "firefox_driver";
private static final String KEY_CHROME_DRIVER = "chrome_driver";
private static final String KEY_BROWSER = "browser";
private static AppProperties INSTANCE = null;
/**
* Factory method.
*
* @return the #AppProperties singleton
* @throws IOException Thrown when file not found or invalid properties file.
*/
public static AppProperties getInstance() throws IOException {
if (INSTANCE == null) {
Path propFile = Paths.get(PROPERTIES_FILE);
if (!Files.exists(propFile)) {
throw new FileNotFoundException(PROPERTIES_FILE);
}
Properties props = new Properties();
try (InputStream in = Files.newInputStream(propFile)) {
props.load(in);
}
INSTANCE = new AppProperties(props);
}
return INSTANCE;
}
private final Properties props;
private AppProperties(Properties props) throws IOException {
this.props = props;
}
public String getFirefoxDriver() {
return prop(KEY_FIREFOX_DRIVER);
}
public String getChromeDriver() {
return prop(KEY_CHROME_DRIVER);
}
public Browser getBrowser() {
return Browser.fromString(prop(KEY_BROWSER));
}
private String prop(String key) {
return props.getProperty(key);
}
} |
<gh_stars>0
from __future__ import absolute_import
import json
import os
import sys
from dxlstreamingclient.channel import Channel, ChannelAuth
root_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(root_dir + "/../..")
sys.path.append(root_dir + "/..")
# Import common logging and configuration
from common import *
# Configure local logger
logging.getLogger().setLevel(logging.INFO)
logger = logging.getLogger(__name__)
# Change these below to match the appropriate details for your
# channel connection.
CHANNEL_URL = "http://127.0.0.1:50080"
CHANNEL_USERNAME = "me"
CHANNEL_PASSWORD = "<PASSWORD>"
CHANNEL_CONSUMER_GROUP = "sample_consumer_group"
CHANNEL_TOPIC_SUBSCRIPTIONS = ["case-mgmt-events",
"my-topic",
"topic-abc123"]
# Path to a CA bundle file containing certificates of trusted CAs. The CA
# bundle is used to validate that the certificate of the server being connected
# to was signed by a valid authority. If set to an empty string, the server
# certificate is not validated.
VERIFY_CERTIFICATE_BUNDLE = ""
# This constant controls the frequency (in seconds) at which the channel 'run'
# call below polls the streaming service for new records.
WAIT_BETWEEN_QUERIES = 5
# Create a new channel object
with Channel(CHANNEL_URL,
auth=ChannelAuth(CHANNEL_URL,
CHANNEL_USERNAME,
CHANNEL_PASSWORD,
verify_cert_bundle=VERIFY_CERTIFICATE_BUNDLE),
consumer_group=CHANNEL_CONSUMER_GROUP,
verify_cert_bundle=VERIFY_CERTIFICATE_BUNDLE) as channel:
# Create a function which will be called back upon by the 'run' method (see
# below) when records are received from the channel.
def process_callback(payloads):
# Print the payloads which were received. 'payloads' is a list of
# dictionary objects extracted from the records received from the
# channel.
logger.info("Received payloads: \n%s",
json.dumps(payloads, indent=4, sort_keys=True))
# Return 'True' in order for the 'run' call to continue attempting to
# consume records.
return True
# Consume records indefinitely
channel.run(process_callback, wait_between_queries=WAIT_BETWEEN_QUERIES,
topics=CHANNEL_TOPIC_SUBSCRIPTIONS)
|
n,m=map(int,input().split())
s=input()
l=list(map(str,input().split()))
z=[0]*26
a=[]
for i in range(len(l)):
z[ord(l[i])-97]=1
for i in range(97,97+26):
a.append(chr(i))
a=dict(zip(a,z))
count=0
sum=0
#print(a)
for i in range(len(s)):
if a[s[i]]==1:
count+=1
else:
if count>0:
sum+=(count*(count+1)//2)
count=0
if i==len(s)-1:
sum+=(count*(count+1)//2)
print(sum) |
/*
* When a new native is dynamically registered from C++, add a reference to the
* generic native thunk for JIT->C++ calls via TNativeFn.
*/
void FlowJitProgram::RegisterNative(ByteCodeRunner *runner, unsigned id, NativeFunction * )
{
while (runner->JitFuncs.size() <= id)
runner->JitFuncs.push_back(invalid_native_ptr);
runner->JitFuncs[id] = generic_native_ptr;
} |
def Args(parser, version=base.ReleaseTrack.GA):
group = parser.add_mutually_exclusive_group()
flags.AddAsyncFlag(group)
flags.AddDeploymentNameFlag(parser)
flags.AddPropertiesFlag(parser)
labels_util.AddCreateLabelsFlags(parser)
group.add_argument(
'--automatic-rollback-on-error',
help='If the create request results in a deployment with resource '
'errors, delete that deployment immediately after creation. '
'(default=False)',
dest='automatic_rollback',
default=False,
action='store_true')
parser.add_argument(
'--description',
help='Optional description of the deployment to insert.',
dest='description')
parser.add_argument(
'--config',
help='Filename of config that specifies resources to deploy. '
'More information is available at '
'https://cloud.google.com/deployment-manager/docs/configuration/.',
dest='config',
required=True)
parser.add_argument(
'--preview',
help='Preview the requested create without actually instantiating the '
'underlying resources. (default=False)',
dest='preview',
default=False,
action='store_true')
parser.display_info.AddFormat(flags.RESOURCES_AND_OUTPUTS_FORMAT) |
<filename>util/cacheUtil.go
package util
import (
"time"
cache "github.com/patrickmn/go-cache"
)
var cacheInstanceMap map[string]cache.Cache = make(map[string]cache.Cache)
func Set(bigKey string, smallKey string, value string, expire int) {
var cacheInstance cache.Cache
cacheInstance, ok := cacheInstanceMap[bigKey]
if !ok {
cacheInstance = *cache.New(5*time.Minute, 10*time.Minute)
cacheInstanceMap[bigKey] = cacheInstance
}
cacheInstance.Set(smallKey, value, time.Duration(expire*1000*1000*1000))
}
func Get(bigKey string, smallKey string) (value string, result bool) {
var cacheInstance cache.Cache
cacheInstance, ok := cacheInstanceMap[bigKey]
if ok {
if x, found := cacheInstance.Get(smallKey); found {
return x.(string), true
}
}
return "", false
}
|
import os
import binascii
from datetime import datetime
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.dispatch import Signal
from django.utils.timezone import utc
from django.utils.translation import gettext_lazy as _
from .managers import BaseEmailUserManager, BaseAPITokenManager
from .utils import get_setting
email_confirmed = Signal()
class BaseEmailUser(AbstractUser):
"""Custom user with email as login field.
The autogenerated "id" field is used for admin URLs,
foreign keys, etc. There is no "username" field,
but subclasses can define one if desired.
"""
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
email = models.EmailField(_('email address'), max_length=255, unique=True)
username = None
objects = BaseEmailUserManager()
class Meta:
abstract = True
verbose_name = _('user')
verbose_name_plural = _('users')
def __str__(self):
return self.email
def get_short_name(self):
return self.email
def natural_key(self):
return (self.email,)
class BaseEmailConfirmation(models.Model):
"""Abstract model for email confirmations.
Subclass in your project to customize to your needs and make
migrations easy.
"""
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_('user'))
confirmed = models.DateTimeField(_('confirmed'), null=True, blank=True)
class Meta:
abstract = True
class IsExpired(Exception):
"""Tried to confirm email after the confirmation expired."""
def __str__(self):
return 'Confirmation for {}'.format(self.user)
def confirm(self):
"""Mark this record as confirmed.
The time period to confirm an email is configured with the setting
email_confirmation_validity_period, which defaults to 60 minutes.
"""
now = datetime.now(utc)
delay = (now - self.created).total_seconds()
validity = get_setting('email_confirmation_validity_period', 60) * 60
if delay > validity:
raise self.IsExpired
self.confirmed = now
self.save()
email_confirmed.send(sender=self.__class__, user=self.user)
class BaseAPIToken(models.Model):
"""Abstract model for API auth tokens.
You can override generate_key in your concrete class to change
the way the keys are created. You can also redefine the key field.
The default logout view calls the revoke method, which by default
deletes the row, and can be overriden to customize behaviour.
For example, you could implement soft deletes with a custom model
field (boolean or datetime) and a matching custom authentication
class that checks the custom field.
Adapted from rest_framework.authtoken.
"""
key = models.CharField(_('key'), max_length=40, primary_key=True)
user = models.ForeignKey(
settings.AUTH_USER_MODEL, related_name='api_tokens',
on_delete=models.CASCADE, verbose_name=_('user'))
objects = BaseAPITokenManager()
class Meta:
abstract = True
def __str__(self):
return 'API token for {user}'.format(user=self.user)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(BaseAPIToken, self).save(*args, **kwargs)
def generate_key(self):
return binascii.hexlify(os.urandom(20)).decode()
def revoke(self):
self.delete()
|
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class class1 {
static int N = 100000;
static Scanner in = new Scanner(System.in);
static Map<Integer, Integer> mp = new HashMap<Integer, Integer>();
static Set<Integer> s=new HashSet<Integer>();
static ArrayList<Integer> ar = new ArrayList<Integer>();
static ArrayList<Integer> ans = new ArrayList<Integer>();
static TreeMap<Integer,Integer> tmap=new TreeMap<Integer,Integer>();
static int cn[] = new int[5];
static int fre[]=new int[26];
public static void main(String[] args) {
int n=in.nextInt(),k=in.nextInt(),ans=Integer.MAX_VALUE;
String x=in.next();
for(int i=0;i<n;i++)
{
fre[x.charAt(i)-'A']++;
}
for(int i=0;i<k;i++)
{
ans=Math.min(ans, fre[i]);
}
System.out.println(ans*k);
}
}
|
Building Community Trust: Lessons from an STD/HIV Peer Educator Program with African American Barbers and Beauticians
Sexually transmitted diseases (STDs), HIV, and AIDS disproportionately affect the African American community. In 1999, the rates of gonorrhea and primary and secondary syphilis among African Americans in the United States were approximately 30 times greater than those rates in Whites. Although African Americans represent only 12% of the population nationwide, they constitute 37% of the cumulative AIDS cases. In North Carolina’s Durham County, African Americans accounted for 88% (553) of the HIV cases reported as of December 2000. There remains a demand for prevention efforts that are culturally relevant, incorporating the social norms and values of the African American community. Through the Barber and Beautician STD/HIV Peer Educator Program of the Durham County Health Department’s Project StraighTalk (PS), local barbers and beauticians provide condoms, educational materials, and education to their clients about STDs/HIV. In collaboration with PS, Lewis and Shain performed a needs assessment of the program, including interviews with stylists and clients, to inform program enhancement and materials development. This article describes the needs assessment process, with a specific focus on the challenges of working closely with a community and the lessons learned. |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// TCP sockets
package net
import (
"os";
"syscall";
)
func sockaddrToTCP(sa syscall.Sockaddr) Addr {
switch sa := sa.(type) {
case *syscall.SockaddrInet4:
return &TCPAddr{&sa.Addr, sa.Port}
case *syscall.SockaddrInet6:
return &TCPAddr{&sa.Addr, sa.Port}
}
return nil;
}
// TCPAddr represents the address of a TCP end point.
type TCPAddr struct {
IP IP;
Port int;
}
// Network returns the address's network name, "tcp".
func (a *TCPAddr) Network() string { return "tcp" }
func (a *TCPAddr) String() string { return joinHostPort(a.IP.String(), itoa(a.Port)) }
func (a *TCPAddr) family() int {
if a == nil || len(a.IP) <= 4 {
return syscall.AF_INET
}
if ip := a.IP.To4(); ip != nil {
return syscall.AF_INET
}
return syscall.AF_INET6;
}
func (a *TCPAddr) sockaddr(family int) (syscall.Sockaddr, os.Error) {
return ipToSockaddr(family, a.IP, a.Port)
}
func (a *TCPAddr) toAddr() sockaddr {
if a == nil { // nil *TCPAddr
return nil // nil interface
}
return a;
}
// ResolveTCPAddr parses addr as a TCP address of the form
// host:port and resolves domain names or port names to
// numeric addresses. A literal IPv6 host address must be
// enclosed in square brackets, as in "[::]:80".
func ResolveTCPAddr(addr string) (*TCPAddr, os.Error) {
ip, port, err := hostPortToIP("tcp", addr);
if err != nil {
return nil, err
}
return &TCPAddr{ip, port}, nil;
}
// TCPConn is an implementation of the Conn interface
// for TCP network connections.
type TCPConn struct {
fd *netFD;
}
func newTCPConn(fd *netFD) *TCPConn {
c := &TCPConn{fd};
setsockoptInt(fd.fd, syscall.IPPROTO_TCP, syscall.TCP_NODELAY, 1);
return c;
}
func (c *TCPConn) ok() bool { return c != nil && c.fd != nil }
// Implementation of the Conn interface - see Conn for documentation.
// Read reads data from the TCP connection.
//
// Read can be made to time out and return err == os.EAGAIN
// after a fixed time limit; see SetTimeout and SetReadTimeout.
func (c *TCPConn) Read(b []byte) (n int, err os.Error) {
if !c.ok() {
return 0, os.EINVAL
}
return c.fd.Read(b);
}
// Write writes data to the TCP connection.
//
// Write can be made to time out and return err == os.EAGAIN
// after a fixed time limit; see SetTimeout and SetReadTimeout.
func (c *TCPConn) Write(b []byte) (n int, err os.Error) {
if !c.ok() {
return 0, os.EINVAL
}
return c.fd.Write(b);
}
// Close closes the TCP connection.
func (c *TCPConn) Close() os.Error {
if !c.ok() {
return os.EINVAL
}
err := c.fd.Close();
c.fd = nil;
return err;
}
// LocalAddr returns the local network address, a *TCPAddr.
func (c *TCPConn) LocalAddr() Addr {
if !c.ok() {
return nil
}
return c.fd.laddr;
}
// RemoteAddr returns the remote network address, a *TCPAddr.
func (c *TCPConn) RemoteAddr() Addr {
if !c.ok() {
return nil
}
return c.fd.raddr;
}
// SetTimeout sets the read and write deadlines associated
// with the connection.
func (c *TCPConn) SetTimeout(nsec int64) os.Error {
if !c.ok() {
return os.EINVAL
}
return setTimeout(c.fd, nsec);
}
// SetReadTimeout sets the time (in nanoseconds) that
// Read will wait for data before returning os.EAGAIN.
// Setting nsec == 0 (the default) disables the deadline.
func (c *TCPConn) SetReadTimeout(nsec int64) os.Error {
if !c.ok() {
return os.EINVAL
}
return setReadTimeout(c.fd, nsec);
}
// SetWriteTimeout sets the time (in nanoseconds) that
// Write will wait to send its data before returning os.EAGAIN.
// Setting nsec == 0 (the default) disables the deadline.
// Even if write times out, it may return n > 0, indicating that
// some of the data was successfully written.
func (c *TCPConn) SetWriteTimeout(nsec int64) os.Error {
if !c.ok() {
return os.EINVAL
}
return setWriteTimeout(c.fd, nsec);
}
// SetReadBuffer sets the size of the operating system's
// receive buffer associated with the connection.
func (c *TCPConn) SetReadBuffer(bytes int) os.Error {
if !c.ok() {
return os.EINVAL
}
return setReadBuffer(c.fd, bytes);
}
// SetWriteBuffer sets the size of the operating system's
// transmit buffer associated with the connection.
func (c *TCPConn) SetWriteBuffer(bytes int) os.Error {
if !c.ok() {
return os.EINVAL
}
return setWriteBuffer(c.fd, bytes);
}
// SetLinger sets the behavior of Close() on a connection
// which still has data waiting to be sent or to be acknowledged.
//
// If sec < 0 (the default), Close returns immediately and
// the operating system finishes sending the data in the background.
//
// If sec == 0, Close returns immediately and the operating system
// discards any unsent or unacknowledged data.
//
// If sec > 0, Close blocks for at most sec seconds waiting for
// data to be sent and acknowledged.
func (c *TCPConn) SetLinger(sec int) os.Error {
if !c.ok() {
return os.EINVAL
}
return setLinger(c.fd, sec);
}
// SetKeepAlive sets whether the operating system should send
// keepalive messages on the connection.
func (c *TCPConn) SetKeepAlive(keepalive bool) os.Error {
if !c.ok() {
return os.EINVAL
}
return setKeepAlive(c.fd, keepalive);
}
// DialTCP is like Dial but can only connect to TCP networks
// and returns a TCPConn structure.
func DialTCP(net string, laddr, raddr *TCPAddr) (c *TCPConn, err os.Error) {
if raddr == nil {
return nil, &OpError{"dial", "tcp", nil, errMissingAddress}
}
fd, e := internetSocket(net, laddr.toAddr(), raddr.toAddr(), syscall.SOCK_STREAM, "dial", sockaddrToTCP);
if e != nil {
return nil, e
}
return newTCPConn(fd), nil;
}
// TCPListener is a TCP network listener.
// Clients should typically use variables of type Listener
// instead of assuming TCP.
type TCPListener struct {
fd *netFD;
}
// ListenTCP announces on the TCP address laddr and returns a TCP listener.
// Net must be "tcp", "tcp4", or "tcp6".
// If laddr has a port of 0, it means to listen on some available port.
// The caller can use l.Addr() to retrieve the chosen address.
func ListenTCP(net string, laddr *TCPAddr) (l *TCPListener, err os.Error) {
fd, err := internetSocket(net, laddr.toAddr(), nil, syscall.SOCK_STREAM, "listen", sockaddrToTCP);
if err != nil {
return nil, err
}
errno := syscall.Listen(fd.fd, listenBacklog());
if errno != 0 {
syscall.Close(fd.fd);
return nil, &OpError{"listen", "tcp", laddr, os.Errno(errno)};
}
l = new(TCPListener);
l.fd = fd;
return l, nil;
}
// AcceptTCP accepts the next incoming call and returns the new connection
// and the remote address.
func (l *TCPListener) AcceptTCP() (c *TCPConn, err os.Error) {
if l == nil || l.fd == nil || l.fd.fd < 0 {
return nil, os.EINVAL
}
fd, err := l.fd.accept(sockaddrToTCP);
if err != nil {
return nil, err
}
return newTCPConn(fd), nil;
}
// Accept implements the Accept method in the Listener interface;
// it waits for the next call and returns a generic Conn.
func (l *TCPListener) Accept() (c Conn, err os.Error) {
c1, err := l.AcceptTCP();
if err != nil {
return nil, err
}
return c1, nil;
}
// Close stops listening on the TCP address.
// Already Accepted connections are not closed.
func (l *TCPListener) Close() os.Error {
if l == nil || l.fd == nil {
return os.EINVAL
}
return l.fd.Close();
}
// Addr returns the listener's network address, a *TCPAddr.
func (l *TCPListener) Addr() Addr { return l.fd.laddr }
|
/**
* Creates a simple mail message. date, from and subject are automatically set.
* @param subject
* @return
*/
public SimpleMailMessage createMessage(String subject) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(configuration.getEmailFrom());
message.setSubject(subject);
message.setSentDate(new Date());
return message;
} |
Eli Pariser. | Wikimedia Commons Once the web's fastest growing aggregator, Upworthy pivots
This viral content site drew almost 50 million unique visitors last August. What happened next will surprise you.
Upworthy, the website that made its name re-packaging heartfelt liberal content for maximum shareability on social media, is shifting its focus to the production of original content, laying off six staffers in the process.
Story Continued Below
"Three years ago, when we started Upworthy, we hired people to curate and package meaningful videos," co-founder Eli Pariser in a statement to Capital. (Pariser launched the company with Peter Koechley in 2012.) "But we are now moving decisively to deepen our focus on original storytelling that supports our mission."
The first hint at Upworthy's impending about-face came in February, when the company hired Amy O'Leary as editorial director. O'Leary had one foot in legacy media and another in digital, having served as the New York Times digital deputy editor on the paper's international desk, and having co-authored its Innovation Report, which outlined strategies to transform the Times into a digital powerhouse.
At Upworthy, she would fill the position vacated by the company's founding editorial director. Under Sara Critchfield, Upworthy had called its editorial staffers "curators." They searched the web for videos that would resonate emotionally with viewers, tested different clickbait-y headlines, and posted the top performers on social media. Critchfield preferred to hire "non-professionally trained writers" as "curators," she told Nieman Lab in 2013.
With O'Leary leading the push into original storytelling, Upworthy is retiring the title "curator."
"To make the transition from curation to storytelling (which we’ll share more on in the coming weeks), we...are asking for different skills and a different work style from our editorial team than we ever have before," Pariser said.
While Upworthy has retained most of its editorial team, it let go six members "who had many strengths that don’t fully translate to the kind of original storytelling we’re investing in going forward," in Pariser's words.
The company has hired five new writers, a company representative confirmed. According to Pariser, it has plans to hire more, as well as "visual storytellers" and "a few new Upworthy leaders."
Following that blockbuster month last year, the site's traffic has declined. In May, it drew fewer than 20 million unique visitors, according to Quantcast.
Pariser and Peter Koechley launched Upworthy in 2012 with the mission of connecting readers to nonprofits and the intention of monetizing that service. Supported by the $12 million it raised during two rounds of venture capital financing, Upworthy has also made money through native advertising. |
package com.adrenalinici.adrenaline.client.rmi;
import com.adrenalinici.adrenaline.common.network.outbox.OutboxMessage;
import com.adrenalinici.adrenaline.common.network.rmi.GameRmiClient;
import java.rmi.RemoteException;
import java.util.concurrent.BlockingQueue;
public class GameRmiClientImpl implements GameRmiClient {
private BlockingQueue<OutboxMessage> clientViewInbox;
public GameRmiClientImpl(BlockingQueue<OutboxMessage> clientViewInbox) {
this.clientViewInbox = clientViewInbox;
}
@Override
public void acceptMessage(OutboxMessage message) throws RemoteException {
this.clientViewInbox.offer(message);
}
}
|
#ifndef DQM_L1TMonitor_L1TStage2Shower_h
#define DQM_L1TMonitor_L1TStage2Shower_h
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DQMServices/Core/interface/DQMOneEDAnalyzer.h"
#include "DQMServices/Core/interface/DQMStore.h"
#include "DataFormats/L1TMuon/interface/EMTFDaqOut.h"
#include "DataFormats/L1TMuon/interface/EMTFHit.h"
#include "DataFormats/L1TMuon/interface/EMTFTrack.h"
#include "DataFormats/L1TMuon/interface/RegionalMuonCand.h"
#include "DataFormats/CSCDigi/interface/CSCShowerDigiCollection.h"
#include "DataFormats/L1TMuon/interface/RegionalMuonShower.h"
class L1TStage2Shower : public DQMOneEDAnalyzer<> {
public:
L1TStage2Shower(const edm::ParameterSet& ps);
~L1TStage2Shower() override;
protected:
void bookHistograms(DQMStore::IBooker&, const edm::Run&, const edm::EventSetup&) override;
void analyze(const edm::Event&, const edm::EventSetup&) override;
private:
edm::EDGetTokenT<l1t::RegionalMuonShowerBxCollection> EMTFShowerToken;
edm::EDGetTokenT<CSCShowerDigiCollection> CSCShowerToken;
std::string monitorDir;
bool verbose;
MonitorElement* cscShowerOccupancyLoose;
MonitorElement* cscShowerOccupancyNom;
MonitorElement* cscShowerOccupancyTight;
MonitorElement* cscShowerStationRing;
MonitorElement* cscShowerChamber;
MonitorElement* emtfShowerTypeOccupancy;
};
#endif
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDebug>
#include <QThread>
#include <QClipboard>
#include <QMimeData>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QSettings settings("EgorCO", "Pixel Sorter");
if (!settings.contains("lastDirectory"))
settings.setValue("lastDirectory", ".");
connect(ui->actionQualityZoomCheckBox, &QAction::toggled, ui->imageWidget, &ImageWidget::setQualityZoom);
connect(ui->imageWidget, &ImageWidget::changeRgbInfoMessage, ui->pixelInfoLineEdit, &QLineEdit::setText);
connect(ui->imageWidget, &ImageWidget::changeRgbInfo, this, &MainWindow::changePixelInfo);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_actionOpen_triggered()
{
QSettings settings("EgorCO", "Pixel Sorter");
QString filename = QFileDialog::getOpenFileName(this, "Open image", settings.value("lastDirectory").toString(),
QString("Image Files (*.png *.jpg *.jpeg *.bmp *.gif *.pbm *.pgm *.ppm *.xbm *.xpm);;") +
"PNG (*.png);;" +
"JPEG (*.jpg *.jpeg);;" +
"GIF (*.gif);;" +
"Bitmap (*.bmp *.pbm *.pgm *.ppm *.xbm *.xpm)");
if (filename.isNull())
return;
QFileInfo fileInfo(filename);
settings.setValue("lastDirectory", fileInfo.dir().absolutePath());
lastSavedFilename.clear();
lastOpenedFilename = filename;
canClose = false;
disableInterface();
OpenThread *thread = new OpenThread(this, filename);
connect(thread, &OpenThread::resultReady, this, &MainWindow::handleOpenResults);
connect(thread, &OpenThread::finished, thread, &QObject::deleteLater);
thread->start();
}
void MainWindow::handleOpenResults(QImage openedImage)
{
if (openedImage.isNull())
{
ui->statusBar->showMessage("Failed to open " + lastOpenedFilename);
canClose = true;
enableInterface();
return;
}
options.mask = QImage();
sourceImage = std::move(openedImage);
displayImage = sourceImage.copy(0, 0, sourceImage.width(), sourceImage.height());
ui->imageWidget->setImage(displayImage);
canClose = true;
enableInterface();
ui->statusBar->showMessage("Opened " + lastOpenedFilename);
}
void MainWindow::on_sortButton_clicked()
{
if (sourceImage.isNull())
{
ui->statusBar->showMessage("No image to sort");
return;
}
disableInterface();
SortingThread *thread = new SortingThread(this, sourceImage, options);
connect(thread, &SortingThread::resultReady, this, &MainWindow::handleSortResults);
connect(thread, &SortingThread::finished, thread, &QObject::deleteLater);
thread->start();
}
void MainWindow::handleSortResults(QImage result)
{
enableInterface();
ui->statusBar->showMessage("Sort complete");
displayImage = std::move(result);
ui->imageWidget->setImage(displayImage);
}
void MainWindow::on_optionsButton_clicked()
{
OptionsDialog dialog(this, lastOptionsTab, sourceImage.size());
dialog.setOptions(options);
if (dialog.exec() == QDialog::Accepted)
{
options = dialog.getOptions();
if (sortAfterChange)
ui->sortButton->click();
}
lastOptionsTab = dialog.getLastOptionsTab();
}
void MainWindow::on_actionReset_triggered()
{
if (sourceImage.isNull())
{
ui->statusBar->showMessage("No image to reset");
return;
}
displayImage = sourceImage.copy(0, 0, sourceImage.width(), sourceImage.height());
ui->imageWidget->setImage(displayImage);
ui->statusBar->showMessage("Image reset");
}
void MainWindow::on_actionSave_as_triggered()
{
if (sourceImage.isNull())
{
ui->statusBar->showMessage("No image to save");
return;
}
QSettings settings("EgorCO", "Pixel Sorter");
QString filename = QFileDialog::getSaveFileName(this, "Save image", settings.value("lastDirectory").toString(),
QString("Image Files (*.png *.jpg *.jpeg *.bmp *.gif *.pbm *.pgm *.ppm *.xbm *.xpm);;") +
"PNG (*.png);;" +
"JPEG (*.jpg *.jpeg);;" +
"GIF (*.gif);;" +
"Bitmap (*.bmp *.pbm *.pgm *.ppm *.xbm *.xpm)");
if (filename.isNull())
return;
canClose = false;
disableInterface();
lastSavedFilename = filename;
saveImage(filename);
}
void MainWindow::handleSaveResults()
{
canClose = true;
enableInterface();
ui->statusBar->showMessage("Saved " + lastSavedFilename);
}
void MainWindow::on_actionSave_triggered()
{
if (lastSavedFilename.isNull())
{
on_actionSave_as_triggered();
}
else
{
saveImage(lastSavedFilename);
}
}
void MainWindow::saveImage(QString filename)
{
SaveThread *thread = new SaveThread(this, displayImage, filename);
connect(thread, &SaveThread::resultReady, this, &MainWindow::handleSaveResults);
connect(thread, &SaveThread::finished, thread, &QObject::deleteLater);
thread->start();
}
void MainWindow::enableInterface()
{
QGuiApplication::restoreOverrideCursor();
ui->menuBar->setEnabled(true);
ui->sortButton->setEnabled(true);
ui->optionsButton->setEnabled(true);
ui->imageWidget->setEnabled(true);
ui->pixelInfoLineEdit->setEnabled(true);
ui->pixelInfoComboBox->setEnabled(true);
}
void MainWindow::disableInterface()
{
QGuiApplication::setOverrideCursor(Qt::WaitCursor);
ui->menuBar->setEnabled(false);
ui->sortButton->setEnabled(false);
ui->optionsButton->setEnabled(false);
ui->imageWidget->setEnabled(false);
ui->pixelInfoLineEdit->setEnabled(false);
ui->pixelInfoComboBox->setEnabled(false);
}
void MainWindow::closeEvent(QCloseEvent *event)
{
if (canClose)
QMainWindow::closeEvent(event);
else
event->ignore();
}
void MainWindow::on_actionCopy_triggered()
{
if (displayImage.isNull())
return;
QClipboard *clibboard = QGuiApplication::clipboard();
clibboard->setImage(displayImage);
}
void MainWindow::on_actionPaste_triggered()
{
QClipboard *clipboard = QGuiApplication::clipboard();
if (const QMimeData *mimeData = clipboard->mimeData())
{
if (mimeData->hasImage())
{
const QImage image = qvariant_cast<QImage>(mimeData->imageData());
if (!image.isNull())
{
sourceImage = image;
displayImage = sourceImage;
ui->imageWidget->setImage(displayImage);
}
}
}
}
void MainWindow::on_actionZoom_in_triggered()
{
ui->imageWidget->scrollImage(ImageWidget::Scroll_UP);
}
void MainWindow::on_actionZoom_out_triggered()
{
ui->imageWidget->scrollImage(ImageWidget::Scroll_DOWN);
}
void MainWindow::on_actionReset_zoom_triggered()
{
ui->imageWidget->resetScroll();
}
void MainWindow::on_actionSort_after_changing_options_2_toggled(bool arg1)
{
sortAfterChange = arg1;
}
void MainWindow::changePixelInfo(const QColor &c)
{
QString infoType = ui->pixelInfoComboBox->currentText();
ui->pixelInfoColorLabel->setStyleSheet("QLabel { background-color : rgb(" +
QString::number(c.red()) + "," +
QString::number(c.green()) + "," +
QString::number(c.blue()) + "); border: 2px solid black }");
if (infoType == "RGB")
{
ui->pixelInfoLineEdit->setText(QString::number(c.red()) + " " + QString::number(c.green()) + " " + QString::number(c.blue()));
}
else if (infoType == "HSV")
{
ui->pixelInfoLineEdit->setText(QString::number(c.hue() + 1) + " " + QString::number(c.saturation()) + " " + QString::number(c.value()));
}
else if (infoType == "lightness")
{
ui->pixelInfoLineEdit->setText(QString::number(c.red() + c.green() + c.blue()));
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Clinic;
import static Clinic.Inventory.Itable;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.MessageFormat;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JTable;
/**
*
* @author jomari
*/
public class viewpatientsInformation extends javax.swing.JDialog {
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
static String tmp;
/**
* Creates new form viewpatientsInformation
*/
public viewpatientsInformation() {
initComponents();
this.setLocationRelativeTo(null);
conn = connection.ConnecrDb();
String sql5 = "select * from clinicmanagement.patients where studentid =?";
try {
pst = conn.prepareStatement(sql5);
pst.setString(1, tmp);
rs = pst.executeQuery();
if (rs.next()) {
String view1 = rs.getString("studentid");
viewpatientstudid.setText(view1);
String view2 = rs.getString("firstname");
viewpatientfirst.setText(view2);
String view3 = rs.getString("lastname");
viewpatientlast.setText(view3);
String view4 = rs.getString("middlename");
viewpatientmiddle.setText(view4);
String view5 = rs.getString("age");
viewpatientage.setText(view5);
String view6 = rs.getString("gender");
viewpatientgender.setText(view6);
String view7 = rs.getString("date");
viewpatientdate.setText(view7);
String view8 = rs.getString("contactnumber");
viewpatientcontact.setText(view8);
String view9 = rs.getString("time");
viewpatienttime.setText(view9);
String view10 = rs.getString("bednumber");
viewpatientbed.setText(view10);
String view11 = rs.getString("sick");
viewpatientsick.setText(view11);
String view12 = rs.getString("guardiannumber");
viewpatientguardian.setText(view12);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "this Data is incomplete");
} finally {
try {
rs.close();
pst.close();
} catch (Exception e) {
}
}
//for modal
setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
getRootPane().
setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
public void printComponent() {
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setJobName(" Patients Information ");
pj.setPrintable(new Printable() {
public int print(Graphics pg, PageFormat pf, int pageNum) {
pf.setOrientation(PageFormat.PORTRAIT);
if (pageNum > 0) {
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) pg;
// g2.scale(pf.getImageableWidth()/jPanel2.getWidth(), pf.getImageableHeight()/jPanel2.getHeight());
g2.translate(pf.getImageableX()+10, pf.getImageableY()+170);
g2.scale(0.80, 0.80);
jPanel2.paint(g2);
return Printable.PAGE_EXISTS;
}
});
if (pj.printDialog() == false) {
return;
}
try {
pj.print();
} catch (PrinterException ex) {
// handle exception
}
}
public static void setRow(String row) {
tmp = row;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
viewpatientfirst = new javax.swing.JLabel();
viewpatientstudid = new javax.swing.JLabel();
viewpatientlast = new javax.swing.JLabel();
viewpatientmiddle = new javax.swing.JLabel();
viewpatientage = new javax.swing.JLabel();
viewpatientgender = new javax.swing.JLabel();
viewpatientdate = new javax.swing.JLabel();
viewpatientcontact = new javax.swing.JLabel();
viewpatienttime = new javax.swing.JLabel();
viewpatientbed = new javax.swing.JLabel();
viewpatientsick = new javax.swing.JLabel();
viewpatientguardian = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jButton4 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setUndecorated(true);
setSize(new java.awt.Dimension(750, 500));
setType(java.awt.Window.Type.POPUP);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel1.setBackground(new java.awt.Color(87, 191, 109));
jPanel1.setPreferredSize(new java.awt.Dimension(750, 100));
jLabel1.setFont(new java.awt.Font("Poppins", 1, 36)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/addnewpatientsimage/viewinformationHeader.png"))); // NOI18N
jLabel1.setText("View Information");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(167, 167, 167)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 434, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(149, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(24, 24, 24))
);
getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setPreferredSize(new java.awt.Dimension(750, 360));
jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel5.setBackground(new java.awt.Color(255, 255, 255));
jLabel5.setFont(new java.awt.Font("Poppins", 0, 14)); // NOI18N
jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/addnewpatientsimage/addnewSTUDID.png"))); // NOI18N
jLabel5.setText("Student ID:");
jLabel5.setOpaque(true);
jPanel2.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 70, 130, 30));
jLabel6.setBackground(new java.awt.Color(255, 255, 255));
jLabel6.setFont(new java.awt.Font("Poppins", 0, 14)); // NOI18N
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/addnewpatientsimage/addnewFIRST.png"))); // NOI18N
jLabel6.setText("First Name:");
jLabel6.setOpaque(true);
jPanel2.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 120, 130, 30));
jLabel7.setBackground(new java.awt.Color(255, 255, 255));
jLabel7.setFont(new java.awt.Font("Poppins", 0, 14)); // NOI18N
jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/addnewpatientsimage/addnewLAST.png"))); // NOI18N
jLabel7.setText("Last Name:");
jLabel7.setOpaque(true);
jPanel2.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 170, 130, 30));
jLabel8.setBackground(new java.awt.Color(255, 255, 255));
jLabel8.setFont(new java.awt.Font("Poppins", 0, 14)); // NOI18N
jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/addnewpatientsimage/addnewMIDDLE.png"))); // NOI18N
jLabel8.setText("Middle Name:");
jLabel8.setOpaque(true);
jPanel2.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 220, 130, 30));
jLabel10.setBackground(new java.awt.Color(255, 255, 255));
jLabel10.setFont(new java.awt.Font("Poppins", 0, 14)); // NOI18N
jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/addnewpatientsimage/addnewGENDER.png"))); // NOI18N
jLabel10.setText("Gender:");
jLabel10.setOpaque(true);
jPanel2.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 320, 130, 30));
jLabel11.setBackground(new java.awt.Color(255, 255, 255));
jLabel11.setFont(new java.awt.Font("Poppins", 0, 14)); // NOI18N
jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/addnewpatientsimage/addnewAGE.png"))); // NOI18N
jLabel11.setText("Age:");
jLabel11.setOpaque(true);
jPanel2.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 270, 130, 30));
jLabel12.setBackground(new java.awt.Color(255, 255, 255));
jLabel12.setFont(new java.awt.Font("Poppins", 0, 14)); // NOI18N
jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/addnewpatientsimage/addnewSICK.png"))); // NOI18N
jLabel12.setText("Sick/Illness:");
jLabel12.setOpaque(true);
jPanel2.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 270, 130, 30));
jLabel13.setBackground(new java.awt.Color(255, 255, 255));
jLabel13.setFont(new java.awt.Font("Poppins", 0, 14)); // NOI18N
jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel13.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/addnewpatientsimage/addnewBED.png"))); // NOI18N
jLabel13.setText("Bed Number:");
jLabel13.setOpaque(true);
jPanel2.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 220, 130, 30));
jLabel9.setBackground(new java.awt.Color(255, 255, 255));
jLabel9.setFont(new java.awt.Font("Poppins", 0, 14)); // NOI18N
jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/addnewpatientsimage/addnewGUARDIAN.png"))); // NOI18N
jLabel9.setText("Guardian Contact Number:");
jLabel9.setOpaque(true);
jPanel2.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 320, 210, 30));
jLabel14.setBackground(new java.awt.Color(255, 255, 255));
jLabel14.setFont(new java.awt.Font("Poppins", 0, 14)); // NOI18N
jLabel14.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel14.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/addnewpatientsimage/addnewTIME.png"))); // NOI18N
jLabel14.setText("Time Admit:");
jLabel14.setOpaque(true);
jPanel2.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 170, 130, 30));
jLabel15.setBackground(new java.awt.Color(255, 255, 255));
jLabel15.setFont(new java.awt.Font("Poppins", 0, 14)); // NOI18N
jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel15.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/addnewpatientsimage/addnewCONTACT.png"))); // NOI18N
jLabel15.setText("Contact Number:");
jLabel15.setOpaque(true);
jPanel2.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 120, 140, 30));
jLabel16.setBackground(new java.awt.Color(255, 255, 255));
jLabel16.setFont(new java.awt.Font("Poppins", 0, 14)); // NOI18N
jLabel16.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel16.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/addnewpatientsimage/addnewCALENDAR.png"))); // NOI18N
jLabel16.setText("Date:");
jLabel16.setOpaque(true);
jPanel2.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 70, 130, 30));
viewpatientfirst.setFont(new java.awt.Font("Poppins Light", 0, 12)); // NOI18N
viewpatientfirst.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
viewpatientfirst.setToolTipText("");
jPanel2.add(viewpatientfirst, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 120, 180, 30));
viewpatientstudid.setFont(new java.awt.Font("Poppins Light", 0, 12)); // NOI18N
viewpatientstudid.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
viewpatientstudid.setToolTipText("");
jPanel2.add(viewpatientstudid, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 70, 180, 30));
viewpatientlast.setFont(new java.awt.Font("Poppins Light", 0, 12)); // NOI18N
viewpatientlast.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
viewpatientlast.setToolTipText("");
jPanel2.add(viewpatientlast, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 170, 180, 30));
viewpatientmiddle.setFont(new java.awt.Font("Poppins Light", 0, 12)); // NOI18N
viewpatientmiddle.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
viewpatientmiddle.setToolTipText("");
jPanel2.add(viewpatientmiddle, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 220, 180, 30));
viewpatientage.setFont(new java.awt.Font("Poppins Light", 0, 12)); // NOI18N
viewpatientage.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
viewpatientage.setToolTipText("");
jPanel2.add(viewpatientage, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 270, 180, 30));
viewpatientgender.setFont(new java.awt.Font("Poppins Light", 0, 12)); // NOI18N
viewpatientgender.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
viewpatientgender.setToolTipText("");
jPanel2.add(viewpatientgender, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 320, 180, 30));
viewpatientdate.setFont(new java.awt.Font("Poppins Light", 0, 12)); // NOI18N
viewpatientdate.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jPanel2.add(viewpatientdate, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 70, 190, 30));
viewpatientcontact.setFont(new java.awt.Font("Poppins Light", 0, 12)); // NOI18N
viewpatientcontact.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jPanel2.add(viewpatientcontact, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 120, 190, 30));
viewpatienttime.setFont(new java.awt.Font("Poppins Light", 0, 12)); // NOI18N
viewpatienttime.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jPanel2.add(viewpatienttime, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 170, 190, 30));
viewpatientbed.setFont(new java.awt.Font("Poppins Light", 0, 12)); // NOI18N
viewpatientbed.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jPanel2.add(viewpatientbed, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 220, 190, 30));
viewpatientsick.setFont(new java.awt.Font("Poppins Light", 0, 12)); // NOI18N
viewpatientsick.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jPanel2.add(viewpatientsick, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 270, 190, 30));
viewpatientguardian.setFont(new java.awt.Font("Poppins Light", 0, 12)); // NOI18N
viewpatientguardian.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jPanel2.add(viewpatientguardian, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 320, 130, 30));
jLabel2.setFont(new java.awt.Font("Poppins", 0, 12)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel2.setText("(Patient Information)");
jPanel2.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 30, 720, 30));
jLabel3.setFont(new java.awt.Font("Poppins", 0, 18)); // NOI18N
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel3.setText("Cavite State University - Silang Campus");
jPanel2.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 10, 720, 30));
getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 100, 750, 360));
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
jButton4.setBackground(new java.awt.Color(237, 74, 65));
jButton4.setFont(new java.awt.Font("Poppins", 0, 14)); // NOI18N
jButton4.setForeground(new java.awt.Color(255, 255, 255));
jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/addnewpatientsimage/addnewClose.png"))); // NOI18N
jButton4.setText("Close");
jButton4.setToolTipText("");
jButton4.setBorder(null);
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton3.setBackground(new java.awt.Color(87, 191, 109));
jButton3.setFont(new java.awt.Font("Poppins", 0, 14)); // NOI18N
jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Clinic/image/printer.png"))); // NOI18N
jButton3.setText("Print");
jButton3.setBorder(null);
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap(465, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(20, Short.MAX_VALUE))
);
getContentPane().add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 460, 750, 80));
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
printComponent();
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
Main viewP = new Main();
viewP.setVisible(true);
setVisible(false);
}//GEN-LAST:event_jButton4ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(viewpatientsInformation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(viewpatientsInformation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(viewpatientsInformation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(viewpatientsInformation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new viewpatientsInformation().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JLabel viewpatientage;
private javax.swing.JLabel viewpatientbed;
private javax.swing.JLabel viewpatientcontact;
private javax.swing.JLabel viewpatientdate;
private javax.swing.JLabel viewpatientfirst;
private javax.swing.JLabel viewpatientgender;
private javax.swing.JLabel viewpatientguardian;
private javax.swing.JLabel viewpatientlast;
private javax.swing.JLabel viewpatientmiddle;
private javax.swing.JLabel viewpatientsick;
private javax.swing.JLabel viewpatientstudid;
private javax.swing.JLabel viewpatienttime;
// End of variables declaration//GEN-END:variables
}
|
Aug 19, 2017-
Former Prime Minister Jhalanath Khanal has demanded immediate release of a Nepali youth, who was arrested in India while he was there for medical treatment of his mother.
The UML leader called Nepali Ambassador to India Deep Kumar Upadhyay over the telephone on Friday and urged him to take initiative to release Udayahang Fago,27, a resident of Suryodaya municipality-10, Ilam, according to Khanal's personal secretary Krishna Bhattarai.
Ambassador Upadhyay, in response, said that talks were being held with the Indian central government and concerned authorities in that regard.
Leader Khanal has also requested the Ministry of Foreign Affairs to talk to the concerned Indian agency to have Fago released.
Fago was arrested by Indian police from Siliguri in West Bengal of India, where he had gone for medical treatment of his mother at the local family clinic. He was charged for inciting violence in Darjeeling protest. RSS
Published: 19-08-2017 14:27 |
def dictionaryFor(pos):
pos = normalizePOS(pos)
try:
d = Dictionaries[pos]
except KeyError:
raise RuntimeError, "The " + `pos` + " dictionary has not been created"
return d |
/*
This method is the splashScreen method. It displays an animation of a finger moving down to press a button. It also creates the highScores file and designs the console.
Variable Dictionary
Name Type Description/Purpose
output PrintWriter variable used to write to the file
bgColor Color creates a dark blue color for the background
handColor Color creates a peach color for the hand
handColor2 Color creates a dark tan color for the hand line
The first try catch structure tries to create the high scores file (a blank file). It catches any IO errors.
The first for loop runs from 0 to 250. It moves the hand animation down 250 pixels.
The second try catch structure tries to delay the animation. It catches any errors.
*/
public void splashScreen ()
{
PrintWriter output;
Color bgColor = new Color (0, 87, 183);
Color handColor = new Color (241, 194, 125);
Color handColor2 = new Color (198, 134, 66);
c.setColor (bgColor);
c.fillRect (0, 0, 640, 500);
c.setTextBackgroundColor (bgColor);
c.setTextColor (Color.white);
try
{
output = new PrintWriter (new FileWriter (FILE_NAME));
output.print ("");
output.close ();
}
catch (IOException e)
{
}
c.setColor (new Color (139, 69, 19));
c.fillRect (0, 350, 640, 400);
c.setColor (Color.gray);
c.fillRect (225, 382, 180, 26);
c.fillOval (225, 365, 180, 80);
c.setColor (Color.lightGray);
c.fillOval (225, 345, 180, 80);
c.setColor (new Color (178, 26, 26));
c.fillRect (240, 340, 150, 30);
c.fillOval (240, 330, 150, 80);
c.setColor (Color.red);
c.fillOval (240, 300, 150, 80);
for (int i = 0 ; i < 251 ; i++)
{
c.setColor (bgColor);
c.fillRect (245, -320 + i, 185, 360);
c.setColor (handColor);
c.fillArc (226, -320 + i, 80, 205, 285, 180);
c.fillArc (315, -350 + i, 80, 205, 100, 180);
c.fillRect (270, -300 + i, 80, 200);
c.fillArc (328, -20 + i, 27, 55, 180, 180);
c.fillRect (328, -120 + i, 27, 130);
c.fillArc (333, -120 + i, 50, 75, 80, 180);
c.fillArc (338, -140 + i, 50, 75, 70, 180);
c.fillArc (340, -150 + i, 45, 70, 315, 180);
c.fillArc (345, -200 + i, 50, 70, 120, 180);
c.fillArc (370, -150 + i, 45, 70, 130, 180);
c.fillArc (380, -115 + i, 45, 45, 150, 180);
c.fillOval (260, -200 + i, 115, 125);
c.fillArc (230, -190 + i, 55, 110, 245, 180);
c.fillRect (250, -95 + i, 100, 30);
c.fillArc (245, -100 + i, 30, 40, 160, 180);
c.fillArc (272, -92 + i, 30, 40, 160, 180);
c.fillArc (300, -85 + i, 30, 40, 170, 180);
c.fillOval (318, -70 + i, 20, 10);
c.setColor (new Color (150, 203, 255));
c.fillArc (333, 10 + i, 18, 30, 180, 180);
c.fillArc (333, 10 + i, 18, 30, 0, 180);
c.fillArc (405, -90 + i, 25, 10, 310, 180);
c.fillArc (405, -90 + i, 25, 10, 130, 180);
c.setColor (handColor2);
c.drawLine (335, -20 + i, 348, -20 + i);
try
{
Thread.sleep (5);
}
catch (Exception e)
{
}
}
} |
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
int main(int argc, char** argv) {
int n, l[100001],r[100001],sumL=0,sumR=0,mx=0,res=0;
cin>>n;
for(int i=0;i<n;++i){
cin>>l[i]>>r[i];
sumL+=l[i];
sumR+=r[i];
}
mx=abs(sumL-sumR);
for(int i=0;i<n;++i){
sumL-=l[i];sumL+=r[i];
sumR-=r[i];sumR+=l[i];
if(abs(sumL-sumR)>mx){
mx=abs(sumL-sumR);
res=i+1;
}
sumL-=r[i];sumL+=l[i];
sumR-=l[i];sumR+=r[i];
}
cout<<res<<endl;
return 0;
} |
Israeli aircraft struck a terror target south of Beirut, hours after terrorists fired four rockets at northern Israel.
Israeli aircraft struck a terror target south of Beirut, Lebanon, on Thursday night, said the IDF Spokesperson’s Unit.
According to the statement, a direct hit was identified and all aircraft returned safely to their bases.
The IDF statement said that the airstrike came in response to Thursday afternoon’s rocket attack from Lebanon at northern Israel.
"Yesterday's attack is a blatant breach of Israeli sovereignty that jeopardized Israeli civilian life. Israel will not tolerate terrorist aggression originating from Lebanese territory. The IDF will continue to operate to safeguard the State of Israel and its civilians," said the statement.
Four rockets were fired from Lebanon on Thursday afternoon, with at least one confirmed as having struck in the area of Nahariya.
One rocket was intercepted by the Iron Dome missile defense system, between Akko and Nahariya, the IDF said. Three others struck in "open areas." Several residents were treated for shock.
The attack was claimed by the Abdullah Azzam Brigades, an Al-Qaeda-linked terror group which had claimed similar rocket fire on Israel in 2009 and 2011.
Prime Minister Binyamin Netanyahu reacted to Thursday’s attack by stressing, "Anyone who hurts us, and anyone who tries to hurt us, must know that we will hit him.”
Lebanon’s president Michel Sleiman condemned the rocket fire from southern Lebanon, saying it was a violation of UNSCR 1701, which brought an end to the Second Lebanon War in 2006, and to Lebanon's sovereignty.
While Sleiman condemned the incident, the Lebanese-based Hezbollah terror group would not. A Hezbollah MP, Hasan Fadlallah, said his party was sticking to its policy regarding attacks against Israel. |
def Get(self, timeout=None):
if timeout is None:
timeout = 0xFFFF
try:
return self.result.get(timeout)
except _multiprocessing.TimeoutError:
raise TimeoutExpiredError("The timeout expired before the thread completed") |
/**
* Utility functions for parsing command line arguments.
*
*/
public class CommandLineUtilities {
/***
* The Regular Expression pattern for JSON arrays.
*/
private static final Pattern JSON_ARRAY_PATTERN
= Pattern.compile(
"\\s*\\[\\s*((\\\".*\\\"\\s*,\\s*)+"
+ "(\\\".*\\\")|(\\\".*\\\")?)\\s*\\]\\s*");
/**
* The JAR file name containing this class.
*/
public static final String JAR_FILE_NAME;
/**
* The base URL of the JAR file containing this class.
*/
public static final String JAR_BASE_URL;
/**
* The URL path to the JAR file containing this class.
*/
public static final String PATH_TO_JAR;
static {
String jarBaseUrl = null;
String jarFileName = null;
String pathToJar = null;
try {
Class<CommandLineUtilities> cls = CommandLineUtilities.class;
String url = cls.getResource(
cls.getSimpleName() + ".class").toString();
if (url.indexOf(".jar") >= 0) {
int index = url.lastIndexOf(
cls.getName().replace(".", "/") + ".class");
jarBaseUrl = url.substring(0, index);
index = jarBaseUrl.lastIndexOf("!");
if (index >= 0) {
url = url.substring(0, index);
index = url.lastIndexOf("/");
if (index >= 0) {
jarFileName = url.substring(index + 1);
}
url = url.substring(0, index);
index = url.indexOf("/");
pathToJar = url.substring(index);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new ExceptionInInitializerError(e);
} finally {
JAR_BASE_URL = jarBaseUrl;
JAR_FILE_NAME = jarFileName;
PATH_TO_JAR = pathToJar;
}
}
/**
* Private default constructor.
*/
private CommandLineUtilities() {
// do nothing
}
/**
* Utility method to ensure a command line argument with the specified index
* exists and if not then throws an exception.
*
* @param args The array of command line arguments.
* @param index The index to check.
* @throws IllegalArgumentException If the argument does not exist.
*/
public static void ensureArgument(String[] args, int index) {
if (index >= args.length) {
String msg = "Missing expected argument following " + args[index - 1];
System.err.println();
System.err.println(msg);
setLastLoggedAndThrow(new IllegalArgumentException(msg));
}
}
/**
* Returns a new {@link String} array that contains the same elements as
* the specified array except for the first N arguments where N is the
* specified count.
*
* @param args The array of command line arguments.
* @param count The number of arguments to shift.
* @return The shifted argument array.
* @throws IllegalArgumentException If the specified count is negative.
*/
public static String[] shiftArguments(String[] args, int count) {
if (count < 0) {
throw new IllegalArgumentException(
"The specified count cannot be negative: " + count);
}
String[] args2 = new String[args.length - count];
for (int index = 0; index < args2.length; index++) {
args2[index] = args[index + count];
}
return args2;
}
/**
* Returns a descriptor for the source of the {@link CommandLineValue}
* for building error messages.
*
* @param commandLineValue The {@link CommandLineValue}.
*/
private static <T extends Enum<T> & CommandLineOption<T>> String
sourceDescriptor(CommandLineValue<T> commandLineValue)
{
switch (commandLineValue.getSource()) {
case COMMAND_LINE:
return commandLineValue.getSpecifier() + " option";
case ENVIRONMENT:
return commandLineValue.getSpecifier() + " environment variable";
default:
return commandLineValue.getOption().getCommandLineFlag() + " default";
}
}
/**
* Stores the option and its value(s) in the specified option map, first
* checking to ensure that the option is NOT already specified and
* checking if the option has any conflicts. If the specified option is
* deprecated then a warning message is returned. If only a single option
* is specified then it is placed as the value. If more than one option is
* specified then the value in the map is an array of the specified values.
*
* @param optionMap The {@link Map} to put the option in.
* @param value the {@link CommandLineValue} to add to the {@link Map}.
*/
public static <T extends Enum<T> & CommandLineOption<T>> void putValue(
Map<T, CommandLineValue<T>> optionMap,
CommandLineValue<T> value)
{
T option = value.getOption();
Set<T> optionKeys = optionMap.keySet();
CommandLineValue<T> prevValue = optionMap.get(option);
if (prevValue != null) {
String msg = (prevValue.getSpecifier().equals(value.getSpecifier()))
? "The " + sourceDescriptor(value) + " cannot be specified more than "
+ "once."
: "Cannot specify both the " + sourceDescriptor(prevValue)
+ " and " + sourceDescriptor(value) + ".";
System.err.println();
System.err.println(msg);
setLastLoggedAndThrow(new IllegalArgumentException(msg));
}
// check for conflicts if the value is NOT a no-arg option with false value
if (!checkNoArgFalse(value) && (value.getSource() != DEFAULT)) {
Set<T> conflicts = option.getConflicts();
for (T opt : optionKeys) {
if (conflicts != null && conflicts.contains(opt)) {
// get the command-line value
CommandLineValue<T> conflictValue = optionMap.get(opt);
// no conflict if the other is a defaulted value
if (conflictValue.getSource() == DEFAULT) continue;
// no conflict if the other is a no-arg option with a false value
if (checkNoArgFalse(conflictValue)) continue;
// handle the conflict
String msg = "Cannot specify both the "
+ sourceDescriptor(conflictValue) + " and "
+ sourceDescriptor(value) + ".";
System.err.println();
System.err.println(msg);
setLastLoggedAndThrow(new IllegalArgumentException(msg));
}
}
}
// check for deprecation
if (option.isDeprecated()) {
System.err.println();
System.err.println("WARNING: The " + sourceDescriptor(value)
+ " option is deprecated and will be removed in a "
+ "future release.");
Set<T> alternatives = option.getDeprecationAlternatives();
if (alternatives.size() == 1) {
T alternative = alternatives.iterator().next();
System.err.println();
System.err.println("Consider using " + alternative.getCommandLineFlag()
+ " instead.");
} else if (alternatives.size() > 1) {
System.err.println();
System.err.println("Consider using one of the following instead:");
for (T alternative : alternatives) {
System.err.println(" " + alternative.getCommandLineFlag());
}
}
System.err.println();
}
// put it in the option map
optionMap.put(option, value);
}
/**
* Checks if the specified {@link CommandLineValue} is a zero or single
*/
private static <T extends Enum<T> & CommandLineOption<T>> boolean
checkNoArgFalse(CommandLineValue<T> cmdLineValue)
{
T option = cmdLineValue.getOption();
// special-case no-arg boolean flags
int minParamCount = option.getMinimumParameterCount();
int maxParamCount = option.getMaximumParameterCount();
return (minParamCount == 0 && maxParamCount >= 0
&& option.getDefaultParameters() != null
&& option.getDefaultParameters().size() == 1
&& "false".equalsIgnoreCase(option.getDefaultParameters().get(0))
&& cmdLineValue.getParameters() != null
&& cmdLineValue.getParameters().size() == 1
&& "false".equalsIgnoreCase(cmdLineValue.getParameters().get(0)));
}
/**
* Returns the enumerated {@link CommandLineOption} value associated with
* the specified command line flag and enumerated {@link CommandLineOption}
* class.
*
* @param enumClass The {@link Class} for the {@link CommandLineOption}
* implementation.
* @param commandLineFlag The command line flag.
* @return The enumerated {@link CommandLineOption} or <tt>null</tt> if not
* found.
*/
public static <T extends Enum<T> & CommandLineOption<T>> T lookup(
Class<T> enumClass,
String commandLineFlag) {
// just iterate to find it rather than using a lookup map given that
// enums are usually not more than a handful of values
EnumSet<T> enumSet = EnumSet.allOf(enumClass);
for (T enumVal : enumSet) {
if (enumVal.getCommandLineFlag().equals(commandLineFlag)) {
return enumVal;
}
}
return null;
}
/**
* Validates the specified {@link Set} of specified {@link CommandLineOption}
* instances and ensures that they logically make sense together. This
* checks for the existing of at least one primary option (if primary options
* exist), ensures there are no conflicts and that all dependencies are
* satisfied.
*
* @throws IllegalArgumentException If the specified options are invalid
* together.
*/
public static <T extends Enum<T> & CommandLineOption<T>> void validateOptions(
Class<T> enumClass,
Map<T, CommandLineValue<T>> optionValues)
throws IllegalArgumentException
{
// check if we need a primary option
boolean primaryRequired = false;
EnumSet<T> enumSet = EnumSet.allOf(enumClass);
for (T enumVal : enumSet) {
if (enumVal.isPrimary()) {
primaryRequired = true;
break;
}
}
if (primaryRequired) {
// if primary option is required then check for at least one
int primaryCount = 0;
for (T option : optionValues.keySet()) {
if (option.isPrimary()) {
primaryCount++;
}
}
if (primaryCount == 0) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.println("Must specify at least one of the following:");
for (T option : enumSet) {
if (option.isPrimary()) {
pw.println(" " + option.getCommandLineFlag()
+ (option.isDeprecated() ? " (deprecated)" : ""));
}
}
String msg = sw.toString();
pw.flush();
System.err.println();
System.err.println(msg);
setLastLoggedAndThrow(new IllegalArgumentException(msg));
}
}
// check for conflicts and dependencies
for (CommandLineValue<T> cmdLineValue : optionValues.values()) {
if (cmdLineValue.getSource() == DEFAULT) continue;
T option = cmdLineValue.getOption();
Set<T> conflicts = option.getConflicts();
Set<Set<T>> dependencies = option.getDependencies();
if (conflicts != null) {
for (T conflict : conflicts) {
// skip if the same option -- cannot conflict with itself
if (option == conflict) continue;
// check if the conflict is present
CommandLineValue<T> conflictValue = optionValues.get(conflict);
if (conflictValue != null) {
if (conflictValue.getSource() == DEFAULT) continue;
String msg = "Cannot specify both the "
+ sourceDescriptor(cmdLineValue)
+ " and the " + sourceDescriptor(conflictValue);
System.err.println();
System.err.println(msg);
setLastLoggedAndThrow(new IllegalArgumentException(msg));
}
}
}
boolean satisfied = (dependencies == null || dependencies.size() == 0);
if (!satisfied) {
for (Set<T> dependencySet : dependencies) {
if (optionValues.keySet().containsAll(dependencySet)) {
satisfied = true;
break;
}
}
}
if (!satisfied) {
System.err.println();
if (dependencies.size() == 1) {
System.err.println(
"The " + sourceDescriptor(cmdLineValue) + " also requires:");
Set<T> dependencySet = dependencies.iterator().next();
for (T dependency : dependencySet) {
if (!optionValues.containsKey(dependency)) {
System.err.println(" " + dependency.getCommandLineFlag());
}
}
} else {
System.err.println(
"The " + sourceDescriptor(cmdLineValue) + " also requires:");
String leader = " ";
for (Set<T> dependencySet : dependencies) {
String prefix = "";
String prevOption = null;
System.err.print(leader);
leader = " or ";
for (T dependency : dependencySet) {
int count = 0;
if (!optionValues.containsKey(dependency)) {
if (prevOption != null) {
count++;
System.err.print(prefix + prevOption);
}
prevOption = dependency.getCommandLineFlag();
prefix = ", ";
}
if (count > 0) {
System.err.print(" and ");
}
System.err.println(prevOption);
}
}
}
setLastLoggedAndThrow(new IllegalArgumentException(
"Missing dependencies for " + sourceDescriptor(cmdLineValue)));
}
}
}
/**
* Creates a lookup map of {@link String} command-line flags to the
* {@link CommandLineOption} values that they map to. This includes any
* synonyms for the options if they exist.
*
* @param enumClass The enumerated class for the {@link CommandLineOption}.
*/
private static <T extends Enum<T> & CommandLineOption<T>> Map<String, T>
createFlagLookupMap(Class<T> enumClass)
{
// get all the options
EnumSet<T> enumSet = EnumSet.allOf(enumClass);
// create a lookup map for the flags
Map<String, T> lookupMap = new LinkedHashMap<>();
for (T option : enumSet) {
// get the flag
String flag = option.getCommandLineFlag();
// do a sanity check
if (lookupMap.containsKey(flag)) {
throw new IllegalStateException(
"Command-line flag (" + flag + ") cannot resolve to different "
+ "options (" + lookupMap.get(flag) + " and " + option
+ "). It must be unique.");
}
// add the primary flag to the lookup map
lookupMap.put(flag, option);
// add the synonym flags if any
Set<String> synonymFlags = option.getSynonymFlags();
if (synonymFlags == null) synonymFlags = Collections.emptySet();
for (String synonym : synonymFlags) {
// check the synonym against the primary flag (sanity check)
if (synonym.equals(flag)) {
throw new IllegalStateException(
"Synonym command-line (" + flag + ") for option (" + option
+ ") is the same as the primary flag.");
}
// do a sanity check
if (lookupMap.containsKey(synonym)) {
throw new IllegalStateException(
"Command-line flag (" + flag + ") cannot resolve to different "
+ "options (" + lookupMap.get(flag) + " and " + option
+ "). It must be unique.");
}
// add to the lookup map
lookupMap.put(synonym, option);
}
}
// return the lookup map
return lookupMap;
}
/**
* Parses the command line arguments and returns a {@link Map} of those
* arguments. This function will attempt to find values for command-line
* options that are not explicitly specified on the command line by using
* environment variables for those options have environment variable
* equivalents defined.
*
* @param enumClass The enumerated {@link CommandLineOption} class.
* @param args The arguments to parse.
* @param processor The {@link ParameterProcessor} to use for handling the
* parameters to the options.
* @return A {@link Map} of {@link CommandLineOption} keys to
*/
public static <T extends Enum<T> & CommandLineOption<T>> Map<T, CommandLineValue<T>>
parseCommandLine(Class<T> enumClass,
String[] args,
ParameterProcessor<T> processor)
{
return parseCommandLine(
enumClass, args, processor, false, null);
}
/**
* Parses the command line arguments and returns a {@link Map} of those
* arguments. Depending on the specified value for <tt>ignoreEnvironment<tt>
* this function will optionally attempt to find values for command-line
* options that are not explicitly specified on the command line by using
* environment variables for those options have environment variable
* equivalents defined.
*
* @param enumClass The enumerated {@link CommandLineOption} class.
* @param args The arguments to parse.
* @param processor The {@link ParameterProcessor} to use for handling the
* parameters to the options.
* @param ignoreEnvironment Flag indicating if the environment variables
* should be ignored in the processing.
* @return A {@link Map} of {@link CommandLineOption} keys to
*/
public static <T extends Enum<T> & CommandLineOption<T>> Map<T, CommandLineValue<T>>
parseCommandLine(Class<T> enumClass,
String[] args,
ParameterProcessor<T> processor,
boolean ignoreEnvironment)
{
return parseCommandLine(
enumClass, args, processor, false, null);
}
/**
* Parses the command line arguments and returns a {@link Map} of those
* arguments. This function will optionally attempt to find values for
* command-line options that are not explicitly specified on the command line
* by using environment variables for those options have environment variable
* equivalents defined. Use of the environment is disabled if the
* <tt>ignoreEnvOption</tt> parameter is non-null and that option is present
* in the explicitly specified command-line arguments and either has no
* parameter value or any value other than <tt>false</tt>.
*
* @param enumClass The enumerated {@link CommandLineOption} class.
* @param args The arguments to parse.
* @param processor The {@link ParameterProcessor} to use for handling the
* parameters to the options.
* @param ignoreEnvOption The optional command-line option value that if
* present with no value or present with any value
* other than <tt>false</tt> will cause the environment
* to be ignored in processing.
*
* @return A {@link Map} of {@link CommandLineOption} keys to
*/
public static <T extends Enum<T> & CommandLineOption<T>> Map<T, CommandLineValue<T>>
parseCommandLine(Class<T> enumClass,
String[] args,
ParameterProcessor<T> processor,
T ignoreEnvOption)
{
return parseCommandLine(
enumClass, args, processor, false, ignoreEnvOption);
}
/**
* Handles processing the specified parameters for the specified option.
*
* @param option The relevant option.
* @param processor The {@link ParameterProcessor}, or <tt>null</tt> if none.
* @param params The {@link List} of {@link String} parameters.
* @return The processed value.
*/
private static <T extends Enum<T> & CommandLineOption<T>> Object processValue(
T option,
ParameterProcessor<T> processor,
List<String> params)
{
// process the parameters
if (processor != null) {
// handle the case where a processor is defined for the parameters
Object value = null;
try {
value = processor.process(option, params);
} catch (Exception e) {
System.err.println();
System.err.println("Bad parameters for " + option.getCommandLineFlag()
+ " option:");
for (String p : params) {
System.err.println(" o " + p);
}
System.err.println();
System.err.println(e.getMessage());
if (e instanceof RuntimeException) {
LoggingUtilities.setLastLoggedAndThrow((RuntimeException) e);
}
LoggingUtilities.setLastLoggedAndThrow(new RuntimeException(e));
}
return value;
} else if (params.size() == 0) {
// handle the case of no parameters and no parameter processor
return null;
} else if (params.size() == 1) {
// handle the case of one parameter and no parameter processor
return params.get(0);
} else {
// handle the case of multiple parameters and no parameter processor
return params.toArray();
}
}
/**
* Parses the command line arguments and returns a {@link Map} of those
* arguments.
*
* @param enumClass The enumerated {@link CommandLineOption} class.
* @param args The arguments to parse.
* @param processor The {@link ParameterProcessor} to use for handling the
* parameters to the options.
* @param ignoreEnvironment Flag indicating if the environment variables
* should be ignored in the processing.
* @param ignoreEnvOption The option to trigger ignoring the environment.
*
* @return A {@link Map} of {@link CommandLineOption} keys to
*/
private static <T extends Enum<T> & CommandLineOption<T>> Map<T, CommandLineValue<T>>
parseCommandLine(Class<T> enumClass,
String[] args,
ParameterProcessor<T> processor,
boolean ignoreEnvironment,
T ignoreEnvOption)
{
// create a lookup map for the flags to their options
Map<String, T> lookupMap = createFlagLookupMap(enumClass);
// iterate over the args and build a map
Map<T, CommandLineValue<T>> result = new LinkedHashMap<>();
Map<T, String> usedFlags = new LinkedHashMap<>();
for (int index = 0; index < args.length; index++) {
// get the next flag
String flag = args[index];
// determine the option from the flag
T option = lookupMap.get(flag);
// check if the option is recognized
if (option == null) {
System.err.println();
System.err.println("Unrecognized option: " + flag);
setLastLoggedAndThrow(new IllegalArgumentException(
"Unrecognized command line option: " + flag));
}
// check if the option has already been specified
String usedFlag = usedFlags.get(option);
if (usedFlag != null && usedFlag.equals(flag)) {
System.err.println();
System.err.println("Option specified more than once: " + flag);
setLastLoggedAndThrow(new IllegalArgumentException(
"Option specified more than once: " + flag));
} else if (usedFlag != null) {
System.err.println();
System.err.println(
"Option specified more than once: " + usedFlag + " and " + flag);
setLastLoggedAndThrow(new IllegalArgumentException(
"Option specified more than once: " + usedFlag + " and " + flag));
}
// get the option parameters
int minParamCount = option.getMinimumParameterCount();
int maxParamCount = option.getMaximumParameterCount();
if (maxParamCount > 0 && maxParamCount < minParamCount) {
throw new IllegalStateException(
"The non-negative maximum parameter count is less than the minimum "
+ "parameter count. min=[ " + minParamCount + " ], max=[ "
+ maxParamCount + " ], option=[ " + option + " ]");
}
List<String> params = new ArrayList<>(maxParamCount<0 ? 5:maxParamCount);
if (minParamCount > 0) {
// check if there are enough parameters
int max = index + minParamCount;
for (index++; index <= max; index++) {
ensureArgument(args, index);
params.add(args[index]);
}
index--;
}
// check if we have a zero-argument parameter
if (minParamCount == 0 && maxParamCount == 0
&& option.getDefaultParameters() != null
&& option.getDefaultParameters().size() == 1
&& "false".equalsIgnoreCase(option.getDefaultParameters().get(0)))
{
// allow a zero-argument parameter to be followed by "true" or "false"
if (args.length > (index + 1)) {
// we have arguments after this one -- check the next one
String param = args[index+1].trim().toLowerCase();
// check if it is a parameter or a command-line flag
if (!param.startsWith("-")) {
// looks like a parameter since a flag starts with "-"
switch (param) {
case "true":
case "false":
params.add(args[++index].trim().toLowerCase());
break;
default:
throw new IllegalArgumentException(
"The " + flag + " command line option can be specified "
+ "with no parameters, but if a parameter is provided it "
+ "must be \"true\" or \"false\": " + args[index + 1]);
}
}
}
} else {
// get the parameters from the command line
int bound = (maxParamCount < 0)
? args.length
: index + (maxParamCount - minParamCount) + 1;
if (bound > args.length) bound = args.length;
for (int nextIndex = index + 1;
nextIndex < bound && !lookupMap.containsKey(args[nextIndex]);
nextIndex++)
{
params.add(args[nextIndex]);
index++;
}
}
// check if we have a zero-parameter option with a "false" default
if (minParamCount == 0 && maxParamCount == 0 && params.size() == 0
&& option.getDefaultParameters() != null
&& option.getDefaultParameters().size() == 1
&& "false".equalsIgnoreCase(option.getDefaultParameters().get(0)))
{
params.add("true");
}
// process the parameters
Object processedValue = processValue(option, processor, params);
// create the command-line value
CommandLineValue<T> cmdLineVal = new CommandLineValue<>(option,
COMMAND_LINE,
flag,
processedValue,
params);
// add to the options map
putValue(result, cmdLineVal);
}
// optionally process the environment
ignoreEnvironment
= (ignoreEnvironment
|| (result.containsKey(ignoreEnvOption)
&& (!Boolean.FALSE.equals(result.get(ignoreEnvOption)))));
if (!ignoreEnvironment) {
try {
processEnvironment(enumClass, processor, result);
} catch (NullPointerException e) {
e.printStackTrace();
throw e;
}
}
try {
// handle setting the default values
processDefaults(enumClass, processor, result);
} catch (NullPointerException e) {
e.printStackTrace();
throw e;
}
// validate the options
try {
validateOptions(enumClass, result);
} catch (NullPointerException e) {
e.printStackTrace();
throw e;
}
return result;
}
/**
* Checka for command-line option values in the environment.
*
*/
private static <T extends Enum<T> & CommandLineOption<T>> void
processEnvironment(Class<T> enumClass,
ParameterProcessor<T> processor,
Map<T, CommandLineValue<T>> optionValues)
{
processEnvironment(EnumSet.allOf(enumClass),
processor,
optionValues,
false);
Set<T> optionKeys = optionValues.keySet();
Set<T> fallbackOptions = new LinkedHashSet<>();
for (T option : optionKeys) {
// get the dependency sets
Set<Set<T>> dependencySets = option.getDependencies();
// check if no dependencies
if (dependencySets == null) continue;
if (dependencySets.size() == 0) continue;
// set the flag indicating the dependencies are not satisfied
boolean satisfied = false;
// iterate over the dependency sets and see if at least one is satisfied
for (Set<T> dependencySet: dependencySets) {
if (optionValues.keySet().containsAll(dependencySet)) {
satisfied = true;
break;
}
}
// check if the option is not satisfied
if (!satisfied) {
// find the first dependency set with missing items with fallbacks
for (Set<T> dependencySet: dependencySets) {
// set the fallback count to zero and create the missing set
int fallbackCount = 0;
Set<T> missingSet = new LinkedHashSet<>();
// iterate over the options
for (T dependency: dependencySet) {
// check if dependency is missing
if (optionValues.containsKey(dependency)) continue;
// add to the missing set
missingSet.add(dependency);
// check if the missing item has fallbacks
List<String> fallbacks = dependency.getEnvironmentFallbacks();
if (fallbacks != null && fallbacks.size() > 0) fallbackCount++;
}
// check if the fallback count and missing count are equal and if
// so then use this dependency set
if (missingSet.size() > 0 && missingSet.size() == fallbackCount) {
fallbackOptions.addAll(missingSet);
break;
}
}
}
}
// check the fallback options
if (fallbackOptions.size() > 0) {
System.err.println();
processEnvironment(fallbackOptions, processor, optionValues, true);
}
}
/**
* Checka for command-line option values in the environment.
*
*/
private static <T extends Enum<T> & CommandLineOption<T>> void
processEnvironment(Set<T> enumSet,
ParameterProcessor<T> processor,
Map<T, CommandLineValue<T>> optionValues,
boolean fallBacks)
{
// get the environment
Map<String, String> env = System.getenv();
// iterate over the options
for (T option: enumSet) {
// prefer explicit command-line arguments, so skip if already present
if (optionValues.containsKey(option)) continue;
List<String> envVars = null;
if (fallBacks) {
// get the fallbacks
envVars = option.getEnvironmentFallbacks();
if (envVars == null) envVars = Collections.emptyList();
} else {
// get the environment variable and its synonyms
String envVar = option.getEnvironmentVariable();
Set<String> synonymSet = option.getEnvironmentSynonyms();
envVars = new ArrayList<>(synonymSet==null ? 1 : synonymSet.size() + 1);
if (envVar != null) envVars.add(envVar);
if (synonymSet != null) envVars.addAll(synonymSet);
}
// iterate over the items in the list
String envVal = null;
String foundVar = null;
for (String envVar: envVars) {
// check if null
if (envVar == null) continue;
// check if contained in the environment
envVal = env.get(envVar);
if (envVal != null) {
foundVar = envVar;
break;
}
}
// check if no value
if (envVal == null) continue;
// process the env value
int minParamCount = option.getMinimumParameterCount();
int maxParamCount = option.getMaximumParameterCount();
if (maxParamCount > 0 && maxParamCount < minParamCount) {
throw new IllegalStateException(
"The non-negative maximum parameter count is less than the minimum "
+ "parameter count. min=[ " + minParamCount + " ], max=[ "
+ maxParamCount + " ], option=[ " + option + " ]");
}
List<String> params = null;
// check the number of parameters
if (minParamCount == 0 && maxParamCount == 0) {
// no parameters, these are boolean on/off options
switch (envVal.trim().toLowerCase()) {
case "":
case "true":
params = List.of("true");
break;
case "false":
params = List.of("false");
break;
default:
throw new IllegalArgumentException(
"The specified value for the " + foundVar
+ " environment variable can only be \"true\""
+ " or \"false\": " + foundVar);
}
} else if (minParamCount <= 1 && maxParamCount == 1) {
// handle the single parameter case
params = List.of(envVal);
} else if ((maxParamCount > 1 || maxParamCount < 0)
&& (JSON_ARRAY_PATTERN.matcher(envVal).matches()))
{
// handle the case of multiple parameters and a JSON array
JsonArray jsonArray = JsonUtils.parseJsonArray(envVal.trim());
params = new ArrayList<>(jsonArray.size());
for (JsonString jsonString: jsonArray.getValuesAs(JsonString.class)) {
params.add(jsonString.getString());
}
} else if (maxParamCount > 1 || maxParamCount < 0) {
// handle the case of multiple parameters, splitting on commas & spaces
String[] tokens = envVal.split("(\\s*,\\s*|\\s+)");
params = Arrays.asList(tokens);
}
// get the parameter count
int paramCount = params.size();
// check the parameter count
if (paramCount != 1 || minParamCount != 0 || maxParamCount != 0) {
// handle the options with parameters
if (paramCount < minParamCount) {
throw new IllegalArgumentException(
"Expected at least " + minParamCount + " parameter(s) but "
+ "found " + paramCount + " for " + foundVar
+ " environment variable: " + envVal);
}
if ((maxParamCount >= 0) && (paramCount > maxParamCount)) {
throw new IllegalArgumentException(
"Expected at most " + maxParamCount + " parameter(s) but "
+ "found " + paramCount + " for " + foundVar
+ " environment variable: " + envVal);
}
}
// process the parameters
Object processedValue = processValue(option, processor, params);
// create the command line value
CommandLineValue<T> cmdLineVal = new CommandLineValue<>(option,
ENVIRONMENT,
foundVar,
processedValue,
params);
// put the value
putValue(optionValues, cmdLineVal);
}
}
/**
* Checka for command-line option values in the environment.
*
*/
private static <T extends Enum<T> & CommandLineOption<T>> void
processDefaults(Class<T> enumClass,
ParameterProcessor<T> processor,
Map<T, CommandLineValue<T>> optionValues)
{
// get all the options
EnumSet<T> enumSet = EnumSet.allOf(enumClass);
// iterate over the options
for (T option: enumSet) {
// prefer explicit command-line arguments, so skip if already present
if (optionValues.containsKey(option)) continue;
// get the default parameters
List<String> params = option.getDefaultParameters();
// check if there are none
if (params == null || params.size() == 0) continue;
// process the parameters
Object processedValue = processValue(option, processor, params);
// create the command line value
CommandLineValue<T> cmdLineVal = new CommandLineValue<>(option,
DEFAULT,
processedValue,
params);
// put the value
putValue(optionValues, cmdLineVal);
}
}
/**
* Processes the {@link Map} of {@link CommandLineOption} keys to {@link
* CommandLineValue} values and produces the {@link Map} of {@link
* CommandLineOption} keys to {@linkplain CommandLineValue#getProcessedValue()
* processed values}.
*
* @param optionValues The {@link Map} of option keys to {@link
* CommandLineValue} values.
* @param processedValues The {@link Map} to populate with the processed
* values if specified, if <tt>null</tt> a new {@link
* Map} is created and returned.
*/
public static <T extends Enum<T> & CommandLineOption<T>> Map<T, Object>
processCommandLine(Map<T, CommandLineValue<T>> optionValues,
Map<T, Object> processedValues)
{
return processCommandLine(optionValues,
processedValues,
null,
null);
}
/**
* Processes the {@link Map} of {@link CommandLineOption} keys to {@link
* CommandLineValue} values and produces the {@link Map} of {@link
* CommandLineOption} keys to {@linkplain CommandLineValue#getProcessedValue()
* processed values}.
*
* @param optionValues The {@link Map} of option keys to {@link
* CommandLineValue} values.
* @param processedValues The {@link Map} to populate with the processed
* values if specified, if <tt>null</tt> a new {@link
* Map} is created and returned.
* @param jsonBuilder If not <tt>null</tt> then this {@link JsonObjectBuilder}
* is populated with startup option information.
*/
public static <T extends Enum<T> & CommandLineOption<T>> Map<T, Object>
processCommandLine(Map<T, CommandLineValue<T>> optionValues,
Map<T, Object> processedValues,
JsonObjectBuilder jsonBuilder)
{
return processCommandLine(optionValues,
processedValues,
jsonBuilder,
null);
}
/**
* Processes the {@link Map} of {@link CommandLineOption} keys to {@link
* CommandLineValue} values and produces the {@link Map} of {@link
* CommandLineOption} keys to {@linkplain CommandLineValue#getProcessedValue()
* processed values}.
*
* @param optionValues The {@link Map} of option keys to {@link
* CommandLineValue} values.
* @param processedValues The {@link Map} to populate with the processed
* values if specified, if <tt>null</tt> a new {@link
* Map} is created and returned.
* @param stringBuilder If not <tt>null</tt>then this {@link StringBuilder}
* is populated with JSON text describing the startup
* options.
*/
public static <T extends Enum<T> & CommandLineOption<T>> Map<T, Object>
processCommandLine(Map<T, CommandLineValue<T>> optionValues,
Map<T, Object> processedValues,
StringBuilder stringBuilder)
{
return processCommandLine(optionValues,
processedValues,
null,
stringBuilder);
}
/**
* Processes the {@link Map} of {@link CommandLineOption} keys to {@link
* CommandLineValue} values and produces the {@link Map} of {@link
* CommandLineOption} keys to {@linkplain CommandLineValue#getProcessedValue()
* processed values}.
*
* @param optionValues The {@link Map} of option keys to {@link
* CommandLineValue} values.
* @param processedValues The {@link Map} to populate with the processed
* values if specified, if <tt>null</tt> a new {@link
* Map} is created and returned.
* @param jsonBuilder If not <tt>null</tt> then this {@link JsonObjectBuilder}
* is populated with startup option information.
* @param stringBuilder If not <tt>null</tt>then this {@link StringBuilder}
* is populated with JSON text describing the startup
* options.
*/
public static <T extends Enum<T> & CommandLineOption<T>> Map<T, Object>
processCommandLine(Map<T, CommandLineValue<T>> optionValues,
Map<T, Object> processedValues,
JsonObjectBuilder jsonBuilder,
StringBuilder stringBuilder)
{
// create the result map if not specified
Map<T, Object> result = (processedValues == null) ? new LinkedHashMap<>()
: processedValues;
// check if we are generating the JSON
boolean doJson = (jsonBuilder != null || stringBuilder != null);
// check if we need to create the JSON object builder
JsonObjectBuilder job = (doJson && jsonBuilder == null)
? Json.createObjectBuilder() : jsonBuilder;
// iterate over the option values and handle them
optionValues.forEach( (key, cmdLineVal) -> {
// create the sub-builder if doing JSON
JsonObjectBuilder job2 = (doJson) ? Json.createObjectBuilder() : null;
// get the parameters
List<String> params = cmdLineVal.getParameters();
// add the parameters if doing JSON
if (doJson) {
// check if there is only a single parameter
if (params.size() == 1) {
// handle a single parameter
job2.add("value", params.get(0));
} else {
// handle multiple parameters
JsonArrayBuilder jab = Json.createArrayBuilder();
for (String param : params) {
jab.add(param);
}
job2.add("values", jab);
}
// add the source
job2.add("source", cmdLineVal.getSource().toString());
// check if we have a specifier to add
if (cmdLineVal.getSpecifier() != null) {
// add the specifier
job2.add("via", cmdLineVal.getSpecifier());
}
// add to the JsonObjectBuilder
job.add(key.toString(), job2);
}
// add to the map
result.put(key, cmdLineVal.getProcessedValue());
});
// append the JSON text if requested
if (stringBuilder != null) {
stringBuilder.append(JsonUtils.toJsonText(job));
}
// return the map
return result;
}
/**
* Checks if the specified {@link Class} was the class whose static
* <tt>main(String[])</tt> function was called to begin execution of the
* current process.
*
* @param cls The {@link Class} to test for.
*
* @return <tt>true</tt> if the specified class' static
* <tt>main(String[])</tt> function was called to begin execution of
* the current process.
*/
public static boolean checkClassIsMain(Class cls) {
// check if called from the ConfigurationManager.main() directly
Throwable t = new Throwable();
StackTraceElement[] trace = t.getStackTrace();
StackTraceElement lastStackFrame = trace[trace.length-1];
String className = lastStackFrame.getClassName();
String methodName = lastStackFrame.getMethodName();
return ("main".equals(methodName) && cls.getName().equals(className));
}
/**
* Returns a multi-line bulleted list of the specified options with the
* specified indentation.
*
* @param indent The number of spaces to indent.
* @param options The zero or more options to write.
*
* @return The multi-line bulleted list of options.
*/
public static String formatUsageOptionsList(int indent,
CommandLineOption... options)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
int maxLength = 0;
StringBuilder sb = new StringBuilder();
for (int index = 0; index < indent; index++) {
sb.append(" ");
}
String indenter = sb.toString();
for (CommandLineOption option : options) {
if (option.getCommandLineFlag().length() > maxLength) {
maxLength = option.getCommandLineFlag().length();
}
}
String spacer = " ";
String bullet = "o ";
maxLength += (bullet.length() + spacer.length());
// check how many options per line we can fit
int columnCount = (80 - indent - spacer.length()) / maxLength;
// check if we can balance things out if we have a single dangling option
if (options.length == columnCount + 1) {
columnCount--;
}
// if less than 1, then set a minimum of 1 column
if (columnCount < 1) columnCount = 1;
int columnIndex = 0;
for (CommandLineOption option: options) {
String flag = option.getCommandLineFlag();
int spaceCount = maxLength - flag.length() - bullet.length();
if (columnIndex == 0) pw.print(indenter);
else pw.print(spacer);
pw.print(bullet);
pw.print(flag);
for (int index = 0; index < spaceCount; index++) {
pw.print(" ");
}
if (columnIndex == columnCount - 1) {
pw.println();
columnIndex = 0;
} else {
columnIndex++;
}
}
if (columnIndex != 0) {
pw.println();
}
pw.flush();
return sw.toString();
}
} |
/**
* <h1>Dynamic Method Dispatch</h1>
* Demonstration of Dynamic Method Dispatch
*
* @author Mani Kumaer Reddy K 13B81A0579
* @since 210215
*/
class A{
void display(){
System.out.println("in A");
}
} |
/*
* (C) 2007-2010 Alibaba Group Holding Limited.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*
* Version: $Id: test_block_chunk.cpp 5 2010-10-21 07:44:56Z
*
* Authors:
* duanfei
* - initial release
*
*/
#include <stdint.h>
#include <set>
#include <Time.h>
#include <gtest/gtest.h>
#include "common/lock.h"
#include "meta_bucket_manager.h"
#include "parameter.h"
using namespace std;
using namespace tfs::common;
using namespace tbsys;
namespace tfs
{
namespace namemetaserver
{
class BucketManagerTest: public ::testing::Test
{
public:
static void SetUpTestCase()
{
TBSYS_LOGGER.setLogLevel("debug");
SYSPARAM_RTSERVER.mts_rts_lease_expired_time_ = 2;
}
static void TearDownTestCase(){}
BucketManagerTest(){}
virtual ~BucketManagerTest(){}
virtual void SetUp(){}
virtual void TearDown(){}
};
TEST_F(BucketManagerTest, update_table)
{
int64_t tables[common::MAX_BUCKET_ITEM_DEFAULT];
for (int32_t i = 1; i <= common::MAX_BUCKET_ITEM_DEFAULT; ++i)
tables[i - 1] = i;
BucketManager bucket;
int32_t iret = bucket.update_table(NULL, MAX_BUCKET_DATA_LENGTH, 0, 1);
EXPECT_EQ(TFS_ERROR, iret);
iret = bucket.update_table((const char*)tables, 0L, 0L, 1);
EXPECT_EQ(TFS_ERROR, iret);
iret = bucket.update_table((const char*)tables, MAX_BUCKET_DATA_LENGTH + 1, 0, 1);
EXPECT_EQ(TFS_ERROR, iret);
iret = bucket.update_table((const char*)tables, MAX_BUCKET_DATA_LENGTH, INVALID_TABLE_VERSION - 1, 1);
EXPECT_EQ(EXIT_TABLE_VERSION_ERROR, iret);
iret = bucket.update_table((const char*)tables, MAX_BUCKET_DATA_LENGTH, 0, 1);
EXPECT_EQ(TFS_SUCCESS, iret);
EXPECT_EQ(0, bucket.update_table_.version_);
}
TEST_F(BucketManagerTest, update_new_table_status)
{
int64_t tables[common::MAX_BUCKET_ITEM_DEFAULT];
for (int32_t i = 1; i <= common::MAX_BUCKET_ITEM_DEFAULT; ++i)
tables[i - 1] = i;
BucketManager bucket;
int32_t iret = bucket.update_table((const char*)tables, MAX_BUCKET_DATA_LENGTH, 0, 1);
EXPECT_EQ(TFS_SUCCESS, iret);
EXPECT_EQ(0, bucket.update_table_.version_);
iret = bucket.update_new_table_status(1);
EXPECT_EQ(TFS_SUCCESS, iret);
EXPECT_TRUE(bucket.active_table_.empty());
Bucket::TABLES_CONST_ITERATOR iter = bucket.update_table_.tables_.begin();
for (; iter != bucket.update_table_.tables_.end(); ++iter)
{
EXPECT_EQ(BUCKET_STATUS_NONE, (*iter).status_);
}
}
TEST_F(BucketManagerTest, switch_table)
{
int64_t tables[common::MAX_BUCKET_ITEM_DEFAULT];
for (int32_t i = 1; i <= common::MAX_BUCKET_ITEM_DEFAULT; ++i)
tables[i - 1] = i;
BucketManager bucket;
int32_t iret = bucket.update_table((const char*)tables, MAX_BUCKET_DATA_LENGTH, 0, 1);
EXPECT_EQ(TFS_SUCCESS, iret);
EXPECT_EQ(0, bucket.update_table_.version_);
iret = bucket.update_new_table_status(1);
EXPECT_EQ(TFS_SUCCESS, iret);
EXPECT_TRUE(bucket.active_table_.empty());
Bucket::TABLES_CONST_ITERATOR iter = bucket.update_table_.tables_.begin();
for (; iter != bucket.update_table_.tables_.end(); ++iter)
{
EXPECT_EQ(BUCKET_STATUS_NONE, (*iter).status_);
}
EXPECT_EQ(0, bucket.update_table_.version_);
std::set<int64_t> tt;
iret = bucket.switch_table(tt, 0, -1);
EXPECT_EQ(EXIT_PARAMETER_ERROR, iret);
iret = bucket.switch_table(tt, 1, -1);
EXPECT_EQ(EXIT_TABLE_VERSION_ERROR, iret);
iret = bucket.switch_table(tt, 1, 0);
EXPECT_EQ(TFS_SUCCESS, iret);
EXPECT_EQ(INVALID_TABLE_VERSION, bucket.update_table_.version_);
EXPECT_EQ(0, bucket.active_table_.version_);
EXPECT_TRUE(bucket.update_table_.empty());
iter = bucket.active_table_.tables_.begin();
for (; iter != bucket.active_table_.tables_.end(); ++iter)
{
if ((*iter).server_ == 1)
EXPECT_EQ(BUCKET_STATUS_RW, (*iter).status_);
else
EXPECT_EQ(BUCKET_STATUS_NONE, (*iter).status_);
}
}
}
}
int main(int argc, char* argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
async def create_post_request(self, method: str, params: Dict = None):
if params is None:
params = {}
headers = {"Content-Type": "application/json"}
payload = {
"method": method,
"params": [params],
"id": next(self.idgen),
"version": "1.0",
}
if self.debug > 1:
_LOGGER.debug("> POST %s with body: %s", self.guide_endpoint, payload)
try:
async with aiohttp.ClientSession(headers=headers) as session:
res = await session.post(
self.guide_endpoint, json=payload, headers=headers
)
if self.debug > 1:
_LOGGER.debug("Received %s: %s" % (res.status, res.text))
if res.status != 200:
res_json = await res.json(content_type=None)
raise SongpalException(
"Got a non-ok (status %s) response for %s"
% (res.status, method),
error=res_json.get("error"),
)
res_json = await res.json(content_type=None)
except (aiohttp.InvalidURL, aiohttp.ClientConnectionError) as ex:
raise SongpalException("Unable to do POST request: %s" % ex) from ex
if "error" in res_json:
raise SongpalException(
"Got an error for %s" % method, error=res_json["error"]
)
if self.debug > 1:
_LOGGER.debug("Got %s: %s", method, pf(res_json))
return res_json |
from flask import Flask, render_template, request, redirect
from sqlite3connection import connectToSQLite3
app = Flask(__name__)
dbname = '/home/balaji/my_db.db'
@app.route("/")
def index():
conn = connectToSQLite3(dbname)
all_animals = conn.query_db('SELECT * FROM animals ORDER BY common_name')
all_pets = conn.query_db('SELECT pets.id, name, common_name FROM pets JOIN animals ON pets.animal_id = animals.id ;')
return render_template("index2.html", all_animals=all_animals, all_pets=all_pets)
@app.route("/add_pet", methods=["POST"])
def add_pet():
print(request.form)
conn = connectToSQLite3(dbname)
data = {
'name': request.form['pet_name'],
'id': int(request.form['pet_type'])
}
query = "INSERT INTO pets ( name, animal_id ) VALUES ( :name, :id )"
conn.query_db(query, data)
return redirect("/")
if __name__ == "__main__":
app.run(debug=True) |
use std::collections::HashMap;
fn exponent(exp: i32) -> i32 {
let mut result = 1;
for _ in 0..exp {
result *= 10;
}
result
}
fn add_strings(nums1: &str, nums2: &str, dict: &HashMap<char, i32>) -> i32 {
let length1 = nums1.len() as i32;
let length2 = nums2.len() as i32;
let mut sum = 0;
let mut count = 1;
for c in nums1.chars() {
//:= MARK: well, (expression) wont take ownship
sum += *dict.get(&c).unwrap() * exponent((length1 - count));
count += 1;
//println!("{}", &sum);
}
count = 1;
for c in nums2.chars() {
sum += *dict.get(&c).unwrap() * exponent((length2 - count));
count += 1;
//println!("{}", &sum);
}
sum
}
fn main() {
let mut dict = HashMap::new();
let mut temp_num = 0;
for c in "0123456789".chars() {
dict.insert(c, temp_num);
temp_num += 1;
}
println!("{}", add_strings(&"102", &"20", &dict));
}
|
// SPDX-License-Identifier: GPL-2.0
/*
* Driver for Goodix touchscreens that use the i2c-hid protocol.
*
* Copyright 2020 Google LLC
*/
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/gpio/consumer.h>
#include <linux/i2c.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/pm.h>
#include <linux/regulator/consumer.h>
#include "i2c-hid.h"
struct goodix_i2c_hid_timing_data {
unsigned int post_gpio_reset_delay_ms;
unsigned int post_power_delay_ms;
};
struct i2c_hid_of_goodix {
struct i2chid_ops ops;
struct regulator *vdd;
struct gpio_desc *reset_gpio;
const struct goodix_i2c_hid_timing_data *timings;
};
static int goodix_i2c_hid_power_up(struct i2chid_ops *ops)
{
struct i2c_hid_of_goodix *ihid_goodix =
container_of(ops, struct i2c_hid_of_goodix, ops);
int ret;
ret = regulator_enable(ihid_goodix->vdd);
if (ret)
return ret;
if (ihid_goodix->timings->post_power_delay_ms)
msleep(ihid_goodix->timings->post_power_delay_ms);
gpiod_set_value_cansleep(ihid_goodix->reset_gpio, 0);
if (ihid_goodix->timings->post_gpio_reset_delay_ms)
msleep(ihid_goodix->timings->post_gpio_reset_delay_ms);
return 0;
}
static void goodix_i2c_hid_power_down(struct i2chid_ops *ops)
{
struct i2c_hid_of_goodix *ihid_goodix =
container_of(ops, struct i2c_hid_of_goodix, ops);
gpiod_set_value_cansleep(ihid_goodix->reset_gpio, 1);
regulator_disable(ihid_goodix->vdd);
}
static int i2c_hid_of_goodix_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_hid_of_goodix *ihid_goodix;
ihid_goodix = devm_kzalloc(&client->dev, sizeof(*ihid_goodix),
GFP_KERNEL);
if (!ihid_goodix)
return -ENOMEM;
ihid_goodix->ops.power_up = goodix_i2c_hid_power_up;
ihid_goodix->ops.power_down = goodix_i2c_hid_power_down;
/* Start out with reset asserted */
ihid_goodix->reset_gpio =
devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH);
if (IS_ERR(ihid_goodix->reset_gpio))
return PTR_ERR(ihid_goodix->reset_gpio);
ihid_goodix->vdd = devm_regulator_get(&client->dev, "vdd");
if (IS_ERR(ihid_goodix->vdd))
return PTR_ERR(ihid_goodix->vdd);
ihid_goodix->timings = device_get_match_data(&client->dev);
return i2c_hid_core_probe(client, &ihid_goodix->ops, 0x0001);
}
static const struct goodix_i2c_hid_timing_data goodix_gt7375p_timing_data = {
.post_power_delay_ms = 10,
.post_gpio_reset_delay_ms = 180,
};
static const struct of_device_id goodix_i2c_hid_of_match[] = {
{ .compatible = "goodix,gt7375p", .data = &goodix_gt7375p_timing_data },
{ }
};
MODULE_DEVICE_TABLE(of, goodix_i2c_hid_of_match);
static struct i2c_driver goodix_i2c_hid_ts_driver = {
.driver = {
.name = "i2c_hid_of_goodix",
.pm = &i2c_hid_core_pm,
.probe_type = PROBE_PREFER_ASYNCHRONOUS,
.of_match_table = of_match_ptr(goodix_i2c_hid_of_match),
},
.probe = i2c_hid_of_goodix_probe,
.remove = i2c_hid_core_remove,
.shutdown = i2c_hid_core_shutdown,
};
module_i2c_driver(goodix_i2c_hid_ts_driver);
MODULE_AUTHOR("Douglas Anderson <[email protected]>");
MODULE_DESCRIPTION("Goodix i2c-hid touchscreen driver");
MODULE_LICENSE("GPL v2");
|
package com.github.mikesafonov.smpp.server;
import com.cloudhopper.smpp.SmppServerSession;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import java.util.ArrayList;
import java.util.List;
/**
* Holder for sessions with RECEIVER and TRANSCEIVER types
*
* @author <NAME>
*/
@EqualsAndHashCode
public class ResponseSessionHolder {
@Getter
private List<SmppServerSession> sessions = new ArrayList<>();
public void add(SmppServerSession session) {
sessions.add(session);
}
public void remove(SmppServerSession session) {
sessions.remove(session);
}
}
|
<reponame>collection-news/collection-news
import React, { useState } from 'react'
import { Divider, IconButton, Popover, PopoverContent, PopoverTrigger } from '@chakra-ui/react'
import Link from 'next/link'
import Image from 'next/image'
import collectionNewsLogoWhite from '../assets/collectionNewsLogoWhite.svg'
import { mediaDescMap } from '../constants/mediaMeta/desc'
export const NavDropdown: React.FC<{ showMainPage?: boolean }> = ({ children, showMainPage = true }) => {
const [isOpen, setIsOpen] = useState(false)
const open = () => setIsOpen(prev => !prev)
const close = () => setIsOpen(false)
return (
<Popover colorScheme="theme" isOpen={isOpen} onClose={close} onOpen={open}>
<PopoverTrigger>{children}</PopoverTrigger>
<PopoverContent borderRadius="sm" w={60} borderWidth={4} borderColor="theme.400" bg="theme.500">
{showMainPage && (
<>
<Link href="/" passHref>
<IconButton
justifyContent="flex-start"
aria-label="Home"
colorScheme="theme"
icon={<Image src={collectionNewsLogoWhite} alt="logo" height="48px" width="80px" />}
data-cy="header-home-btn"
h="full"
paddingLeft={2}
onClick={close}
/>
</Link>
<Divider borderColor="theme.400" borderWidth={2} />
</>
)}
{mediaDescMap.map(({ key, logoFullWhite }) => (
<Link key={key} href={`/${key}`} passHref>
<IconButton
justifyContent="flex-start"
aria-label="Media Home"
colorScheme="theme"
icon={<Image src={logoFullWhite} alt="logo" height="48px" width="80px" />}
data-cy={`header-media-${key}-btn`}
h="full"
paddingLeft={2}
onClick={close}
/>
</Link>
))}
</PopoverContent>
</Popover>
)
}
|
CXCL10 and its related key genes as potential biomarkers for psoriasis
Abstract Although several studies have attempted to investigate the etiology of and mechanism underlying psoriasis, the precise molecular mechanism remains unclear. Our study aimed to explore the molecular mechanism underlying psoriasis based on bioinformatics. GSE30999, GSE34248, GSE41662, and GSE50790 datasets were obtained from the Gene Expression Omnibus database. The Gene Expression Omnibus profiles were integrated to obtain differentially expressed genes in R software. Then a series of analyses was performed, such as Gene Ontology annotation, Kyoto Encyclopedia of Genes and Genomes pathway analysis, protein-protein interaction network analysis, among others. The key genes were obtained by CytoHubba, and validated by real-time quantitative polymerase chain reaction. A total of 359 differentially expressed genes were identified between 270 paired lesional and non-lesional skin groups. The common enriched pathways were nucleotide-binding and oligomerization domain-like receptor signaling pathway, and cytokine-cytokine receptor interaction. Seven key genes were identified, including CXCL1, ISG15, CXCL10, STAT1, OASL, IFIT1, and IFIT3. These key genes were validated as upregulated in the 4 datasets and M5-induced HaCaT cells. Our study identified 7 key genes, namely CXCL1, ISG15, CXCL10, STAT1, OASL, IFIT1, and IFIT3, and 2 mostly enriched pathways (nucleotide-binding and oligomerization domain-like receptor signaling pathway, and cytokine-cytokine receptor interaction) involved in psoriatic pathogenesis. More importantly, CXCL1, ISG15, STAT1, OASL, IFIT1, IFIT3, and especially CXCL10 may be potential biomarkers. Therefore, our findings may bring a new perspective to the molecular mechanism underlying psoriasis and suggest potential biomarkers.
Introduction
Psoriasis is a chronic and systemic inflammatory cutaneous disorder with a global prevalence of 2% to 3%. The occurrence of psoriasis is due to complex interactions among genetics, immunology, and the environment. Although many studies have investigated the etiologies and mechanisms, the precise molecular mechanism of psoriasis remains unclear. A thorough exploration of psoriasis pathogenesis would be helpful for discovery of potential biomarkers and could provide novel clues for diagnosis and treatment.
Bioinformatics has been extensively applied to many diseases, including psoriasis. Gene Expression Omnibus (GEO) is an online and free database, that includes various disease gene expression datasets. Thus, we can utilize bioinformatics analysis to conveniently explore the molecular mechanism underlying psoriasis from the GEO database.
As we know, the diagnosis of psoriasis is not difficult, however its effective treatment does not exist till now. It is helpful to explore key genes for discovering potential biomarkers and provide therapeutic targets for psoriasis. Thus, our primary objective is to search key genes for psoriasis that could be potential biomarkers.
In our study, we attempted to identify key genes and associated pathways in psoriasis using bioinformatics analysis, and compare the expression levels of key genes between lesional and nonlesional psoriatic skin based on 4 datasets. Finally, we carried out real-time quantitative polymerase chain reaction (RT-qPCR) experiments in M5 induced HaCaT cells for validation. Since some studies confirmed that M5 (IL-22, TNF-a, IL-17A, IL-1a, and Oncostatin M) can induce a better psoriatic cell model, we use it to treat HaCaT cells in our experiments. Therefore, our findings may bring a new perspective to the molecular mechanism underlying psoriasis and suggest potential biomarkers. Figure 1 demonstrates the workflow of this study. Four microarray datasets (GSE30999, GSE34248, GSE41662, and GSE50790 ) were downloaded from GEO (https://www.ncbi. nlm.nih.gov/geo/). A total of 127 paired lesional and non-lesional skin samples were selected as subjects from plaque psoriasis patients in the 4 datasets. All subjects were from homo sapiens and GPL570 platform ( Affymetrix Human Genome U133 Plus 2.0 Array). The detailed sample information was summarized in Table 1 (The data were by the year of March 2021).
Microarray datasets collection and identification of differentially expressed genes
The raw data of 4 datasets were collated and analyzed using R software (version4.0.2.). Since the raw data were from 4 different microarray datasets, the collated data were processed by background correction and normalized using the "affy" package, and the batch effect was eliminated using the ComBat function of sva package. The limma package was used to identify differentially expressed genes (DEGs) between 127 paired lesional and non-lesional psoriatic skin tissues. The cutoff value was set as jlogFCj > 1.5 and adjusted P < .05, which was demonstrated as a volcano plot. Then the clustering of samples was shown as a heatmap.
Gene Ontology and Kyoto Encyclopedia of Genes and Genomes enrichment analyses of DEGs
Gene Ontology (GO) annotation and Kyoto Encyclopedia of Genes and Genomes (KEGG) enrichment analysis of DEGs were performed using Metascape (http://metascape.org), which is a free and online analysis tool. GO annotation comprises cellular component, molecular function, and biological process. The cutoff criteria were a P value < .05, minimum overlap of 3, and minimum enrichment of 1.5.
Protein-protein interaction network construction and screening for key genes
The STRING database (version 11.0, http://www.string-db.org/) was utilized to obtain protein-protein interaction (PPI) information for DEGs (high confidence of 0.7 was chosen). Then, Cytoscape 3.8.0 was applied to visualize the PPI network. The modules of the PPI network were explored using MCODE, and key genes were screened with CytoHubba. This could provide 12 topological analysis methods to identify the top 10 genes. A key gene was identified, if the gene was predicted to be one of the top 10 genes in all 12 methods. Finally, the interactions between the hub genes were returned to the STRING database for analysis.
Functional enrichment analysis of 7 key genes
To confirm the validity of the 7 key genes, functional enrichment analysis of these genes was further analyzed with http://www. bioinformatics.com.cn.
Statistical analysis
The data extracted from GEO datasets were examined by the normality test and homogeneity of variance test. t testing and analysis of variance testing were used for comparisons between 2 groups and among 3 or more groups respectively. Spearman correlation analysis was utilized to investigate the relationships between CXCL10 and other hub genes. GraphPad Prism 8.0.1 was used to perform these tests.
Identification of DEGs
Finally, 359 DEGs were identified between 270 paired lesional and non-lesional skin groups with jlogFCj > 1.5 and adjusted P < .05, of which 284 were up-regulated and 65 were downregulated. The volcano plot and heatmap of DEGs were shown in Figures 2 and 3, respectively.
GO and KEGG pathway analyses of DEGs
The GO annotation of DEGs was mostly enriched in 6 clustering groups, including response to bacterium, defense response to other organism, anti-microbial humoral response, flavonoid glucuronidation, skin development, and monocarboxylic acid metabolic process (Fig. 4A, B). The top 20 GO items were of the biological process group (15), and molecular function group (5) ( Table 2). KEGG pathway analysis of DEGs indicated that genes were mostly enriched in 3 clustering groups, including steroid hormone biosynthesis, nucleotide-binding and oligomerization domain (NOD)-like receptor signaling pathway, and cytokinecytokine receptor interaction (Fig. 4C, D). The top 20 KEGG pathway enriched items were shown in Table 3.
Functional enrichment analysis of 7 key genes
Seven key genes were further analyzed using an online tool (http:// www.bioinformatics.com.cn). The enrichment results of 7 hub genes were shown in chord plots based on the adjusted P values (Fig. 6). For GO analysis, the top 5 terms were response to bacterium, defense response to other organism, anti-microbial humoral response, flavonoid glucuronidation, and chemokine receptor binding (Fig. 6A). For KEGG pathway analysis, the top 3 terms were NOD-like receptor signaling pathway, cytokinecytokine receptor interaction, and amoebiasis (Fig. 6B). These results were consistent with the Metascape analysis, which strengthened the reliability of the results.
Validation of 7 key genes in 4 datasets
The expression levels of 7 key genes were confirmed in GSE30999, GSE34248, GSE41662, and GSE50790 datasets.
Except for CXCL1, STAT1, and OASL in GSE50790, the other key genes were obviously up-regulated in psoriatic lesional skin tissues (Fig. 7).
Relationship between CXCL10 and the other key genes
For the relationships among the 7 key genes, CXCL10 was central to the network (Fig. 5C), had a higher rank (Table 5), and a demonstrated positive correlation with the other 6 key genes in the 4 aforementioned datasets (Fig. 8), suggesting the close relationship between CXCL10 and the other 6 key genes.
Validation of key genes via qRT-PCR
The expression levels of 7 key genes were validated by RT-qPCR (n = 3). The results of qRT-PCR showed that the transcription levels of CXCL10, CXCL1, ISG15, STAT1, OASL, IFIT1, and ITIT3 were significantly up-regulated in 10 ng/mL M5 induced HaCaT cells (Fig. 9). The expression levels of these genes were consistent with the microarray results.
Discussion
Psoriasis is a chronic, relapsing-remitting, and inflammatory skin disease that affects 2% to 3% of the population worldwide. Recurrence has been common after treatment in psoriasis. That is to say, there are currently no known radical treatments for Table 4 The detailed information of cluster networks in MCODE.
Cluster Score (density * #nodes) Nodes Edges Node IDs 1 14.519 28 196 GAL, CXCL13, GBP1, IFIT3, RTP4, IFIT1, MX1, OASL, IFI44, ISG15, CCL27, OAS1, RSAD2, CXCR2, CXCL8, IFI44L, IRF7, STAT1, CXCL1, PTGER3, OAS2, HERC6, IFI6, IFI27, CCL20, CXCL9, CXCL10, CXCL2 2 12.167 13 73 DLGAP5, KIAA0101, KIF20A, CCNA2, CDC6, BUB1, CENPE, RRM2, CDK1, CCNB1, MCM10, TTK, SPC25 3 9.8 11 49 LCE3D, SPRR2B, IVL, SPRR3, SPRR1A, PKP1, DSG3, CDSN, DSC2, TGM1, PI3 4 6 9 24 TCN1, IL1B, IL17A, RAB27A, LRG1, HPSE, ARG1, LCN2, LTF 5 4 4 6 KRT16, KRT6A, KRT77, KRT6B 6 3 3 3 S100A12, S100A9, S100A8 Table 5 The detailed information of 7 key genes. psoriasis. Thus, it is important and urgent to investigate the molecular mechanisms involved in the pathogenesis of psoriasis to provide new clues for treatment. An important discovery of our study was the confirmation of key genes in psoriasis by bioinformatics and via RT-qPCR. The 7 key genes comprised CXCL10, CXCL1, ISG15, STAT1, OASL, IFIT1, and IFIT3, and the 2 common enriched pathways were NODlike receptor signaling pathway and cytokine-cytokine receptor interaction. Among the 7 key genes, CXCL10 was a higher ranked gene and had positive correlations with other 6 hub genes, suggesting that it might be the most significant gene. Furthermore, the RT-qPCR results of CXCL10 confirmed this prediction. Some studies have also reported several hub genes in psoriasis, some of which are consistent with ours, especially the study of Luo et al. They reported that CXCR2, CXCL10, IVL, OASL, and ISG15 were hub genes, and CXCL10 was the hub gene with the highest degree. However they did not perform experiments to validate the hub genes. CXCL10 is a member of the CXC family of chemokines, and plays a significant role in inflammation through its T-cell chemotactic and adhesion properties. Researches have also indicated CXCL10 is up-regulated in psoriatic skin lesions and serum. It has been hypothesized that CXCL10 could be a good marker for psoriasis. Although CXCL10 and CXCL1 belong to the chemokine "CXC" family, they play different roles in psoriasis. CXCL10 attracts T helper (Th) 1 cells, and whereas CXCL1 attracts neutrophils. It was reported that CXCL10 production by keratinocytes depends on STAT1. -STAT1 is known as a member of the STAT family, involved in type I and type II interferon signaling. The expression of STAT1 is increased in psoriatic skin, and it also has a vital role in the pathogenesis of psoriasis. The remaining 4 genes (ISG15, OASL, IFIT1, and IFIT3) are anti-viral genes, which may explain the relatively fewer viral skin infections found in psoriasis patients. Ubiquitin-like protein ISG15 is an interferon-stimulated protein that has a critical role in the control of microbial infections. Some studies reported that ISG15 is elevated in psoriatic skin compared with levels in atopic dermatitis skin and healthy skin. The interferoninducible oligoadenylate synthetases-like (OASL) protein belongs to the atypical oligoadenylate synthetase family, possesses antiviral activity, and boosts innate immunity. Gao et al also identified OASL as a hub gene, but it has been rarely studied in psoriasis patients. Although the expression of OASL was upregulated in M5-induced HaCaT cells in our study, this needs to be further confirmed. The IFITs include IFIT1, IFIT2, IFIT3, and IFIT5, which regulate immune responses and function as essential anti-viral proteins. One study indicated that IFIT3 binding to IFIT1 is vital for stabilizing IFIT1 expression, and is indispensable for inhibiting infection by viruses lacking 2 0 -O methylation. In this study, IFIT1 was enriched in the NOD-like receptor signaling pathway, but IFIT3 was not. Currently, there are few studies on IFITs in psoriasis; however, IFIT1 and IFIT3 are overexpressed in oral squamous cell carcinoma, and promote tumor growth and regional and distant metastasis. Therefore, this new finding warrants further study.
Rank
The NOD-like receptor is a type of pattern-recognition receptor. It is also associated with various diseases related to infection and immunity. Some studies showed that the NODlike receptor signaling pathway was enriched in psoriatic epidermis. Meanwhile, some researchers have found that cytokine-cytokine receptor interaction is related to the pathogenesis of psoriasis via combined transcriptomic analysis. These results are consistent with ours.
In summary, we identified 7 key genes and 2 mostly enriched pathways for psoriasis. Our findings may bring a profound understanding for the molecular mechanism underlying psoriasis. However, this study has some limitations. First, the sample size is limited to a portion of the publicly available datasets and cannot be representative of the entire population. Second, there is potential bias of our data, due to different datasets. Third, we only performed 1 cell experiment. More experiments, such as skin tissues, are needed to support our results.
Conclusion
In our study, we tried to identify DEGs between psoriatic and non-psoriatic lesions by bioinformatics, discovered 7 hub genes and 2 mostly enriched pathways that might participate in the pathogenesis of psoriasis, and validated the hub genes upregulated in a psoriatic cell model through RT-qPCR. More interestingly, the 7 hub genes, namely CXCL1, ISG15, STAT1, OASL, IFIT1, IFIT3, and especially CXCL10 may be used as potential biomarkers. Therefore, our findings may bring a new perspective to the molecular mechanism underlying psoriasis and suggest potential biomarkers. |
import test from "ava";
import {ContainerFactory, Make} from "../container";
import {MessageBus} from "./message-bus";
import {Message} from "./message";
import {Packet} from "./packet";
import {IMessageService} from "./types";
import {ToString} from "../utils";
import {AbstractMessageService} from "./message-service";
@ToString('foo.bar.some-message-service')
class SomeMessageService extends AbstractMessageService {
public onStateMessage(message: Message, packet: Packet): IMessageService {
packet.message(new Message('hovno', 'nope', {'foo': 'bar'}));
return this;
}
}
test('Message: Unknown service', test => {
const container = ContainerFactory.container();
const messageBus = container.create<MessageBus>(MessageBus);
test.throws(() => {
messageBus.packet(messageBus.import({
messages: [
{
type: 'foo',
target: 'kaboom',
}
]
}));
}, {message: 'Cannot resolve message service for message type [foo]. Please register one message service of [kaboom, message-bus.foo-message-service, message-bus.common-message-service] to Container.'});
});
test('Message: Common', test => {
const container = ContainerFactory.container()
.register(SomeMessageService, Make.service(SomeMessageService));
const messageBus = container.create<MessageBus>(MessageBus);
const response = messageBus.packet(messageBus.import({
messages: [
{
type: 'state',
target: 'foo.bar.some-message-service',
}
]
}));
test.is(response.messages().getCount(), 1);
const message = (<Message>response.messages().index(0));
test.is('hovno', message.getType());
test.is('nope', message.getTarget());
test.deepEqual({'foo': 'bar'}, message.getAttrs().toObject());
});
|
// Reads entry from the FAT corresponding to cluster.
// Negative numbers are errors
int fat_get_table_value(uint32_t cluster, uint32_t *tv) {
uint8_t buffer[fat_pinfo.bytes_per_sector];
uint32_t idx = cluster * 4;
uint32_t sec = fat_pinfo.fat_begin_addr +
(idx / fat_pinfo.bytes_per_sector);
uint32_t entry_idx = idx % fat_pinfo.bytes_per_sector;
if (0 != fat_read_single_block(sec, buffer)) {
return FAT_FAIL;
}
*tv = fat_get_uint32(buffer + entry_idx) & 0x0FFFFFFF;
return FAT_SUCCESS;
} |
// Actually calls ffprobe on a file and returns a ProbeInfo object
func Probe(path string) (info *ProbeInfo, err error) {
if len(path) == 0 {
return nil, fmt.Errorf("Probe() path cannot be empty")
}
input := NewInput(
path,
NewParamSet(
NewParam("v", "quiet"),
NewParam("print_format", "json"),
NewParam("show_format", nil),
NewParam("show_streams", nil),
),
)
cmdline, _ := NewCommand("ffprobe", input)
cmd := DefaultCommandFunc(cmdline.Path, cmdline.Slice()...)
out, err := cmd.Output()
if err != nil {
return nil, err
}
return NewInfo(string(out))
} |
<reponame>djordjeviclazar/redesigned-umbrella
package com.example.meetnature.authentication.data.dtos;
public class LoginUserDTO {
public String email;
public String password;
public String username;
}
|
<reponame>uploadexpress/app
package models
import (
"time"
"github.com/globalsign/mgo/bson"
"github.com/uploadexpress/app/constants"
)
type Upload struct {
Id string `json:"id" bson:"_id,omitempty"`
Name string `json:"name" bson:"name"`
Files []*File `json:"files" bson:"files"`
Backgrounds []*Image `json:"backgrounds" bson:"backgrounds"`
DownloadCount int `json:"download_count" bson:"download_count"`
Public bool `json:"public" bson:"public"`
Ready bool `json:"-" bson:"ready"`
Gallery bool `json:"gallery" bson:"gallery"`
RequestId string `json:"request_id" bson:"request_id"`
Date int64 `json:"date" bson:"date"`
ExpirationDate *int64 `json:"expiration_date,omitempty" bson:"expiration_date,omitempty"`
}
func (upload *Upload) BeforeCreate() {
// Assigns an ID to each file
for _, file := range upload.Files {
if file.Id == "" {
file.Id = bson.NewObjectId().Hex()
}
}
upload.Id = bson.NewObjectId().Hex()
upload.Ready = false
upload.Date = time.Now().Unix()
}
func (upload *Upload) Size() constants.ByteSize {
var size int64 = 0
for _, file := range upload.Files {
size += file.Size
}
return constants.ByteSize(size)
}
const UploadsCollection = "uploads"
|
def build_anchor_labeler(cfg, anchor_generator):
anchor_type = ANCHORS['AnchorLabeler']
return anchor_type(anchors=anchor_generator,
num_classes=cfg.INPUT.NUM_CLASSES,
match_threshold=cfg.MODEL.RPN.POSITIVE_OVERLAP,
unmatched_threshold=cfg.MODEL.RPN.NEGATIVE_OVERLAP,
rpn_batch_size_per_im=cfg.MODEL.RPN.BATCH_SIZE_PER_IMAGE,
rpn_fg_fraction=cfg.MODEL.RPN.FG_FRACTION) |
<reponame>levush/hipl
/*
* Copyright (c) 2010-2012 Aalto University and RWTH Aachen University.
*
* 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.
*/
/**
* @file
* This file contains the implementation for the middlebox authentication
* extension.
*/
#include <errno.h>
#include <stdint.h>
#include <string.h>
#include "libcore/builder.h"
#include "libcore/common.h"
#include "libcore/ife.h"
#include "libcore/modularization.h"
#include "libcore/protodefs.h"
#include "libcore/solve.h"
#include "libcore/state.h"
#include "libhipl/hidb.h"
#include "libhipl/pkt_handling.h"
#include "modules/midauth/lib/midauth_builder.h"
#include "modules/update/hipd/update.h"
#include "midauth.h"
/**
* Handle the CHALLENGE_REQUEST parameter.
*
* @param packet_type The packet type of the control message (RFC 5201, 5.3.)
* @param ha_state The host association state (RFC 5201, 4.4.1.)
* @param ctx Pointer to the packet context, containing all information for
* the packet handling (received message, source and destination
* address, the ports and the corresponding entry from the host
* association database).
*
* @return zero if the challenge was processed correctly or no challenge
* parameter was attached to the packet, negative value otherwise.
*/
static int handle_challenge_request_param(UNUSED const uint8_t packet_type,
UNUSED const enum hip_state ha_state,
struct hip_packet_context *ctx)
{
const struct hip_challenge_request *request = NULL;
request = hip_get_param(ctx->input_msg, HIP_PARAM_CHALLENGE_REQUEST);
// each on-path middlebox may add a challenge on its own
while (request &&
hip_get_param_type(request) == HIP_PARAM_CHALLENGE_REQUEST) {
struct puzzle_hash_input tmp_puzzle;
const unsigned int len = hip_challenge_request_opaque_len(request);
if (hip_midauth_puzzle_seed(request->opaque, len, tmp_puzzle.puzzle)) {
HIP_ERROR("failed to derive midauth puzzle\n");
return -1;
}
tmp_puzzle.initiator_hit = ctx->input_msg->hit_receiver;
tmp_puzzle.responder_hit = ctx->input_msg->hit_sender;
if (hip_solve_puzzle(&tmp_puzzle, request->K)) {
HIP_ERROR("Solving of middlebox challenge failed\n");
return -EINVAL;
}
if (hip_build_param_challenge_response(ctx->output_msg,
request,
tmp_puzzle.solution) < 0) {
HIP_ERROR("Error while creating CHALLENGE_RESPONSE parameter\n");
return -1;
}
// process next challenge parameter, if available
request = (const struct hip_challenge_request *)
hip_get_next_param(ctx->input_msg, &request->tlv);
}
return 0;
}
/**
* Add a HOST_ID parameter corresponding to the local HIT of the association to
* an UPDATE packet.
*
* @param packet_type The packet type of the control message (RFC 5201, 5.3.)
* @param ha_state The host association state (RFC 5201, 4.4.1.)
* @param ctx Pointer to the packet context, containing all information for
* the packet handling (received message, source and destination
* address, the ports and the corresponding entry from the host
* association database).
*
* @return zero on success, negative value otherwise
*/
static int add_host_id_param_update(UNUSED const uint8_t packet_type,
UNUSED const enum hip_state ha_state,
struct hip_packet_context *ctx)
{
const struct hip_challenge_request *const challenge_request =
hip_get_param(ctx->input_msg, HIP_PARAM_CHALLENGE_REQUEST);
// add HOST_ID to packets containing a CHALLENGE_RESPONSE
if (challenge_request) {
const struct local_host_id *const host_id_entry =
hip_get_hostid_entry_by_lhi_and_algo(&ctx->input_msg->hit_receiver,
HIP_ANY_ALGO,
-1);
if (!host_id_entry) {
HIP_ERROR("Unknown HIT\n");
return -1;
}
if (hip_build_param_host_id(ctx->output_msg, &host_id_entry->host_id)) {
HIP_ERROR("Building of host id failed\n");
return -1;
}
}
return 0;
}
/**
* Initialization function for the midauth module.
*
* @return zero on success, negative value otherwise
*/
int hip_midauth_init(void)
{
if (lmod_register_parameter_type(HIP_PARAM_CHALLENGE_REQUEST,
"HIP_PARAM_CHALLENGE_REQUEST")) {
HIP_ERROR("failed to register parameter type\n");
return -1;
}
if (lmod_register_parameter_type(HIP_PARAM_CHALLENGE_RESPONSE,
"HIP_PARAM_CHALLENGE_RESPONSE")) {
HIP_ERROR("failed to register parameter type\n");
return -1;
}
const enum hip_state challenge_request_R1_states[] = { HIP_STATE_I1_SENT,
HIP_STATE_I2_SENT,
HIP_STATE_CLOSING,
HIP_STATE_CLOSED };
for (unsigned i = 0; i < ARRAY_SIZE(challenge_request_R1_states); i++) {
if (hip_register_handle_function(HIP_ALL, HIP_R1,
challenge_request_R1_states[i],
&handle_challenge_request_param,
32500)) {
HIP_ERROR("Error on registering MIDAUTH handle function.\n");
return -1;
}
}
//
// we hook on every occasion that causes an R2 to get sent.
// R2 packet is first allocated at 40000, so we use a higher
// base priority here.
//
const enum hip_state challenge_request_I2_states[] = { HIP_STATE_UNASSOCIATED,
HIP_STATE_I1_SENT,
HIP_STATE_I2_SENT,
HIP_STATE_R2_SENT,
HIP_STATE_ESTABLISHED,
HIP_STATE_CLOSING,
HIP_STATE_CLOSED,
HIP_STATE_NONE };
for (unsigned i = 0; i < ARRAY_SIZE(challenge_request_I2_states); i++) {
if (hip_register_handle_function(HIP_ALL, HIP_I2,
challenge_request_I2_states[i],
&handle_challenge_request_param,
40322)) {
HIP_ERROR("Error on registering MIDAUTH handle function.\n");
return -1;
}
}
//
// Priority computed the same as above, but UPDATE response is sent at
// priority 30000 already (checking is 20000) and we must add our
// CHALLENGE_REQUEST verification in between, hence a lower base priority.
//
const enum hip_state challenge_request_UPDATE_states[] = { HIP_STATE_R2_SENT,
HIP_STATE_ESTABLISHED };
for (unsigned i = 0; i < ARRAY_SIZE(challenge_request_UPDATE_states); i++) {
if (hip_register_handle_function(HIP_ALL, HIP_UPDATE,
challenge_request_UPDATE_states[i],
&handle_challenge_request_param,
20322)) {
HIP_ERROR("Error on registering MIDAUTH handle function.\n");
return -1;
}
if (hip_register_handle_function(HIP_ALL, HIP_UPDATE,
challenge_request_UPDATE_states[i],
&add_host_id_param_update,
20750)) {
HIP_ERROR("Error on registering MIDAUTH handle function.\n");
return -1;
}
}
return 0;
}
|
import os.path, re, sys, subprocess
def makedirs(d) :
if os.path.exists(d) : return
os.makedirs(d)
def parent(k,d) :
if k == 0 : return d
return parent(k-1,os.path.dirname(d))
this_script_dir = parent(1,os.path.realpath(__file__))
testroot = parent(2,os.path.realpath(__file__))
benchroot = os.path.join(testroot,"benchmarks/")
config_path = os.path.join(this_script_dir,"local-test-settings.conf")
blank_config = """\
# Please edit this file with the local paths to various tool installations on your machine
# This should be the directory containing the duet.native binary
chora_root=%s
# This should be the directory containing the icra binary
icra_root=
# This should be the directory containing the duet.native binary
duetcra_root=
""" % parent(4,os.path.realpath(__file__))
config = dict()
if not os.path.exists(config_path) :
with open(config_path,"wb") as config_file :
print >>config_file, blank_config
with open(config_path,"rb") as config_file :
for line in config_file :
if len(line.strip()) == 0 or "=" not in line : continue
parts = line.split("=",1)
if len(parts[1].strip()) == 0 : continue
config[parts[0].strip()]=parts[1].strip()
if "suppress_color" not in config or not config["suppress_color"] :
color_start = "\033[91m"
color_stop = "\033[0m"
else :
color_start = ""
color_stop = ""
def require_config(key, message) :
if key in config : return config[key]
print "Please add a line to your local configuration file\n " + config_path + "\nof the form:"
print " " + key + "=" + message
sys.exit(0)
def specify_tool_root_requirement(ID, binary_relative_path_suggestion=None) :
if ID + "_root" in config : return config[ID + "_root"]
if binary_relative_path_suggestion is not None :
require_config(ID + "_root",
"<TOOLDIR>\nsuch that the " + ID + " tool executable is found at <TOOLDIR>/"
+binary_relative_path_suggestion + " on your machine")
require_config(ID + "_root",
"<TOOLDIR>\nsuch that <TOOLDIR> is the directory of the tool " + ID + " on your machine")
def get_tool_root(ID) :
if ID + "_root" in config : return config[ID + "_root"]
tool = get_tool_by_ID(ID,False)
if tool is not None :
return tool.get("root")
require_config(ID + "_root",
"<ROOTDIR>\nsuch that <ROOTDIR> is the root directory of the tool " + ID + " on your machine")
scriptroot = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0,scriptroot)
##
class StringRing :
def __init__(self, length) :
self.length = length
self.ring = list()
for i in range(self.length) : self.ring.append("")
self.cursor = 0
def advance(self) :
self.cursor = (self.cursor + 1) % self.length
def add(self, line) :
self.ring[self.cursor] = line
self.advance()
def readout(self) :
output = ""
self.advance()
for i in range(self.length) :
line = self.ring[self.cursor]
if line != "" :
if output != "" : output += "\n"
output += line
self.advance()
return output
def generic_error_callout(params) :
if "logpath" not in params :
print "ERROR: generic_error_callout was called without a path"
sys.exit(0)
ring = StringRing(5)
# It probably isn't safe to say "error" here; that word is used
# too often in non-exceptional cases.
errorRegex = re.compile("failure|fatal|exception",re.IGNORECASE)
with open(params["logpath"],"rb") as logfile :
mode = 0
for line in logfile :
if len(line.strip()) == 0 : continue
if errorRegex.search(line) :
ring.add(line.rstrip())
return ring.readout()
##
def defaulting_field(d,kind,*fields) :
if len(fields) == 0 :
print "TEST SCRIPT ERROR: missing field in "+kind+" description: " + str(d)
if fields[0] in d : return d[fields[0]]
return defaulting_field(d,kind,*fields[1:])
def enforce_rules(kind, d) :
if kind == "tool" :
d["displayname"] = defaulting_field(d,kind,"displayname","ID")
d["shortname"] = defaulting_field(d,kind,"shortname","ID")
for req in ["cmd"] :
if req not in d :
print "ERROR: " + kind + " component " + d["ID"] + " does not define " + req
sys.exit(0)
elif kind == "batch" :
pass
else :
raise Exception("Unknown component kind: " + kind)
class Component :
def __init__(self, d, kind, ID) :
# We could put the contents of d into __dict__, but if we
# avoid doing so, that enforces a little more orderliness
d["ID"] = ID
enforce_rules(kind, d)
self.d = d
self.ID = ID
def hasattr(self, attr) : return (attr in self.d)
def get(self, attr) : return self.d[attr]
def flag(self, attr) :
return self.hasattr(attr) and (self.get(attr) == True)
##
defdirs = dict()
defdirs["tool"] = os.path.join(scriptroot,"tooldefs")
defdirs["batch"] = os.path.join(scriptroot,"batchdefs")
loaded_components = dict()
def get_component_by_ID(kind, ID, exit_on_failure=True) :
if kind not in loaded_components :
loaded_components[kind] = dict()
if ID in loaded_components[kind] :
return loaded_components[kind][ID]
for py in os.listdir(defdirs[kind]) :
if py == kind+"_"+ID+".py" :
component_module = getattr(__import__(kind+"defs."+kind+"_"+ID),kind+"_"+ID)
if not hasattr(component_module,kind) :
if not exit_on_failure : return None
print "ERROR: No "+kind+" variable was defined by the "+kind+" module "+kind+"defs/"+kind+"_"+ID+".py"
sys.exit(0)
comp = Component(getattr(component_module,kind),kind,ID)
loaded_components[kind][ID] = comp
return comp
else :
if not exit_on_failure : return None
print "Unrecognized "+kind+" ID: " + ID
print_known_components(kind)
sys.exit(0)
def clone_component(kind, ID) :
return dict(get_component_by_ID(kind, ID).d)
def print_known_components(kind) :
known_components = list()
for py in os.listdir(defdirs[kind]) :
if py.startswith(kind+"_") and py.endswith(".py") :
known_components.append(py[len(kind+"_"):-len(".py")])
print "Valid "+kind+" IDs are: " + str(known_components)
##
def get_tool_by_ID(ID,f=True) : return get_component_by_ID("tool",ID,f)
def clone_tool(ID) : return clone_component("tool",ID)
def print_known_tools() : return print_known_components("tool")
def get_default_tool_dict() : return dict()
##
def get_batch_by_ID(ID,f=True) : return get_component_by_ID("batch",ID,f)
def clone_batch(ID) : return clone_component("batch",ID)
def print_known_batches() : return print_known_components("batch")
def get_default_batch_dict() :
batch = dict()
batch["timeout"] = 300
batch["toolIDs"] = ["chora"]
batch["root"] = benchroot
batch["format_alternate_bgcolor"] = True
batch["format_style"] = "assert"
return batch
############################
def getMostRecentCommitHash(path) :
cwd = os.getcwd()
try :
os.chdir(path)
hashcode = subprocess.check_output(["git","rev-parse","HEAD"]).strip()
except :
hashcode = ""
os.chdir(cwd)
return hashcode
def getMostRecentCommitDate(path) :
"Get the most recent commit date"
cwd = os.getcwd()
try :
os.chdir(path)
date = subprocess.check_output(["git","show","-s","--format=%ci"]).strip()
except :
date = ""
os.chdir(cwd)
return date
def getMostRecentCommitMessage(path) :
"Get the most recent commit message"
cwd = os.getcwd()
try :
os.chdir(path)
date = subprocess.check_output(["git","show","-s","--format=%s"]).strip()
except :
date = ""
os.chdir(cwd)
return date
def getHostname() :
try :
hostname = subprocess.check_output(["hostname"]).strip()
except :
hostname = ""
return hostname
def getOpamList() :
try :
text = subprocess.check_output(["opam","list"]).strip()
except :
text = ""
return text
|
/**
* Consumer which runs at the end of a replication, ensures removal from the
* replicating set
* <p>
* eventually switch to a better interface for notifications
* so we can have multiple outputs. i.e. email, slack, db, etc
*/
private class Completer implements BiFunction<ReplicationStatus, Throwable, ReplicationStatus> {
private final Logger log = LoggerFactory.getLogger(Completer.class);
final Replication replication;
Completer(Replication replication) {
this.replication = replication;
}
@Override
public ReplicationStatus apply(ReplicationStatus status, Throwable throwable) {
String body;
String subject;
ReplicationStatus response = status;
String replicationId = replicationIdentifier(replication);
try {
// Send mail if there is an exception
if (throwable != null) {
log.warn("Replication did not complete successfully, returned throwable is",
throwable);
response = ReplicationStatus.FAILURE;
body = throwable.getMessage()
+ "\n"
+ Arrays.toString(throwable.getStackTrace());
subject = "Failed to replicate " + replicationId;
send(subject, body);
} else if (status == ReplicationStatus.FAILURE) {
// todo: figure out if we want to send mail here
log.warn("[{}] Replication failed during processing", replicationId);
} else if (properties.getSmtp().getSendOnSuccess() &&
status == ReplicationStatus.SUCCESS) {
// Send mail if we are set to and the replication is complete
subject = "Successful replication of " + replicationId;
body = "";
send(subject, body);
}
} catch (Exception e) {
log.error("Exception caught sending mail", e);
} finally {
log.debug("{} removing from thread pool", replicationId);
replicating.remove(replication);
}
return response;
}
private void send(String subject, String body) {
SimpleMailMessage message = reporter.createMessage(properties.getNode(), subject, body);
reporter.send(message);
}
} |
Aramid Nanofiber Membranes for Energy Harvesting from Proton Gradients
Harvesting osmotic energy from industrial wastewater is an often‐overlooked source of electricity that can be used as a part of the comprehensive distributed energy systems. However, this concept requires, a new generation of inexpensive ion‐selective membranes that must withstand harsh chemical conditions with both high/low pH, have high temperature resilience, display exceptional mechanical properties, and support high ionic conductance. Here, aramid nanofibers (ANFs) based membranes with high chemical/thermal stability, mechanical strength, toughness, and surface charge density make them capable of high‐performance osmotic energy harvesting from pH gradients generated upon wastewater dilution. ANF membranes produce an averaged output power density of 17.3 W m−2 for more than 240 h at pH 0. Taking advantage of the high temperature resilience of aramid, the output power density is increased further to 77 W m−2 at 70 °C, typical for industrial wastewater. Such output power performance is 10× better compared to the current state‐of‐the‐art membranes being augmented by Kevlar‐like environmental robustness of ANF membranes. The improved efficiency of energy harvesting is ascribed to the high proton selectivity of ANFs. Retaining high output power density for large membrane area and fluoride‐free synthesis of ANFs from recyclable material opens the door for scalable wastewater energy harvesting. |
/**
* Returns the {@link IVarDef input variable} representing the values for an object instance.
*/
@SuppressWarnings("rawtypes")
private IVarDef objectValueVar( String instanceVarTag, Schema<?> instanceSchema, boolean instanceItem)
{
IVarDef valueVar;
Set<?> enums = nullableEnums( asOrderedSet( instanceSchema.getEnum()), instanceSchema.getNullable());
if( !enums.isEmpty())
{
valueVar =
VarDefBuilder.with( "Value")
.hasIf( "itemEnums", Optional.of( enums).filter( e -> instanceItem).orElse( null))
.when( has( instanceValueProperty( instanceVarTag)))
.values( enums.stream().map( i -> VarValueDefBuilder.with( i).build()))
.values( VarValueDefBuilder.with( "Other").type( VarValueDef.Type.FAILURE).has( "excluded", enums).build())
.build();
}
else
{
Map<String,Schema> propertyDefs = Optional.ofNullable( instanceSchema.getProperties()).orElse( new LinkedHashMap<String,Schema>());
Optional.ofNullable( instanceSchema.getRequired())
.map( required -> required.stream().filter( property -> !propertyDefs.containsKey( property)).collect( toList()))
.filter( undefined -> !undefined.isEmpty())
.ifPresent( undefined -> {
undefined.stream().forEach( required -> propertyDefs.put( required, emptySchema()));
instanceSchema.setProperties( propertyDefs);
});
instanceSchema.setRequired(
Optional.ofNullable( instanceSchema.getRequired()).orElse( emptyList())
.stream()
.filter( property -> expectedInView( propertyDefs.get( property)))
.collect( toList()));
PropertyCountConstraints constraints = new PropertyCountConstraints();
constraints.setRequiredCount( Optional.ofNullable( instanceSchema.getRequired()).orElse( emptyList()).size());
constraints.setTotalCount( objectTotalProperties( instanceSchema));
constraints.setHasAdditional(
Optional.ofNullable( instanceSchema.getAdditionalProperties())
.map( additional -> additional.getClass().equals( Boolean.class)? (Boolean) additional : true)
.orElse( true)
&&
Optional.ofNullable( instanceSchema.getMaxProperties())
.map( max -> max > constraints.getRequiredCount())
.orElse( true));
instanceSchema.setMinProperties(
Optional.ofNullable( instanceSchema.getMinProperties())
.map( min -> Optional.ofNullable( instanceSchema.getMaxProperties()).map( max -> adjustedMinOf( "Properties", min, max)).orElse( min))
.orElse( null));
instanceSchema.setMinProperties(
Optional.ofNullable( instanceSchema.getMinProperties())
.filter( min -> isUsablePropertyLimit( "minProperties", min, constraints))
.orElse( null));
instanceSchema.setMaxProperties(
Optional.ofNullable( instanceSchema.getMaxProperties())
.filter( max -> isUsablePropertyMax( "maxProperties", max, constraints))
.orElse( null));
Integer minProperties = instanceSchema.getMinProperties();
constraints.setRequiresAdditional(
Optional.ofNullable( minProperties)
.map( min -> min > constraints.getTotalCount() && constraints.hasAdditional())
.orElse( false));
constraints.setAllRequired(
Optional.ofNullable( minProperties)
.map( min -> min == constraints.getTotalCount() && !constraints.hasAdditional())
.orElse( false));
valueVar =
VarSetBuilder.with( "Value")
.when( has( instanceValueProperty( instanceVarTag)))
.members( iterableOf( objectPropertyCountVar( instanceVarTag, instanceSchema, constraints)))
.members( objectPropertiesVar( instanceVarTag, instanceSchema, constraints))
.build();
}
return valueVar;
} |
/**
* Check OpenCL init with device selection
*/
string cl_get_device_type_setup() {
switch(query_device_type) {
case CL_DEVICE_TYPE_CPU:
return "CPU";
break;
case CL_DEVICE_TYPE_GPU:
return "GPU";
break;
case CL_DEVICE_TYPE_ACCELERATOR:
return "ACCELERATOR";
break;
case CL_DEVICE_TYPE_ALL:
return "ALL";
break;
default:
return "ERROR invalid";
}
} |
When Apple enters any kind of business, it tends to turn heads. But when it comes to Apple Music, the company’s new music streaming service, it’s getting a different kind of attention—the federal trust-busting kind.
Technology is filled with all kinds of rumors and speculation — real and fabricated. BitStream collects all those whispers into one place to deliver your morning buzz.
Advertisement
Rumors started last week that the Federal Trade Commission was probing into whether Apple Music was doing more harm than good for music streaming competition. Services like Spotify, Rdio, and Pandora rely on the iTunes store to reach its iPhone-wielding audience while Apple takes a cut of revenue from those apps themselves.
Now with Apple Music in the mix, things get a little more messy. Essentially, competition feel like they have to charge more adjusting for the “Apple Tax” whereas Apple clearly doesn’t charge itself for putting Apple Music on every iPhone running iOS 8.4.
This week, streaming services received subpoenas as the government’s investigation continues. The FTC is also receiving support from senators including Al Franken, who wrote a letter urging the FTC and Department of Justice to take a peek at Apple’s allegedly anticompetitive practices:
“Increased competition in the music streaming market should mean that consumers will ultimately benefit through more choices of better products and at lower prices. I am concerned, however, that Apple’s position as a dominant platform operator may actually undermine many of the potential consumer benefits of its entry into the market.”
Advertisement
Although the letter is a little late to get the ball rolling, since the FTC is already mid-probe, Franken and other congressional support for the investigation could ensure that the FTC’s probe doesn’t extinguish with a fizzle but actually end with some impending legal action if necessary.
It’s anyone’s guess what this will end up meaning to Apple and its fledgling music streaming platform. The problem is additionally confusing considering iTunes is not the be-all-end-all method of distributing apps (just the most convenient), but despite Apple’s wish to avoid another complication in what has already been a bumpy launch, it looks like this annoying antitrust gnat won’t be swatted away so easily.
[VentureBeat]
Google Glass strikes back: Google’s faceputer didn’t receive much love as a commercial product, maybe it’s better for business. At least that’s Google’s thinking as it redesigns Glass to be foldable, water resistant, and all-around more rugged so it’s more suitable for work. This isn’t the dramatic revision of the Glass that we’ve already heard about, more like a few minor tweaks to make Glass more appealing for a different type of person. [9to5Google]
Advertisement
Welcome to the VR bandwagon, Nokia: Like almost every other technology company out there, Nokia is also testing waters for its own “VR Product.” Is it a headset? Controller? Glorified Smartphone Holder like Gear VR? We have no clue. But an ominous invitation only saying “NOWHERE” should tells us much, much more. Or is it “now here?” [Recode]
Apple Car shifts gears: The details surrounding Cupertino’s auto ambitions are still pretty elusive, but what’s certain is Apple ravenously snatching up auto industry veterans for its electric car cause codenamed “Titan.” Hires come from all over the industry including Tesla, European car companies, and University graduate students. We’ll have to wait and see what this ragtag team of experts can dream up. [WSJ]
What You Might Have Missed on Gizmodo
Is It OK To Shoot Down Your Neighbor’s Drone?
Behold, The Most #UnexcitingVideoGames You Can Think Of
Welcome to the Connected States: Living in a Van in America
Why I’m Upgrading to Windows 10
If You Want To See the Future of TV, Watch the Tour de France |
/*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.internal.batchimport.staging;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.RETURNS_MOCKS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.neo4j.configuration.Config.defaults;
import static org.neo4j.configuration.GraphDatabaseSettings.pagecache_memory;
import static org.neo4j.internal.batchimport.AdditionalInitialIds.EMPTY;
import static org.neo4j.internal.batchimport.input.DataGeneratorInput.bareboneNodeHeader;
import static org.neo4j.internal.batchimport.input.DataGeneratorInput.bareboneRelationshipHeader;
import static org.neo4j.io.ByteUnit.mebiBytes;
import static org.neo4j.io.pagecache.context.CursorContextFactory.NULL_CONTEXT_FACTORY;
import static org.neo4j.io.pagecache.tracing.PageCacheTracer.NULL;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.EnumMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.neo4j.collection.Dependencies;
import org.neo4j.csv.reader.Extractors;
import org.neo4j.internal.batchimport.Configuration;
import org.neo4j.internal.batchimport.DataStatistics;
import org.neo4j.internal.batchimport.IndexImporterFactory;
import org.neo4j.internal.batchimport.Monitor;
import org.neo4j.internal.batchimport.NodeDegreeCountStage;
import org.neo4j.internal.batchimport.ParallelBatchImporter;
import org.neo4j.internal.batchimport.cache.PageCacheArrayFactoryMonitor;
import org.neo4j.internal.batchimport.cache.idmapping.IdMappers;
import org.neo4j.internal.batchimport.input.Collector;
import org.neo4j.internal.batchimport.input.DataGeneratorInput;
import org.neo4j.internal.batchimport.input.Group;
import org.neo4j.internal.batchimport.input.Groups;
import org.neo4j.internal.batchimport.input.IdType;
import org.neo4j.internal.batchimport.input.Input;
import org.neo4j.internal.batchimport.staging.HumanUnderstandableExecutionMonitor.ImportStage;
import org.neo4j.internal.batchimport.store.BatchingNeoStores;
import org.neo4j.io.fs.FileSystemAbstraction;
import org.neo4j.io.layout.DatabaseLayout;
import org.neo4j.kernel.impl.store.NodeStore;
import org.neo4j.kernel.impl.store.RelationshipStore;
import org.neo4j.kernel.impl.transaction.log.EmptyLogTailMetadata;
import org.neo4j.logging.internal.NullLogService;
import org.neo4j.memory.EmptyMemoryTracker;
import org.neo4j.scheduler.JobScheduler;
import org.neo4j.storageengine.api.LogFilesInitializer;
import org.neo4j.test.RandomSupport;
import org.neo4j.test.extension.DefaultFileSystemExtension;
import org.neo4j.test.extension.Inject;
import org.neo4j.test.extension.Neo4jLayoutExtension;
import org.neo4j.test.extension.RandomExtension;
import org.neo4j.test.extension.testdirectory.TestDirectorySupportExtension;
import org.neo4j.test.scheduler.ThreadPoolJobScheduler;
@Neo4jLayoutExtension
@ExtendWith({RandomExtension.class, DefaultFileSystemExtension.class, TestDirectorySupportExtension.class})
class HumanUnderstandableExecutionMonitorIT {
private static final long NODE_COUNT = 1_000;
private static final long RELATIONSHIP_COUNT = 10_000;
@Inject
private RandomSupport random;
@Inject
private DatabaseLayout databaseLayout;
@Inject
private FileSystemAbstraction fileSystem;
@Test
void shouldReportProgressOfNodeImport() throws Exception {
// given
CapturingMonitor progress = new CapturingMonitor();
PrintStream nullStream = new PrintStream(OutputStream.nullOutputStream());
HumanUnderstandableExecutionMonitor monitor =
new HumanUnderstandableExecutionMonitor(progress, nullStream, nullStream);
IdType idType = IdType.INTEGER;
DataGeneratorInput.DataDistribution dataDistribution = DataGeneratorInput.data(NODE_COUNT, RELATIONSHIP_COUNT);
Groups groups = new Groups();
Group group = groups.getOrCreate(null);
var extractors = new Extractors();
Input input = new DataGeneratorInput(
dataDistribution,
idType,
random.seed(),
bareboneNodeHeader(idType, group, extractors),
bareboneRelationshipHeader(idType, group, extractors),
groups);
// when
try (JobScheduler jobScheduler = new ThreadPoolJobScheduler()) {
new ParallelBatchImporter(
databaseLayout,
fileSystem,
NULL,
Configuration.DEFAULT,
NullLogService.getInstance(),
monitor,
EMPTY,
new EmptyLogTailMetadata(defaults()),
defaults(pagecache_memory, mebiBytes(8)),
Monitor.NO_MONITOR,
jobScheduler,
Collector.EMPTY,
LogFilesInitializer.NULL,
IndexImporterFactory.EMPTY,
EmptyMemoryTracker.INSTANCE,
NULL_CONTEXT_FACTORY)
.doImport(input);
// then
progress.assertAllProgressReachedEnd();
}
}
@Test
void shouldStartFromNonFirstStage() {
// given
PrintStream nullStream = new PrintStream(OutputStream.nullOutputStream());
HumanUnderstandableExecutionMonitor monitor = new HumanUnderstandableExecutionMonitor(
HumanUnderstandableExecutionMonitor.NO_MONITOR, nullStream, nullStream);
Dependencies dependencies = new Dependencies();
dependencies.satisfyDependency(Input.knownEstimates(10, 10, 10, 10, 10, 10, 10));
BatchingNeoStores neoStores = mock(BatchingNeoStores.class);
NodeStore nodeStore = mock(NodeStore.class, RETURNS_MOCKS);
RelationshipStore relationshipStore = mock(RelationshipStore.class, RETURNS_MOCKS);
when(neoStores.getNodeStore()).thenReturn(nodeStore);
when(neoStores.getRelationshipStore()).thenReturn(relationshipStore);
dependencies.satisfyDependency(neoStores);
dependencies.satisfyDependency(IdMappers.actual());
dependencies.satisfyDependency(mock(PageCacheArrayFactoryMonitor.class));
dependencies.satisfyDependency(new DataStatistics(10, 10, new DataStatistics.RelationshipTypeCount[0]));
monitor.initialize(dependencies);
// when/then
StageExecution execution = mock(StageExecution.class);
when(execution.getStageName()).thenReturn(NodeDegreeCountStage.NAME);
assertThatCode(() -> monitor.start(execution)).doesNotThrowAnyException();
}
private static class CapturingMonitor implements HumanUnderstandableExecutionMonitor.Monitor {
final EnumMap<ImportStage, AtomicInteger> progress = new EnumMap<>(ImportStage.class);
@Override
public void progress(ImportStage stage, int percent) {
if (percent > 100) {
fail("Expected percentage to be 0..100% but was " + percent);
}
AtomicInteger stageProgress = progress.computeIfAbsent(stage, s -> new AtomicInteger());
int previous = stageProgress.getAndSet(percent);
if (previous > percent) {
fail("Progress should go forwards only, but went from " + previous + " to " + percent);
}
}
void assertAllProgressReachedEnd() {
Assertions.assertEquals(ImportStage.values().length, progress.size());
progress.values().forEach(p -> assertEquals(100, p.get()));
}
}
}
|
N,M = (int(x) for x in input().split())
a = set(int(input()) for _ in range(M))
dp = [0] * N
broke = False
if N == 1:
print('1')
broke = True
elif 1 in a and 2 not in a:
dp[1] = 1
elif 1 not in a and 2 in a:
dp[0] = 1
else:
dp[0] = 1
dp[1] = 2
if 1 in a and 2 in a:
print('0')
broke = True
else:
for i in range(3,N+1):
if i-1 in a and i-2 in a:
print('0')
broke = True
break
elif i-1 in a:
dp[i-1] = dp[i-3]
elif i-2 in a:
dp[i-1] = dp[i-2]
else:
dp[i-1] = (dp[i-2] + dp[i-3]) % 1000000007
if broke == False:
print(dp[N-1]) |
// NewEncoding returns a new Encoding defined by the given alphabet,
// which must be a 58-byte string.
func NewEncoding(encoder string, options ...opts) *Encoding {
if len(encoder) != 58 {
panic("encoding alphabet is not 58-bytes long")
}
e := new(Encoding)
e.encode = encoder
e.checkFunc = func(b []byte) []byte {
sh1, sh2 := sha256.New(), sha256.New()
sh1.Write(b)
sh2.Write(sh1.Sum(nil))
return sh2.Sum(nil)
}
for i := 0; i < len(e.decodeMap); i++ {
e.decodeMap[i] = -1
}
for i := 0; i < len(encoder); i++ {
e.decodeMap[encoder[i]] = int8(i)
}
for _, opt := range options {
opt(e)
}
return e
} |
#ifndef MAKEFILESEMANTISDC_H_WUAST
#define MAKEFILESEMANTISDC_H_WUAST
#include "parser.hpp"
#include <string>
#include <vector>
#include <stdexcept>
#include <memory>
#include <map>
#include <set>
#include <iostream>
class VString : public std::string
{
public:
VString()
: std::string()
{}
VString(const std::string &s)
: std::string(s)
{
}
void push_back(const std::string &s) {
if (size())
(*this) += " ";
(*this) += s;
}
std::vector<std::string> split() const;
};
class Context;
class MakefileSemantics;
class Function
{
public:
virtual ~Function() {}
virtual VString operator()(
Context *ctx,
const std::string &functionName,
std::vector <Expression::Ptr> args,
Expression::Ptr callContext
) = 0;
};
class IncludeHandler
{
public:
virtual ~IncludeHandler() {}
virtual bool operator()(
Context *ctx,
IncludeNode::Ptr node,
MakefileParser *parser
) = 0;
};
class Context
{
public:
std::map<std::string, Function *> functions;
std::map<std::string, Expression::Ptr> values;
std::vector<IncludeHandler *> includeHandlers;
static Context *global;
VString eval(Expression::Ptr);
VString evalLiteral(LiteralExpression::Ptr);
VString evalReference(ReferenceExpression::Ptr);
VString evalCall(CallExpression::Ptr);
VString evalCluster(Expression::Ptr);
private:
friend class MakefileSemantics;
void error (const std::string &text, Node::Ptr);
std::set<std::string> stateInsideDeref;
};
#define REGISTER_FUNCTION_STR(name, klass, str) struct ___construct##name { \
___construct##name () {Context::global->functions[str] = new klass;} \
} static ___init_construct##name;
#define REGISTER_FUNCTION(name, klass) REGISTER_FUNCTION_STR(name, klass, #name)
class MakeScriptFunction;
class MakefileSemantics
{
public:
Context *context;
MakefileSemantics(MakefileParser *parser);
MakefileParser *parser;
void d();
private:
void error (const std::string &text, Node::Ptr);
bool n(Node::Ptr);
bool nAssign(Assignment::Ptr);
bool nCall(CallExpression::Ptr);
bool nInclude(IncludeNode::Ptr);
bool nIfCondition(IfCondition::Ptr, bool &result);
bool nFunction(FunctionNode::Ptr);
friend class MakeScriptFunction;
};
#endif
|
Bi-directional resetting scheme of the magamp post-regulator
A simple bi-directional magamp control scheme is proposed. The scheme effectively reduces the influence of the time delay, or dead time of magamp core on the output voltage regulation at extreme load conditions. The scheme is very useful in the converters with magamp as post-regulator to eliminate the dead time of the magamp core due to the squareness of the core materials and to extend the load variation range. |
/*
* Copyright 1993-2009 NVIDIA Corporation. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and
* proprietary rights in and to this software and related documentation and
* any modifications thereto. Any use, reproduction, disclosure, or distribution
* of this software and related documentation without an express license
* agreement from NVIDIA Corporation is strictly prohibited.
*
*/
/* CUda UTility Library */
#ifndef _STOPWATCH_H_
#define _STOPWATCH_H_
// stop watch base class
#include <stopwatch_base.h>
// include OS specific policy
#ifdef _WIN32
# include <stopwatch_win.h>
typedef StopWatchWin OSStopWatch;
#else
# include <stopwatch_linux.h>
typedef StopWatchLinux OSStopWatch;
#endif
// concrete stop watch type
typedef StopWatchBase<OSStopWatch> StopWatchC;
namespace StopWatch
{
//! Create a stop watch
const unsigned int create();
//! Get a handle to the stop watch with the name \a name
StopWatchC& get( const unsigned int& name);
// Delete the stop watch with the name \a name
void destroy( const unsigned int& name);
} // end namespace, stopwatch
#endif // _STOPWATCH_H_
|
from website.utils import is_committee
from .models import Fresher, Helper
def is_fresher(user):
return Fresher.objects.filter(pk=user.username).exists()
def is_helper(user):
return Helper.objects.filter(pk=user.username).exists()
def jumpstart_check(user):
return is_committee(user) or is_fresher(user) or is_helper(user)
|
/**
* Double write from 1.x to 2 task.
*
* @author xiweng.yy
*/
public class DoubleWriteInstanceChangeToV2Task extends AbstractExecuteTask {
private final String namespace;
private final String serviceName;
private final Instance instance;
private final boolean register;
public DoubleWriteInstanceChangeToV2Task(String namespace, String serviceName, Instance instance,
boolean register) {
this.register = register;
this.namespace = namespace;
this.serviceName = serviceName;
this.instance = instance;
}
@Override
public void run() {
try {
InstanceOperatorClientImpl instanceOperator = ApplicationUtils.getBean(InstanceOperatorClientImpl.class);
if (register) {
instanceOperator.registerInstance(namespace, serviceName, instance);
} else {
instanceOperator.removeInstance(namespace, serviceName, instance);
}
} catch (Exception e) {
if (Loggers.SRV_LOG.isDebugEnabled()) {
Loggers.SRV_LOG
.debug("Double write task for {}#{} instance from 1 to 2 failed", namespace, serviceName, e);
}
ServiceChangeV1Task retryTask = new ServiceChangeV1Task(namespace, serviceName, instance.isEphemeral(),
DoubleWriteContent.INSTANCE);
retryTask.setTaskInterval(INTERVAL);
String taskKey = ServiceChangeV1Task.getKey(namespace, serviceName, instance.isEphemeral());
ApplicationUtils.getBean(DoubleWriteDelayTaskEngine.class).addTask(taskKey, retryTask);
}
}
} |
package com.hkmvend.sdk.client;
import android.app.Application;
import android.os.AsyncTask;
import com.hkmvend.sdk.model.gdata.ApiWrapGTable;
import com.hkmvend.sdk.model.sheetsu.ResponseSheetsu;
import com.hkmvend.sdk.model.sheetsu.apiEntryRow;
import com.hkmvend.sdk.storage.Bill.BillContainer;
import com.hkmvend.sdk.storage.Menu.EntryContainer;
import com.hkmvend.sdk.storage.Menu.MenuEntry;
import com.squareup.okhttp.Request;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import retrofit.Call;
import retrofit.Response;
import retrofit.http.GET;
import retrofit.http.Path;
/**
* Created by zJJ on 1/23/2016.
*/
public class RestaurantPOS extends retrofitClientBasic {
private static RestaurantPOS static_instance;
public RestaurantPOS(Application c) {
super(c);
registerJsonAdapter();
container = EntryContainer.getInstnce(c);
billtainer = BillContainer.getInstnce(c);
}
@Override
protected Request.Builder universal_header(Request.Builder chain) {
chain.addHeader("Content-type", "text/plain; charset=utf-8");
chain.addHeader("Accept-Language", "en-US,en;q=0.8");
chain.addHeader("Accept-Encoding", "gzip, deflate, sdch");
chain.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36");
chain.addHeader("Accept", "*/*");
return chain;
}
public static RestaurantPOS newInstance(Application ctx) {
return new RestaurantPOS(ctx);
}
public static RestaurantPOS getInstance(Application context) {
if (static_instance == null) {
static_instance = newInstance(context);
return static_instance;
} else {
static_instance.setContext(context);
return static_instance;
}
}
//https://spreadsheets.google.com/feeds/list/17ahMMUjnfKYg1hVsFKUzR1weoSZU3kP-Id0xmvn8154/od6/public/values?alt=json-in-script&callback=cds
//https://developers.google.com/chart/interactive/docs/querylanguage
private interface workerService {
/* @GET("/feeds/list/{doc_id}/od6/public/values?alt=json-in-script&callback=cds")
Call<String> getMenu(
@Path("doc_id") final String document_id,
@Query("tqx") final String extra,
@Query("REGION") final String region);*/
@GET("/apis/{doc_key}")
Call<ResponseSheetsu> getMenuSheetsu(@Path("doc_key") final String document_key);
}
public interface DataConfigCB {
void success(List<MenuEntry> list);
void failure(String error_cause);
}
private workerService createService() {
return api.create(workerService.class);
}
@Override
protected String getBaseEndpoint() {
// return "https://spreadsheets.google.com/";
return "https://sheetsu.com";
}
private String ensureJsonData(String result) {
int start = result.indexOf("{", result.indexOf("{") + 1);
int end = result.lastIndexOf("}");
String jsonResponse = result.substring(start, end);
return jsonResponse;
}
public RestaurantPOS setCB(DataConfigCB cb) {
call_back = cb;
return this;
}
public EntryContainer getContainer() {
return container;
}
public BillContainer getBillContainer() {
return billtainer;
}
public RestaurantPOS setDatabaseId(String restaurant_menu_db_id) {
this.restaurant_menu_db_id = restaurant_menu_db_id;
container.saveRestaurantMenuId(restaurant_menu_db_id);
return this;
}
public void runType() throws Exception {
boot_load_sync f = new boot_load_sync();
if (call_back == null) throw new Exception("call back is not setup");
if (!container.isMenuExisted() && restaurant_menu_db_id == null)
throw new Exception("menu id is not setup");
final String id = restaurant_menu_db_id == null ? container.loadRestaurantMenuId() : restaurant_menu_db_id;
f.execute(id);
}
private String restaurant_menu_db_id;
private DataConfigCB call_back;
private EntryContainer container;
private BillContainer billtainer;
private class boot_load_sync extends AsyncTask<String, Void, Void> {
private ApiWrapGTable stored_object;
boolean need_to_login_first = false;
String failure = "", plain_json = "";
@Override
protected Void doInBackground(String[] params) {
try {
final String doc_id = params[0];
/* if (container.isConfigurationStored()) {
plain_json = container.loadConfigFile();
} else {*/
Call<ResponseSheetsu> service = createService().getMenuSheetsu(doc_id);
Response<ResponseSheetsu> response = service.execute();
if (!response.isSuccess()) {
throw new IOException("server maybe down");
}
if (response.code() != 200) {
throw new IOException("server " + response.code());
}
ResponseSheetsu body = response.body();
// Log.i("TAGService", body);
// plain_json = ensureJsonData(body);
// Log.i("TAGService", plain_json);
//}
plain_json = gsonsetup.toJson(body);
container.saveConfigFile(plain_json);
savePlainFileToRealm(gsonsetup.toJson(body));
} catch (IOException e) {
failure = e.getCause().getMessage();
cancel(true);
} catch (Exception e) {
failure = e.getMessage();
cancel(true);
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
call_back.success(container.getAllRecords());
}
@Override
protected void onCancelled(Void aVoid) {
super.onCancelled(aVoid);
call_back.failure(failure);
}
}
private void savePlainFileToRealm(String file) {
ResponseSheetsu stored_object = gsonsetup.fromJson(file, ResponseSheetsu.class);
List<apiEntryRow> row = stored_object.result;
container.flushRecords();
Iterator<apiEntryRow> ri = row.iterator();
while (ri.hasNext()) {
apiEntryRow H = ri.next();
boolean success = container.addNewRecord(
MenuEntry.valueOf(H.cate),
H.entryId,
H.chinese,
H.english,
H.price
);
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vision;
import javax.swing.JOptionPane;
import vision.funcionario.MenuFuncionario;
import vision.voluntario.MenuVoluntario;
import vision.gerente.MenuGerente;
/**
*
* @author Altayr
*/
public class TelaLogin extends javax.swing.JFrame {
/**
* Creates new form TelaLogin
*/
public TelaLogin() {
initComponents();
this.setLocationRelativeTo(null);
}
public boolean loginFuncionario(String login, String senha) {
return login.equals("funcionario") && senha.equals("<PASSWORD>");
}
public boolean loginUsuario(String login, String senha) {
return login.equals("voluntario") && senha.equals("<PASSWORD>");
}
public boolean loginGerente(String login, String senha){
return login.equals("gerente") && senha.equals("<PASSWORD>");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jBtLogin = new javax.swing.JButton();
jLUsuario = new javax.swing.JLabel();
jLLogin = new javax.swing.JLabel();
jLSenha = new javax.swing.JLabel();
jTxtLogin = new javax.swing.JTextField();
jTxtSenha = new javax.swing.JPasswordField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Login");
setResizable(false);
jBtLogin.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jBtLogin.setText("Entrar");
jBtLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBtLoginActionPerformed(evt);
}
});
jLUsuario.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLUsuario.setText("Usuário");
jLLogin.setFont(new java.awt.Font("Tempus Sans ITC", 1, 24)); // NOI18N
jLLogin.setText("LOGIN");
jLSenha.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLSenha.setText("Senha");
jTxtLogin.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jTxtLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTxtLoginActionPerformed(evt);
}
});
jTxtSenha.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLLogin)
.addGap(190, 190, 190))
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLSenha)
.addComponent(jLUsuario))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(91, 91, 91)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTxtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTxtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(189, 189, 189)
.addComponent(jBtLogin)))
.addContainerGap(89, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLLogin)
.addGap(36, 36, 36)
.addComponent(jLUsuario)
.addGap(18, 18, 18)
.addComponent(jTxtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addComponent(jLSenha)
.addGap(16, 16, 16)
.addComponent(jTxtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(jBtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(64, Short.MAX_VALUE))
);
getAccessibleContext().setAccessibleDescription("");
pack();
}// </editor-fold>//GEN-END:initComponents
private void jBtLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtLoginActionPerformed
// TODO add your handling code here:
if(jTxtLogin.getText().equals("")) {
JOptionPane.showMessageDialog(null,"POR FAVOR \n digite o usuario","ERRO USUÁRIO",3);
return;
}
if(jTxtSenha.getPassword().equals("")) {
JOptionPane.showMessageDialog(null,"POR FAVOR \n digite a senha","ERRO SENHA",3);
}
if(this.loginFuncionario(jTxtLogin.getText(), new String(jTxtSenha.getPassword()))){
JOptionPane.showMessageDialog(null,"SEJA BEM VINDO\n FUNCIONARIO");
MenuFuncionario telaPrincipal = new MenuFuncionario();
telaPrincipal.setVisible(true);
dispose();
}
else if (this.loginUsuario(jTxtLogin.getText(), new String(jTxtSenha.getPassword()))){
JOptionPane.showMessageDialog(null,"SEJA BEM VINDO\n VOLUNTARIO");
MenuVoluntario telaPrincipal = new MenuVoluntario();
telaPrincipal.setVisible(true);
dispose();
}
else if (this.loginGerente(jTxtLogin.getText(), new String(jTxtSenha.getPassword()))){
JOptionPane.showMessageDialog(null,"SEJA BEM VINDO\n GERENTE");
MenuGerente telaPrincipal = new MenuGerente();
telaPrincipal.setVisible(true);
dispose();
}
// if(this.loginUsuario(txtLogin.getText(), new String(txtSenha.getPassword()))) {
//
// Icon loginCertoUsuario = new ImageIcon(getClass().getResource("/iconMensagem/pin-ok-32.png"));
// JOptionPane.showMessageDialog(null,"SEJA BEM VINDO\n USUÁRIO","USUÁRIO",JOptionPane.INFORMATION_MESSAGE,loginCertoUsuario);
// TelaPrincipalUsuario telaPrincipal = new TelaPrincipalUsuario();
// telaPrincipal.setVisible(true);
// dispose();
// }
else {
JOptionPane.showMessageDialog(null,"SENHA OU LOGIN INVÁLIDO");
}
}//GEN-LAST:event_jBtLoginActionPerformed
private void jTxtLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTxtLoginActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTxtLoginActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TelaLogin().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jBtLogin;
private javax.swing.JLabel jLLogin;
private javax.swing.JLabel jLSenha;
private javax.swing.JLabel jLUsuario;
private javax.swing.JTextField jTxtLogin;
private javax.swing.JPasswordField jTxtSenha;
// End of variables declaration//GEN-END:variables
}
|
/**
* C4Exercise1:
* (1)Create a class containing an uninitialized String reference. Demonstrate
* that this reference is initialized by Java to null.
*/
public class C4Exercise1 {
int s;
public static void main(String[] args) {
C4Exercise1 foo = new C4Exercise1();
System.out.println(foo.s);
}
} |
/**
* Created by Noah Huppert on 1/17/2015.
*/
public class Function extends Token {
private ArrayList<Variable> arguments;
public Function(String id, TokenPosition tokenPosition, ArrayList<Variable> arguments){
super(TokenType.FUNCTION_CALL, id, tokenPosition);
if(arguments != null) {
setArguments(arguments);
} else{
setArguments(new ArrayList<Variable>());
}
}
/* Actions */
public void executeInRobocode(Robot robot){};
/* Getters */
public ArrayList<Variable> getArguments() {
return arguments;
}
/* Setters */
public void setArguments(ArrayList<Variable> arguments) {
this.arguments = arguments;
}
} |
def _get_tag_arrays(dom_node):
child_dict = {}
for child in dom_node:
if child.tag not in child_dict:
child_dict[child.tag] = []
child_dict[child.tag].append(child)
return child_dict |
<gh_stars>1-10
from ..common import *
from .. import basetools
__all__ = [
'judge_installed_library', # 判断是否注册应用程序
]
def judge_installed_library(name = 'simpleui', type=retools.PATT_INSTALLED_APPS)->bool:
"""获取已经安装的第三方库(从 INSTALL_APP 中获取判断)"""
register_obj = basetools.get_list_patt_content(type, basetools.get_django_settings_path())
del_comment = [retools.PATT_COMMENT.sub(' ', _) for _ in register_obj.split('\n')]
if name in '\n'.join(del_comment):
return True
else:
return False
|
<filename>server/src/utils/streams.ts
import { Transform } from 'stream'
export const jsonStream = () => {
let first = true
return new Transform({
flush: cb => cb(null, ']\n'),
objectMode: true,
transform: (chunk, _, cb) => {
if (first) {
first = false
return cb(null, `[${JSON.stringify(chunk)}`)
} else {
return cb(null, `,${JSON.stringify(chunk)}`)
}
},
})
}
|
Tar Sands Toxins with Keystone XL Link Underestimated
One of the biggest concerns about producing crude oil from the Alberta tar sands is its impact on climate change, which has been a major part of the debate about whether the Keystone XL Pipeline should be built.
A new University of Toronto-Scarborough study published Monday says there’s another reason to be concerned about oil production in the tar sands: The Canadian government may have underestimated emissions of carcinogens known as polycyclic aromatic hydrocarbons, or PAHs, from the Alberta tar sands, and they may be a major hazard to both human and ecosystem health.
Alberta Tar Sands.
Credit: Howl Arts Collective/flickr
Official estimates of PAH emissions from the Alberta tar sands have been used by the Canadian government to approve new tar sands development, and estimates for PAH concentrations in air, water and food in the region may also be too low, leading to an underestimation of PAH risk to human health, the study says.
PAHs are not greenhouse gases, and have no direct effect on climate change. But their source does: The U.S. State Department in its Final Supplemental Environmental Impact Statement for the proposed Keystone XL Pipeline, released Friday, says the production and processing of a barrel of tar sands crude releases 17 percent more carbon emissions than the average barrel of crude produced elsewhere.
For anyone living along the Keystone XL Pipeline’s route, PAHs are a big deal, said Jules M. Blais, a University of Ottawa chemical and toxicology professor who is unaffiliated with the study.
“From the standpoint of Keystone, the concerns are regarding potential breaches that could contaminate soils,” he said. “The same kinds of things that are getting into the Athabasca River could be relevant to Keystone.”
PAHs, which include phenanthrene, pyrene and benzo(a)pyrene, “are among the most toxic hydrocarbons,” Blais said. “They’re some of the worst things out there.”
The study, conducted by a team co-led by University of Toronto-Scarborough environmental chemistry professor Frank Wania, used computer models to examine the plausibility of official Canadian inventories of PAHs against actual measured PAH concentrations found in the Athabasca Oil Sands Region where Alberta’s tar sands are produced near the northern end of the proposed Keystone XL Pipeline.
Proposed Keystone XL pipeline.
Click image to enlarge. Credit: U.S. Department of State
Previous studies have found that fish and other aquatic species are harmed when they’re exposed to oil sands water and sediments produced in the region, according to the study. Increased concentrations of PAHs are found in oil sands tailings ponds and have been found in the Athabasca River, which threads through the oil sands region.
“We found that the predictions the model uses were too low than what has been measured,” Wania said. “The officially reported emissions are very likely too low.”
When Wania’s team looked for reasons the emissions inventories were too low, they discovered that tar sands tailings ponds — storage ponds used often for toxic mining waste material — might be an answer.
“In our second set of model calculations, we included tailings ponds and allowed evaporation of PAHs to occur,” he said. “The concentration we calculated was closer to what is being measured, so it indicates that quite possibly tailings pond emissions are part of the explanation of why the emissions are too low.”
Blowing dust could also be a source of PAHs, he said.
Because sources of these emissions may not have been considered in official inventories, the risk PAHs pose to human health and the environment may be much greater than previously thought, Wania said.
“The implication of these results is that the emissions from tailing ponds are being underreported,” Blais said. “We can explain this a number of ways. These emissions from tailing ponds can be very difficult to estimate. They could be occurring below the surface of the ground. They could be below surface, below grade. They could be following fissures or fractures in the rock.”
Blais said Wania’s team’s modeling is very useful in revealing whether official PAH inventories are realistic.
That’s important because PAHs are a health issue for anyone living near the tar sands or the Keystone XL pipeline if it were to leak, he said.
You May Also Like
Time is Running Out for California Drought Relief
January’s Temps Leave a Nation Blowing Hot and Cold
6 Degrees: Sunsets, Cows, Obama and More
Climate Change Cuisine: It’s What’s for Dinner |
In exchange, Iran was to receive arms from the Reagan Administration. Mr. Bani-Sadr does not have firsthand knowledge of the arrangement, he said, because the mullahs who consummated the deal were his political rivals and were simultaneously plotting to remove him from office.
Reagan campaign officials have strenuously denied that any such deal ever occurred. The persistent but unproven allegations were revived with the publication last month of an Op-Ed page article in The New York Times by Gary Sick, who was a staff member of the National Security Council under President Carter and who was involved in the hostage situation.
Mr. Sick, who now teaches at Columbia University, wrote that he now believed such a deal may have been initiated in July 1980 in a hotel meeting in Madrid between William J. Casey, the Reagan campaign chairman, and Hojatolislam Mehdi Karrubi, a cleric close to Ayatollah Ruhollah Khomeini, the Iranian revolutionary leader.
Newsletter Sign Up Continue reading the main story Please verify you're not a robot by clicking the box. Invalid email address. Please re-enter. You must select a newsletter to subscribe to. Sign Up You will receive emails containing news content , updates and promotions from The New York Times. You may opt-out at any time. You agree to receive occasional updates and special offers for The New York Times's products and services. Thank you for subscribing. An error has occurred. Please try again later. View all New York Times newsletters.
Mr. Sick said he was less convinced of charges that George Bush, then the Vice-Presidential candidate, attended meetings in Paris in October when the arrangment was consummated.
Last week, Mr. Bush sharply denied he was in Paris at any time during that period and said the talk about such a deal was "rumor-mongering" that should be put to rest.
Mr. Bani-Sadr said today that in 1980 he was told that a nephew of Ayatollah Khomeini helped arrange a meeting between some Reagan campaign officials and one of Iran's religious rulers in Spain that spring.
An example of Mr. Bani-Sadr's reasoning is an episode in which he said he was asked by a rival, Ayatollah Mohammed Beheshti, about a plan to release the hostages and later saw a different proposal from the Carter Administration. "I realized then that there was another agreement in the works and that it had nothing to do with Carter," he writes. "With whom then, if not his rival for the White House, Ronald Reagan?"
L. Bruce Laingen, in the foreword to the book published by Brassey's, said neither he nor the publisher found Mr. Bani-Sadr's evidence convincing. He said it showed an Iranian penchant for intrigue. "Somewhere behind every pillar or every tree is the hand of the foreigner, pulling the strings," he wrote.
Mr. Bani-Sadr's book was rushed into print in an English translation by the American publisher months ahead of schedule to take advantage of recent interest in the subject. Mr. Bani-Sadr was initially denied a visa by the State Department, which relented last week.
Advertisement Continue reading the main story
Mr. Bani-Sadr has lived in Versailles, France, for the last 10 years with his wife and three children. |
<reponame>sannorozco/RoboFont-2<filename>Extensions/Curve EQ.roboFontExt/lib/MojoDrawingToolsPen.py
from fontTools.pens.basePen import BasePen
from fontTools.pens.transformPen import TransformPen
from mojo.drawingTools import newPath, moveTo, lineTo, curveTo, closePath, drawPath
class MojoDrawingToolsPen(BasePen):
def __init__(self, g, f):
self.g = g
self.glyphSet = f
self.__currentPoint = None
newPath()
def _moveTo(self, pt):
moveTo(pt)
def _lineTo(self, pt):
lineTo(pt)
def _curveToOne(self, pt1, pt2, pt3):
curveTo(pt1, pt2, pt3)
def _closePath(self):
closePath()
def _endPath(self):
closePath()
def draw(self):
drawPath()
def addComponent(self, baseName, transformation):
glyph = self.glyphSet[baseName]
tPen = TransformPen(self, transformation)
glyph.draw(tPen)
|
Art Collections of the Russian State Library
The former Lenin State Library in Moscow, now the Russian State Library, holds extensive collections of graphic and photographic materials, Russian and foreign, dating from the 15th century to the present day. These include a collection of some 434,000 posters, of which film and political posters form the largest subsections; a smaller number of pre-Revolutionary posters is of special interest. The collection of engravings totals some 93,000 items, and includes both works of European masters and Russian popular prints. There are also collections of postcards, “albums”, and manuscripts. |
New report finds only 129 of 4,069 largest companies listed on the world’s stock exchanges are disclosing the most basic sustainability information
Only 128 of the 4,609 largest companies listed on the world’s stock exchanges disclose the most basic information on how they meet their responsibilities to society, according to a new report.
The study by Canadian investment advisory firm Corporate Knights Capital says 97% of companies are failing to provide data on the full set of “first-generation” sustainability indicators - employee turnover, energy, greenhouse gas emissions (GHGs), injury rate, pay equity, waste and water.
While the number of companies disclosing individual metrics has risen in recent years, the study says it remains “disconcertingly low” and the improvement is starting to tail off.
More than 60% of the world’s largest listed companies currently fail to disclose their GHGs, three quarters are not transparent about their water consumption and 88% do not divulge their employee turnover rate.
The slowing down of disclosure is illustrated by the fact that while the number of large listed companies disclosing their energy use increased by 88% from 2008 to 2012, there was only a 5% rise from 2011 to 2012. A similar reporting slowdown is occurring on the other first-generation indicators.
The reason these figures are so important is because there is a direct correlation between transparency and companies taking substantive action to improve their performance.
Paul Druckman, who heads up the International Integrated Reporting Council, said: “We know that reporting influences behaviour, so corporate reporting reform should encourage behaviour that focuses on longer-term value creation in order to achieve financial stability and sustainability.”
The report, which rates disclosure levels of companies listed on individual stock exchanges, puts Helsinki at the top of the league table, followed by Amsterdam’s Euronext and Johannesburg.
London scores ninth with the New York Stock Exchange and Nasdaq were close to the bottom of the global rankings, in 34th and 39th place respectively. The worst performers were Saudi Arabia, Warsaw, Qatar, Kuwait and Lima, which came bottom in 46th place.
The lack of transparency highlighted in the report prompted the CEO of multinational insurance group Aviva, who co-sponsored the report, to call on securities regulators to take urgent action.
Mark Wilson said: “There is a clear need for a global mandate and a globally co-ordinated approach to corporate sustainability reporting, which is clearly understood and consistently applied.
“A proliferation of national approaches, as well as overlapping and competing voluntary international standards and guidance, has led to difficulties in interpretation and implementation for companies operating in different countries and markets.”
He called on the International Organization of Securities Commissions (IOSCO), the body that brings together the world’s securities regulators, to co-ordinate more effective reporting.
IOSCO sets global disclosure standards and has focused in recent years on financial transparency. But over the coming months it will start looking at the responsibilities of companies around non-financial reporting.
“IOSCO has intervened fruitfully in similar areas in the past,” Wilson said. “An IOSCO intervention on narrative reporting might therefore be the spur to a global solution to this challenge.”
Beyond the action of regulators, the report by Corporate Knights Capital says there is an urgent need to minimise the time gap between companies’ financial and sustainability reporting cycles and calls on stock exchanges to link the pay of their senior executives to the sustainability disclosure practices of their listed companies.
It also says it is vital that the world’s three major sustainability standard-setters – the Carbon Disclosure Project (CDP), the Global Reporting Initiative (GRI), and the Sustainability Accounting Standards Board (SASB) - harmonise their competing reporting methodologies and guidelines.
According to Druckman, while progress has been slow, the report does show there is cause for optimism, given progress being made particularly by stock exchanges in emerging markets.
Companies trading in China, Colombia, Malaysia, Mexico, the Philippines, Thailand and Turkey were found to be quickly closing the disclosure gap between themselves and listed companies trading in developed markets.
Druckman also pointed to the birth of the concept of “stewardship” embedded in investor codes in countries such as South Africa, Malaysia, Japan, Australia and the Netherlands, and highlighted Brazil’s BM&F Bovespa which recently announced that it would be encouraging businesses listed on its platform to produce an integrated or sustainability report on a “report-or-explain” basis.
Within the developed markets, the recent EU Parliament’s directive on non-financial and diversity information will almost certainly lead to an increase in reporting on the seven first-generation indicators. The EU estimates that only 10% of the 6,000 companies that are expected to be affected currently report information that will be required.
“For capitalism to take a new direction, institutions, businesses and investors must think about value creation in a holistic sense when formulating strategy and allocating dwindling resources, particularly as they seek to build long-term value,” Druckman said.
“The businesses leading the way are those that are anticipating and responding to the changing needs of their stakeholder community, society and the external environment.”
The report points out that the paucity of corporate reporting on the first-generation indicators stands in stark contrast to investors’ growing interest in building sustainable investment strategies. Only recently a global investor coalition announced it is seeking to carbon footprint $500bn of institutional investments by next December’s UN Climate Summit in Paris.
The report also warns companies of increasing risks if major businesses fail to become more transparent in their performance: “While companies can face barriers in setting up systems to measure and publicly disclose their performance on the seven first-generation indicators, the opportunity cost of opaqueness is rising.”
Read more stories like this:
The finance hub is funded by EY. All content is editorially independent except for pieces labelled advertisement feature. Find out more here.
Join the community of sustainability professionals and experts. Become a GSB member to get more stories like this direct to your inbox |
/** Perform a table creation operation.
*@param tableName is the name of the table to create.
*@param columnMap is the map describing the columns and types. NOTE that these are abstract
* types, which will be mapped to the proper types for the actual database inside this
* layer.
*@param invalidateKeys are the cache keys that should be invalidated, if any.
*/
public void performCreate(String tableName, Map<String,ColumnDescription> columnMap, StringSet invalidateKeys)
throws ManifoldCFException
{
StringBuilder queryBuffer = new StringBuilder("CREATE CACHED TABLE ");
queryBuffer.append(tableName);
queryBuffer.append('(');
Iterator<String> iter = columnMap.keySet().iterator();
boolean first = true;
while (iter.hasNext())
{
String columnName = iter.next();
ColumnDescription cd = columnMap.get(columnName);
if (!first)
queryBuffer.append(',');
else
first = false;
appendDescription(queryBuffer,columnName,cd,false);
}
queryBuffer.append(')');
performModification(queryBuffer.toString(),null,invalidateKeys);
} |
Relevance of claudication pain distance in patients with peripheral arterial occlusive disease.
BACKGROUND
Determination of both the pain-free and the maximum walking distances is part of a routine program in the angiological examination of patients with PAOD. It is however as yet not clear which of these two parameters is more relevant in determining a patient's pathological condition.
PATIENTS AND METHODS
In 150 patients with stable intermittent claudication, the claudication pain distance (CPD) and the maximum pain distance (MPD) were determined on a treadmill at 3.0 km/h and 12% inclination. The results were compared with the angiographic findings, the Doppler pressure values and the subjective quality of life (PAVK-86-Questionnaire).
RESULTS
The average pain-free walking distance was 89 +/- 71 m, and the maximum walking distance was 198 +/- 141 m. There was no correlation between both walking distances and the angiographic extent of PAOD. Only the MPD correlated with the ankle systolic Doppler pressure and the ankle/brachial pressure index of the claudicating leg (r = 0.16, p < 0.05 and r = 0.20, p < 0.01). Both the CPD and the MDP had a significant influence on the life quality of the patients (CPD: r = -0.41, p < 0.001; MPD: r = -0.47, p < 0.001). In the multiple regression analysis, beside the body mass index, the MPD was found to be the greatest predictor for the pathologically relevant quality of life dimensions pain, complaints and functional status.
CONCLUSIONS
The maximum walking distance correlated in a better way than pain-free walking distance with the objective and subjective assessment criteria of PAOD. Therefore, as regards the stage of the disease and the life quality of the patient, this parameter has a greater importance. This fact deserves to receive greater attention in everyday clinical practice and when conducting clinical trials. |
package routes
import (
"GopherBlog/constant"
"GopherBlog/controller"
"GopherBlog/middleware"
"GopherBlog/utils"
"github.com/gin-contrib/multitemplate"
"github.com/gin-gonic/gin"
"net/http"
)
// createMyRender 自定义渲染器
func createMyRender() multitemplate.Renderer {
p := multitemplate.NewRenderer()
// 第一个参数用于设置HTML模板渲染的模板名称,可用于HTML函数的第二个参数
// 第二个参数表示模板文件的绝对路径
p.AddFromFiles("admin", "static/admin/index.html")
p.AddFromFiles("front", "static/admin/index.html")
return p
}
// InitRouter 初始化路由
func InitRouter() {
// 设置项目启动模式, debug表示调试模式,test表示测试模式,release表示发布模式(用于生产环境)
gin.SetMode(utils.ServerCfg.AppMode)
r := gin.New()
//r.HTMLRender = createMyRender()
//
r.Use(middleware.Log())
// 当出现panic时会导致程序崩溃退出,该中间件会恢复panic导致的崩溃并返回http code 500
r.Use(gin.Recovery())
// 支持跨域资源共享
r.Use(middleware.Cors())
// 第一个参数是URL路径,第二个参数是静态资源的相对路径, 用于设置访问静态资源的URL
r.Static("/static", "/static/front/static")
r.Static("/admin", "/static/admin")
// 指定某个具体的文件为静态资源, 第一个参数仍然指的是URL路径,第二个是静态资源文件路径
r.StaticFile("/favicon.ico", "/static/front/favicon.ico")
// 用户主页路由
r.GET("/", func(c *gin.Context) {
// 实际上使用的是static/admin/index.html模板文件进行
c.HTML(http.StatusOK, "front", nil)
})
// 后台管理系统主页路由
r.GET("/admin", func(c *gin.Context) {
c.HTML(http.StatusOK, "admin", nil)
})
// 需要鉴权的接口
auth := r.Group("/api/v1")
// 添加JWT中间件
auth.Use(middleware.JwtToken())
{
// 用户模块
auth.GET("/admin/users", controller.GetUserList)
auth.PUT("/admin/reset-password/:id", controller.ChangeUserPassword)
auth.PUT("/users/:id", controller.EditUserInfo)
auth.DELETE("/users/:id", controller.DeleteUser)
// 个人信息模块
auth.GET("/admin/profiles/:id", controller.GetProfileInfo)
auth.PUT("/profiles/:id", controller.UpdateProfileInfo)
// 分类功能
auth.GET("/admin/categories", controller.GetCategoryList)
auth.POST("/categories", controller.AddCategory)
auth.PUT("/categories/:id", controller.EditCategoryInfo)
auth.DELETE("/categories/:id", controller.DeleteCategory)
// 文章模块
auth.GET("/admin/articles/:id", controller.GetArticleInfo)
auth.GET("/admin/articles", controller.GetArticleList)
auth.POST("/articles", controller.AddArticle)
auth.PUT("/articles/:id", controller.EditArticleInfo)
auth.DELETE("/articles/:id", controller.DeleteArticle)
// 评论模块
auth.GET("/admin/comments", controller.GetCommentList)
auth.GET("/admin/articles/:id/comments", controller.GetCommentListByArticleId)
auth.PUT("/comments-status/:id", controller.UpdateCommentStatus)
//auth.PUT("/comments-uncheck/:id", controller.TakeDownComment)
auth.DELETE("/comments/:id", controller.DeleteComment)
}
// 设置路由组,定义无需鉴权的接口
router := r.Group("/api/v1")
{
// 验证token
router.POST("/admin/token-check", controller.CheckToken)
// 登录模块
router.POST("/login", controller.Login)
//router.POST("/login_front", controller.LoginFront)
// 用户信息模块
router.POST("/users", controller.AddUser)
router.GET("/users/:id", controller.GetUserInfo)
router.GET("/users", controller.GetUserList)
// 获取个人信息
router.GET("/profiles/:id", controller.GetProfileInfo)
// 文章分类模块
router.GET("/categories/:id", controller.GetCategoryInfo)
router.GET("/categories", controller.GetCategoryList)
// 文章模块
router.GET("/articles/:id", controller.GetArticleInfo)
router.GET("/articles", controller.GetArticleList)
router.GET("/categories/:id/articles", controller.GetArticleListByCategoryId) // 获取同一分类的所有文章
// 评论模块
router.POST("/comments", controller.AddComment)
router.GET("/comments/:id", controller.GetCommentInfo)
router.GET("/articles/:id/comments-count", controller.GetCommentCount)
router.GET("/articles/:id/comments", controller.GetCommentListByArticleId)
}
// 运行项目
err := r.Run(utils.ServerCfg.HttpPort)
if err != nil {
utils.Logger.Panic(constant.ConvertForLog(constant.StartProjectError), err)
}
}
|
#pragma once
#include <SDL2/SDL.h>
class FallingPoint {
private:
SDL_Renderer* renderer = nullptr;
SDL_Rect box;
int startY;
public:
FallingPoint(
SDL_Renderer* renderer,
int x,
int y,
int size
);
~FallingPoint() {}
void render();
void update();
}; |
Crystal chemistry of synthetic Ca2Al3Si3O12OH–Sr2Al3Si3O12OH solid-solution series of zoisite and clinozoisite
Abstract Coexisting solid-solution series of synthetic zoisite-(Sr) and clinozoisite-(Sr) were synthesized in a 1 M (Ca,Sr)Cl2 solution at 2.0 GPa, 600 °C for 6 days in a piston cylinder press. Solid solutions were synthesized from XSrZo = Sr/(Ca + Sr) = 0.06 to 1 and XSrCzo = 0.08 to 0.5 in zoisite and clinozoisite, respectively. The products were characterized with SEM, EMP, and powder-XRD. Zoisites form crystals up to 30 μm in size. Lattice parameters of zoisite increase linearly with increasing Sr content. For synthetic zoisite-(Sr) lattice parameters are a = 16.3567(5) Å, b = 5.5992(2) Å, c = 10.2612(5) Å, and V = 939.78(7) Å3 in space group Pnma. Volume of clinozoisite (P21/m) increases with increasing XSrCzo, but the lattice parameter a collapses, and b, c, and β have a discontinuity at XSrCzo ≈ 0.25. The decrease in angle β of clinozoisite results in compression of M3 and T3 polyhedra and increase of the A2 polyhedron. A1-O7 distance of 2.12 Å in clinozoisite is extremely short at XSr Czo ≈ 0.25, but with further Sr incorporation on A2 this distance relaxes quickly to 2.24 Å, combined with a torsion of T3. In zoisite, Sr incorporation leads to an opposite movement of neighboring octahedral chains parallel a and causes changes in the linked T3, and angle O5-T3-O6 increases with XSr from 96.3 to 101°. The intra-crystalline distribution of Sr shows that A2 is the favored position and continuous incorporation on A1-position starts above XSrZo ≈ 0.35 for zoisite and above XSrCzo ≈ 0.45 for clinozoisite. |
<filename>hc/http.go
package hc
import (
"bytes"
"crypto/tls"
"fmt"
"github.com/guanaitong/crab/json"
"io"
"mime/multipart"
"net"
"net/http"
u "net/url"
"os"
"strings"
"time"
)
var tr = &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
MaxIdleConns: 200,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: time.Duration(90) * time.Second,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
}
var client = &http.Client{
Timeout: time.Minute * 5, //设置一个最大超时60分钟
Transport: tr, // https insecure
}
func Get(url string, params map[string]interface{}) (*Resp, error) {
var values = make(u.Values)
if params != nil {
for k, v := range params {
values.Set(k, fmt.Sprint(v))
}
}
if len(values) > 0 {
if strings.Contains(url, "?") {
url = url + "&" + values.Encode()
} else {
url = url + "?" + values.Encode()
}
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
return Request(req)
}
func Delete(url string, params map[string]interface{}) (*Resp, error) {
var values = make(u.Values)
if params != nil {
for k, v := range params {
values.Set(k, fmt.Sprint(v))
}
}
if len(values) > 0 {
if strings.Contains(url, "?") {
url = url + "&" + values.Encode()
} else {
url = url + "?" + values.Encode()
}
}
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return nil, err
}
return Request(req)
}
func PostForm(url string, params map[string]interface{}) (*Resp, error) {
var values = make(u.Values)
if params != nil {
for k, v := range params {
values.Set(k, fmt.Sprint(v))
}
}
req, err := http.NewRequest("POST", url, strings.NewReader(values.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return Request(req)
}
func PostFormFile(url string, params map[string]interface{}) (*Resp, error) {
// build params
fieldName, ok := params["FormFile"].(string)
if !ok {
return nil, fmt.Errorf("Not found 'FormFile'")
}
fileName, ok := params["FileName"].(string)
if !ok {
return nil, fmt.Errorf("Not found 'FileName'")
}
// Create buffer
buf := new(bytes.Buffer)
// caveat IMO dont use this for large files
// create a tmpfile and assemble your multipart from there (not tested)
w := multipart.NewWriter(buf)
// Create file field
fw, err := w.CreateFormFile(fieldName, fileName)
if err != nil {
return nil, err
}
fd, err := os.Open(fileName)
if err != nil {
return nil, err
}
if fd != nil {
defer fd.Close()
}
// Write file field from file to upload
_, err = io.Copy(fw, fd)
if err != nil {
return nil, err
}
// required
if w != nil {
w.Close()
}
req, err := http.NewRequest("POST", url, buf)
if err != nil {
return nil, err
}
// Important if you do not close the multipart writer you will not have a
// terminating boundry
req.Header.Set("Content-Type", w.FormDataContentType())
// Auth
if auth, ok := params["Auth"].(map[string]string); ok {
username, _ := auth["username"]
passport, _ := auth["passport"]
req.SetBasicAuth(username, passport)
}
// Headers
if headers, ok := params["Headers"].(map[string]string); ok {
for k, v := range headers {
req.Header.Set(k, v)
}
}
return Request(req)
}
func PostJson(url string, params interface{}) (*Resp, error) {
b, err := json.Marshal(params)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", url, bytes.NewReader(b))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
return Request(req)
}
func Request(request *http.Request) (*Resp, error) {
request.Header.Set("User-Agent", "GAT_GO_HTTP_CLIENT")
response, err := client.Do(request)
if err != nil {
return nil, err
}
return newResp(request, response)
}
|
public class LeetCode074 {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length ==0) return false;
int[] nums = helper(0,matrix.length-1,matrix,target);
if(nums == null) return false;
return helper2(0,nums.length-1,nums,target);
}
private int[] helper(int start, int end, int[][] matrix, int target){
if(start==end) return matrix[start];
if(start>end) return null;
int mid = (start + end)/2;
if(matrix[mid][0] <= target && target < matrix[mid +1][0])
return matrix[mid];
if(matrix[mid][0] > target){
return helper(start, mid -1,matrix,target);
}else{
return helper(mid + 1,end,matrix,target);
}
}
private boolean helper2(int start, int end, int[] nums, int target){
if(start>end) return false;
int mid = (start + end)/2;
if(nums[mid] == target)
return true;
if(nums[mid] > target){
return helper2(start, mid -1,nums,target);
}else{
return helper2(mid + 1,end,nums,target);
}
}
}
|
<reponame>tmarrec/cowboy-engine
#pragma once
#include "../../utils.h"
#include <glad/gl.h>
#include <GLFW/glfw3.h>
#include <memory>
struct glfwDeleter
{
void operator()(GLFWwindow* window);
};
class Window
{
public:
Window();
bool windowShouldClose() const;
void pollEvents();
void swapBuffers();
void windowGetFramebufferSize(uint32_t& width, uint32_t& height);
private:
void windowInit();
static void glfwError(int error, const char* description);
static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
std::unique_ptr<GLFWwindow, glfwDeleter> _glfwWindow = nullptr;
};
|
// Package recovery provides a number of grip-integrated panic
// handling tools for capturing and responding to panics using grip
// loggers.
//
// These handlers are very useful for capturing panic messages that
// might otherwise be lost, as well as providing implementations for
// several established panic handling practices. Nevertheless, this
// assumes that the panic, or an underlying system issue does not
// affect the logging system or its dependencies. For example, panics
// caused by disk-full or out of memory situations are challenging to
// handle with this approach.
//
// All log message are logged with the default standard logger in the
// grip package.
package recovery
import (
"os"
"strings"
"github.com/mongodb/grip"
"github.com/mongodb/grip/message"
)
const killOverrideVarName = "__GRIP_EXIT_OVERRIDE"
// LogStackTraceAndExit captures a panic, captures and logs a stack
// trace at the Emergency level and then exits.
//
// This operation also attempts to close the underlying log sender.
func LogStackTraceAndExit(opDetails ...string) {
if p := recover(); p != nil {
m := message.Fields{
message.FieldsMsgName: "hit panic; exiting",
"panic": panicString(p),
"stack": message.NewStack(1, "").Raw(),
}
if len(opDetails) > 0 {
m["operation"] = strings.Join(opDetails, " ")
}
// check this env var so that we can avoid exiting in the test.
if os.Getenv(killOverrideVarName) == "" {
_ = grip.GetSender().Close()
grip.EmergencyFatal(m)
} else {
grip.Emergency(m)
}
}
}
// LogStackTraceAndContinue recovers from a panic, and then logs the
// captures a stack trace and logs a structured message at "Alert"
// level without further action.
//
// The "opDetails" argument is optional, and is joined as an
// "operation" field in the log message for providing additional
// context.
//
// Use in a common defer statement, such as:
//
// defer recovery.LogStackTraceAndContinue("operation")
//
func LogStackTraceAndContinue(opDetails ...string) {
if p := recover(); p != nil {
m := message.Fields{
message.FieldsMsgName: "hit panic; recovering",
"panic": panicString(p),
"stack": message.NewStack(1, "").Raw(),
}
if len(opDetails) > 0 {
m["operation"] = strings.Join(opDetails, " ")
}
grip.Alert(m)
}
}
// HandlePanicWithError is used to convert a panic to an error.
//
// The "opDetails" argument is optional, and is joined as an
// "operation" field in the log message for providing additional
// context.
//
// You must construct a recovery function as in the following example:
//
// defer func() { err = recovery.HandlePanicWithError(recover(), err, "op") }()
//
// This defer statement must occur in a function that declares a
// default error return value as in:
//
// func operation() (err error) {}
//
func HandlePanicWithError(p interface{}, err error, opDetails ...string) error {
catcher := grip.NewSimpleCatcher()
catcher.Add(err)
if p != nil {
perr := panicError(p)
catcher.Add(perr)
m := message.Fields{
message.FieldsMsgName: "hit panic; adding error",
"stack": message.NewStack(2, "").Raw(),
"panic": perr.Error(),
}
if err != nil {
m["error"] = err.Error()
}
if len(opDetails) > 0 {
m["operation"] = strings.Join(opDetails, " ")
}
grip.Alert(m)
}
return catcher.Resolve()
}
|
by Brian Shilhavy
Health Impact News
In 2013, nursing student Nichole Bruff was dismissed from Baker College in Michigan for allegedly asking questions about the way her instructors were teaching nursing students how to coerce parents into receiving vaccines for their children, even if the children or parents did not want them. Nichole wondered why a patient’s right to choose or refuse a medical procedure was not being followed in administering vaccines. To her, this seemed to violate medical ethical issues she had been taught in nursing school, so she wanted clarification on why vaccines were different when it came to patient rights and ethics.
Is this not part of the American educational process, the right of students to question their instructors?
Shortly before she was due to graduate, she was dismissed from the school without warning, and with no recourse to appeal the dismissal. She soon found out that her dismissal prevented her from being accepted at other nursing schools. Nichole tells Health Impact News:
My dream of being a nurse practitioner of midwifery is gone.
Now, she is fighting back by filing a lawsuit against the school.
A Nursing Student Who Dares to Ask Questions About How to Administer Vaccines
Nichole first reached out to the alternative media with her story in 2013, and told her story anonymously. It was originally published on the VacTruth Facebook Page. We republished it on Health Impact News, since things tend to “disappear” sometimes on Facebook. She told Health Impact News that she was “devastated” at the time, and still is today. Here is how she recounted the events back in 2013 that she believes led to her dismissal:
I am reaching out for assistance. This week I was dismissed from nursing school and I was almost finished. The reason for my dismissal according to the DON, and Dean was harassment of faculty. Apparently discussing vaccines and their unethical approach to teaching us was considered harassment. I only posed questions how the way they were teaching us and how it went against the ANA standards set forth for all nurses. Two weeks ago, 2 different instructors were promoting manipulation and misleading information as a way to coerce parents that deny vaccines into compliance. The first scenario was: Some hospitals require expecting moms and dads to be vaccinated with TDaP before walking into the labor and delivery floor. If significant other is not vaccinated, we the students would be administrating these vaccines. I asked for the rationale behind this. The instructor said this and I quote ” What if you were a new mother and an unvaccinated person came onto the floor carrying pertussis and your newborn contracted it and died.” My response was ” This is a worse case scenario, but vaccinating on the floor doesn’t provide antibodies to pertussis for 6 weeks to 6 months and sometimes not even at all.” I asked how they could promote this when they were giving these families a false sense of security. The instructor ended the conversation and said we would be discussing this more in the coming weeks. The end of our first pediatric clinical, during post conference, the peds instructor brought up that there will be children that are not UTD on their vaccines, we are to get them UTD before discharge. I asked how they expected us to 1. administer vaccines to sick kids when that is contraindicated. Sick kids aren’t supposed to be vaccinated until they are no longer sick. 2. If the parent declines, which most that are not UTD have made that decision for their children, how would you like us to proceed? Her response was that we are to try and educate them on the benefits and get them to comply. Well, this goes against everything that we are taught about ethics, their right to refuse, not to coerce, family-centered care and not pushing our own personal propaganda. This is against ANA standards. It is the job of the nurse to offer, educate and ultimately respect the decision of the patient/parent. That brings me to the last scenario. Our OB instructor, who is a past public health nurse, doing a vaccine speech in peds class. She said and I quote “When a parent refuses, I go in there real sweet and tell them that we have new and important information regarding vaccines. It isn’t really new, it has been around for 20 years but they do not know this.” I raised my hand and asked if this was ethical to mislead parents into thinking there is new info when there really isn’t. 2 weeks later I am dismissed from the program based on harassment of staff during class discussions. I am sick over this. This is my future. With a dismissal I may never be able to apply to any school of nursing. I am being an advocate, like we are taught to be. The DON said at the end of this meeting “We don’t feel comfortable allowing you to complete your education here, take the NCLEX and be responsible for vulnerable patients.” WOW! Each one of my clinical instructors have given me rave evaluations regarding my advocacy skills, going above and beyond etc. My grades are all A’s. I am not 100% against vaccines. I am a mother of 4, and I delay vax and deny some. That is my choice as their mother. If someone questioned my parenting regarding my decision to deny and delay, I would be furious. I just don’t know where to go at the moment. I feel as if my dreams have been crushed because of power hungry women. I challenged their ethics and that is not allowed.
Complaint Filed Against Baker College in Michigan
Nichole Bruff is anonymous no more. She has retained the services of attorney Philip L. Ellison of Outside Legal Counsel PLC, and on April 6, 2015 she filed a complaint against the school in the Circuit Court for the County of Genesee in Michigan.
The nursing instructor she mentioned in the first scenario above, who allegedly instructed the students to require expecting moms and dads to be vaccinated with TDaP before walking into the labor and delivery floor, is named in the complaint as Connie Smith, Assistant Director of Nursing. According to the complaint, Nichole inquired what the rationale was (i.e. what the nursing students are taught to understand as ‘evidence based practice’) behind this expected activity given that it takes anywhere from four weeks to six weeks for an injected DTaP vaccination to begin to become effective against pertussis (i.e. whooping cough).
According to the complaint, Smith replied that this was just the way it went and further stated that the students were to affirmatively misrepresent to patients certain facts about the immunization injection, in case the patient (all new mothers and their partners) were concerned about autism or other medical and ethical concerns as potential side effects of receiving vaccinations.
Nichole then asked why she would be required to misrepresent facts to gain patient compliance when the ethical standards of the nursing profession makes it unethical to lie to gain compliance for suggested medical procedures as being contrary to the legal standard of a patient’s informed consent.
Next, the pediatrics instructor Nichole refers to who allegedly told all the nursing students that all children admitted to the hospital had to be brought up-to-date on their vaccines prior to being discharged, is named in the complaint as Alysia Osoff, also known then as Alysia Gilreath. The discussions of immunizations and vaccinations were initially raised by Osoff as part of the debriefing the students went through after a pediatric clinical experience.
As Nichole noted above, she questioned how sick children could be forced to receive vaccines when vaccine inserts themselves contraindicated the administration of vaccines to children while they are sick. According to the complaints, Osoff told the nursing students that they were to do whatever possible to convince visitors to the pediatrics department at Sparrow Hospital to consent to immunizations and vaccinations, even over the objections of the patient (which could also include the patient’s visitors).
The complaint also claims that Osoff stated and instructed that the students tell patients and their partners that failure to have immunization/vaccination for pertussis could result in the patient having to pay for their entire stay at the hospital, that the state would deny payment coverage, and that those on Medicare (traditionally underprivileged members of the community) would be personally liable to pay for all damages suffered by those in the hospital.
In other words, Osoff was instructing students to wrongfully threaten and panic patients into receiving an immunization to override a patient’s informed consent.
Shortly after questioning these instructors during the course of her instruction, she was dismissed by the school with no recourse to appeal the dismissal.
You can read the entire legal complaint filed against Baker College here.
Ethical and Legal Concerns for Nurses in Michigan: Guilty of Assault and Battery?
According to Nichole’s attorney, Philip L. Ellison:
Obtaining uninformed or false consent for a medical procedure under false pretenses is assault and battery under both criminal and civil law. Under Michigan law, patients have a right to refuse any and all medical treatment, including life saving procedures. The non-consensual touching of another is an unlawful battery. For one person (i.e. a nurse) to have the right to touch or invade the person of another (i.e. a patient), the doctrine of informed consent directs that consent obtained by untruths or misrepresentations is no consent at all. If a nursing student uses fraud, no consent was obtained and thus committed a battery. Such can also be criminal assault and battery. Obtaining uninformed or false consent for a medical procedure under false pretenses is also a violation of the American Nursing Association Code of Ethics for nurses.
As we have previously reported here at Health Impact News, brave nurses all across the United States are taking a stand against medical tyranny regarding vaccines, and we encourage more nurses and nursing students to take a stand against unethical and potentially illegal activities regarding vaccines in their profession.
See:
Ethical and Legal Concerns for Patients: Know Your Rights!
Thanks to the brave efforts of Nichole Bruff, who has sacrificed her a career to stand up for the truth, we have a window to peer through and see how patient rights are routinely abused when it comes to the issue of vaccines and informed consent in the medical profession. This right is under constant assault all across the United States today, as misinformation and coercion is used to promote pharmaceutical products like vaccines, which cannot survive in a true free market. The government has taken away all legal liabilities for pharmaceutical companies, and the only recourse left for patients is informed consent and the right to refuse medical procedures like vaccines. If more people do not take a stand like Nichole has, we may soon lose all of our rights to refuse medical procedures like vaccines.
Comment on this article at VaccineImpact.com
To keep up-to-date on vaccine policies and proposed changes in vaccine laws in your state, sign up for alerts from the National Vaccine Information Center Advocacy Portal:
Medical Doctors Opposed to Forced Vaccinations – Should Their Views be Silenced?
One of the biggest myths being propagated in the compliant mainstream media today is that doctors are either pro-vaccine or anti-vaccine, and that the anti-vaccine doctors are all “quacks.”
However, nothing could be further from the truth in the vaccine debate. Doctors are not unified at all on their positions regarding “the science” of vaccines, nor are they unified in the position of removing informed consent to a medical procedure like vaccines.
The two most extreme positions are those doctors who are 100% against vaccines and do not administer them at all, and those doctors that believe that ALL vaccines are safe and effective for ALL people, ALL the time, by force if necessary.
Very few doctors fall into either of these two extremist positions, and yet it is the extreme pro-vaccine position that is presented by the U.S. Government and mainstream media as being the dominant position of the medical field.
In between these two extreme views, however, is where the vast majority of doctors practicing today would probably categorize their position. Many doctors who consider themselves “pro-vaccine,” for example, do not believe that every single vaccine is appropriate for every single individual.
Many doctors recommend a “delayed” vaccine schedule for some patients, and not always the recommended one-size-fits-all CDC childhood schedule. Other doctors choose to recommend vaccines based on the actual science and merit of each vaccine, recommending some, while determining that others are not worth the risk for children, such as the suspect seasonal flu shot.
These doctors who do not hold extreme positions would be opposed to government-mandated vaccinations and the removal of all parental exemptions.
In this eBook, I am going to summarize the many doctors today who do not take the most extremist pro-vaccine position, which is probably not held by very many doctors at all, in spite of what the pharmaceutical industry, the federal government, and the mainstream media would like the public to believe. |
package cockroach
import (
"context"
"github.com/interuss/dss/pkg/rid/repos"
"github.com/interuss/stacktrace"
)
type GarbageCollector struct {
repos repos.Repository
writer string
}
func NewGarbageCollector(repos repos.Repository, writer string) *GarbageCollector {
return &GarbageCollector{
repos: repos,
writer: writer,
}
}
func (gc *GarbageCollector) DeleteRIDExpiredRecords(ctx context.Context) error {
err := gc.DeleteExpiredISAs(ctx)
if err != nil {
return stacktrace.Propagate(err,
"Failed to delete RID expired records")
}
err = gc.DeleteExpiredSubscriptions(ctx)
if err != nil {
return stacktrace.Propagate(err,
"Failed to delete RID expired records")
}
return nil
}
func (gc *GarbageCollector) DeleteExpiredISAs(ctx context.Context) error {
expiredISAs, err := gc.repos.ListExpiredISAs(ctx, gc.writer)
if err != nil {
return stacktrace.Propagate(err,
"Failed to list expired ISAs")
}
for _, isa := range expiredISAs {
isaOut, err := gc.repos.DeleteISA(ctx, isa)
if isaOut != nil {
return stacktrace.Propagate(err,
"Deleted ISA")
}
if err != nil {
return stacktrace.Propagate(err,
"Failed to delete ISAs")
}
}
return nil
}
func (gc *GarbageCollector) DeleteExpiredSubscriptions(ctx context.Context) error {
expiredSubscriptions, err := gc.repos.ListExpiredSubscriptions(ctx, gc.writer)
if err != nil {
return stacktrace.Propagate(err,
"Failed to list expired Subscriptions")
}
for _, sub := range expiredSubscriptions {
subOut, err := gc.repos.DeleteSubscription(ctx, sub)
if subOut != nil {
return stacktrace.Propagate(err,
"Deleted Subscription")
}
if err != nil {
return stacktrace.Propagate(err,
"Failed to delete Subscription")
}
}
return nil
}
|
// RevokeCertificatePair revokes a certificate pair from the ECA. Not yet implemented.
//
func (ecap *ECAP) RevokeCertificatePair(context.Context, *pb.ECertRevokeReq) (*pb.CAStatus, error) {
ecapLogger.Debug("gRPC ECAP:RevokeCertificate")
return nil, errors.New("ECAP:RevokeCertificate method not (yet) implemented")
} |
<reponame>drewatk/electron-react-boilerplate-typescript
describe('description', () => {
it('should have description', () => {
expect(1 + 2).toBe(3);
const foo: string = 4;
});
});
|
/// Computes the dominance frontiers for all vertices in the graph
///
/// # Warning
/// Unsure of correctness of this implementation
pub fn compute_dominance_frontiers(
&self,
start_index: usize,
) -> Result<HashMap<usize, HashSet<usize>>> {
let mut df: HashMap<usize, HashSet<usize>> = HashMap::new();
for vertex in &self.vertices {
df.insert(*vertex.0, HashSet::new());
}
let idoms = self.compute_immediate_dominators(start_index)?;
for vertex in &self.vertices {
let vertex_index: usize = *vertex.0;
if self.edges_in[&vertex_index].len() >= 2 {
for edge in &self.edges_in[&vertex_index] {
let mut runner = edge.head();
while idoms.contains_key(&edge.head()) && runner != idoms[&edge.head()] {
df.get_mut(&runner).unwrap().insert(vertex_index);
if !idoms.contains_key(&runner) {
break;
}
runner = idoms[&runner];
}
}
}
}
Ok(df)
} |
/**
* @author Mikolaj Izdebski
*/
@ApplicationScoped
public class ModuleDAO {
@Inject
private EntityManager em;
public Module getByName(String name) {
return em.find(Module.class, name);
}
public List<Module> getAll() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Module> criteria = cb.createQuery(Module.class);
Root<Module> module = criteria.from(Module.class);
criteria.select(module).orderBy(cb.asc(module.get(Module_.name)));
return em.createQuery(criteria).getResultList();
}
@Transactional
public void persist(Module module) {
em.persist(module);
}
} |
<filename>src/index.ts
import { useState, useEffect } from "react";
import debounce from "lodash.debounce";
interface Breakpoints {
xs?: 0;
sm: number;
md?: number;
lg: number;
xl?: number;
}
const bootstrapBreakpoints: Breakpoints = {
xs: 0,
sm: 576,
md: 768,
lg: 992,
xl: 1200,
};
interface BreakpointResults {
xs?: boolean;
sm: boolean;
md?: boolean;
lg: boolean;
xl?: boolean;
only: {
xs?: boolean;
sm: boolean;
md?: boolean;
lg: boolean;
xl?: boolean;
};
up: {
xs?: true;
sm: boolean;
md?: boolean;
lg: boolean;
xl?: boolean;
};
down: {
xs?: boolean;
sm: boolean;
md?: boolean;
lg: boolean;
xl?: true;
};
between: {
xs?: {
sm: boolean;
md?: boolean;
lg: boolean;
xl?: true;
};
sm: {
md?: boolean;
lg: boolean;
xl?: boolean;
};
md?: {
lg: boolean;
xl?: boolean;
};
lg?: {
xl: boolean;
};
};
}
/**
* React hook for using window width breakpoints.
* @param {Breakpoints} [breakpoints] - Set of window width breakpoints to be used
* @param {0} [breakpoints.xs] - Lower bound of extra-small window widths, in pixels
* @param {number} breakpoints.sm - Lower bound of small window widths, in pixels
* @param {number} [breakpoints.md] - Lower bound of medium window widths, in pixels
* @param {number} breakpoints.lg - Lower bound of large window widths, in pixels
* @param {number} [breakpoints.xs] - Lower bound of extra-large window widths, in pixels
* @returns {BreakpointResults} A full set of breakpoint queries and their boolean values
*/
export default function useWindowWidthBreakpoints(
breakpoints: Breakpoints = bootstrapBreakpoints
): BreakpointResults {
// Validate breakpoint inputs
if (breakpoints.sm === undefined)
throw new TypeError("sm breakpoint is required.");
if (breakpoints.lg === undefined)
throw new TypeError("lg breakpoint is required.");
if (
(breakpoints.xs !== undefined && typeof breakpoints.xs !== "number") ||
typeof breakpoints.sm !== "number" ||
(breakpoints.md !== undefined && typeof breakpoints.md !== "number") ||
typeof breakpoints.lg !== "number" ||
(breakpoints.xl !== undefined && typeof breakpoints.xl !== "number")
)
throw new TypeError("Breakpoints must be numbers.");
if (!(breakpoints.xs === 0))
if (breakpoints.sm !== 0)
throw new RangeError("Smallest breakpoint must be 0.");
if (breakpoints.xs === 0 && breakpoints.sm <= breakpoints.xs)
throw new RangeError("sm breakpoint must be larger than xs breakpoint.");
if (breakpoints.md !== undefined) {
if (breakpoints.md <= breakpoints.sm)
throw new RangeError("md breakpoint must be larger than sm breakpoint.");
if (breakpoints.lg <= breakpoints.md)
throw new RangeError("lg breakpoint must be larger than md breakpoint.");
} else if (breakpoints.lg <= breakpoints.sm) {
throw new RangeError("lg breakpoint must be larger than sm breakpoint.");
}
if (breakpoints.xl !== undefined && breakpoints.xl <= breakpoints.lg)
throw new RangeError("xl breakpoint must be larger than lg breakpoint.");
// Track window width
const [windowWidth, setWindowWidth] = useState(0);
useEffect(() => {
const handleResize = debounce(
() => setWindowWidth(window.innerWidth),
400,
{ leading: true, trailing: true }
);
handleResize();
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
handleResize.cancel();
};
}, []);
// Determine current breakpoint
let currentBreakpoint: "xs" | "sm" | "md" | "lg" | "xl";
if (breakpoints.xl && windowWidth >= breakpoints.xl) {
currentBreakpoint = "xl";
} else if (windowWidth >= breakpoints.lg) {
currentBreakpoint = "lg";
} else if (breakpoints.md && windowWidth >= breakpoints.md) {
currentBreakpoint = "md";
} else if (windowWidth >= breakpoints.sm) {
currentBreakpoint = "sm";
} else {
currentBreakpoint = "xs";
}
// Return full set of breakpoint queries
return {
...(breakpoints.xs === 0 && { xs: currentBreakpoint === "xs" }),
sm: currentBreakpoint === "sm",
...(breakpoints.md && { md: currentBreakpoint === "md" }),
lg: currentBreakpoint === "lg",
...(breakpoints.xl && { xl: currentBreakpoint === "xl" }),
only: {
...(breakpoints.xs === 0 && { xs: currentBreakpoint === "xs" }),
sm: currentBreakpoint === "sm",
...(breakpoints.md && { md: currentBreakpoint === "md" }),
lg: currentBreakpoint === "lg",
...(breakpoints.xl && { xl: currentBreakpoint === "xl" }),
},
up: {
...(breakpoints.xs === 0 && { xs: true }),
sm: ["sm", "md", "lg", "xl"].includes(currentBreakpoint),
...(breakpoints.md && {
md: ["md", "lg", "xl"].includes(currentBreakpoint),
}),
lg: ["lg", "xl"].includes(currentBreakpoint),
...(breakpoints.xl && { xl: ["xl"].includes(currentBreakpoint) }),
},
down: {
...(breakpoints.xs === 0 && { xs: ["xs"].includes(currentBreakpoint) }),
sm: ["xs", "sm"].includes(currentBreakpoint),
...(breakpoints.md && {
md: ["xs", "sm", "md"].includes(currentBreakpoint),
}),
lg: ["xs", "sm", "md", "lg"].includes(currentBreakpoint),
...(breakpoints.xl && { xl: true }),
},
between: {
...(breakpoints.xs === 0 && {
xs: {
sm: ["xs", "sm"].includes(currentBreakpoint),
...(breakpoints.md && {
md: ["xs", "sm", "md"].includes(currentBreakpoint),
}),
lg: ["xs", "sm", "md", "lg"].includes(currentBreakpoint),
...(breakpoints.xl && { xl: true }),
},
}),
sm: {
...(breakpoints.md && { md: ["sm", "md"].includes(currentBreakpoint) }),
lg: ["sm", "md", "lg"].includes(currentBreakpoint),
...(breakpoints.xl && {
xl: ["sm", "md", "lg", "xl"].includes(currentBreakpoint),
}),
},
...(breakpoints.md && {
md: {
lg: ["md", "lg"].includes(currentBreakpoint),
...(breakpoints.xl && {
xl: ["md", "lg", "xl"].includes(currentBreakpoint),
}),
},
}),
...(breakpoints.xl && {
lg: {
xl: ["lg", "xl"].includes(currentBreakpoint),
},
}),
},
};
}
|
package sql2struct
import (
"os"
"strings"
"testing"
"gopkg.in/go-playground/assert.v1"
)
var sql = `
CREATE TABLE rg_user (
id SERIAL PRIMARY KEY NOT NULL,
identity_id VARCHAR(18) UNIQUE NOT NULL,
phone VARCHAR(12) UNIQUE NOT NULL,
email VARCHAR(50) NOT NULL,
name VARCHAR(20) NOT NULL,
passwd VARCHAR(50) NOT NULL,
role INTEGER NOT NULL, -- 32位的bit用来表示角色
last_login TIMESTAMP -- something
);
CREATE TABLE exam_type (
id SERIAL PRIMARY KEY NOT NULL ,
category VARCHAR(50) UNIQUE NOT NULL
);
INSERT INTO exam_type (category)
VALUES ('统考'), ('省考'), ('英语听说'), ('毕业论文'), ('实践性环节');
`
func Test_MatchStmt(t *testing.T) {
blocks := matchStmt(strings.NewReader(sql))
for i := range blocks {
t := handleStmtBlock(blocks[i])
t.GenType(os.Stdout)
}
}
func Test_camelTohun(t *testing.T) {
str := "aaaaBcccDeeeBB"
nstr := camelTohun([]byte(str))
expect := "aaaa_bccc_deee_bb"
assert.Equal(t, nstr, expect)
}
|
It’s the campaign scenario that keeps partisan operatives and lawyers awake at night: Donald Trump and Hillary Clinton end Election Day deadlocked with key states in a recount, and a short-handed Supreme Court can't resolve the matter because the eight justices split down the middle.
In such a case, a lower-court ruling would probably be left to stand, and the decision would carry even less authority than Bush v. Gore, the high court’s widely criticized 5-4 ruling resolving the 2000 presidential election.
Story Continued Below
With Trump and Clinton concluding one of the most toxic presidential campaigns in modern history, amid charges of foreign influence and "rigged" procedures, the lack of a fully functioning Supreme Court to act as a legal backstop is worrisome to some operatives on both sides.
“There’s a hell of a scary thought,” said Jim Manley, a longtime Democratic staffer. “I’m not sure the country can handle that right now.”
“This would not be a good moment for the Supreme Court to have to deal with a partisan dispute,” added Trevor Potter, a veteran Republican attorney and former chairman at the Federal Election Commission.
To date, the Supreme Court has managed to withstand the political maelstrom of the 2016 election by staying out of it. But it’s been called upon to resolve highly charged partisan disputes in just the last few days.
On Monday, a unanimous court dismissed a last-minute Democratic plea to reinstate an injunction that would have blocked Trump’s campaign and its allies from taking actions that would allegedly intimidate voters in Ohio. That ruling came right on the heels of a Saturday order reinstating an Arizona law banning the collection of independent ballots.
Both of those high court moves favored Republicans, and court watchers noted the rulings — both issued without recorded dissent — reflected the eight sitting justices’ attempts to keep themselves out of direct fire in an already venomous presidential campaign.
But while a lay-low approach can work in cases involving the kinds of voting questions that matter before Election Day, it may not work so easily if there are any legal disputes stemming from Tuesday, especially on issues involving recounts or other voting disputes where the overall results are close and battleground states like Florida or North Carolina are still up for grabs.
“It’ll be the first thing people think if there’s a contested election,” Potter said.
And there’s reason to see the courts coming into play. Trump’s real estate and business career are coursed with litigation and the Republican has run his presidential campaign alleging everything from voter fraud to widespread “rigging” by the political establishment and the media.
“It does seem if Trump loses there’s going to be challenges to the voting results. When you spend all your time saying the results are rigged you’ve got to expect there are lawsuits challenging results,” said Adam Winkler, a UCLA constitutional law professor.
It’s also apparent to the campaigns that a short-handed Supreme Court would be a key consideration in any post-election legal strategies. After all, any decisions where the high court splits 4-4 would mean that the underlying ruling stands. That means the federal appeals courts or state supreme courts could wind up being the final arbiters in deciding who wins the White House.
“It absolutely raises the stakes in the federal circuit courts and the state court systems when you don’t have a fully staffed Supreme Court,” said Alicia Bannon of the liberal Brennan Center at New York University.
This is also the scenario that would “increase the possibility of strategic litigation,” Potter said.
“What litigants would do is bring their claims according to which court they think is likely to be more favorable to them,” added Dan Tokaji, a professor of election law at Ohio State University. “If you’re a Democratic lawyer and you’re in a jurisdiction with an unfriendly state supreme court you could try to head towards the circuit court by framing a claim under federal law. And vice versa for Republican lawyers.”
So how would these kinds of cases break down? Democrats would have an advantage in many of the federal appeals courts, where their party’s appointees hold majorities in eight of the 12 geographic circuits. Democratic appointees seem especially likely to carry the day in federal court decisions in battleground states like North Carolina, part of the 4th Circuit, and Florida, part of the 11th.
However, federal courts might not be friendly to Democrats in an election-related fight emerging in Ohio or Michigan. Those states are part of the 6th Circuit, where Republican nominees outnumber Democrats, 10-5.
“Imagine a disputed outcome in Ohio or Michigan, followed by a 6th Circuit decision that determined the winner with the Supreme Court paralyzed,” said Stephen Gillers, an NYU law professor.
By and large, Republicans are in better shape in state supreme courts, where conservative activists have been making efforts in recent years to get friendly judges appointed and elected. Several of the key swing states have high courts that lean to the GOP.
The Florida Supreme Court, for example, has four Republican appointees, two Democratic appointees and one justice who got nods from governors of both parties. North Carolina’s Supreme Court, which is in the midst of a hotly contest election itself, has four GOP justices to three Democrats. Ohio’s high court has six GOP justices and just one Democrat.
”Republicans and conservative groups have really prioritized state supreme courts,” said Bannon. Most of the effort seems to have been directed at obtaining rulings that rein in personal-injury lawsuits and give GOP-led legislatures wide latitude in setting the boundaries of congressional districts, she said.
“The specific potential of the courts to decide a presidential election—I don’t think that’s been the main focus of any of these groups,” Bannon added.
Experts say judges of both parties tend to vote along party lines in election-related cases, but Republicans are more likely to favor the GOP than Democrats are to favor their fellow partisans. The association gets stronger when they’re elected judges who’ve gotten large sums campaign donations.
“Bush v. Gore is a very famous election case but these happen all the time in state supreme courts, typically for less important offices,” said Emory law professor Joanna Shepherd. “If a Republican is slightly more likely to favor Republican litigants in a contested election situation . . . money seems to make it worse.”
Critics point out the current eight-member U.S. Supreme Court has had an easier time with less thorny topics since the February death of Justice Antonin Scalia, creating a vacancy prolonged by the subsequent Senate GOP blockade against President Barack Obama’s replacement nominee, Merrick Garland. But there’s little doubt the court has struggled since Scalia’s death when it’s handled the tough stuff like immigration and birth control.
The eight remaining justices have tried to varying degrees to skirt the 4-4 issue. “We will deal with it,” Justice Samuel Alito said shortly after Scalia’s death in February. But Justice Ruth Bader Ginsburg earlier this summer said eight justices “was not good enough” for handling cases involving politically charged issues like immigration.
Justice Stephen Breyer, asked directly last month during an appearance on MSNBC about how the court would handle any election-related cases, first tried to explain just how infrequent a split ruling comes down. “Half of our cases are unanimous,” Breyer said.
Pressed on whether he was concerned about a split court being forced to weigh in on the 2016 election, Breyer replied, “When you say ‘not concerned,’ I’m trying to give you a picture. There were about four or five cases, depending on how you count, maybe four or five out of 70 to 75 cases during the year where the court did split 4-4.”
No doubt, the very notion that the Supreme Court could be forced into the election would be mired in politics. Whoever is the next president will get to decide whether Garland’s nomination should be resubmitted. And even the sitting justices have gotten in hot water when talking about the presidential campaign.
Ginsberg earlier this year slammed Trump for not releasing his tax returns, calling the GOP nominee a “faker” with “no consistency about him.” While she later apologized, Trump has taken issue with the justice’s remarks. On Twitter he wrote that the liberal judge had “embarrassed all by making very dump political statements about me. Her mind is shot — resign!”
Several longtime Supreme Court watchers shrugged off concern that the justices would even have to deal with election questions. Ilya Somin, a George Mason law professor, said there’s a “low probability” the Supreme Court would be a final arbiter in the 2016 campaign.
“But if it does happen,” he warned, “it surely won’t be good.” |
<reponame>thomasboyt/Vim
import * as vscode from 'vscode';
import * as _ from 'lodash';
import { ModeName } from './mode';
import { ModeHandler, VimState } from './modeHandler';
interface IKeybinding {
before: string[];
after : string[];
}
class Remapper {
private _mostRecentKeys: string[] = [];
private _remappings: IKeybinding[] = [];
private _isInsertModeRemapping = false;
constructor(configKey: string, insertModeRemapping = false) {
this._isInsertModeRemapping = insertModeRemapping;
this._remappings = vscode.workspace.getConfiguration('vim')
.get<IKeybinding[]>(configKey, []);
}
private _longestKeySequence(): number {
if (this._remappings.length > 0) {
return _.maxBy(this._remappings, map => map.before.length).before.length;
} else {
return 1;
}
}
public async sendKey(key: string, modeHandler: ModeHandler, vimState: VimState): Promise<boolean> {
if ((vimState.currentMode === ModeName.Insert && !this._isInsertModeRemapping) ||
(vimState.currentMode !== ModeName.Insert && this._isInsertModeRemapping)) {
this._reset();
return false;
}
const longestKeySequence = this._longestKeySequence();
this._mostRecentKeys.push(key);
this._mostRecentKeys = this._mostRecentKeys.slice(-longestKeySequence);
for (let sliceLength = 1; sliceLength <= longestKeySequence; sliceLength++) {
const slice = this._mostRecentKeys.slice(-sliceLength);
const remapping = _.find(this._remappings, map => map.before.join("") === slice.join(""));
if (remapping) {
if (this._isInsertModeRemapping) {
vimState.historyTracker.undoAndRemoveChanges(this._mostRecentKeys.length);
}
await modeHandler.handleMultipleKeyEvents(remapping.after);
this._mostRecentKeys = [];
return true;
}
}
return false;
}
private _reset(): void {
this._mostRecentKeys = [];
}
}
export class InsertModeRemapper extends Remapper {
constructor() {
super("insertModeKeyBindings", true);
}
}
export class OtherModesRemapper extends Remapper {
constructor() {
super("otherModesKeyBindings", false);
}
} |
/**
* Copyright 2016 <NAME>
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* 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 com.palantir.atlasdb.keyvalue.cassandra;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.cassandra.thrift.Cassandra;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.palantir.atlasdb.cassandra.CassandraKeyValueServiceConfig;
import com.palantir.common.base.FunctionCheckedException;
public class CassandraClientPoolTest {
public static final int POOL_REFRESH_INTERVAL_SECONDS = 10;
public static final int DEFAULT_PORT = 5000;
public static final int OTHER_PORT = 6000;
public static final String HOSTNAME_1 = "1.0.0.0";
public static final String HOSTNAME_2 = "2.0.0.0";
public static final String HOSTNAME_3 = "3.0.0.0";
@Test
public void shouldReturnAddressForSingleHostInPool() throws UnknownHostException {
InetSocketAddress host = new InetSocketAddress(HOSTNAME_1, DEFAULT_PORT);
CassandraClientPool cassandraClientPool = clientPoolWithServersInCurrentPool(ImmutableSet.of(host));
InetSocketAddress resolvedHost = cassandraClientPool.getAddressForHost(HOSTNAME_1);
assertThat(resolvedHost, equalTo(host));
}
@Test
public void shouldReturnAddressForSingleServer() throws UnknownHostException {
InetSocketAddress host = new InetSocketAddress(HOSTNAME_1, DEFAULT_PORT);
CassandraClientPool cassandraClientPool = clientPoolWithServers(ImmutableSet.of(host));
InetSocketAddress resolvedHost = cassandraClientPool.getAddressForHost(HOSTNAME_1);
assertThat(resolvedHost, equalTo(host));
}
@Test
public void shouldUseCommonPortIfThereIsOnlyOneAndNoAddressMatches() throws UnknownHostException {
InetSocketAddress host1 = new InetSocketAddress(HOSTNAME_1, DEFAULT_PORT);
InetSocketAddress host2 = new InetSocketAddress(HOSTNAME_2, DEFAULT_PORT);
CassandraClientPool cassandraClientPool = clientPoolWithServers(ImmutableSet.of(host1, host2));
InetSocketAddress resolvedHost = cassandraClientPool.getAddressForHost(HOSTNAME_3);
assertThat(resolvedHost, equalTo(new InetSocketAddress(HOSTNAME_3, DEFAULT_PORT)));
}
@Test(expected = UnknownHostException.class)
public void shouldThrowIfPortsAreNotTheSameAddressDoesNotMatch() throws UnknownHostException {
InetSocketAddress host1 = new InetSocketAddress(HOSTNAME_1, DEFAULT_PORT);
InetSocketAddress host2 = new InetSocketAddress(HOSTNAME_2, OTHER_PORT);
CassandraClientPool cassandraClientPool = clientPoolWithServers(ImmutableSet.of(host1, host2));
cassandraClientPool.getAddressForHost(HOSTNAME_3);
}
@Test
public void shouldReturnAbsentIfPredicateMatchesNoServers() {
InetSocketAddress host = new InetSocketAddress(HOSTNAME_1, DEFAULT_PORT);
CassandraClientPool cassandraClientPool = clientPoolWithServersInCurrentPool(ImmutableSet.of(host));
Optional<CassandraClientPoolingContainer> container
= cassandraClientPool.getRandomGoodHostForPredicate(address -> false);
assertThat(container.isPresent(), is(false));
}
@Test
public void shouldOnlyReturnHostsMatchingPredicate() {
InetSocketAddress host1 = new InetSocketAddress(HOSTNAME_1, DEFAULT_PORT);
InetSocketAddress host2 = new InetSocketAddress(HOSTNAME_2, DEFAULT_PORT);
CassandraClientPool cassandraClientPool = clientPoolWithServersInCurrentPool(ImmutableSet.of(host1, host2));
int numTrials = 50;
for (int i = 0; i < numTrials; i++) {
Optional<CassandraClientPoolingContainer> container
= cassandraClientPool.getRandomGoodHostForPredicate(address -> address.equals(host1));
assertThat(container.isPresent(), is(true));
assertThat(container.get().getHost(), equalTo(host1));
}
}
@Test
public void shouldNotReturnHostsNotMatchingPredicateEvenWithNodeFailure() {
InetSocketAddress host1 = new InetSocketAddress(HOSTNAME_1, DEFAULT_PORT);
InetSocketAddress host2 = new InetSocketAddress(HOSTNAME_2, DEFAULT_PORT);
CassandraClientPool cassandraClientPool = clientPoolWithServersInCurrentPool(ImmutableSet.of(host1, host2));
cassandraClientPool.blacklistedHosts.put(host1, System.currentTimeMillis());
Optional<CassandraClientPoolingContainer> container
= cassandraClientPool.getRandomGoodHostForPredicate(address -> address.equals(host1));
assertThat(container.isPresent(), is(true));
assertThat(container.get().getHost(), equalTo(host1));
}
@Test
public void shouldNotAttemptMoreThanOneConnectionOnSuccess() {
InetSocketAddress host = new InetSocketAddress(HOSTNAME_1, DEFAULT_PORT);
CassandraClientPool cassandraClientPool = clientPoolWithServersInCurrentPool(ImmutableSet.of(host));
cassandraClientPool.runWithRetryOnHost(host, input -> null);
verifyNumberOfAttemptsOnHost(host, cassandraClientPool, 1);
}
@Test
public void shouldRetryOnSameNodeToFailureAndThenRedirect() {
int numHosts = CassandraClientPool.MAX_TRIES_TOTAL - CassandraClientPool.MAX_TRIES_SAME_HOST + 1;
List<InetSocketAddress> hostList = Lists.newArrayList();
for (int i = 0; i < numHosts; i++) {
hostList.add(new InetSocketAddress(i));
}
CassandraClientPool cassandraClientPool = throwingClientPoolWithServersInCurrentPool(
ImmutableSet.copyOf(hostList), new SocketTimeoutException());
try {
cassandraClientPool.runWithRetryOnHost(hostList.get(0), input -> null);
fail();
} catch (Exception e) {
// expected, keep going
}
verifyNumberOfAttemptsOnHost(hostList.get(0), cassandraClientPool, CassandraClientPool.MAX_TRIES_SAME_HOST);
for (int i = 1; i < numHosts; i++) {
verifyNumberOfAttemptsOnHost(hostList.get(i), cassandraClientPool, 1);
}
}
@Test
public void shouldKeepRetryingIfNowhereToRedirectTo() {
InetSocketAddress host = new InetSocketAddress(HOSTNAME_1, DEFAULT_PORT);
CassandraClientPool cassandraClientPool = throwingClientPoolWithServersInCurrentPool(
ImmutableSet.of(host), new SocketTimeoutException());
try {
cassandraClientPool.runWithRetryOnHost(host, input -> null);
fail();
} catch (Exception e) {
// expected, keep going
}
verifyNumberOfAttemptsOnHost(host, cassandraClientPool, CassandraClientPool.MAX_TRIES_TOTAL);
}
private void verifyNumberOfAttemptsOnHost(InetSocketAddress host,
CassandraClientPool cassandraClientPool,
int numAttempts) {
Mockito.verify(cassandraClientPool.currentPools.get(host), Mockito.times(numAttempts)).runWithPooledResource(
Mockito.<FunctionCheckedException<Cassandra.Client, Object, RuntimeException>>any()
);
}
private CassandraClientPool clientPoolWithServers(ImmutableSet<InetSocketAddress> servers) {
return clientPoolWith(servers, ImmutableSet.of(), Optional.empty());
}
private CassandraClientPool clientPoolWithServersInCurrentPool(ImmutableSet<InetSocketAddress> servers) {
return clientPoolWith(ImmutableSet.of(), servers, Optional.empty());
}
private CassandraClientPool throwingClientPoolWithServersInCurrentPool(ImmutableSet<InetSocketAddress> servers,
Exception exception) {
return clientPoolWith(ImmutableSet.of(), servers, Optional.of(exception));
}
private CassandraClientPool clientPoolWith(
ImmutableSet<InetSocketAddress> servers,
ImmutableSet<InetSocketAddress> serversInPool,
Optional<Exception> failureMode) {
CassandraKeyValueServiceConfig config = mock(CassandraKeyValueServiceConfig.class);
when(config.poolRefreshIntervalSeconds()).thenReturn(POOL_REFRESH_INTERVAL_SECONDS);
when(config.servers()).thenReturn(servers);
CassandraClientPool cassandraClientPool = CassandraClientPool.createWithoutChecksForTesting(config);
cassandraClientPool.currentPools = serversInPool.stream()
.collect(Collectors.toMap(Function.identity(),
address -> getMockPoolingContainerForHost(address, failureMode)));
return cassandraClientPool;
}
private CassandraClientPoolingContainer getMockPoolingContainerForHost(InetSocketAddress address,
Optional<Exception> failureMode) {
CassandraClientPoolingContainer poolingContainer = mock(CassandraClientPoolingContainer.class);
when(poolingContainer.getHost()).thenReturn(address);
if (failureMode.isPresent()) {
try {
when(poolingContainer.runWithPooledResource(
Mockito.<FunctionCheckedException<Cassandra.Client, Object, Exception>>any()))
.thenThrow(failureMode.get());
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
return poolingContainer;
}
}
|
Electronic-nose for plant health monitoring in a closed environment system
With the net zero carbon emissions target by 2050, in the agricultural sector, it is essential to employ technologies to reduce the consumption of energy and resources while enhancing the yield of crops. Learning about how measurable signals can indicate the growth status of various plants will be beneficial for designing plant health monitoring systems (PHMSs) that can be used around the globe for the efficient growth of plants. In this work, we have designed and employed an array of gas sensors, acting as an electronic nose, to monitor the health status of lettuce being grown in a chamber by measuring the emission and consumption of various gases and volatile organic compounds (VOCs). While emission of ethylene is a strong indicator, we have found that accurate concentration measurements of CO2 and alcohols can also be used to assess the health status of the plant at its different stages of growth, particularly at the seedling and vegetative stages. ~20% change in the alcohol concentration and more than 2 folds increase in the equivalent CO2 level was observed when brown leaves started growing before the plant died. The results of the studies can help to design a simple PHMS that can help grow vegetables at a high yield with minimum supervision |
dp = [1] + [0]*300
for c in range(1,18):
for i in range(301-c**2):
dp[i+c**2] += dp[i]
while 1:
n = input()
if n == 0: break
print dp[n] |
/**
* A utility class for iterating through a posting list of a given term and
* retrieving the payload of the first occurrence in every document. Comes with
* its own working space (buffer).
*
* @lucene.experimental
*/
public class PayloadIterator {
protected byte[] buffer;
protected int payloadLength;
TermPositions tp;
private boolean hasMore;
public PayloadIterator(IndexReader indexReader, Term term)
throws IOException {
this(indexReader, term, new byte[1024]);
}
public PayloadIterator(IndexReader indexReader, Term term, byte[] buffer)
throws IOException {
this.buffer = buffer;
this.tp = indexReader.termPositions(term);
}
/**
* (re)initialize the iterator. Should be done before the first call to
* {@link #setdoc(int)}. Returns false if there is no category list found
* (no setdoc() will never return true).
*/
public boolean init() throws IOException {
hasMore = tp.next();
return hasMore;
}
/**
* Skip forward to document docId. Return true if this document exists and
* has any payload.
* <P>
* Users should call this method with increasing docIds, and implementations
* can assume that this is the case.
*/
public boolean setdoc(int docId) throws IOException {
if (!hasMore) {
return false;
}
if (tp.doc() > docId) {
return false;
}
// making sure we have the requested document
if (tp.doc() < docId) {
// Skipping to requested document
if (!tp.skipTo(docId)) {
this.hasMore = false;
return false;
}
// If document not found (skipped to much)
if (tp.doc() != docId) {
return false;
}
}
// Prepare for payload extraction
tp.nextPosition();
this.payloadLength = tp.getPayloadLength();
if (this.payloadLength == 0) {
return false;
}
if (this.payloadLength > this.buffer.length) {
// Growing if necessary.
this.buffer = new byte[this.payloadLength * 2 + 1];
}
// Loading the payload
tp.getPayload(this.buffer, 0);
return true;
}
/**
* Get the buffer with the content of the last read payload.
*/
public byte[] getBuffer() {
return buffer;
}
/**
* Get the length of the last read payload.
*/
public int getPayloadLength() {
return payloadLength;
}
} |
// TestCollectionMinReplFactDeprecatedClusterInv tests if minReplicationFactor is forwarded to ClusterInfo
func TestCollectionMinReplFactDeprecatedClusterInv(t *testing.T) {
c := createClientFromEnv(t, true)
version := skipBelowVersion(c, "3.5", t)
skipNoCluster(c, t)
db := ensureDatabase(nil, c, "collection_min_repl_test", nil, t)
name := "test_min_repl_cluster_invent"
minRepl := 2
ensureCollection(nil, db, name, &driver.CreateCollectionOptions{
ReplicationFactor: minRepl,
MinReplicationFactor: minRepl,
}, t)
cc, err := c.Cluster(nil)
if err != nil {
t.Fatalf("Failed to get Cluster: %s", describe(err))
}
inv, err := cc.DatabaseInventory(nil, db)
if err != nil {
t.Fatalf("Failed to get Database Inventory: %s", describe(err))
}
col, found := inv.CollectionByName(name)
if !found {
t.Fatalf("Failed to get find collection: %s", describe(err))
}
if col.Parameters.MinReplicationFactor != minRepl {
t.Errorf("Collection does not have the correct min replication factor value, expected `%d`, found `%d`",
minRepl, col.Parameters.MinReplicationFactor)
}
if version.Version.CompareTo("3.6") >= 0 {
if col.Parameters.WriteConcern != minRepl {
t.Errorf("Collection does not have the correct WriteConcern value, expected `%d`, found `%d`",
minRepl, col.Parameters.WriteConcern)
}
}
} |
import ServerNode from "../ServerNode";
import {saveAs} from 'file-saver';
import NodeParameter from "../../core/NodeParameter";
export default class DownloadCSV extends ServerNode {
save = saveAs
constructor(options = {}) {
super({
// Defaults
name: 'DownloadCSV',
summary: 'Download features as CSV',
category: 'Workflow',
defaultInPorts: ['Input'],
defaultOutPorts: ['Output'],
// Explicitly configured
...options,
})
}
async run() {
const filename = this.getParameterValue('filename')
const separator = ' '
const headers = Object.keys(this.input().find(first => true).original).join(separator)
const rows = this.input().map(feature => {
return Object.values(feature.original).join(separator)
})
const csv = [
headers,
...rows
].join('\n')
// @ts-ignore: By adding 'dom' to tsconfig lib Blob IS accessible here
var blob = new Blob([csv], {type: "text/plain;charset=utf-8"});
this.save(blob, filename);
}
getParameters() {
return [
...super.getParameters(),
NodeParameter.string('filename').withValue('data.csv'),
]
}
} |
Now playing: Watch this: 900 million Android devices harbor security flaws
Four newly-discovered vulnerabilities found in Android phones and tablets that ship with a Qualcomm chip could allow an attacker to take complete control of an affected device.
The set of vulnerabilities, dubbed "Quadrooter," affects over 900 million phone and tablets, according to Check Point researchers who discovered the flaws.
An attacker would have to trick a user into installing a malicious app, which wouldn't require any special permissions.
If successfully exploited, an attacker can gain root access, which gives the attacker full access to an affected Android device, its data, and its hardware -- including its camera and microphone.
Google's own branded Nexus 5X, Nexus 6, and Nexus 6P devices are affected, as are Samsung's Galaxy S7 and S7 Edge, to name just a few of the models in question. The recently-announced BlackBerry DTEK50, which the company touts as the "most secure Android smartphone," is also vulnerable to one of the flaws.
A patch that will fix one of the flaws will not be widely released until September, a Google spokesperson confirmed.
You can read more of this story on our sister site ZDNet. |
<reponame>olanaso/sunat-jaxb
package io.github.carlosthe19916.beans;
import io.github.carlosthe19916.beans.ubl.ubl20.Invoice20Bean;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Calendar;
public class InvoiceBeanBuilderTest {
// @Test
// public void testBuilder() {
// Invoice20Bean invoiceBean = InvoiceBeanBuilder.InvoiceBean()
// .serie("F001")
// .numero(1)
// .codigoTipoComprobante("01")
// .observaciones("Sin observaciones")
// .fecha(
// FechaBeanBuilder.FechaBean()
// .fechaEmision(Calendar.getInstance().getTime())
// .fechaVencimiento(Calendar.getInstance().getTime())
// .build()
// )
// .firmante(
// AbstractMonedaBeanBuilder.builder()
// .codigo("PEN")
// .tipoCambio(new BigDecimal("3.21"))
// .build()
// )
// .firmante(
// ImpuestosBeanBuilder.Impuestos()
// .igv(new BigDecimal("10"))
// .isc(new BigDecimal("1"))
// .build()
// )
// .total(
// TotalBeanBuilder.Total()
// .pagar(new BigDecimal("5"))
// .descuentoGlobal(new BigDecimal("6"))
// .otrosCargos(new BigDecimal("5"))
// .build()
// )
// .totalInformacionAdicional(
// TotalInformacionAdicionalBeanBuilder.TotalInformacionAdicionalBean()
// .gravado(BigDecimal.ZERO)
// .inafecto(BigDecimal.ZERO)
// .exonerado(BigDecimal.ZERO)
// .gratuito(BigDecimal.ZERO)
// .build()
// )
// .proveedor(
// ProveedorBeanBuilder.ProveedorBean()
// .codigoTipoDocumento("6")
// .numeroDocumento("10467793549")
// .nombreComercial("Wolsnut4 S.A.")
// .razonSocial("Wolsnut4 Consultores")
// .codigoPostal("050101")
// .direccion("Jr. ayacucho 123")
// .region("Ayacucho")
// .provincia("Huamanga")
// .distrito("Jesus Nazareno")
// .codigoPais("PE")
// .build()
// )
// .cliente(
// ClienteBeanBuilder.ClienteBean()
// .codigoTipoDocumento("3")
// .numeroDocumento("46779354")
// .nombre("<NAME>")
// .email("<EMAIL>")
// .direccion("Jr. carlos 997")
// .build()
// )
// .build();
//
// Assert.assertNotNull(invoiceBean);
// Assert.assertEquals(invoiceBean.getSerie(), "F001");
// Assert.assertEquals(invoiceBean.getNumero(), Integer.valueOf(1));
// Assert.assertEquals(invoiceBean.getTipoDocumento(), "01");
// Assert.assertEquals(invoiceBean.getObservaciones(), "Sin observaciones");
// Assert.assertNotNull(invoiceBean.getFecha());
// Assert.assertNotNull(invoiceBean.getMoneda());
// Assert.assertNotNull(invoiceBean.getImpuestos());
// Assert.assertNotNull(invoiceBean.getTotal());
// Assert.assertNotNull(invoiceBean.getTotalInformacionAdicional());
// Assert.assertNotNull(invoiceBean.getProveedor());
// Assert.assertNotNull(invoiceBean.getCliente());
// }
}
|
def OnRanButton(self, evt):
childRandomPull = randint(1,(len(childIDList)-1))
ranChild = childIDList[childRandomPull]
dlg = wx.MessageDialog(self,
ranChild,'Observe This Child:',wx.OK
)
dlg.ShowModal()
dlg.Destroy() |
CM Punk may not have had the performance of a lifetime at UFC 203, but he still got paid like a star. The former WWE superstar cashed a flat $500,000 purse for his mixed martial arts debut, which he lost via first-round rear-naked choke to Mickey Gall at UFC 203, according to figures released by the Ohio Athletic Commission to MMA Fighting on Monday.
Punk, 37, signed with the UFC with no martial arts background in Dec. 2014 following an enormously successful run as a professional wrestler with WWE. He trained for nearly two years at Roufusport to prepare for his UFC debut, but ultimately lost a lopsided match to the 24-year-old Gall, who earned $30,000 in victory. It is also worth noting that Punk's salary was a flat $500,000 fee, meaning he wouldn't have received a win bonus had he defeated Gall.
UFC 203 took place Sept. 10 at the Quicken Loans Arena in Cleveland, Ohio. The night's main card aired live on pay-per-view.
Aside from Punk, five other fighters on the card hit the six-figure mark in earnings, including heavyweight headliners Stipe Miocic and Alistair Overeem. Miocic cashed a flat $600,000 purse for his first-round knockout victory over Overeem ($800,000) to successfully defend his UFC heavyweight title for the first time in front of his hometown Cleveland crowd.
In addition to their commission-reported salaries, Miocic, Overeem, Jessica Andrade, and Yancy Medeiros also took home $50,000 fight night bonuses for their performances.
A complete list of the UFC 203 salaries can be seen below. As always, these figures do not represent a fighter's total earnings, as certain sponsorship incomes, pay-per-view bonuses, or discretionary post-fight bonuses are not publicly disclosed.
Main Card (Pay-per-view)
Stipe Miocic ($600,000 + no win bonus = $600,000) def. Alistair Overeem ($800,000)
Fabricio Werdum ($250,000 + $125,000 = $375,000) def. Travis Browne ($120,000)
Mickey Gall ($15,000 + $15,000 = $30,000) def. CM Punk ($500,000)
Jimmie Rivera ($24,000 + $24,000 = $48,000) def. Urijah Faber ($160,000)
Jessica Andrade ($23,000 + $23,000 = $46,000) def. Joanne Calderwood ($25,000)
Preliminary Card (FOX Sports 1)
Bethe Correia ($25,000 + $25,000 = $50,000) def. Jessica Eye ($25,000)
Brad Tavares ($28,000 + $28,000 = $56,000) def. Caio Magalhaes ($20,000)
Nik Lentz ($38,000 + $38,000 = $76,000) def. Michael McBride ($12,000)
Drew Dober ($19,000 + $19,000 = $38,000) def. Jason Gonzales ($10,000)
Preliminary Card (UFC Fight Pass)
Yancy Medeiros ($24,000 + $24,000 = $48,000) def. Sean Spencer ($17,000) |
SHRIKANT GANPAT Shirsat, an independent candidate who contested the Brihanmumbai Municipal Corporation (BMC) polls, made a sensational claim after the results were declared on February 23. Alleging tampering of electronic voting machines (EVMs), the 34-year-old claimed that he did not get a single vote from his own polling booth even though he had voted for himself, and demanded a repoll.
Advertising
Over the last two months, Shirsat’s claim was quoted by political parties to level allegations of EVM hacking in the assembly elections of UP, Uttarakhand and Punjab. It was also the inspiration behind AAP’s live demonstration of hacking an EVM prototype in the Delhi Assembly on Tuesday.
But Shirsat’s claim doesn’t match the facts.
Speaking to The Indian Express on Thursday, Maharashtra’s Deputy Election Commissioner Avinash T Sanas said, “He (Shirsat) stood for election from ward number 164 in Saki Naka. His claim had prompted an inquiry and we discovered that Shirsat is enrolled as a voter at two polling booths. Contrary to his claim, he hasn’t got ‘zero votes’ at either of the two polling booths.”
According to officials in the State Election Commission (SEC) of Maharashtra, which conducts local body elections, Shirsat secured a total of 44 votes from ward number 164. Out of the 44 votes, he got 11 votes at booth number 29 and two votes at booth number 15.
“Since he lives in the same area as booth number 29, we presume he must have cast his vote there. So his claim that his own vote and that of his family and neighbours disappeared is not true,” said an SEC official, speaking on the condition of anonymity.
Advertising
“Interestingly, Shirsat, in his February 27 complaint to the SEC, had made no mention of getting no votes in his own polling booth. He only said this to the media. In his letter, he has only raised suspicions over EVMs and demanded a repoll,” the official said.
When contacted by The Indian Express on Thursday, Shirsat said he did not wish to comment on the matter.
According to SEC officials, Shirsat’s name appears on the voters’ list along with those of his mother and father for polling booth 29 of the Municipal Corporation of Greater Mumbai. He also registered as voter at polling booth 15 along with his brother and sister.
Sections 17 and 18 of the Representation of the People Act state that a person cannot be enrolled as a voter in more than one place in the same constituency or in more than one constituency.
On February 27, Shirsat was quoted by Mumbai Mirror as saying, “In the last assembly polls, I got 1,500 votes. Now, apparently, I have got 44, and from my booth, zero. I voted for myself, my family voted for me and so did my neighbours (on 90-feet Road in Saki Naka) — where did those votes go?”
On Tuesday, the day of AAP’s live demonstration, Delhi’s Deputy Chief Minister Manish Sisodia said, “Questions are being raised about why we did not complain when we won 67 seats in Delhi. Yes, we did not complain then, nor did we raise questions about the 272 seats won by BJP in the 2014 Lok Sabha polls, or the Maharashtra and Jharkhand assembly polls. But when a candidate in the BMC polls pointed out that he did not get a single vote despite voting for himself, it made us think.”
The AAP also staged a protest outside the Election Commission’s office on Thursday; the poll panel has called for all-party meeting on Friday to allay fears
regarding EVM hacking.
Last month, a delegation of Opposition parties led by the Congress had met the three election commissioners to urge them to revert to the ballot system of voting on the ground that the accuracy of EVMs is questionable. The memorandum submitted by this joint delegation had also mentioned Shirsat’s claim of ‘zero votes’ as an example of EVM tampering.
Following the declaration of the UP election results on March 11, BSP chief Mayawati was the first to complain against the EVMs. She had alleged that large-scale EVM tampering had facilitated the BJP sweep in UP.
Advertising
Later, Delhi Chief Minister Arvind Kejriwal challenged the commission to make the EVMs available to the party for 72 hours and claimed that “we will read the code and rewrite it too”.
(With inputs from ENS/Mumbai) |
# -*- coding: utf-8 -*-
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.forms.models import ModelForm
from django.http.response import HttpResponseRedirect
from django.utils.timezone import now
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from website.models import User, File, Resolution, Execution, participants_from_doc, createDeletionNotification, \
createInfoCreationNotification
# model
from website.models import Document
# forms
from website.view.account import user_is_admin
from website.view.file import FileForm
from website.view.resolution import NewResolutionForm
class DocumentForm(ModelForm):
class Meta:
model = Document
exclude = ()
class NewDocumentForm(ModelForm):
class Meta:
model = Document
exclude = ('version', 'creator_id', 'created_date')
# views
class ListDocumentView(LoginRequiredMixin, ListView):
model = Document
template_name = 'document/list.html'
paginate_by = 5
def get_context_data(self, **kwargs):
context = super(ListDocumentView, self).get_context_data(**kwargs)
context['is_admin'] = user_is_admin(self.request.user)
context['active_menu'] = 'documents'
return context
def get_queryset(self):
super(ListDocumentView, self).get_queryset();
account = self.request.user
user = User.objects.get(login=account.username)
doc_from_this_user = Q(from_id=user.pk)
doc_to_this_user = Q(to_id=user.pk)
resolution_from_this_user = Q(resolution__from_id=user.pk)
resolution_to_this_user = Q(resolution__to_id=user.pk)
created_by_this_user = Q(creator_id=user.pk)
queryset = Document.objects \
.filter(
created_by_this_user | doc_from_this_user | doc_to_this_user | resolution_from_this_user | resolution_to_this_user)\
.distinct()
return queryset
class CreateDocumentView(LoginRequiredMixin, CreateView):
form_class = NewDocumentForm
template_name = 'document/new.html'
def get_success_url(self):
return reverse('document-edit', kwargs={'pk': self.object.id})
def get_context_data(self, **kwargs):
context = super(CreateDocumentView, self).get_context_data(**kwargs)
context['action'] = reverse('document-new')
context['is_admin'] = user_is_admin(self.request.user)
context['active_menu'] = 'documents'
return context
def form_valid(self, form):
document = form.save(commit=False)
account = self.request.user
user = User.objects.get(login__exact=account.username)
document.creator_id = user
document.created_date = now
document.version = 1
document.save()
users = participants_from_doc(document)
for user in users:
createInfoCreationNotification(user, unicode('Новый документ <b>%s</b>','utf-8') % (unicode(document.name)))
self.object = document
return HttpResponseRedirect(self.get_success_url())
class UpdateDocumentView(LoginRequiredMixin, UpdateView):
model = Document
template_name = 'document/card.html'
fields = ('__all__')
def get_success_url(self):
return reverse('document-list')
def get_context_data(self, **kwargs):
context = super(UpdateDocumentView, self).get_context_data(**kwargs)
context['action'] = reverse('document-edit', kwargs={'pk': self.get_object().id})
context['is_admin'] = user_is_admin(self.request.user)
context['active_menu'] = 'documents'
try:
execution = Execution.objects.get(doc_id=self.get_object().id)
except Execution.DoesNotExist:
execution = None
context['execution'] = execution
resolutions = Resolution.objects.filter(doc_id=self.get_object().id)
context['resolution_list'] = resolutions
context['resolution_form'] = NewResolutionForm()
files = File.objects.filter(doc_id=self.get_object().id)
context['file_list'] = files
context['form'] = FileForm
return context
class DeleteDocumentView(LoginRequiredMixin, DeleteView):
model = Document
template_name = 'document/delete.html'
def get_context_data(self, **kwargs):
context = super(DeleteDocumentView, self).get_context_data(**kwargs)
context['is_admin'] = user_is_admin(self.request.user)
context['active_menu'] = 'documents'
return context
def get_success_url(self):
return reverse('document-list')
def delete(self, request, *args, **kwargs):
document = self.get_object()
users = participants_from_doc(document)
url = super(DeleteDocumentView, self).delete(request, args, kwargs)
for user in users:
createDeletionNotification(user, unicode('Документ <b>%s</b> удален','utf-8') % (unicode(document.name)))
return url
|
def delete(data_product):
if exists(data_product):
filepath = _get_replica_filepath(data_product)
try:
experiment_data_storage.delete(filepath)
except Exception as e:
logger.error("Unable to delete file {} for data product uri {}"
.format(filepath, data_product.productUri))
raise
else:
raise ObjectDoesNotExist("Replica file does not exist") |
<gh_stars>1000+
import {PrimaryGeneratedColumn} from "../../../../src/decorator/columns/PrimaryGeneratedColumn";
import {Column, Entity, Generated } from "../../../../src";
@Entity()
export class ReallyReallyVeryVeryVeryLongTableName {
@PrimaryGeneratedColumn() // typeORM requires a pkey
PrimaryGeneratedColumnIDBlahBlahBlahThisIsReallyLong: number;
@Column()
Name: string;
@Column() @Generated("increment")
MyNumber: number;
}
|
<filename>src/main/java/com/microsoft/store/partnercenter/applicationconsents/ICustomerApplicationConsentCollection.java
// -----------------------------------------------------------------------
// <copyright file="ICustomerApplicationConsentCollection.java" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
package com.microsoft.store.partnercenter.applicationconsents;
import com.microsoft.store.partnercenter.IPartnerComponentString;
import com.microsoft.store.partnercenter.genericoperations.IEntityCreateOperations;
import com.microsoft.store.partnercenter.genericoperations.IEntitySelector;
import com.microsoft.store.partnercenter.models.applicationconsents.ApplicationConsent;
/**
* Encapsulates the operations on the ApplicationConsent collection.
*/
public interface ICustomerApplicationConsentCollection
extends IPartnerComponentString,
IEntitySelector<IApplicationConsent>,
IEntityCreateOperations<ApplicationConsent, ApplicationConsent>
{
/**
* Gets a single application consent behavior.
*
* @param applicationId The application identifier.
*
* @return The application consent operations.
*/
IApplicationConsent byId(String applicationId);
/**
* Adds application consents.
*
* @param newEntity ApplicationConsent to add.
*
* @return ApplicationConsent entity.
*/
ApplicationConsent create(ApplicationConsent newEntity);
}
|
def file_path_with_directory(request, tmp_path):
yield FilePathWithDirectoryFactory.create(tmp_path, request.param) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.