text
stringlengths 1
1.05M
|
|---|
#!/bin/bash
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
echo ---------------------
echo Starting IoTDB
echo ---------------------
if [ -z "${IOTDB_HOME}" ]; then
export IOTDB_HOME="`dirname "$0"`/.."
fi
IOTDB_CONF=${IOTDB_HOME}/conf
# IOTDB_LOGS=${IOTDB_HOME}/logs
if [ -f "$IOTDB_CONF/iotdb-env.sh" ]; then
. "$IOTDB_CONF/iotdb-env.sh"
else
echo "can't find $IOTDB_CONF/iotdb-env.sh"
fi
if [ -n "$JAVA_HOME" ]; then
for java in "$JAVA_HOME"/bin/amd64/java "$JAVA_HOME"/bin/java; do
if [ -x "$java" ]; then
JAVA="$java"
break
fi
done
else
JAVA=java
fi
if [ -z $JAVA ] ; then
echo Unable to find java executable. Check JAVA_HOME and PATH environment variables. > /dev/stderr
exit 1;
fi
CLASSPATH=""
for f in ${IOTDB_HOME}/lib/*.jar; do
CLASSPATH=${CLASSPATH}":"$f
done
classname=org.apache.iotdb.db.service.IoTDB
launch_service()
{
class="$1"
iotdb_parms="-Dlogback.configurationFile=${IOTDB_CONF}/logback.xml"
iotdb_parms="$iotdb_parms -DIOTDB_HOME=${IOTDB_HOME}"
iotdb_parms="$iotdb_parms -DTSFILE_HOME=${IOTDB_HOME}"
iotdb_parms="$iotdb_parms -DIOTDB_CONF=${IOTDB_CONF}"
iotdb_parms="$iotdb_parms -Dname=iotdb\.IoTDB"
exec "$JAVA" $iotdb_parms $IOTDB_JMX_OPTS $iotdb_parms -cp "$CLASSPATH" "$class"
return $?
}
# Start up the service
launch_service "$classname"
exit $?
|
SELECT MIN(price)
FROM product
WHERE category_id = 'x'
|
package graphproc
import (
"testing"
"time"
)
func TestNewAspect(t *testing.T) {
dur := time.Duration(10 * time.Millisecond)
NewAspect(testaspect, dur, 0, RETRY)
}
func testaspect(n string, m []byte, scope *Scope) error {
return nil
}
func TestTrace(t *testing.T) {
Level1()
}
func Level1() {
Level2()
}
func Level2() {
Trace("name", nil, nil)
}
|
def movie_recommender_system(user):
"""
This function uses a collaborative filtering algorithm
to suggest movies to the given user
"""
# Get the list of rated movies by the user
user_movies = user.get_rated_movies()
# Get the list of ratings given by other users
user_ratings = user.get_ratings()
# Calculate the similarity between the user and other users
user_similarity = user.calculate_similarity(user_movies, user_ratings)
# Get the list of movies rated highly by other users
other_rated_movies = user.get_top_rated_movies(user_ratings)
# Find the movies which the user has not seen so far, but recommended by other users
unseen_movies = [m for m in other_rated_movies if m not in user_movies]
# Sort the movies based on their similarity and the ratings given by other users
sorted_movies = sorted(unseen_movies,
key=lambda m: user_similarity[m] * user_ratings[m],
reverse=True)
# Get the top 10 movies
top_movies = sorted_movies[:10]
return top_movies
|
#!/bin/sh
# Script.sh
# Primeri
#
# Created by ZhouQi on 14-7-20.
# Copyright (c) 2014 Bither. All rights reserved.
cp 1C6FiRktL3UPd4sywhyU5CYSeLdKhvHxhR.tx ~/Library/Application\ Support/iPhone\ Simulator/7.1-64/Documents/1C6FiRktL3UPd4sywhyU5CYSeLdKhvHxhR.tx
mkdir -p ~/Library/Application\ Support/iPhone\ Simulator/7.1-64/Documents/Script
cp Script/* ~/Library/Application\ Support/iPhone\ Simulator/7.1-64/Documents/Script/
|
#!/bin/bash
NV_GPU=$1 nvidia-docker run -tid --rm --shm-size=20g --ulimit memlock=-1 -v /home/paulomann/workspace/practical-nlp-pytorch:/workspace/practical-nlp practical-nlp:latest
|
const parser = require('./parseOpenscad')
// const parser = require('./openscadParser.js').parser
var fs = require('fs')
import { exec } from './parserBase.js'
const input = fs.readFileSync(__dirname + '/test.scad', 'utf8')
exec(parser, input, 'root' , function (data) {
fs.writeFileSync(__dirname + '/../shaders/demo-data/convTest.frag', data)
})
|
<reponame>ch1huizong/learning
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
import fnmatch
pattern='fnmatch_*.py'
print'Pattern :',pattern
print'Regex :',fnmatch.translate(pattern)
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head):
prev = None
current = head
while current is not None:
nxt = current.next
current.next = prev
prev = current
current = nxt
head = prev
return head
|
package sse
import (
"net/http"
"time"
"github.com/r3labs/sse"
"github.com/stellar/go/services/bifrost/common"
"github.com/stellar/go/support/log"
)
func (s *Server) init() {
s.eventsServer = sse.New()
s.lastID = -1
s.log = common.CreateLogger("SSEServer")
}
func (s *Server) BroadcastEvent(address string, event AddressEvent, data []byte) {
s.initOnce.Do(s.init)
eventRecord := Event{
Address: address,
Event: event,
Data: string(data),
}
err := s.Storage.AddEvent(eventRecord)
if err != nil {
s.log.WithFields(log.F{"err": err, "event": eventRecord}).Error("Error broadcasting event")
}
}
// StartPublishing starts publishing events from the shared storage.
func (s *Server) StartPublishing() error {
s.initOnce.Do(s.init)
var err error
s.lastID, _, err = s.Storage.GetEventsSinceID(s.lastID)
if err != nil {
return err
}
go func() {
// Start publishing
for {
lastID, events, err := s.Storage.GetEventsSinceID(s.lastID)
if err != nil {
s.log.WithField("err", err).Error("Error GetEventsSinceID")
time.Sleep(time.Second)
continue
}
if len(events) == 0 {
time.Sleep(time.Second)
continue
}
for _, event := range events {
s.publishEvent(event.Address, event.Event, []byte(event.Data))
}
s.lastID = lastID
}
}()
return nil
}
func (s *Server) publishEvent(address string, event AddressEvent, data []byte) {
s.initOnce.Do(s.init)
// Create SSE stream if not exists
if !s.eventsServer.StreamExists(address) {
s.eventsServer.CreateStream(address)
}
// github.com/r3labs/sse does not send new lines - TODO create PR
if data == nil {
data = []byte("{}\n")
} else {
data = append(data, byte('\n'))
}
s.eventsServer.Publish(address, &sse.Event{
ID: []byte(event),
Event: []byte(event),
Data: data,
})
}
func (s *Server) CreateStream(address string) {
s.initOnce.Do(s.init)
s.eventsServer.CreateStream(address)
}
func (s *Server) StreamExists(address string) bool {
s.initOnce.Do(s.init)
return s.eventsServer.StreamExists(address)
}
func (s *Server) HTTPHandler(w http.ResponseWriter, r *http.Request) {
s.initOnce.Do(s.init)
s.eventsServer.HTTPHandler(w, r)
}
|
#!/bin/bash
set -e -x
python -m pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple -U -e .[dev]
python setup.py webhost
|
<filename>b2b-nextjs/components/Nav.tsx
import { signIn, useSession } from 'next-auth/react';
import Link from 'next/link';
import { Router, withRouter } from 'next/router';
import React, { Fragment, useEffect, useState } from 'react';
import AuthCheck from './AuthCheck';
import OrgContext from './OrgContext';
import ProfileImage from './ProfileImage';
type Props = {
router: any;
};
type State = {
mobileOpen: boolean;
};
class Nav extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
mobileOpen: false,
};
Router.events.on("routeChangeComplete", (url) => {
this.setState({
mobileOpen: false,
});
});
Router.events.on("hashChangeComplete", (url) => {
this.setState({
mobileOpen: false,
});
});
}
triggerMenu() {
this.setState({
mobileOpen: !this.state.mobileOpen,
});
}
componentWillUnmount() {
Router.events.off("routeChangeComplete", () => {});
Router.events.off("hashChangeComplete", () => {});
}
render() {
return (
<nav className="font-normal z-50 transition-all duration-300 ease-in-out fixed top-0 inset-x-0 h-14 bg-lnav dark:bg-dnav shadow-lnav backdrop-nav dark:shadow-dnav">
<div className="h-full max-w-7xl mx-auto flex items-center px-6">
<div className="min-w-40 relative">
<Link href="/">
<a className="h-10 block">
<img
height={40}
width={147.5}
className="navimgd"
src="/zitadel-logo-light.svg"
alt="ZITADEL logo dark"
/>
</a>
</Link>
<span className="text-xl font-bold absolute -bottom-1 -right-6 text-zitadelaccent-500">
B2B
</span>
</div>
<AuthCheck fallback={<div></div>}>
<OrgContext />
</AuthCheck>
<span className="flex-grow"></span>
<ul className="hidden md:flex items-center flex-grow justify-end">
<li className="text-gray-500 dark:text-gray-300 hover:text-black dark:hover:text-white">
<Link href="/">
<a className="flex items-center h-14 relative px-4 text-sm">
Home
</a>
</Link>
</li>
<li className="text-gray-500 dark:text-gray-300 hover:text-black dark:hover:text-white">
<a
href="https://console.zitadel.ch"
target="_blank"
rel="noreferrer"
className="flex items-center h-14 relative px-4 text-sm"
>
<span>Console</span>
<i className="text-xl h-5 -mt-2 ml-2 las la-external-link-alt"></i>
</a>
</li>
<NavButtons></NavButtons>
</ul>
<ul className="pt-flex md:hidden">
<li className="text-gray-500 dark:text-gray-200">
<button
onClick={() => this.triggerMenu()}
className="flex items-center box-border px-4 outline-none focus:outline-none"
>
<i className="text-lg las la-bars"></i>
</button>
<div
className={`${
this.state.mobileOpen
? "absolute inset-0 top-14 h-screen w-full dark:bg-zitadelblue-700 dark:bg-opacity-80"
: "hidden"
}`}
onClick={() => this.triggerMenu()}
></div>
<div
className={`${
this.state.mobileOpen
? "absolute top-14 left-0 right-0 bottom-0 flex-col"
: "hidden "
} `}
>
<MobileList></MobileList>
</div>
</li>
</ul>
</div>
</nav>
);
}
}
function NavButtons() {
const { data: session, status } = useSession();
function login() {
signIn("zitadel" as any, {
callbackUrl: "/",
});
}
if (session) {
return <ProfileImage user={session.user} />;
} else {
return (
<div className="flex items-center justify-center py-2">
<button
onClick={login}
className="whitespace-nowrap py-2 px-4 mx-2 shadow rounded-md text-sm hidden md:block hover:bg-gray-100 dark:bg-zitadelblue-400 dark:hover:bg-zitadelblue-300 dark:hover:bg-opacity-80 font-normal"
>
Login
</button>
</div>
);
}
}
function MobileList() {
return (
<div className="overflow-y-scroll max-h-screenmnav m-2 py-2 bg-white dark:bg-zitadelblue-400 shadow-xl dark:text-white rounded-xl relative">
<Link href="/">
<a className="px-4 py-4 flex items-center hover:text-purple-700 dark:hover:text-zitadelaccent-400 justify-center">
Home
</a>
</Link>
<Link href="/aboutus">
<a className="px-4 py-4 flex items-center hover:text-purple-700 dark:hover:text-zitadelaccent-400 justify-center">
About Us
</a>
</Link>
<Link href="/contact">
<a className="px-4 py-4 flex items-center hover:text-purple-700 dark:hover:text-zitadelaccent-400 justify-center">
Contact
</a>
</Link>
<Link href="/jobs">
<a className="px-4 py-4 flex items-center hover:text-purple-700 dark:hover:text-zitadelaccent-400 justify-center">
Jobs
</a>
</Link>
</div>
);
}
export default withRouter(Nav);
|
#!/bin/bash
echo 'Copying script to /Applications/Adobe Photoshop CC 2017/Preset/Scripts/....'
cp Create-iOS-icons.jsx /Applications/Adobe\ Photoshop\ CC\ 2017/Presets/Scripts/
cp Create-iMessage-icons.jsx /Applications/Adobe\ Photoshop\ CC\ 2017/Presets/Scripts/
cp Create-iMessage-stickers.jsx /Applications/Adobe\ Photoshop\ CC\ 2017/Presets/Scripts/
echo '๐ Done! ๐บ'
|
package employeeApp;
public class Company{
private static int maxID = 0;
// final = can't be changed
public final static double match401K = 0.05;
public int id;
public String name;
public int debt;
public Company(String name, int debt){
maxID++;
this.id = maxID;
this.name = name;
this.debt = debt;
}
}
|
#!/bin/bash
#
# Creat Time :Sun 17 Nov 2013 03:00:10 AM GMT
# Autoor : lili
# i ๆๅ
ฅ
# ไผๅฐๆๆฌๆๅ
ฅๅจๆฐๆฎๆต็ๅ้ข
# [address]command\
# command : a่ฟฝๅ iๆๅ
ฅ
echo "______________echo "Test 11111111" | sed 'i\Test 22222222'"
echo "Test 11111111" | sed 'i\Test 22222222'
# a ่ฟฝๅ
# ไผๅฐๆๆฌ่ฟฝๅ ๅฐๆฐๆฎๆต็ๅ้ข
echo "______________echo "Test 11111111" | sed 'a\Test 2222222'"
echo "Test 11111111" | sed 'a\Test 2222222'
echo "______________sed '3i\xxxxxxxxxxxxxxxxxxxxxxxxx'"
sed '3i\
xxxxxxxxxxxxxxxxxxxxxxxxxx
' file_3_4_d_i_a.txt
echo "______________sed '\$a\xxxxxxxxxxxxxxxxxxxxxxxxx'"
sed '$a\
xxxxxxxxxxxxxxxxxxxxxxxxxx
' file_3_4_d_i_a.txt
# c ๆดๆน่กๅ
ๅฎน
echo "_____________sed '3c\xxxxxxxxxxxxxxxxxxx' file_3_4_d_i_a.txt"
sed '3c\xxxxxxxxxxxxxxxxxxx' file_3_4_d_i_a.txt
# ๆๆฌๆจกๅผๆฅๅน้
ๆดๆนๅ
ๅฎน
echo "_____________sed '/22/c\xxxxxxxxxxxxxxxxxxxxx' file_3_4_d_i_a.txt"
sed '/22/c\xxxxxxxxxxxxxxxxxxxxx' file_3_4_d_i_a.txt
|
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* ็จๆทๅงๅๆจกๅ
*
* @author auto create
* @since 1.0, 2021-07-28 12:10:09
*/
public class TransferUserName extends AlipayObject {
private static final long serialVersionUID = 3739783327721438775L;
/**
* ๅง
*/
@ApiField("first_name")
private String firstName;
/**
* ๅ
จๅ
*/
@ApiField("full_name")
private String fullName;
/**
* ๅ
*/
@ApiField("last_name")
private String lastName;
/**
* ไธญ้ดๅๅญ
*/
@ApiField("middle_name")
private String middleName;
/**
* ๆฌๅฐๅๅญ
*/
@ApiField("native_name")
private String nativeName;
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFullName() {
return this.fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleName() {
return this.middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getNativeName() {
return this.nativeName;
}
public void setNativeName(String nativeName) {
this.nativeName = nativeName;
}
}
|
#!/bin/bash
#check if authentication is required
isAuth=`mongo --eval "db.getUsers()" | grep "not auth"`
#check if we have previous upgrade needed
FEATVER=$(mongo admin --eval "printjson(db.adminCommand( { getParameter: 1, featureCompatibilityVersion: 1 } ).featureCompatibilityVersion)" --quiet);
VER=$(mongod -version | grep "db version" | cut -d ' ' -f 3 | cut -d 'v' -f 2)
DEBIAN_FRONTEND=noninteractive
if ! [ -z "$isAuth" ] ; then
echo "mongod auth is ENABLED, manual upgrade will be required"
exit 0
fi
if [ -x "$(command -v mongo)" ]; then
if echo $VER | grep -q -i "3.4" ; then
if echo $FEATVER | grep -q -i "3.2" ; then
echo "run this command to ugprade to 3.4";
echo "mongo admin --eval \"db.adminCommand( { setFeatureCompatibilityVersion: \\\"3.4\\\" } )\"";
else
echo "We already have version 3.4";
fi
exit 0;
elif echo $VER | grep -q -i "3.6" ; then
echo "Already on 3.6";
exit 0;
elif echo $VER | grep -q -i "3.2" ; then
echo "Upgrading to MongoDB 3.4";
else
echo "Unsupported MongodB version $VER";
echo "Upgrade to MongoDB 3.2 first and then run this script";
exit 1;
fi
if [ -f /etc/redhat-release ]; then
#uninstall mognodb
yum erase -y mongodb-org mongodb-org-mongos mongodb-org-server mongodb-org-shell mongodb-org-tools
fi
if [ -f /etc/lsb-release ]; then
#uninstall mognodb
apt-get remove -y mongodb-org mongodb-org-mongos mongodb-org-server mongodb-org-shell mongodb-org-tools
fi
fi
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/../.." && pwd )"
if [ -f /etc/redhat-release ]; then
#install latest mongodb
#select source based on release
if grep -q -i "release 6" /etc/redhat-release ; then
echo "[mongodb-org-3.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/6/mongodb-org/3.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc" > /etc/yum.repos.d/mongodb-org-3.4.repo
elif grep -q -i "release 7" /etc/redhat-release ; then
echo "[mongodb-org-3.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/7/mongodb-org/3.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc" > /etc/yum.repos.d/mongodb-org-3.4.repo
fi
yum install -y nodejs mongodb-org
#disable transparent-hugepages (requires reboot)
cp -f $DIR/scripts/disable-transparent-hugepages /etc/init.d/disable-transparent-hugepages
chmod 755 /etc/init.d/disable-transparent-hugepages
chkconfig --add disable-transparent-hugepages
fi
if [ -f /etc/lsb-release ]; then
#install latest mongodb
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5
UBUNTU_YEAR="$(lsb_release -sr | cut -d '.' -f 1)";
if [ "$UBUNTU_YEAR" == "14" ]
then
echo "14"
echo "deb [ arch=amd64 ] http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.4 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.4.list ;
elif [ "$UBUNTU_YEAR" == "16" ]
then
echo "16"
echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.4.list ;
else
echo "18"
echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.4.list ;
fi
apt-get update
#install mongodb
apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" install mongodb-org --force-yes || (echo "Failed to install mongodb." ; exit)
#disable transparent-hugepages (requires reboot)
cp -f $DIR/scripts/disable-transparent-hugepages /etc/init.d/disable-transparent-hugepages
chmod 755 /etc/init.d/disable-transparent-hugepages
update-rc.d disable-transparent-hugepages defaults
fi
if [ -f /etc/redhat-release ]; then
#mongodb might need to be started
if grep -q -i "release 6" /etc/redhat-release ; then
service mongod restart || echo "mongodb service does not exist"
else
systemctl restart mongod || echo "mongodb systemctl job does not exist"
fi
fi
if [ -f /etc/lsb-release ]; then
if [[ `/sbin/init --version` =~ upstart ]]; then
restart mongod || echo "mongodb upstart job does not exist"
else
systemctl restart mongod || echo "mongodb systemctl job does not exist"
fi
fi
until nc -z localhost 27017; do echo Waiting for MongoDB; sleep 1; done
mongo admin --eval "printjson(db.adminCommand( { getParameter: 1, featureCompatibilityVersion: 1 } ))"
echo "run this command to ugprade to 3.4"
echo "mongo admin --eval \"db.adminCommand( { setFeatureCompatibilityVersion: \\\"3.4\\\" } )\""
|
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {HttpClient, HttpClientModule} from '@angular/common/http';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {TranslateModule, TranslateLoader,
MissingTranslationHandler, MissingTranslationHandlerParams, TranslateService, LangChangeEvent} from '@ngx-translate/core';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {LogoComponent, ToolbarComponent} from './components';
import {DashboardLayoutComponent} from './layouts/dashboard-layout/dashboard-layout.component';
import {SharedModule} from './shared';
import { ChartsModule } from 'ng2-charts';
import { TableDataPointsComponent } from './components/table-data-points/table-data-points.component';
import { FunctionSettingsComponent } from './components/function-settings/function-settings.component';
import { PointsSettingsComponent } from './components/points-settings/points-settings.component';
import { GTellerSettingsComponent } from './components/g-teller-settings/g-teller-settings.component';
import { GlobalSettingsComponent } from './components/global-settings/global-settings.component';
import { ChartComponent } from './components/chart/chart.component';
import { ChartSettingsComponent } from './components/chart-settings/chart-settings.component';
import { GlobalService } from './services/global/global.service';
import { DialogsModule } from './components/dialogs';
import { MathjaxModule } from './components/mathjax';
import { MatPaginatorIntl } from '@angular/material';
import { PaginatorI18n } from './shared/utils/paginatorI18n.model';
// AoT requires an exported function for factories
export function HttpLoaderFactory(httpClient: HttpClient) {
return new TranslateHttpLoader(httpClient, './assets/i18n/', '.json');
}
export class MyMissingTranslationHandler implements MissingTranslationHandler {
handle(params: MissingTranslationHandlerParams) {
return 'lang!';
}
}
@NgModule({
declarations: [
AppComponent,
ToolbarComponent,
LogoComponent,
DashboardLayoutComponent,
TableDataPointsComponent,
FunctionSettingsComponent,
PointsSettingsComponent,
GTellerSettingsComponent,
GlobalSettingsComponent,
ChartComponent,
ChartSettingsComponent,
],
imports: [
BrowserModule,
SharedModule,
ChartsModule,
DialogsModule,
MathjaxModule,
AppRoutingModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
},
missingTranslationHandler: {provide: MissingTranslationHandler, useClass: MyMissingTranslationHandler},
})
],
providers: [
GlobalService,
{
provide: MatPaginatorIntl, deps: [TranslateService],
useClass: PaginatorI18n
}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
|
module RubyIAR
module ToolchainAPI
end
end
|
/* KataSpace
* chat.js
*
* Copyright (c) 2010, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
Kata.require([
'katajs/oh/GUISimulation.js',
'../../scripts/util/url.js'
], function() {
var SUPER = Kata.GUISimulation.prototype;
/** Manages a chat UI on a page. Supports multiple chat windows. */
ChatUI = function(channel, name, width) {
SUPER.constructor.call(this, channel);
this.mName = name;
this.mWidth = width; // width of chat boxes
this.mGap = 30;
this.mNextDivID = 0;
this.mChats = [];
// We might later support multiple chat windows. For now we're
// just doing one large community chat, like IRC
this.mSingle = true;
};
Kata.extend(ChatUI, SUPER);
ChatUI.prototype.create = function(title) {
// Create a new div to hold it
var divID = this.mNextDivID++;
var newdiv = document.createElement('div');
var divIDstr = "chatdiv" + divID;
newdiv.setAttribute('id', divIDstr);
$(newdiv).chatbox({id : divIDstr,
title : title,
// offset doesn't matter, we just reflow
offset : 200,
width : this.mWidth,
messageSent : this._getMessageSentHandler(),
boxClosed : this._getClosedHandler(),
});
this.mChats.push(divIDstr);
this.reflow();
};
// Reflow the layout of the chat boxes
ChatUI.prototype.reflow = function() {
var cur_offset = 10;
for(var idx = 0; idx < this.mChats.length; idx++) {
var chatdiv = $("#"+this.mChats[idx]);
// Set to current offest
chatdiv.chatbox("option", "offset", cur_offset);
// And increment for the next guy
var offset = chatdiv.chatbox("option", "width");
cur_offset += offset + this.mGap;
}
};
ChatUI.prototype._handleMessageSent = function(id, user, msg) {
// Update the box
var chatdiv = $("#"+this.mChats[0]); // FIXME only works for single mode
var display_msg = URL.convertURLsToLinks(msg, true);
chatdiv.chatbox("option", "boxManager").addMsg(this.mName, display_msg);
// Send the message
this.mChannel.sendMessage(
new Kata.ScriptProtocol.ToScript.GUIMessage(
{
msg : 'chat',
event: { msg : msg }
}
)
);
};
ChatUI.prototype._getMessageSentHandler = function() {
var self = this;
return function(id, user, msg) {
self._handleMessageSent(id, user, msg);
};
};
ChatUI.prototype._handleClosed = function(id) {
this.mChats = this.mChats.filter(
function(el) { return el !== id; }
);
this.reflow();
};
ChatUI.prototype._getClosedHandler = function() {
var self = this;
return function(id) {
self._handleClosed(id);
};
};
// GUISimulation interface
ChatUI.prototype.handleGUIMessage = function(evt) {
var revt = evt.event;
// If we're in single chat mode with no chats, there's nothing to do
if (this.mSingle && this.mChats.length == 0) return;
if (revt.action == 'enter') {
var chatdiv = $("#"+this.mChats[0]); // FIXME only works for single mode
chatdiv.chatbox("option", "boxManager").addBuddy(revt.name);
}
else if (revt.action == 'say') {
var chatdiv = $("#"+this.mChats[0]); // FIXME only works for single mode
var display_msg = URL.convertURLsToLinks(revt.msg, true);
chatdiv.chatbox("option", "boxManager").addMsg(revt.name, display_msg);
}
else if (revt.action == 'exit') {
var chatdiv = $("#"+this.mChats[0]); // FIXME only works for single mode
chatdiv.chatbox("option", "boxManager").removeBuddy(revt.name);
}
};
});
|
class ArrayManipulator
{
public function manipulateArray(array $array, bool $isStripe): array
{
$result = [];
foreach ($array as $row) {
if ($isStripe) {
array_shift($row); // Remove the first element of the row
} else {
$result[] = array_reverse($row); // Reverse the elements of the row
}
}
return $isStripe ? $array : $result;
}
}
|
#include <iostream>
#include <string>
// Class to represent a message
class CMessage {
private:
std::string content;
public:
CMessage(const std::string& msg) : content(msg) {}
std::string GetContent() const {
return content;
}
};
// Class representing a network server
class CNetworkServer {
private:
CUDPSocket* m_pSocket;
public:
// Constructor
CNetworkServer() {
m_pSocket = new CUDPSocket;
}
// Destructor
~CNetworkServer() {
delete m_pSocket;
}
// Method to send a message over the network
void SendMessage(const CMessage& message) {
// Assume implementation of SendData method in CUDPSocket to send message content
m_pSocket->SendData(message.GetContent());
}
};
int main() {
CNetworkServer server;
CMessage message("Hello, world!");
server.SendMessage(message);
return 0;
}
|
import { customElement } from '../../../../../../runtime';
@customElement({ name: 'about', template: `<template>ABOUT <input></template>` })
export class About { }
|
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT 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/MIT
* 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.
*
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "qcloud.h"
#define PRIi32 "i"
#define PRIi16 "i"
#define PRIi8 "i"
#define PRIu32 "u"
#define PRIu16 "u"
#define PRIu8 "u"
#define SCNi8 "hhi"
#define SCNu8 "hhu"
#define SCNi16 "hi"
#define SCNu16 "hu"
#define SCNi32 "i"
#define SCNu32 "u"
__QCLOUD_STATIC__ qcloud_err_t shadow_json_value_do_update(char *value, shadow_dev_property_t *dev_property)
{
switch (dev_property->type) {
case JSON_DATA_TYPE_BOOL:
return LITE_get_boolean(dev_property->data, value);
case JSON_DATA_TYPE_INT32:
return LITE_get_int32(dev_property->data, value);
case JSON_DATA_TYPE_INT16:
return LITE_get_int16(dev_property->data, value);
case JSON_DATA_TYPE_INT8:
return LITE_get_int8(dev_property->data, value);
case JSON_DATA_TYPE_UINT32:
return LITE_get_uint32(dev_property->data, value);
case JSON_DATA_TYPE_UINT16:
return LITE_get_uint16(dev_property->data, value);
case JSON_DATA_TYPE_UINT8:
return LITE_get_uint8(dev_property->data, value);
case JSON_DATA_TYPE_FLOAT:
return LITE_get_float(dev_property->data, value);
case JSON_DATA_TYPE_DOUBLE:
return LITE_get_double(dev_property->data, value);
case JSON_DATA_TYPE_STRING:
case JSON_DATA_TYPE_OBJECT:
QCLOUD_LOG_D("string/object to be deal, %d %s", dev_property->type, value);
return QCLOUD_ERR_SUCCESS;
default:
QCLOUD_LOG_E("unknow type, %d",dev_property->type);
return QCLOUD_ERR_FAILURE;
}
}
/**
* @brief ๆฃๆฅๅฝๆฐsnprintf็่ฟๅๅผ
*
* @param returnCode ๅฝๆฐsnprintf็่ฟๅๅผ
* @param maxSizeOfWrite ๅฏๅๆๅคงๅญ่ๆฐ
* @return ่ฟๅQCLOUD_ERR_JSON, ่กจ็คบๅบ้; ่ฟๅQCLOUD_ERR_JSON_BUFFER_TRUNCATED, ่กจ็คบๆชๆญ
*/
__QCLOUD_INTERNAL__ qcloud_err_t shadow_json_snprintf_rc2errno(int rc, size_t write_max)
{
if (rc < 0) {
return QCLOUD_ERR_JSON;
}
if (rc >= write_max) {
return QCLOUD_ERR_JSON_BUFFER_TRUNCATED;
}
return QCLOUD_ERR_SUCCESS;
}
__QCLOUD_INTERNAL__ qcloud_err_t shadow_json_client_token_generate(char *json_doc, size_t json_doc_size, uint32_t token_num, char *device_product_id)
{
int rc_snprintf;
rc_snprintf = osal_snprintf(json_doc, json_doc_size, "%s-%u", device_product_id, token_num);
return shadow_json_snprintf_rc2errno(rc_snprintf, json_doc_size);
}
__QCLOUD_INTERNAL__ qcloud_err_t shadow_json_node_add(char *json_doc, size_t json_doc_size, const char *key, void *data, json_data_type_t type)
{
qcloud_err_t rc;
int32_t rc_snprintf = 0;
size_t remain_size = 0;
if ((remain_size = json_doc_size - strlen(json_doc)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SHORT;
}
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "\"%s\":", key);
rc = shadow_json_snprintf_rc2errno(rc_snprintf, remain_size);
QCLOUD_FUNC_EXIT_RC_IF_NOT(rc, QCLOUD_ERR_SUCCESS, rc);
if ((remain_size = json_doc_size - strlen(json_doc)) <= 1) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_JSON_BUFFER_TOO_SHORT);
}
if (!data) {
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "null,");
QCLOUD_FUNC_EXIT_RC(shadow_json_snprintf_rc2errno(rc_snprintf, remain_size));
}
switch (type) {
case JSON_DATA_TYPE_INT32:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIi32
",", *(int32_t *)(data));
break;
case JSON_DATA_TYPE_INT16:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIi16
",", *(int16_t *)(data));
break;
case JSON_DATA_TYPE_INT8:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIi8
",", *(int8_t *)(data));
break;
case JSON_DATA_TYPE_UINT32:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIu32
",", *(uint32_t *)(data));
break;
case JSON_DATA_TYPE_UINT16:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIu16
",", *(uint16_t *)(data));
break;
case JSON_DATA_TYPE_UINT8:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIu8
",", *(uint8_t *)(data));
break;
case JSON_DATA_TYPE_DOUBLE:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%f,", *(double *)(data));
break;
case JSON_DATA_TYPE_FLOAT:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%f,", *(float *)(data));
break;
case JSON_DATA_TYPE_BOOL:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%s,", *(bool *)(data) ? "true" : "false");
break;
case JSON_DATA_TYPE_STRING:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "\"%s\",", (char *)(data));
break;
case JSON_DATA_TYPE_OBJECT:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%s,", (char *)(data));
break;
}
return shadow_json_snprintf_rc2errno(rc_snprintf, remain_size);
}
__QCLOUD_INTERNAL__ qcloud_err_t shadow_json_empty_doc_build(char *json_doc, uint32_t token_num, char *device_product_id)
{
int rc_snprintf;
rc_snprintf = osal_snprintf(json_doc, QCLOUD_SHADOW_JSON_WITH_CLIENT_TOKEN_MAX, "{\"clientToken\":\"%s-%u\"}", device_product_id, token_num);
return shadow_json_snprintf_rc2errno(rc_snprintf, QCLOUD_SHADOW_JSON_WITH_CLIENT_TOKEN_MAX);
}
__QCLOUD_INTERNAL__ int shadow_json_client_token_parse(char *json_doc, char **client_token)
{
*client_token = LITE_json_value_of(SHADOW_FIELD_CLIENT_TOKEN, json_doc);
return *client_token != NULL;
}
__QCLOUD_INTERNAL__ int shadow_json_version_parse(char *json_doc, uint32_t *version)
{
int rc = QCLOUD_TRUE;
char *version_str;
version_str = LITE_json_value_of(SHADOW_PAYLOAD_VERSION, json_doc);
if (!version_str) {
return QCLOUD_FALSE;
}
if (sscanf(version_str, "%" SCNu32, version) != 1) {
QCLOUD_LOG_E("parse shadow version failed, rc: %d", QCLOUD_ERR_JSON_PARSE);
rc = QCLOUD_FALSE;
}
osal_free(version_str);
return rc;
}
__QCLOUD_INTERNAL__ int shadow_json_operation_type_parse(char *json_doc, char **type)
{
*type = LITE_json_value_of(SHADOW_FIELD_TYPE, json_doc);
return *type != NULL;
}
__QCLOUD_INTERNAL__ int shadow_json_operation_result_code_parse(char *json_doc, int16_t *result_code)
{
int rc = QCLOUD_TRUE;
char *result_code_str;
result_code_str = LITE_json_value_of(SHADOW_FIELD_RESULT, json_doc);
if (!result_code_str) {
return QCLOUD_FALSE;
}
if (sscanf(result_code_str, "%" SCNi16, result_code) != 1) {
QCLOUD_LOG_E("parse result code failed, %d", QCLOUD_ERR_JSON_PARSE);
rc = QCLOUD_FALSE;
}
osal_free(result_code_str);
return rc;
}
__QCLOUD_INTERNAL__ int shadow_json_delta_parse(char *json_doc, char **delta)
{
*delta = LITE_json_value_of(SHADOW_PAYLOAD_STATE, json_doc);
return *delta != NULL;
}
__QCLOUD_INTERNAL__ int shadow_json_operation_delta_get(char *json_doc, char **delta)
{
*delta = LITE_json_value_of(SHADOW_PAYLOAD_STATE_DELTA, json_doc);
return *delta != NULL;
}
__QCLOUD_INTERNAL__ int shadow_state_parse(char *json_doc, char **state)
{
*state = LITE_json_value_of(SHADOW_PAYLOAD_VERSION, json_doc);
return *state != NULL;
}
__QCLOUD_INTERNAL__ int shadow_json_value_update(char *json, shadow_dev_property_t *dev_property)
{
char *data;
data = LITE_json_value_of((char *)dev_property->key, json);
if (!data || strncmp(data, "null", 4) == 0 || strncmp(data, "NULL", 4) == 0) {
return QCLOUD_FALSE;
}
shadow_json_value_do_update(data, dev_property);
osal_free(data);
return QCLOUD_TRUE;
}
#ifdef __cplusplus
}
#endif
|
#!/bin/bash
BINARY=Trinity
BINARY_HOME=$PREFIX/bin
TRINITY_HOME=$PREFIX/bin/trinity-$PKG_VERSION
TRINITY_EXE=$TRINITY_HOME/Trinity
# go to trinity
cd $SRC_DIR
# remove the sample data
rm -rf $SRC_DIR/sample_data
# build source
make
# copy source to bin
mkdir -p $TRINITY_HOME
cp -R $SRC_DIR/* $TRINITY_HOME/
cd $TRINITY_HOME && chmod +x Trinity
cd $BINARY_HOME && ln -s trinity-$PKG_VERSION/Trinity $BINARY
|
#!/bin/bash
echo "Running migrations"
./manage.py makemigrations
./manage.py migrate
echo "Creating admin user"
./manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'nkmurli99@gmail.com', 'adminpassword')"
echo "Starting Django server"
gunicorn vasuapp.wsgi:application
|
package de.unibi.agbi.biodwh2.drugbank.model;
import com.fasterxml.jackson.annotation.JsonValue;
public enum State {
Solid("solid"),
Liquid("liquid"),
Gas("gas");
private State(String value) {
this.value = value;
}
public final String value;
@JsonValue
public String toValue() {
return value;
}
}
|
package com.java110.things.adapt.car;
import com.alibaba.fastjson.JSONObject;
import com.java110.things.adapt.car.compute.IComputeTempCarFee;
import com.java110.things.constant.SystemConstant;
import com.java110.things.entity.app.AppAttrDto;
import com.java110.things.entity.app.AppDto;
import com.java110.things.entity.car.*;
import com.java110.things.entity.community.CommunityDto;
import com.java110.things.entity.machine.MachineDto;
import com.java110.things.entity.parkingArea.ParkingAreaDto;
import com.java110.things.entity.parkingArea.ParkingAreaTextCacheDto;
import com.java110.things.entity.parkingArea.ParkingBoxDto;
import com.java110.things.entity.parkingArea.ResultParkingAreaTextDto;
import com.java110.things.entity.response.ResultDto;
import com.java110.things.factory.ApplicationContextFactory;
import com.java110.things.factory.HttpFactory;
import com.java110.things.factory.ParkingAreaTextFactory;
import com.java110.things.factory.TempCarFeeFactory;
import com.java110.things.service.app.IAppService;
import com.java110.things.service.car.ICarBlackWhiteService;
import com.java110.things.service.car.ICarInoutService;
import com.java110.things.service.car.ICarService;
import com.java110.things.service.community.ICommunityService;
import com.java110.things.service.fee.ITempCarFeeConfigService;
import com.java110.things.service.hc.ICarCallHcService;
import com.java110.things.service.parkingArea.IParkingAreaService;
import com.java110.things.service.parkingBox.IParkingBoxService;
import com.java110.things.util.Assert;
import com.java110.things.util.DateUtil;
import com.java110.things.util.SeqUtil;
import com.java110.things.util.StringUtil;
import com.java110.things.ws.BarrierGateControlWebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* ๆๅๅคดไธๅกๅค็็ฑป
*/
@Service
public class CallCarServiceImpl implements ICallCarService {
Logger logger = LoggerFactory.getLogger(CallCarServiceImpl.class);
@Autowired
private ICarBlackWhiteService carBlackWhiteServiceImpl;
@Autowired
private ICarService carServiceImpl;
@Autowired
private ICarInoutService carInoutServiceImpl;
@Autowired
private ICarCallHcService carCallHcServiceImpl;
@Autowired
private ITempCarFeeConfigService tempCarFeeConfigServiceImpl;
@Autowired
private IParkingAreaService parkingAreaServiceImpl;
@Autowired
private ICommunityService communityServiceImpl;
@Autowired
private IParkingBoxService parkingBoxServiceImpl;
@Autowired
private IAppService appServiceImpl;
@Autowired
private RestTemplate restTemplate;
@Override
public ResultParkingAreaTextDto ivsResult(String type, String carNum, MachineDto machineDto) throws Exception {
String machineDirection = machineDto.getDirection();
ResultParkingAreaTextDto resultParkingAreaTextDto = null;
//ๆฅ่ฏข ๅฒไบญ
ParkingBoxDto parkingBoxDto = new ParkingBoxDto();
parkingBoxDto.setExtBoxId(machineDto.getLocationObjId());
parkingBoxDto.setCommunityId(machineDto.getCommunityId());
List<ParkingAreaDto> parkingAreaDtos = parkingAreaServiceImpl.queryParkingAreasByBox(parkingBoxDto);
//Assert.listOnlyOne(parkingAreaDtos, "ๅ่ฝฆๅบไธๅญๅจ");
if (parkingAreaDtos == null || parkingAreaDtos.size() < 1) {
throw new IllegalArgumentException("ๅ่ฝฆๅบไธๅญๅจ");
}
BarrierGateControlDto barrierGateControlDto = new BarrierGateControlDto(BarrierGateControlDto.ACTION_INOUT, carNum, machineDto);
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
switch (machineDirection) {
case MachineDto.MACHINE_DIRECTION_ENTER: // ่ฝฆ่พ่ฟๅบ
resultParkingAreaTextDto = enterParkingArea(type, carNum, machineDto, parkingAreaDtos);
break;
case MachineDto.MACHINE_DIRECTION_OUT://่ฝฆ่พๅบๅบ
resultParkingAreaTextDto = outParkingArea(type, carNum, machineDto, parkingAreaDtos);
if (resultParkingAreaTextDto.getCode()
== ResultParkingAreaTextDto.CODE_CAR_OUT_SUCCESS
|| resultParkingAreaTextDto.getCode()
== ResultParkingAreaTextDto.CODE_FREE_CAR_OUT_SUCCESS
|| resultParkingAreaTextDto.getCode()
== ResultParkingAreaTextDto.CODE_MONTH_CAR_OUT_SUCCESS
|| resultParkingAreaTextDto.getCode()
== ResultParkingAreaTextDto.CODE_TEMP_CAR_OUT_SUCCESS
) {
carOut(carNum, machineDto);
}
break;
default:
resultParkingAreaTextDto = new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_CAR_OUT_ERROR, "็ณป็ปๅผๅธธ");
}
return resultParkingAreaTextDto;
}
/**
* ่ฝฆ่พๅบๅบ ่ฎฐๅฝ
*
* @param carNum
*/
private void carOut(String carNum, MachineDto machineDto) throws Exception {
//ๆฅ่ฏขๆฏๅฆๆๅ
ฅๅบๆฐๆฎ
CarInoutDto carInoutDto = new CarInoutDto();
carInoutDto.setCarNum(carNum);
carInoutDto.setPaId(machineDto.getLocationObjId());
carInoutDto.setStates(new String[]{CarInoutDto.STATE_IN, CarInoutDto.STATE_PAY});
carInoutDto.setInoutType(CarInoutDto.INOUT_TYPE_IN);
List<CarInoutDto> carInoutDtos = carInoutServiceImpl.queryCarInout(carInoutDto);
if (carInoutDtos != null && carInoutDtos.size() > 0) {
carInoutDto.setState(CarInoutDto.STATE_OUT);
carInoutServiceImpl.updateCarInout(carInoutDto);
}
carInoutDto = new CarInoutDto();
carInoutDto.setCarNum(carNum);
carInoutDto.setCarType("1");
carInoutDto.setCommunityId(machineDto.getCommunityId());
carInoutDto.setGateName(machineDto.getMachineName());
carInoutDto.setInoutId(SeqUtil.getId());
carInoutDto.setInoutType(CarInoutDto.INOUT_TYPE_OUT);
carInoutDto.setMachineCode(machineDto.getMachineCode());
carInoutDto.setOpenTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
carInoutDto.setPaId(machineDto.getLocationObjId());
carInoutDto.setState("3");
carInoutDto.setRemark("ๆญฃๅธธๅบๅบ");
if (carInoutDtos != null && carInoutDtos.size() > 0) {
carInoutDto.setPayCharge(carInoutDtos.get(0).getPayCharge());
carInoutDto.setRealCharge(carInoutDtos.get(0).getRealCharge());
carInoutDto.setPayType(carInoutDtos.get(0).getPayType());
} else {
carInoutDto.setPayCharge("0");
carInoutDto.setRealCharge("0");
carInoutDto.setPayType("1");
}
carInoutDto.setMachineCode(machineDto.getMachineCode());
carInoutServiceImpl.saveCarInout(carInoutDto);
// //ๅผๆญฅไธๆฅHCๅฐๅบ็ฎก็็ณป็ป
// carCallHcServiceImpl.carInout(carInoutDto);
}
/**
* ่ฝฆ่พๅบๅบ
*
* @param type ่ฝฆ็็ฑปๅ
* @param carNum ่ฝฆ็ๅท
* @param machineDto ่ฎพๅคไฟกๆฏ
* @return
*/
private ResultParkingAreaTextDto outParkingArea(String type, String carNum, MachineDto machineDto, List<ParkingAreaDto> parkingAreaDtos) throws Exception {
//ๆฅ่ฏข่ฟๅบ่ฎฐๅฝ
CarInoutDto carInoutDto = new CarInoutDto();
carInoutDto.setCarNum(carNum);
carInoutDto.setPaId(getDefaultPaId(parkingAreaDtos));
carInoutDto.setCommunityId(machineDto.getCommunityId());
carInoutDto.setStates(new String[]{CarInoutDto.STATE_IN, CarInoutDto.STATE_PAY});
List<CarInoutDto> carInoutDtos = carInoutServiceImpl.queryCarInout(carInoutDto);
int day = judgeOwnerCar(machineDto, carNum, parkingAreaDtos);
if ((carInoutDtos == null || carInoutDtos.size() < 1) && day < 1) {
BarrierGateControlDto barrierGateControlDto
= new BarrierGateControlDto(BarrierGateControlDto.ACTION_FEE_INFO, carNum, machineDto, 0, null, carNum + ",่ฝฆๆชๅ
ฅๅบ", "ๅผ้จๅคฑ่ดฅ");
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_CAR_NO_IN, carNum, "่ฝฆๆชๅ
ฅๅบ", "", "", carNum + ",่ฝฆๆชๅ
ฅๅบ", carNum);
}
//ๅคๆญๆฏๅฆไธบ็ฝๅๅ
if (judgeWhiteCar(machineDto, carNum, parkingAreaDtos, type, carInoutDtos)) {
BarrierGateControlDto barrierGateControlDto
= new BarrierGateControlDto(BarrierGateControlDto.ACTION_FEE_INFO, carNum, machineDto, 0, carInoutDtos.get(0), carNum + ",ๅ
่ดน่ฝฆ่พ", "ๅผ้จๆๅ");
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_FREE_CAR_OUT_SUCCESS, carNum, "ๅ
่ดน่ฝฆ่พ", "", "", carNum + ",ๅ
่ดน่ฝฆ่พ", carNum);
}
//ๅคๆญ่ฝฆ่พๆฏๅฆไธบๆ็ง่ฝฆ
ParkingAreaTextCacheDto parkingAreaTextCacheDto = ParkingAreaTextFactory.getText(parkingAreaDtos, ParkingAreaTextFactory.TYPE_CD_MONTH_CAR_OUT);
//ๆฟๆข่ๆฌไธญไฟกๆฏ
replaceParkingAreaTextCache(parkingAreaTextCacheDto, carNum, "", "", "", day + "");
if (day > 0) {
BarrierGateControlDto barrierGateControlDto
= new BarrierGateControlDto(BarrierGateControlDto.ACTION_FEE_INFO, carNum, machineDto, 0, carInoutDtos.get(0), carNum + ",ๆ็ง่ฝฆๅฉไฝ" + day + "ๅคฉ", "ๅผ้จๆๅ");
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
if (parkingAreaTextCacheDto != null) {
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_MONTH_CAR_OUT_SUCCESS, parkingAreaTextCacheDto,carNum);
}
ResultParkingAreaTextDto resultParkingAreaTextDto
= new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_MONTH_CAR_OUT_SUCCESS, carNum,
"ๆ็ง่ฝฆๅฉไฝ" + day + "ๅคฉ", "", "", carNum + ",ๆ็ง่ฝฆ", carNum);
resultParkingAreaTextDto.setDay(day);
return resultParkingAreaTextDto;
}
//ๅคๆญๅฒไบญๆฏๅฆๆถ่ดน
ParkingBoxDto parkingBoxDto = new ParkingBoxDto();
parkingBoxDto.setExtBoxId(machineDto.getLocationObjId());
parkingBoxDto.setCommunityId(machineDto.getCommunityId());
List<ParkingBoxDto> parkingBoxDtos = parkingBoxServiceImpl.queryParkingBoxs(parkingBoxDto);
Assert.listOnlyOne(parkingBoxDtos, "่ฎพๅคไธๅญๅจ ๅฒไบญ");
if (!"Y".equals(parkingBoxDtos.get(0).getFee())) {
BarrierGateControlDto barrierGateControlDto
= new BarrierGateControlDto(BarrierGateControlDto.ACTION_FEE_INFO, carNum, machineDto, 0, carInoutDtos.get(0), carNum + ",ไธ่ทฏๅนณๅฎ,่ฏฅๅฒไบญไธๆถ่ดน", "ๅผ้จๆๅ");
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_CAR_OUT_SUCCESS, carNum, "ๆฌข่ฟๅ
ไธด", "", "", carNum + ",ไธ่ทฏๅนณๅฎ", carNum);
}
//ๆฃๆฅๆฏๅฆๆฏไปๅฎๆ
parkingAreaTextCacheDto = ParkingAreaTextFactory.getText(parkingAreaDtos, ParkingAreaTextFactory.TYPE_CD_TEMP_CAR_OUT);
//ๆฟๆข่ๆฌไธญไฟกๆฏ
replaceParkingAreaTextCache(parkingAreaTextCacheDto, carNum, "", "", "", "");
if (TempCarFeeFactory.judgeFinishPayTempCarFee(carInoutDtos.get(0))) {
BarrierGateControlDto barrierGateControlDto
= new BarrierGateControlDto(BarrierGateControlDto.ACTION_FEE_INFO, carNum, machineDto, 0, carInoutDtos.get(0), carNum + ",ไธดๆถ่ฝฆ,ๆฌข่ฟๅ
ไธด", "ๅผ้จๆๅ");
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
if (parkingAreaTextCacheDto != null) {
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_TEMP_CAR_OUT_SUCCESS, parkingAreaTextCacheDto,carNum);
}
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_TEMP_CAR_OUT_SUCCESS, carNum, "ไธดๆถ่ฝฆ่พ,ๆฌข่ฟๅ
ไธด", "", "", carNum + ",ไธดๆถ่ฝฆ,ๆฌข่ฟๅ
ไธด", carNum);
}
TempCarFeeConfigDto tempCarFeeConfigDto = new TempCarFeeConfigDto();
tempCarFeeConfigDto.setPaId(getDefaultPaId(parkingAreaDtos));
tempCarFeeConfigDto.setCommunityId(carInoutDtos.get(0).getCommunityId());
List<TempCarFeeConfigDto> tempCarFeeConfigDtos = tempCarFeeConfigServiceImpl.queryTempCarFeeConfigs(tempCarFeeConfigDto);
if (tempCarFeeConfigDtos == null || tempCarFeeConfigDtos.size() < 1) {
BarrierGateControlDto barrierGateControlDto
= new BarrierGateControlDto(BarrierGateControlDto.ACTION_FEE_INFO, carNum, machineDto, 0, carInoutDtos.get(0), "ๆช้
็ฝฎไธดๆถ่ฝฆๆถ่ดน่งๅ", "ๅผ้จๅคฑ่ดฅ");
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_CAR_NO_PRI, "ไธดๆถ่ฝฆๆ ๆ้");
}
IComputeTempCarFee computeTempCarFee = ApplicationContextFactory.getBean(tempCarFeeConfigDtos.get(0).getRuleId(), IComputeTempCarFee.class);
TempCarFeeResult result = computeTempCarFee.computeTempCarFee(carInoutDtos.get(0), tempCarFeeConfigDtos.get(0));
//ไธๆถ่ดน๏ผ็ดๆฅๅบๅบ
if (result.getPayCharge() == 0) {
BarrierGateControlDto barrierGateControlDto
= new BarrierGateControlDto(BarrierGateControlDto.ACTION_FEE_INFO, carNum, machineDto, 0, carInoutDtos.get(0), carNum + "ๅ่ฝฆ" + result.getHours() + "ๆถ" + result.getMin() + "ๅ", "ๅผ้จๆๅ");
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_CAR_OUT_SUCCESS, carNum, "ๅ่ฝฆ" + result.getHours() + "ๆถ" + result.getMin() + "ๅ", "", "", carNum + ",ไธดๆถ่ฝฆ,ๆฌข่ฟๅ
ไธด", carNum);
}
parkingAreaTextCacheDto = ParkingAreaTextFactory.getText(parkingAreaDtos, ParkingAreaTextFactory.TYPE_CD_TEMP_CAR_NO_PAY);
//ๆฟๆข่ๆฌไธญไฟกๆฏ
replaceParkingAreaTextCache(parkingAreaTextCacheDto, carNum, result.getHours() + "", result.getMin() + "", result.getPayCharge() + "", "");
BarrierGateControlDto barrierGateControlDto
= new BarrierGateControlDto(BarrierGateControlDto.ACTION_FEE_INFO, carNum, machineDto, result.getPayCharge(), carInoutDtos.get(0),
carNum + "ๅ่ฝฆ" + result.getHours() + "ๅฐๆถ" + result.getMin() + "ๅ้,่ฏท็ผด่ดน" + result.getPayCharge() + "ๅ
", "ๅผ้จๅคฑ่ดฅ");
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
if (parkingAreaTextCacheDto != null) {
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_CAR_OUT_ERROR, parkingAreaTextCacheDto,carNum);
}
ResultParkingAreaTextDto resultParkingAreaTextDto = new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_CAR_OUT_ERROR, "ๅ่ฝฆ" + result.getHours() + "ๆถ" + result.getMin() + "ๅ", "่ฏทไบค่ดน" + result.getPayCharge() + "ๅ
", "", "",
carNum + ",ๅ่ฝฆ" + result.getHours() + "ๆถ" + result.getMin() + "ๅ,่ฏทไบค่ดน" + result.getPayCharge() + "ๅ
", carNum);
resultParkingAreaTextDto.setHours(result.getHours());
resultParkingAreaTextDto.setMin(result.getMin());
resultParkingAreaTextDto.setPayCharge(result.getPayCharge());
return resultParkingAreaTextDto;
}
/**
* ๆฟๆข้
็ฝฎไธญ็้
็ฝฎ
*
* @param parkingAreaTextCacheDto
* @param carNum
* @param hours
* @param min
* @param payCharge
*/
private void replaceParkingAreaTextCache(ParkingAreaTextCacheDto parkingAreaTextCacheDto, String carNum, String hours, String min, String payCharge, String day) {
if (parkingAreaTextCacheDto == null) {
return;
}
String replaceAfter = "";
if (!StringUtil.isEmpty(parkingAreaTextCacheDto.getText1())) {
replaceAfter = parkingAreaTextCacheDto.getText1()
.replaceAll("carNum", carNum)
.replaceAll("hours", hours)
.replaceAll("min", min)
.replaceAll("day", day)
.replaceAll("payCharge", payCharge);
parkingAreaTextCacheDto.setText1(replaceAfter);
}
if (!StringUtil.isEmpty(parkingAreaTextCacheDto.getText2())) {
replaceAfter = parkingAreaTextCacheDto.getText2()
.replaceAll("carNum", carNum)
.replaceAll("hours", hours)
.replaceAll("min", min)
.replaceAll("day", day)
.replaceAll("payCharge", payCharge)
;
parkingAreaTextCacheDto.setText2(replaceAfter);
}
if (!StringUtil.isEmpty(parkingAreaTextCacheDto.getText3())) {
replaceAfter = parkingAreaTextCacheDto.getText3()
.replaceAll("carNum", carNum)
.replaceAll("hours", hours)
.replaceAll("min", min)
.replaceAll("day", day)
.replaceAll("payCharge", payCharge)
;
parkingAreaTextCacheDto.setText3(replaceAfter);
}
if (!StringUtil.isEmpty(parkingAreaTextCacheDto.getText4())) {
replaceAfter = parkingAreaTextCacheDto.getText4()
.replaceAll("carNum", carNum)
.replaceAll("hours", hours)
.replaceAll("min", min)
.replaceAll("day", day)
.replaceAll("payCharge", payCharge)
;
parkingAreaTextCacheDto.setText4(replaceAfter);
}
if (!StringUtil.isEmpty(parkingAreaTextCacheDto.getVoice())) {
replaceAfter = parkingAreaTextCacheDto.getVoice()
.replaceAll("carNum", carNum)
.replaceAll("hours", hours)
.replaceAll("min", min)
.replaceAll("day", day)
.replaceAll("payCharge", payCharge)
;
parkingAreaTextCacheDto.setVoice(replaceAfter);
}
}
/**
* ๅคๆญๆฏๅฆไธบๆ็ง่ฝฆ
*
* @param machineDto
* @param carNum
* @param parkingAreaDtos
* @return -1 ่กจ็คบไธดๆถ่ฝฆ
*/
private int judgeOwnerCar(MachineDto machineDto, String carNum, List<ParkingAreaDto> parkingAreaDtos) throws Exception {
List<String> paIds = new ArrayList<>();
for (ParkingAreaDto parkingAreaDto : parkingAreaDtos) {
paIds.add(parkingAreaDto.getPaId());
}
CarDto carDto = new CarDto();
carDto.setPaIds(paIds.toArray(new String[paIds.size()]));
carDto.setCarNum(carNum);
List<CarDto> carDtos = carServiceImpl.queryCars(carDto);
if (carDtos == null || carDtos.size() < 1) {
return -1;
}
int day = DateUtil.differentDays(carDtos.get(0).getEndTime(), DateUtil.getCurrentDate());
if (day < 0) {
return 0;
}
return day;
}
/**
* ็ฝๅๅ่ฝฆ่พ
*/
private Boolean judgeWhiteCar(MachineDto machineDto, String carNum,
List<ParkingAreaDto> parkingAreaDtos,
String type, List<CarInoutDto> carInoutDtos) throws Exception {
List<String> paIds = new ArrayList<>();
for (ParkingAreaDto parkingAreaDto : parkingAreaDtos) {
paIds.add(parkingAreaDto.getPaId());
}
//1.0 ๅคๆญๆฏๅฆไธบ้ปๅๅ
CarBlackWhiteDto carBlackWhiteDto = new CarBlackWhiteDto();
carBlackWhiteDto.setCommunityId(machineDto.getCommunityId());
carBlackWhiteDto.setPaIds(paIds.toArray(new String[paIds.size()]));
carBlackWhiteDto.setCarNum(carNum);
carBlackWhiteDto.setBlackWhite(CarBlackWhiteDto.BLACK_WHITE_WHITE);
List<CarBlackWhiteDto> blackWhiteDtos = carBlackWhiteServiceImpl.queryCarBlackWhites(carBlackWhiteDto);
//็ฝๅๅ็ดๆฅๅบๅบ
CarInoutDto carInoutDto = null;
if (blackWhiteDtos != null && blackWhiteDtos.size() > 0) {
return true;
}
return false;
}
/**
* ่ฝฆ่พ่ฟๅบ
*
* @param type ่ฝฆ็็ฑปๅ
* @param carNum ่ฝฆ็ๅท
* @param machineDto ่ฎพๅคไฟกๆฏ
* @return
*/
private ResultParkingAreaTextDto enterParkingArea(String type, String carNum, MachineDto machineDto, List<ParkingAreaDto> parkingAreaDtos) throws Exception {
//1.0 ๅคๆญๆฏๅฆไธบ้ปๅๅ
List<String> paIds = new ArrayList<>();
for (ParkingAreaDto parkingAreaDto : parkingAreaDtos) {
paIds.add(parkingAreaDto.getPaId());
}
CarBlackWhiteDto carBlackWhiteDto = new CarBlackWhiteDto();
carBlackWhiteDto.setCommunityId(machineDto.getCommunityId());
carBlackWhiteDto.setPaIds(paIds.toArray(new String[paIds.size()]));
carBlackWhiteDto.setCarNum(carNum);
carBlackWhiteDto.setBlackWhite(CarBlackWhiteDto.BLACK_WHITE_BLACK);
List<CarBlackWhiteDto> blackWhiteDtos = carBlackWhiteServiceImpl.queryCarBlackWhites(carBlackWhiteDto);
//้ปๅๅ่ฝฆ่พไธ่ฝ่ฟๅ
ฅ
if (blackWhiteDtos != null && blackWhiteDtos.size() > 0) {
BarrierGateControlDto barrierGateControlDto
= new BarrierGateControlDto(BarrierGateControlDto.ACTION_FEE_INFO, carNum, machineDto, "ๆญค่ฝฆไธบ้ปๅๅ่ฝฆ่พ" + carNum + ",็ฆๆญข้่ก", "ๅผ้จๅคฑ่ดฅ");
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_CAR_BLACK, "ๆญค่ฝฆไธบ้ปๅๅ่ฝฆ่พ", carNum + ",็ฆๆญข้่ก", "", "", "ๆญค่ฝฆไธบ้ปๅๅ่ฝฆ่พ," + carNum + ",็ฆๆญข้่ก", carNum);
}
//ๅคๆญ่ฝฆ่พๆฏๅฆไธบๆ็ง่ฝฆ
int day = judgeOwnerCar(machineDto, carNum, parkingAreaDtos);
//ๅคๆญ่ฝฆ่พๆฏๅฆๅจ ๅบๅ
CarInoutDto inoutDto = new CarInoutDto();
inoutDto.setCarNum(carNum);
inoutDto.setPaIds(paIds.toArray(new String[paIds.size()]));
inoutDto.setState("1");
List<CarInoutDto> carInoutDtos = carInoutServiceImpl.queryCarInout(inoutDto);
// ไธดๆถ่ฝฆๅๅบๅ
ไธ่ฎฉ่ฟ ้่ฆๅทฅไฝไบบๅๅค็ ๆๅทฅๅบๅบ
if (carInoutDtos != null && carInoutDtos.size() > 0 && day < 1) {
BarrierGateControlDto barrierGateControlDto
= new BarrierGateControlDto(BarrierGateControlDto.ACTION_FEE_INFO, carNum, machineDto, carNum + ",่ฝฆๅทฒๅจๅบ", "ๅผ้จๅคฑ่ดฅ");
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_CAR_INED, carNum, "่ฝฆๅทฒๅจๅบ", "", "", carNum + ",่ฝฆๅทฒๅจๅบ", carNum);
}
//2.0 ่ฟๅบ
CarInoutDto carInoutDto = new CarInoutDto();
carInoutDto.setCarNum(carNum);
carInoutDto.setCarType(type);
carInoutDto.setCommunityId(machineDto.getCommunityId());
carInoutDto.setGateName(machineDto.getMachineName());
carInoutDto.setInoutId(SeqUtil.getId());
carInoutDto.setInoutType(CarInoutDto.INOUT_TYPE_IN);
carInoutDto.setMachineCode(machineDto.getMachineCode());
carInoutDto.setOpenTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
carInoutDto.setPaId(getDefaultPaId(parkingAreaDtos));
carInoutDto.setState("1");
ResultDto resultDto = carInoutServiceImpl.saveCarInout(carInoutDto);
if (resultDto.getCode() != ResultDto.SUCCESS) {
BarrierGateControlDto barrierGateControlDto
= new BarrierGateControlDto(BarrierGateControlDto.ACTION_FEE_INFO, carNum, machineDto, resultDto.getMsg(), "ๅผ้จๅคฑ่ดฅ");
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_CAR_IN_ERROR, carNum, "็ฆๆญขๅ
ฅๅบ", "", "", carNum + ",็ฆๆญขๅ
ฅๅบ", carNum);
}
ParkingAreaTextCacheDto parkingAreaTextCacheDto = ParkingAreaTextFactory.getText(parkingAreaDtos, ParkingAreaTextFactory.TYPE_CD_MONTH_CAR_IN);
//ๆฟๆข่ๆฌไธญไฟกๆฏ
replaceParkingAreaTextCache(parkingAreaTextCacheDto, carNum, "", "", "", day + "");
if (day > -1 && parkingAreaTextCacheDto != null) {
BarrierGateControlDto barrierGateControlDto
= new BarrierGateControlDto(BarrierGateControlDto.ACTION_FEE_INFO, carNum, machineDto, "ๆ็ง่ฝฆ," + carNum + ",ๆฌข่ฟๅ
ไธด", "ๅผ้จๆๅ");
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_MONTH_CAR_SUCCESS, parkingAreaTextCacheDto,carNum);
}
parkingAreaTextCacheDto = ParkingAreaTextFactory.getText(parkingAreaDtos, ParkingAreaTextFactory.TYPE_CD_TEMP_CAR_IN);
//ๆฟๆข่ๆฌไธญไฟกๆฏ
replaceParkingAreaTextCache(parkingAreaTextCacheDto, carNum, "", "", "", "");
if (day < 0 && parkingAreaTextCacheDto != null) {
BarrierGateControlDto barrierGateControlDto
= new BarrierGateControlDto(BarrierGateControlDto.ACTION_FEE_INFO, carNum, machineDto, "ไธดๆถ่ฝฆ," + carNum + ",ๆฌข่ฟๅ
ไธด", "ๅผ้จๆๅ");
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_TEMP_CAR_SUCCESS, parkingAreaTextCacheDto,carNum);
}
BarrierGateControlDto barrierGateControlDto
= new BarrierGateControlDto(BarrierGateControlDto.ACTION_FEE_INFO, carNum, machineDto, carNum + ",ๆฌข่ฟๅ
ไธด", "ๅผ้จๆๅ");
sendInfo(barrierGateControlDto, machineDto.getLocationObjId(), machineDto);
return new ResultParkingAreaTextDto(ResultParkingAreaTextDto.CODE_CAR_IN_SUCCESS, carNum, "ๆฌข่ฟๅ
ไธด", "", "", carNum + ",ๆฌข่ฟๅ
ไธด", carNum);
}
private String getDefaultPaId(List<ParkingAreaDto> parkingAreaDtos) {
String defaultPaId = "";
for (ParkingAreaDto parkingAreaDto : parkingAreaDtos) {
if ("T".equals(parkingAreaDto.getDefaultArea())) {
defaultPaId = parkingAreaDto.getPaId();
}
}
if (StringUtil.isEmpty(defaultPaId)) {
defaultPaId = parkingAreaDtos.get(0).getPaId();
}
return defaultPaId;
}
public void sendInfo(BarrierGateControlDto barrierGateControlDto, String extBoxId, MachineDto machineDto) throws Exception {
BarrierGateControlWebSocketServer.sendInfo(barrierGateControlDto.toString(), extBoxId);
CommunityDto communityDto = new CommunityDto();
communityDto.setCommunityId(machineDto.getCommunityId());
List<CommunityDto> communityDtos = communityServiceImpl.queryCommunitys(communityDto);
Assert.listOnlyOne(communityDtos, "ๅฐๅบไธๅญๅจ");
barrierGateControlDto.setExtCommunityId(communityDtos.get(0).getExtCommunityId());
barrierGateControlDto.setExtBoxId(extBoxId);
barrierGateControlDto.setExtMachineId(machineDto.getExtMachineId());
//ไธๆฅ็ฌฌไธๆน็ณป็ป
AppDto appDto = new AppDto();
appDto.setAppId(communityDtos.get(0).getAppId());
List<AppDto> appDtos = appServiceImpl.getApp(appDto);
Assert.listOnlyOne(appDtos, "ๆชๆพๅฐๅบ็จไฟกๆฏ");
AppAttrDto appAttrDto = appDtos.get(0).getAppAttr(AppAttrDto.SPEC_CD_OPEN_PARKING_AREA_DOOR_CONTROL_LOG);
if (appAttrDto == null) {
return;
}
String value = appAttrDto.getValue();
String upLoadAppId = "";
String securityCode = "";
appAttrDto = appDtos.get(0).getAppAttr(AppAttrDto.SPEC_CD_APP_ID);
if (appAttrDto != null) {
upLoadAppId = appAttrDto.getValue();
}
appAttrDto = appDtos.get(0).getAppAttr(AppAttrDto.SPEC_CD_SECURITY_CODE);
if (appAttrDto != null) {
securityCode = appAttrDto.getValue();
}
Map<String, String> headers = new HashMap<>();
headers.put(SystemConstant.HTTP_APP_ID, upLoadAppId);
ResponseEntity<String> tmpResponseEntity = HttpFactory.exchange(restTemplate, value, JSONObject.toJSONString(barrierGateControlDto), headers, HttpMethod.POST, securityCode);
if (tmpResponseEntity.getStatusCode() != HttpStatus.OK) {
logger.error("ๆง่ก็ปๆๅคฑ่ดฅ" + tmpResponseEntity.getBody());
}
}
}
|
#!/usr/bin/env zsh
if (( $+functions[zpm] )); then #DO_NOT_INCLUDE_LINE_IN_ZPM_CACHE
zpm load zpm-zsh/colors #DO_NOT_INCLUDE_LINE_IN_ZPM_CACHE
fi #DO_NOT_INCLUDE_LINE_IN_ZPM_CACHE
DIRCOLORS_CACHE_FILE="${TMPDIR:-/tmp}/zsh-${UID}/material-dircolors.zsh"
# Dircolors
source "${DIRCOLORS_CACHE_FILE}" 2>/dev/null || {
# Standarized $0 handling, following:
# https://github.com/zdharma/Zsh-100-Commits-Club/blob/master/Zsh-Plugin-Standard.adoc
0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}"
0="${${(M)0:#/*}:-$PWD/$0}"
_DIRNAME="${0:h}"
mkdir -p "${TMPDIR:-/tmp}/zsh-${UID}"
local COMMAND
if (( $+commands[dircolors] )); then
COMMAND="dircolors"
elif (( $+commands[gdircolors] )); then
COMMAND="gdircolors"
fi
for file in "${_DIRNAME}/dircolors/"*.dircolors; do
cat "$file"
done | $COMMAND - > "${DIRCOLORS_CACHE_FILE}"
source "${DIRCOLORS_CACHE_FILE}"
}
zstyle ':completion:*' list-dirs-first true
# Zsh colors
if [[ "$CLICOLOR" != '0' ]]; then
zstyle ':completion:*:options' list-colors "=^(-- *)=${c[raw_red]};${c[raw_dim]}" "=*=${c[raw_bold]};${c[raw_cyan]}"
zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}" 'ma=1;30;43'
fi
# GCC Colors
GCC_COLORS=''
GCC_COLORS+="error=${c[raw_bold]};${c[raw_red]}"
GCC_COLORS+=":warning=${c[raw_bold]};${c[raw_yellow]}"
GCC_COLORS+=":note=${c[raw_bold]};${c[raw_white]}"
GCC_COLORS+=":caret=${c[raw_bold]};${c[raw_white]}"
GCC_COLORS+=":locus=${c[raw_bg_black]};${c[raw_bold]};${c[raw_magenta]}"
GCC_COLORS+=":quote=${c[raw_bold]};${c[raw_yellow]}"
export GCC_COLORS
# Less Colors
export LESS_TERMCAP_mb="${c[green]}"
export LESS_TERMCAP_md="${c[bold]}${c[blue]}${c[bg_black]}"
export LESS_TERMCAP_so="${c[bold]}${c[bg_yellow]}${c[black]}"
export LESS_TERMCAP_us="${c[green]}"
export LESS_TERMCAP_ue="${c[reset]}"
export LESS_TERMCAP_me="${c[reset]}"
export LESS_TERMCAP_se="${c[reset]}"
# Grep Colors
GREP_COLORS=''
GREP_COLORS+=":mt=${c[raw_bold]};${c[raw_cyan]}"
GREP_COLORS+=":ms=${c[raw_bg_red]};${c[raw_bold]};${c[raw_black]}"
GREP_COLORS+=":mc=${c[raw_bold]};${c[raw_bg_red]}"
GREP_COLORS+=':sl='
GREP_COLORS+=':cx='
GREP_COLORS+=":fn=${c[raw_bold]};${c[raw_magenta]};${c[raw_bg_black]}"
GREP_COLORS+=':ln=32'
GREP_COLORS+=':bn=32'
GREP_COLORS+=":se=${c[raw_bold]};${c[raw_cyan]};${c[raw_bg_black]}"
export GREP_COLORS
# Ag Colors
function ag() {
command ag \
--color-path "${c[raw_bg_black]};${c[raw_bold]};${c[raw_magenta]}" \
--color-match "${c[raw_bg_red]};${c[raw_bold]};${c[raw_black]}" \
--color-line-number "${c[raw_bg_black]};${c[raw_bold]};${c[raw_green]}" \
$@
}
# FSH Colors
zstyle :plugin:fast-syntax-highlighting theme "material"
typeset -g FAST_THEME_NAME="material"
typeset -Ag FAST_HIGHLIGHT_STYLES
FAST_HIGHLIGHT_STYLES[materialdefault]=none
FAST_HIGHLIGHT_STYLES[materialunknown-token]=fg=red,bold
FAST_HIGHLIGHT_STYLES[materialreserved-word]=fg=yellow,bold
FAST_HIGHLIGHT_STYLES[materialalias]=fg=green,bold
FAST_HIGHLIGHT_STYLES[materialsuffix-alias]=fg=green,bold
FAST_HIGHLIGHT_STYLES[materialbuiltin]=fg=green,bold
FAST_HIGHLIGHT_STYLES[materialfunction]=fg=green,bold
FAST_HIGHLIGHT_STYLES[materialcommand]=fg=green,bold
FAST_HIGHLIGHT_STYLES[materialprecommand]=fg=green,bold,underline
FAST_HIGHLIGHT_STYLES[materialcommandseparator]=fg=magenta,bold
FAST_HIGHLIGHT_STYLES[materialhashed-command]=fg=green,bold
FAST_HIGHLIGHT_STYLES[materialpath]=fg=cyan,bold
FAST_HIGHLIGHT_STYLES[materialpath_pathseparator]=fg=red,bold
FAST_HIGHLIGHT_STYLES[materialglobbing]=fg=magenta,bold
FAST_HIGHLIGHT_STYLES[materialglobbing-ext]=fg=yellow,bold
FAST_HIGHLIGHT_STYLES[materialhistory-expansion]=fg=blue,bold
FAST_HIGHLIGHT_STYLES[materialsingle-hyphen-option]=fg=cyan,bold
FAST_HIGHLIGHT_STYLES[materialdouble-hyphen-option]=fg=cyan,bold
FAST_HIGHLIGHT_STYLES[materialback-quoted-argument]=none,bold
FAST_HIGHLIGHT_STYLES[materialsingle-quoted-argument]=fg=yellow,bold
FAST_HIGHLIGHT_STYLES[materialdouble-quoted-argument]=fg=yellow,bold
FAST_HIGHLIGHT_STYLES[materialdollar-quoted-argument]=fg=yellow,bold
FAST_HIGHLIGHT_STYLES[materialback-or-dollar-double-quoted-argument]=fg=cyan,bold
FAST_HIGHLIGHT_STYLES[materialback-dollar-quoted-argument]=fg=cyan,bold
FAST_HIGHLIGHT_STYLES[materialassign]=fg=blue,bold
FAST_HIGHLIGHT_STYLES[materialredirection]=fg=magenta,bold
FAST_HIGHLIGHT_STYLES[materialcomment]=fg=black,bold
FAST_HIGHLIGHT_STYLES[materialvariable]=fg=cyan,bold
FAST_HIGHLIGHT_STYLES[materialmathvar]=fg=blue,bold
FAST_HIGHLIGHT_STYLES[materialmathnum]=fg=magenta,bold
FAST_HIGHLIGHT_STYLES[materialmatherr]=fg=red,bold
FAST_HIGHLIGHT_STYLES[materialassign-array-bracket]=fg=cyan,bold
FAST_HIGHLIGHT_STYLES[materialfor-loop-variable]=fg=blue,bold
FAST_HIGHLIGHT_STYLES[materialfor-loop-number]=fg=magenta,bold
FAST_HIGHLIGHT_STYLES[materialfor-loop-operator]=fg=red,bold
FAST_HIGHLIGHT_STYLES[materialfor-loop-separator]=fg=green,bold
FAST_HIGHLIGHT_STYLES[materialexec-descriptor]=fg=yellow,bold
FAST_HIGHLIGHT_STYLES[materialhere-string-tri]=fg=yellow,bold
FAST_HIGHLIGHT_STYLES[materialhere-string-text]=fg=blue,bold
FAST_HIGHLIGHT_STYLES[materialhere-string-var]=fg=cyan,bg=black
FAST_HIGHLIGHT_STYLES[materialcase-input]=fg=green,bold
FAST_HIGHLIGHT_STYLES[materialcase-parentheses]=fg=yellow,bold
FAST_HIGHLIGHT_STYLES[materialcase-condition]=bg=blue,none,bold
FAST_HIGHLIGHT_STYLES[materialcorrect-subtle]=fg=blue,bold,bg=black
FAST_HIGHLIGHT_STYLES[materialincorrect-subtle]=fg=red,bold,bg=black
FAST_HIGHLIGHT_STYLES[materialsubtle-separator]=bg=black,fg=green,bold
FAST_HIGHLIGHT_STYLES[materialsubtle-bg]=bg=black
FAST_HIGHLIGHT_STYLES[materialpath-to-dir]=fg=blue,bold
FAST_HIGHLIGHT_STYLES[materialpaired-bracket]=bg=blue
FAST_HIGHLIGHT_STYLES[materialbracket-level-1]=fg=green,bold
FAST_HIGHLIGHT_STYLES[materialbracket-level-2]=fg=yellow,bold
FAST_HIGHLIGHT_STYLES[materialbracket-level-3]=fg=cyan,bold
FAST_HIGHLIGHT_STYLES[materialglobal-alias]=fg=green,bold
FAST_HIGHLIGHT_STYLES[materialsubcommand]=fg=yellow,bold
FAST_HIGHLIGHT_STYLES[materialsingle-sq-bracket]=fg=green,bold
FAST_HIGHLIGHT_STYLES[materialdouble-sq-bracket]=fg=green,bold
FAST_HIGHLIGHT_STYLES[materialdouble-paren]=fg=yellow,bold
FAST_HIGHLIGHT_STYLES[materialoptarg-string]=fg=yellow,bold
FAST_HIGHLIGHT_STYLES[materialoptarg-number]=fg=magenta,bold
FAST_HIGHLIGHT_STYLES[materialrecursive-base]=fg=default
FAST_HIGHLIGHT_STYLES[materialsecondary]=material
|
from pypy.interpreter.astcompiler import ast, consts, misc
from pypy.interpreter.astcompiler import asthelpers # Side effects
from pypy.interpreter import error
from pypy.interpreter.pyparser.pygram import syms, tokens
from pypy.interpreter.pyparser.error import SyntaxError
from pypy.interpreter.pyparser import parsestring
from pypy.rlib.objectmodel import specialize
def ast_from_node(space, node, compile_info):
"""Turn a parse tree, node, to AST."""
return ASTBuilder(space, node, compile_info).build_ast()
augassign_operator_map = {
'+=' : ast.Add,
'-=' : ast.Sub,
'/=' : ast.Div,
'//=' : ast.FloorDiv,
'%=' : ast.Mod,
'<<=' : ast.LShift,
'>>=' : ast.RShift,
'&=' : ast.BitAnd,
'|=' : ast.BitOr,
'^=' : ast.BitXor,
'*=' : ast.Mult,
'**=' : ast.Pow
}
operator_map = misc.dict_to_switch({
tokens.VBAR : ast.BitOr,
tokens.CIRCUMFLEX : ast.BitXor,
tokens.AMPER : ast.BitAnd,
tokens.LEFTSHIFT : ast.LShift,
tokens.RIGHTSHIFT : ast.RShift,
tokens.PLUS : ast.Add,
tokens.MINUS : ast.Sub,
tokens.STAR : ast.Mult,
tokens.SLASH : ast.Div,
tokens.DOUBLESLASH : ast.FloorDiv,
tokens.PERCENT : ast.Mod
})
class ASTBuilder(object):
def __init__(self, space, n, compile_info):
self.space = space
self.compile_info = compile_info
self.root_node = n
def build_ast(self):
"""Convert an top level parse tree node into an AST mod."""
n = self.root_node
if n.type == syms.file_input:
stmts = []
for i in range(len(n.children) - 1):
stmt = n.children[i]
if stmt.type == tokens.NEWLINE:
continue
sub_stmts_count = self.number_of_statements(stmt)
if sub_stmts_count == 1:
stmts.append(self.handle_stmt(stmt))
else:
stmt = stmt.children[0]
for j in range(sub_stmts_count):
small_stmt = stmt.children[j * 2]
stmts.append(self.handle_stmt(small_stmt))
return ast.Module(stmts)
elif n.type == syms.eval_input:
body = self.handle_testlist(n.children[0])
return ast.Expression(body)
elif n.type == syms.single_input:
first_child = n.children[0]
if first_child.type == tokens.NEWLINE:
# An empty line.
return ast.Interactive([])
else:
num_stmts = self.number_of_statements(first_child)
if num_stmts == 1:
stmts = [self.handle_stmt(first_child)]
else:
stmts = []
for i in range(0, len(first_child.children), 2):
stmt = first_child.children[i]
if stmt.type == tokens.NEWLINE:
break
stmts.append(self.handle_stmt(stmt))
return ast.Interactive(stmts)
else:
raise AssertionError("unknown root node")
def number_of_statements(self, n):
"""Compute the number of AST statements contained in a node."""
stmt_type = n.type
if stmt_type == syms.compound_stmt:
return 1
elif stmt_type == syms.stmt:
return self.number_of_statements(n.children[0])
elif stmt_type == syms.simple_stmt:
# Divide to remove semi-colons.
return len(n.children) // 2
else:
raise AssertionError("non-statement node")
def error(self, msg, n):
"""Raise a SyntaxError with the lineno and column set to n's."""
raise SyntaxError(msg, n.lineno, n.column,
filename=self.compile_info.filename)
def error_ast(self, msg, ast_node):
raise SyntaxError(msg, ast_node.lineno, ast_node.col_offset,
filename=self.compile_info.filename)
def check_forbidden_name(self, name, node):
try:
misc.check_forbidden_name(name)
except misc.ForbiddenNameAssignment, e:
self.error("cannot assign to %s" % (e.name,), node)
def set_context(self, expr, ctx):
"""Set the context of an expression to Store or Del if possible."""
try:
expr.set_context(ctx)
except ast.UnacceptableExpressionContext, e:
self.error_ast(e.msg, e.node)
except misc.ForbiddenNameAssignment, e:
self.error_ast("cannot assign to %s" % (e.name,), e.node)
def handle_print_stmt(self, print_node):
dest = None
expressions = None
newline = True
start = 1
child_count = len(print_node.children)
if child_count > 2 and print_node.children[1].type == tokens.RIGHTSHIFT:
dest = self.handle_expr(print_node.children[2])
start = 4
if (child_count + 1 - start) // 2:
expressions = [self.handle_expr(print_node.children[i])
for i in range(start, child_count, 2)]
if print_node.children[-1].type == tokens.COMMA:
newline = False
return ast.Print(dest, expressions, newline, print_node.lineno,
print_node.column)
def handle_del_stmt(self, del_node):
targets = self.handle_exprlist(del_node.children[1], ast.Del)
return ast.Delete(targets, del_node.lineno, del_node.column)
def handle_flow_stmt(self, flow_node):
first_child = flow_node.children[0]
first_child_type = first_child.type
if first_child_type == syms.break_stmt:
return ast.Break(flow_node.lineno, flow_node.column)
elif first_child_type == syms.continue_stmt:
return ast.Continue(flow_node.lineno, flow_node.column)
elif first_child_type == syms.yield_stmt:
yield_expr = self.handle_expr(first_child.children[0])
return ast.Expr(yield_expr, flow_node.lineno, flow_node.column)
elif first_child_type == syms.return_stmt:
if len(first_child.children) == 1:
values = None
else:
values = self.handle_testlist(first_child.children[1])
return ast.Return(values, flow_node.lineno, flow_node.column)
elif first_child_type == syms.raise_stmt:
exc = None
value = None
traceback = None
child_count = len(first_child.children)
if child_count >= 2:
exc = self.handle_expr(first_child.children[1])
if child_count >= 4:
value = self.handle_expr(first_child.children[3])
if child_count == 6:
traceback = self.handle_expr(first_child.children[5])
return ast.Raise(exc, value, traceback, flow_node.lineno,
flow_node.column)
else:
raise AssertionError("unknown flow statement")
def alias_for_import_name(self, import_name, store=True):
while True:
import_name_type = import_name.type
if import_name_type == syms.import_as_name:
name = import_name.children[0].value
if len(import_name.children) == 3:
as_name = import_name.children[2].value
self.check_forbidden_name(as_name, import_name.children[2])
else:
as_name = None
self.check_forbidden_name(name, import_name.children[0])
return ast.alias(name, as_name)
elif import_name_type == syms.dotted_as_name:
if len(import_name.children) == 1:
import_name = import_name.children[0]
continue
alias = self.alias_for_import_name(import_name.children[0],
store=False)
asname_node = import_name.children[2]
alias.asname = asname_node.value
self.check_forbidden_name(alias.asname, asname_node)
return alias
elif import_name_type == syms.dotted_name:
if len(import_name.children) == 1:
name = import_name.children[0].value
if store:
self.check_forbidden_name(name, import_name.children[0])
return ast.alias(name, None)
name_parts = [import_name.children[i].value
for i in range(0, len(import_name.children), 2)]
name = ".".join(name_parts)
return ast.alias(name, None)
elif import_name_type == tokens.STAR:
return ast.alias("*", None)
else:
raise AssertionError("unknown import name")
def handle_import_stmt(self, import_node):
import_node = import_node.children[0]
if import_node.type == syms.import_name:
dotted_as_names = import_node.children[1]
aliases = [self.alias_for_import_name(dotted_as_names.children[i])
for i in range(0, len(dotted_as_names.children), 2)]
return ast.Import(aliases, import_node.lineno, import_node.column)
elif import_node.type == syms.import_from:
child_count = len(import_node.children)
module = None
modname = None
i = 1
dot_count = 0
while i < child_count:
child = import_node.children[i]
if child.type == syms.dotted_name:
module = self.alias_for_import_name(child, False)
i += 1
break
elif child.type != tokens.DOT:
break
i += 1
dot_count += 1
i += 1
after_import_type = import_node.children[i].type
star_import = False
if after_import_type == tokens.STAR:
names_node = import_node.children[i]
star_import = True
elif after_import_type == tokens.LPAR:
names_node = import_node.children[i + 1]
elif after_import_type == syms.import_as_names:
names_node = import_node.children[i]
if len(names_node.children) % 2 == 0:
self.error("trailing comma is only allowed with "
"surronding parenthesis", names_node)
else:
raise AssertionError("unknown import node")
if star_import:
aliases = [self.alias_for_import_name(names_node)]
else:
aliases = [self.alias_for_import_name(names_node.children[i])
for i in range(0, len(names_node.children), 2)]
if module is not None:
modname = module.name
return ast.ImportFrom(modname, aliases, dot_count,
import_node.lineno, import_node.column)
else:
raise AssertionError("unknown import node")
def handle_global_stmt(self, global_node):
names = [global_node.children[i].value
for i in range(1, len(global_node.children), 2)]
return ast.Global(names, global_node.lineno, global_node.column)
def handle_exec_stmt(self, exec_node):
child_count = len(exec_node.children)
globs = None
locs = None
to_execute = self.handle_expr(exec_node.children[1])
if child_count >= 4:
globs = self.handle_expr(exec_node.children[3])
if child_count == 6:
locs = self.handle_expr(exec_node.children[5])
return ast.Exec(to_execute, globs, locs, exec_node.lineno,
exec_node.column)
def handle_assert_stmt(self, assert_node):
child_count = len(assert_node.children)
expr = self.handle_expr(assert_node.children[1])
msg = None
if len(assert_node.children) == 4:
msg = self.handle_expr(assert_node.children[3])
return ast.Assert(expr, msg, assert_node.lineno, assert_node.column)
def handle_suite(self, suite_node):
first_child = suite_node.children[0]
if first_child.type == syms.simple_stmt:
end = len(first_child.children) - 1
if first_child.children[end - 1].type == tokens.SEMI:
end -= 1
stmts = [self.handle_stmt(first_child.children[i])
for i in range(0, end, 2)]
else:
stmts = []
for i in range(2, len(suite_node.children) - 1):
stmt = suite_node.children[i]
stmt_count = self.number_of_statements(stmt)
if stmt_count == 1:
stmts.append(self.handle_stmt(stmt))
else:
simple_stmt = stmt.children[0]
for j in range(0, len(simple_stmt.children), 2):
stmt = simple_stmt.children[j]
if not stmt.children:
break
stmts.append(self.handle_stmt(stmt))
return stmts
def handle_if_stmt(self, if_node):
child_count = len(if_node.children)
if child_count == 4:
test = self.handle_expr(if_node.children[1])
suite = self.handle_suite(if_node.children[3])
return ast.If(test, suite, None, if_node.lineno, if_node.column)
otherwise_string = if_node.children[4].value
if otherwise_string == "else":
test = self.handle_expr(if_node.children[1])
suite = self.handle_suite(if_node.children[3])
else_suite = self.handle_suite(if_node.children[6])
return ast.If(test, suite, else_suite, if_node.lineno,
if_node.column)
elif otherwise_string == "elif":
elif_count = child_count - 4
after_elif = if_node.children[elif_count + 1]
if after_elif.type == tokens.NAME and \
after_elif.value == "else":
has_else = True
elif_count -= 3
else:
has_else = False
elif_count /= 4
if has_else:
last_elif = if_node.children[-6]
last_elif_test = self.handle_expr(last_elif)
elif_body = self.handle_suite(if_node.children[-4])
else_body = self.handle_suite(if_node.children[-1])
otherwise = [ast.If(last_elif_test, elif_body, else_body,
last_elif.lineno, last_elif.column)]
elif_count -= 1
else:
otherwise = None
for i in range(elif_count):
offset = 5 + (elif_count - i - 1) * 4
elif_test_node = if_node.children[offset]
elif_test = self.handle_expr(elif_test_node)
elif_body = self.handle_suite(if_node.children[offset + 2])
new_if = ast.If(elif_test, elif_body, otherwise,
elif_test_node.lineno, elif_test_node.column)
otherwise = [new_if]
expr = self.handle_expr(if_node.children[1])
body = self.handle_suite(if_node.children[3])
return ast.If(expr, body, otherwise, if_node.lineno, if_node.column)
else:
raise AssertionError("unknown if statement configuration")
def handle_while_stmt(self, while_node):
loop_test = self.handle_expr(while_node.children[1])
body = self.handle_suite(while_node.children[3])
if len(while_node.children) == 7:
otherwise = self.handle_suite(while_node.children[6])
else:
otherwise = None
return ast.While(loop_test, body, otherwise, while_node.lineno,
while_node.column)
def handle_for_stmt(self, for_node):
target_node = for_node.children[1]
target_as_exprlist = self.handle_exprlist(target_node, ast.Store)
if len(target_node.children) == 1:
target = target_as_exprlist[0]
else:
target = ast.Tuple(target_as_exprlist, ast.Store,
target_node.lineno, target_node.column)
expr = self.handle_testlist(for_node.children[3])
body = self.handle_suite(for_node.children[5])
if len(for_node.children) == 9:
otherwise = self.handle_suite(for_node.children[8])
else:
otherwise = None
return ast.For(target, expr, body, otherwise, for_node.lineno,
for_node.column)
def handle_except_clause(self, exc, body):
test = None
target = None
suite = self.handle_suite(body)
child_count = len(exc.children)
if child_count >= 2:
test = self.handle_expr(exc.children[1])
if child_count == 4:
target_child = exc.children[3]
target = self.handle_expr(target_child)
self.set_context(target, ast.Store)
return ast.ExceptHandler(test, target, suite, exc.lineno, exc.column)
def handle_try_stmt(self, try_node):
body = self.handle_suite(try_node.children[2])
child_count = len(try_node.children)
except_count = (child_count - 3 ) // 3
otherwise = None
finally_suite = None
possible_extra_clause = try_node.children[-3]
if possible_extra_clause.type == tokens.NAME:
if possible_extra_clause.value == "finally":
if child_count >= 9 and \
try_node.children[-6].type == tokens.NAME:
otherwise = self.handle_suite(try_node.children[-4])
except_count -= 1
finally_suite = self.handle_suite(try_node.children[-1])
except_count -= 1
else:
otherwise = self.handle_suite(try_node.children[-1])
except_count -= 1
if except_count:
handlers = []
for i in range(except_count):
base_offset = i * 3
exc = try_node.children[3 + base_offset]
except_body = try_node.children[5 + base_offset]
handlers.append(self.handle_except_clause(exc, except_body))
except_ast = ast.TryExcept(body, handlers, otherwise,
try_node.lineno, try_node.column)
if finally_suite is None:
return except_ast
body = [except_ast]
return ast.TryFinally(body, finally_suite, try_node.lineno,
try_node.column)
def handle_with_stmt(self, with_node):
body = self.handle_suite(with_node.children[-1])
i = len(with_node.children) - 1
while True:
i -= 2
item = with_node.children[i]
test = self.handle_expr(item.children[0])
if len(item.children) == 3:
target = self.handle_expr(item.children[2])
self.set_context(target, ast.Store)
else:
target = None
wi = ast.With(test, target, body, with_node.lineno,
with_node.column)
if i == 1:
break
body = [wi]
return wi
def handle_classdef(self, classdef_node, decorators=None):
name_node = classdef_node.children[1]
name = name_node.value
self.check_forbidden_name(name, name_node)
if len(classdef_node.children) == 4:
body = self.handle_suite(classdef_node.children[3])
return ast.ClassDef(name, None, body, decorators,
classdef_node.lineno, classdef_node.column)
if classdef_node.children[3].type == tokens.RPAR:
body = self.handle_suite(classdef_node.children[5])
return ast.ClassDef(name, None, body, decorators,
classdef_node.lineno, classdef_node.column)
bases = self.handle_class_bases(classdef_node.children[3])
body = self.handle_suite(classdef_node.children[6])
return ast.ClassDef(name, bases, body, decorators, classdef_node.lineno,
classdef_node.column)
def handle_class_bases(self, bases_node):
if len(bases_node.children) == 1:
return [self.handle_expr(bases_node.children[0])]
return self.get_expression_list(bases_node)
def handle_funcdef(self, funcdef_node, decorators=None):
name_node = funcdef_node.children[1]
name = name_node.value
self.check_forbidden_name(name, name_node)
args = self.handle_arguments(funcdef_node.children[2])
body = self.handle_suite(funcdef_node.children[4])
return ast.FunctionDef(name, args, body, decorators,
funcdef_node.lineno, funcdef_node.column)
def handle_decorated(self, decorated_node):
decorators = self.handle_decorators(decorated_node.children[0])
definition = decorated_node.children[1]
if definition.type == syms.funcdef:
node = self.handle_funcdef(definition, decorators)
elif definition.type == syms.classdef:
node = self.handle_classdef(definition, decorators)
else:
raise AssertionError("unkown decorated")
node.lineno = decorated_node.lineno
node.col_offset = decorated_node.column
return node
def handle_decorators(self, decorators_node):
return [self.handle_decorator(dec) for dec in decorators_node.children]
def handle_decorator(self, decorator_node):
dec_name = self.handle_dotted_name(decorator_node.children[1])
if len(decorator_node.children) == 3:
dec = dec_name
elif len(decorator_node.children) == 5:
dec = ast.Call(dec_name, None, None, None, None,
decorator_node.lineno, decorator_node.column)
else:
dec = self.handle_call(decorator_node.children[3], dec_name)
return dec
def handle_dotted_name(self, dotted_name_node):
base_value = dotted_name_node.children[0].value
name = ast.Name(base_value, ast.Load, dotted_name_node.lineno,
dotted_name_node.column)
for i in range(2, len(dotted_name_node.children), 2):
attr = dotted_name_node.children[i].value
name = ast.Attribute(name, attr, ast.Load, dotted_name_node.lineno,
dotted_name_node.column)
return name
def handle_arguments(self, arguments_node):
if arguments_node.type == syms.parameters:
if len(arguments_node.children) == 2:
return ast.arguments(None, None, None, None)
arguments_node = arguments_node.children[1]
i = 0
child_count = len(arguments_node.children)
defaults = []
args = []
variable_arg = None
keywords_arg = None
have_default = False
while i < child_count:
argument = arguments_node.children[i]
arg_type = argument.type
if arg_type == syms.fpdef:
parenthesized = False
complex_args = False
while True:
if i + 1 < child_count and \
arguments_node.children[i + 1].type == tokens.EQUAL:
default_node = arguments_node.children[i + 2]
defaults.append(self.handle_expr(default_node))
i += 2
have_default = True
elif have_default:
if parenthesized and not complex_args:
msg = "parenthesized arg with default"
else:
msg = ("non-default argument follows default "
"argument")
self.error(msg, arguments_node)
if len(argument.children) == 3:
sub_arg = argument.children[1]
if len(sub_arg.children) != 1:
complex_args = True
args.append(self.handle_arg_unpacking(sub_arg))
else:
parenthesized = True
argument = sub_arg.children[0]
continue
if argument.children[0].type == tokens.NAME:
name_node = argument.children[0]
arg_name = name_node.value
self.check_forbidden_name(arg_name, name_node)
name = ast.Name(arg_name, ast.Param, name_node.lineno,
name_node.column)
args.append(name)
i += 2
break
elif arg_type == tokens.STAR:
name_node = arguments_node.children[i + 1]
variable_arg = name_node.value
self.check_forbidden_name(variable_arg, name_node)
i += 3
elif arg_type == tokens.DOUBLESTAR:
name_node = arguments_node.children[i + 1]
keywords_arg = name_node.value
self.check_forbidden_name(keywords_arg, name_node)
i += 3
else:
raise AssertionError("unknown node in argument list")
if not defaults:
defaults = None
if not args:
args = None
return ast.arguments(args, variable_arg, keywords_arg, defaults)
def handle_arg_unpacking(self, fplist_node):
args = []
for i in range((len(fplist_node.children) + 1) / 2):
fpdef_node = fplist_node.children[i * 2]
while True:
child = fpdef_node.children[0]
if child.type == tokens.NAME:
arg = ast.Name(child.value, ast.Store, child.lineno,
child.column)
args.append(arg)
else:
child = fpdef_node.children[1]
if len(child.children) == 1:
fpdef_node = child.children[0]
continue
args.append(self.handle_arg_unpacking(child))
break
tup = ast.Tuple(args, ast.Store, fplist_node.lineno, fplist_node.column)
self.set_context(tup, ast.Store)
return tup
def handle_stmt(self, stmt):
stmt_type = stmt.type
if stmt_type == syms.stmt:
stmt = stmt.children[0]
stmt_type = stmt.type
if stmt_type == syms.simple_stmt:
stmt = stmt.children[0]
stmt_type = stmt.type
if stmt_type == syms.small_stmt:
stmt = stmt.children[0]
stmt_type = stmt.type
if stmt_type == syms.expr_stmt:
return self.handle_expr_stmt(stmt)
elif stmt_type == syms.print_stmt:
return self.handle_print_stmt(stmt)
elif stmt_type == syms.del_stmt:
return self.handle_del_stmt(stmt)
elif stmt_type == syms.pass_stmt:
return ast.Pass(stmt.lineno, stmt.column)
elif stmt_type == syms.flow_stmt:
return self.handle_flow_stmt(stmt)
elif stmt_type == syms.import_stmt:
return self.handle_import_stmt(stmt)
elif stmt_type == syms.global_stmt:
return self.handle_global_stmt(stmt)
elif stmt_type == syms.assert_stmt:
return self.handle_assert_stmt(stmt)
elif stmt_type == syms.exec_stmt:
return self.handle_exec_stmt(stmt)
else:
raise AssertionError("unhandled small statement")
elif stmt_type == syms.compound_stmt:
stmt = stmt.children[0]
stmt_type = stmt.type
if stmt_type == syms.if_stmt:
return self.handle_if_stmt(stmt)
elif stmt_type == syms.while_stmt:
return self.handle_while_stmt(stmt)
elif stmt_type == syms.for_stmt:
return self.handle_for_stmt(stmt)
elif stmt_type == syms.try_stmt:
return self.handle_try_stmt(stmt)
elif stmt_type == syms.with_stmt:
return self.handle_with_stmt(stmt)
elif stmt_type == syms.funcdef:
return self.handle_funcdef(stmt)
elif stmt_type == syms.classdef:
return self.handle_classdef(stmt)
elif stmt_type == syms.decorated:
return self.handle_decorated(stmt)
else:
raise AssertionError("unhandled compound statement")
else:
raise AssertionError("unknown statment type")
def handle_expr_stmt(self, stmt):
if len(stmt.children) == 1:
expression = self.handle_testlist(stmt.children[0])
return ast.Expr(expression, stmt.lineno, stmt.column)
elif stmt.children[1].type == syms.augassign:
# Augmented assignment.
target_child = stmt.children[0]
target_expr = self.handle_testlist(target_child)
self.set_context(target_expr, ast.Store)
value_child = stmt.children[2]
if value_child.type == syms.testlist:
value_expr = self.handle_testlist(value_child)
else:
value_expr = self.handle_expr(value_child)
op_str = stmt.children[1].children[0].value
operator = augassign_operator_map[op_str]
return ast.AugAssign(target_expr, operator, value_expr,
stmt.lineno, stmt.column)
else:
# Normal assignment.
targets = []
for i in range(0, len(stmt.children) - 2, 2):
target_node = stmt.children[i]
if target_node.type == syms.yield_expr:
self.error("can't assign to yield expression", target_node)
target_expr = self.handle_testlist(target_node)
self.set_context(target_expr, ast.Store)
targets.append(target_expr)
value_child = stmt.children[-1]
if value_child.type == syms.testlist:
value_expr = self.handle_testlist(value_child)
else:
value_expr = self.handle_expr(value_child)
return ast.Assign(targets, value_expr, stmt.lineno, stmt.column)
def get_expression_list(self, tests):
return [self.handle_expr(tests.children[i])
for i in range(0, len(tests.children), 2)]
def handle_testlist(self, tests):
if len(tests.children) == 1:
return self.handle_expr(tests.children[0])
else:
elts = self.get_expression_list(tests)
return ast.Tuple(elts, ast.Load, tests.lineno, tests.column)
def handle_expr(self, expr_node):
# Loop until we return something.
while True:
expr_node_type = expr_node.type
if expr_node_type == syms.test or expr_node_type == syms.old_test:
first_child = expr_node.children[0]
if first_child.type in (syms.lambdef, syms.old_lambdef):
return self.handle_lambdef(first_child)
elif len(expr_node.children) > 1:
return self.handle_ifexp(expr_node)
else:
expr_node = first_child
elif expr_node_type == syms.or_test or \
expr_node_type == syms.and_test:
if len(expr_node.children) == 1:
expr_node = expr_node.children[0]
continue
seq = [self.handle_expr(expr_node.children[i])
for i in range(0, len(expr_node.children), 2)]
if expr_node_type == syms.or_test:
op = ast.Or
else:
op = ast.And
return ast.BoolOp(op, seq, expr_node.lineno, expr_node.column)
elif expr_node_type == syms.not_test:
if len(expr_node.children) == 1:
expr_node = expr_node.children[0]
continue
expr = self.handle_expr(expr_node.children[1])
return ast.UnaryOp(ast.Not, expr, expr_node.lineno,
expr_node.column)
elif expr_node_type == syms.comparison:
if len(expr_node.children) == 1:
expr_node = expr_node.children[0]
continue
operators = []
operands = []
expr = self.handle_expr(expr_node.children[0])
for i in range(1, len(expr_node.children), 2):
operators.append(self.handle_comp_op(expr_node.children[i]))
operands.append(self.handle_expr(expr_node.children[i + 1]))
return ast.Compare(expr, operators, operands, expr_node.lineno,
expr_node.column)
elif expr_node_type == syms.expr or \
expr_node_type == syms.xor_expr or \
expr_node_type == syms.and_expr or \
expr_node_type == syms.shift_expr or \
expr_node_type == syms.arith_expr or \
expr_node_type == syms.term:
if len(expr_node.children) == 1:
expr_node = expr_node.children[0]
continue
return self.handle_binop(expr_node)
elif expr_node_type == syms.yield_expr:
if len(expr_node.children) == 2:
exp = self.handle_testlist(expr_node.children[1])
else:
exp = None
return ast.Yield(exp, expr_node.lineno, expr_node.column)
elif expr_node_type == syms.factor:
if len(expr_node.children) == 1:
expr_node = expr_node.children[0]
continue
return self.handle_factor(expr_node)
elif expr_node_type == syms.power:
return self.handle_power(expr_node)
else:
raise AssertionError("unknown expr")
def handle_lambdef(self, lambdef_node):
expr = self.handle_expr(lambdef_node.children[-1])
if len(lambdef_node.children) == 3:
args = ast.arguments(None, None, None, None)
else:
args = self.handle_arguments(lambdef_node.children[1])
return ast.Lambda(args, expr, lambdef_node.lineno, lambdef_node.column)
def handle_ifexp(self, if_expr_node):
body = self.handle_expr(if_expr_node.children[0])
expression = self.handle_expr(if_expr_node.children[2])
otherwise = self.handle_expr(if_expr_node.children[4])
return ast.IfExp(expression, body, otherwise, if_expr_node.lineno,
if_expr_node.column)
def handle_comp_op(self, comp_op_node):
comp_node = comp_op_node.children[0]
comp_type = comp_node.type
if len(comp_op_node.children) == 1:
if comp_type == tokens.LESS:
return ast.Lt
elif comp_type == tokens.GREATER:
return ast.Gt
elif comp_type == tokens.EQEQUAL:
return ast.Eq
elif comp_type == tokens.LESSEQUAL:
return ast.LtE
elif comp_type == tokens.GREATEREQUAL:
return ast.GtE
elif comp_type == tokens.NOTEQUAL:
return ast.NotEq
elif comp_type == tokens.NAME:
if comp_node.value == "is":
return ast.Is
elif comp_node.value == "in":
return ast.In
else:
raise AssertionError("invalid comparison")
else:
raise AssertionError("invalid comparison")
else:
if comp_op_node.children[1].value == "in":
return ast.NotIn
elif comp_node.value == "is":
return ast.IsNot
else:
raise AssertionError("invalid comparison")
def handle_binop(self, binop_node):
left = self.handle_expr(binop_node.children[0])
right = self.handle_expr(binop_node.children[2])
op = operator_map(binop_node.children[1].type)
result = ast.BinOp(left, op, right, binop_node.lineno,
binop_node.column)
number_of_ops = (len(binop_node.children) - 1) / 2
for i in range(1, number_of_ops):
op_node = binop_node.children[i * 2 + 1]
op = operator_map(op_node.type)
sub_right = self.handle_expr(binop_node.children[i * 2 + 2])
result = ast.BinOp(result, op, sub_right, op_node.lineno,
op_node.column)
return result
def handle_factor(self, factor_node):
# Fold '-' on constant numbers.
if factor_node.children[0].type == tokens.MINUS and \
len(factor_node.children) == 2:
factor = factor_node.children[1]
if factor.type == syms.factor and len(factor.children) == 1:
power = factor.children[0]
if power.type == syms.power and len(power.children) == 1:
atom = power.children[0]
if atom.type == syms.atom and \
atom.children[0].type == tokens.NUMBER:
num = atom.children[0]
num.value = "-" + num.value
return self.handle_atom(atom)
expr = self.handle_expr(factor_node.children[1])
op_type = factor_node.children[0].type
if op_type == tokens.PLUS:
op = ast.UAdd
elif op_type == tokens.MINUS:
op = ast.USub
elif op_type == tokens.TILDE:
op = ast.Invert
else:
raise AssertionError("invalid factor node")
return ast.UnaryOp(op, expr, factor_node.lineno, factor_node.column)
def handle_power(self, power_node):
atom_expr = self.handle_atom(power_node.children[0])
if len(power_node.children) == 1:
return atom_expr
for i in range(1, len(power_node.children)):
trailer = power_node.children[i]
if trailer.type != syms.trailer:
break
tmp_atom_expr = self.handle_trailer(trailer, atom_expr)
tmp_atom_expr.lineno = atom_expr.lineno
tmp_atom_expr.col_offset = atom_expr.col_offset
atom_expr = tmp_atom_expr
if power_node.children[-1].type == syms.factor:
right = self.handle_expr(power_node.children[-1])
atom_expr = ast.BinOp(atom_expr, ast.Pow, right, power_node.lineno,
power_node.column)
return atom_expr
def handle_slice(self, slice_node):
first_child = slice_node.children[0]
if first_child.type == tokens.DOT:
return ast.Ellipsis()
if len(slice_node.children) == 1 and first_child.type == syms.test:
index = self.handle_expr(first_child)
return ast.Index(index)
lower = None
upper = None
step = None
if first_child.type == syms.test:
lower = self.handle_expr(first_child)
if first_child.type == tokens.COLON:
if len(slice_node.children) > 1:
second_child = slice_node.children[1]
if second_child.type == syms.test:
upper = self.handle_expr(second_child)
elif len(slice_node.children) > 2:
third_child = slice_node.children[2]
if third_child.type == syms.test:
upper = self.handle_expr(third_child)
last_child = slice_node.children[-1]
if last_child.type == syms.sliceop:
if len(last_child.children) == 1:
step = ast.Name("None", ast.Load, last_child.lineno,
last_child.column)
else:
step_child = last_child.children[1]
if step_child.type == syms.test:
step = self.handle_expr(step_child)
return ast.Slice(lower, upper, step)
def handle_trailer(self, trailer_node, left_expr):
first_child = trailer_node.children[0]
if first_child.type == tokens.LPAR:
if len(trailer_node.children) == 2:
return ast.Call(left_expr, None, None, None, None,
trailer_node.lineno, trailer_node.column)
else:
return self.handle_call(trailer_node.children[1], left_expr)
elif first_child.type == tokens.DOT:
attr = trailer_node.children[1].value
return ast.Attribute(left_expr, attr, ast.Load,
trailer_node.lineno, trailer_node.column)
else:
middle = trailer_node.children[1]
if len(middle.children) == 1:
slice = self.handle_slice(middle.children[0])
return ast.Subscript(left_expr, slice, ast.Load,
middle.lineno, middle.column)
slices = []
simple = True
for i in range(0, len(middle.children), 2):
slc = self.handle_slice(middle.children[i])
if not isinstance(slc, ast.Index):
simple = False
slices.append(slc)
if not simple:
ext_slice = ast.ExtSlice(slices)
return ast.Subscript(left_expr, ext_slice, ast.Load,
middle.lineno, middle.column)
elts = []
for idx in slices:
assert isinstance(idx, ast.Index)
elts.append(idx.value)
tup = ast.Tuple(elts, ast.Load, middle.lineno, middle.column)
return ast.Subscript(left_expr, ast.Index(tup), ast.Load,
middle.lineno, middle.column)
def handle_call(self, args_node, callable_expr):
arg_count = 0
keyword_count = 0
generator_count = 0
for argument in args_node.children:
if argument.type == syms.argument:
if len(argument.children) == 1:
arg_count += 1
elif argument.children[1].type == syms.comp_for:
generator_count += 1
else:
keyword_count += 1
if generator_count > 1 or \
(generator_count and (keyword_count or arg_count)):
self.error("Generator expression must be parenthesized "
"if not sole argument", args_node)
if arg_count + keyword_count + generator_count > 255:
self.error("more than 255 arguments", args_node)
args = []
keywords = []
used_keywords = {}
variable_arg = None
keywords_arg = None
child_count = len(args_node.children)
i = 0
while i < child_count:
argument = args_node.children[i]
if argument.type == syms.argument:
if len(argument.children) == 1:
expr_node = argument.children[0]
if keywords:
self.error("non-keyword arg after keyword arg",
expr_node)
if variable_arg:
self.error("only named arguments may follow "
"*expression", expr_node)
args.append(self.handle_expr(expr_node))
elif argument.children[1].type == syms.comp_for:
args.append(self.handle_genexp(argument))
else:
keyword_node = argument.children[0]
keyword_expr = self.handle_expr(keyword_node)
if isinstance(keyword_expr, ast.Lambda):
self.error("lambda cannot contain assignment",
keyword_node)
elif not isinstance(keyword_expr, ast.Name):
self.error("keyword can't be an expression",
keyword_node)
keyword = keyword_expr.id
if keyword in used_keywords:
self.error("keyword argument repeated", keyword_node)
used_keywords[keyword] = None
self.check_forbidden_name(keyword, keyword_node)
keyword_value = self.handle_expr(argument.children[2])
keywords.append(ast.keyword(keyword, keyword_value))
elif argument.type == tokens.STAR:
variable_arg = self.handle_expr(args_node.children[i + 1])
i += 1
elif argument.type == tokens.DOUBLESTAR:
keywords_arg = self.handle_expr(args_node.children[i + 1])
i += 1
i += 1
if not args:
args = None
if not keywords:
keywords = None
return ast.Call(callable_expr, args, keywords, variable_arg,
keywords_arg, callable_expr.lineno,
callable_expr.col_offset)
def parse_number(self, raw):
base = 10
if raw.startswith("-"):
negative = True
raw = raw.lstrip("-")
else:
negative = False
if raw.startswith("0"):
if len(raw) > 2 and raw[1] in "Xx":
base = 16
elif len(raw) > 2 and raw[1] in "Bb":
base = 2
## elif len(raw) > 2 and raw[1] in "Oo": # Fallback below is enough
## base = 8
elif len(raw) > 1:
base = 8
# strip leading characters
i = 0
limit = len(raw) - 1
while i < limit:
if base == 16 and raw[i] not in "0xX":
break
if base == 8 and raw[i] not in "0oO":
break
if base == 2 and raw[i] not in "0bB":
break
i += 1
raw = raw[i:]
if not raw[0].isdigit():
raw = "0" + raw
if negative:
raw = "-" + raw
w_num_str = self.space.wrap(raw)
w_index = None
w_base = self.space.wrap(base)
if raw[-1] in "lL":
tp = self.space.w_long
return self.space.call_function(tp, w_num_str, w_base)
elif raw[-1] in "jJ":
tp = self.space.w_complex
return self.space.call_function(tp, w_num_str)
try:
return self.space.call_function(self.space.w_int, w_num_str, w_base)
except error.OperationError, e:
if not e.match(self.space, self.space.w_ValueError):
raise
return self.space.call_function(self.space.w_float, w_num_str)
def handle_atom(self, atom_node):
first_child = atom_node.children[0]
first_child_type = first_child.type
if first_child_type == tokens.NAME:
return ast.Name(first_child.value, ast.Load,
first_child.lineno, first_child.column)
elif first_child_type == tokens.STRING:
space = self.space
encoding = self.compile_info.encoding
flags = self.compile_info.flags
unicode_literals = flags & consts.CO_FUTURE_UNICODE_LITERALS
try:
sub_strings_w = [parsestring.parsestr(space, encoding, s.value,
unicode_literals)
for s in atom_node.children]
except error.OperationError, e:
if not e.match(space, space.w_UnicodeError):
raise
# UnicodeError in literal: turn into SyntaxError
self.error(e.errorstr(space), atom_node)
sub_strings_w = [] # please annotator
# This implements implicit string concatenation.
if len(sub_strings_w) > 1:
w_sub_strings = space.newlist(sub_strings_w)
w_join = space.getattr(space.wrap(""), space.wrap("join"))
final_string = space.call_function(w_join, w_sub_strings)
else:
final_string = sub_strings_w[0]
return ast.Str(final_string, atom_node.lineno, atom_node.column)
elif first_child_type == tokens.NUMBER:
num_value = self.parse_number(first_child.value)
return ast.Num(num_value, atom_node.lineno, atom_node.column)
elif first_child_type == tokens.LPAR:
second_child = atom_node.children[1]
if second_child.type == tokens.RPAR:
return ast.Tuple(None, ast.Load, atom_node.lineno,
atom_node.column)
elif second_child.type == syms.yield_expr:
return self.handle_expr(second_child)
return self.handle_testlist_gexp(second_child)
elif first_child_type == tokens.LSQB:
second_child = atom_node.children[1]
if second_child.type == tokens.RSQB:
return ast.List(None, ast.Load, atom_node.lineno,
atom_node.column)
if len(second_child.children) == 1 or \
second_child.children[1].type == tokens.COMMA:
elts = self.get_expression_list(second_child)
return ast.List(elts, ast.Load, atom_node.lineno,
atom_node.column)
return self.handle_listcomp(second_child)
elif first_child_type == tokens.LBRACE:
maker = atom_node.children[1]
if maker.type == tokens.RBRACE:
return ast.Dict(None, None, atom_node.lineno, atom_node.column)
n_maker_children = len(maker.children)
if n_maker_children == 1 or maker.children[1].type == tokens.COMMA:
elts = []
for i in range(0, n_maker_children, 2):
elts.append(self.handle_expr(maker.children[i]))
return ast.Set(elts, atom_node.lineno, atom_node.column)
if maker.children[1].type == syms.comp_for:
return self.handle_setcomp(maker)
if (n_maker_children > 3 and
maker.children[3].type == syms.comp_for):
return self.handle_dictcomp(maker)
keys = []
values = []
for i in range(0, n_maker_children, 4):
keys.append(self.handle_expr(maker.children[i]))
values.append(self.handle_expr(maker.children[i + 2]))
return ast.Dict(keys, values, atom_node.lineno, atom_node.column)
elif first_child_type == tokens.BACKQUOTE:
expr = self.handle_testlist(atom_node.children[1])
return ast.Repr(expr, atom_node.lineno, atom_node.column)
else:
raise AssertionError("unknown atom")
def handle_testlist_gexp(self, gexp_node):
if len(gexp_node.children) > 1 and \
gexp_node.children[1].type == syms.comp_for:
return self.handle_genexp(gexp_node)
return self.handle_testlist(gexp_node)
def count_comp_fors(self, comp_node, for_type, if_type):
count = 0
current_for = comp_node
while True:
count += 1
if len(current_for.children) == 5:
current_iter = current_for.children[4]
else:
return count
while True:
first_child = current_iter.children[0]
if first_child.type == for_type:
current_for = current_iter.children[0]
break
elif first_child.type == if_type:
if len(first_child.children) == 3:
current_iter = first_child.children[2]
else:
return count
else:
raise AssertionError("should not reach here")
def count_comp_ifs(self, iter_node, for_type):
count = 0
while True:
first_child = iter_node.children[0]
if first_child.type == for_type:
return count
count += 1
if len(first_child.children) == 2:
return count
iter_node = first_child.children[2]
@specialize.arg(2)
def comprehension_helper(self, comp_node,
handle_source_expr_meth="handle_expr",
for_type=syms.comp_for, if_type=syms.comp_if,
iter_type=syms.comp_iter,
comp_fix_unamed_tuple_location=False):
handle_source_expression = getattr(self, handle_source_expr_meth)
fors_count = self.count_comp_fors(comp_node, for_type, if_type)
comps = []
for i in range(fors_count):
for_node = comp_node.children[1]
for_targets = self.handle_exprlist(for_node, ast.Store)
expr = handle_source_expression(comp_node.children[3])
assert isinstance(expr, ast.expr)
if len(for_node.children) == 1:
comp = ast.comprehension(for_targets[0], expr, None)
else:
col = comp_node.column
line = comp_node.lineno
# Modified in python2.7, see http://bugs.python.org/issue6704
if comp_fix_unamed_tuple_location:
expr_node = for_targets[0]
assert isinstance(expr_node, ast.expr)
col = expr_node.col_offset
line = expr_node.lineno
target = ast.Tuple(for_targets, ast.Store, line, col)
comp = ast.comprehension(target, expr, None)
if len(comp_node.children) == 5:
comp_node = comp_iter = comp_node.children[4]
assert comp_iter.type == iter_type
ifs_count = self.count_comp_ifs(comp_iter, for_type)
if ifs_count:
ifs = []
for j in range(ifs_count):
comp_node = comp_if = comp_iter.children[0]
ifs.append(self.handle_expr(comp_if.children[1]))
if len(comp_if.children) == 3:
comp_node = comp_iter = comp_if.children[2]
comp.ifs = ifs
if comp_node.type == iter_type:
comp_node = comp_node.children[0]
assert isinstance(comp, ast.comprehension)
comps.append(comp)
return comps
def handle_genexp(self, genexp_node):
elt = self.handle_expr(genexp_node.children[0])
comps = self.comprehension_helper(genexp_node.children[1],
comp_fix_unamed_tuple_location=True)
return ast.GeneratorExp(elt, comps, genexp_node.lineno,
genexp_node.column)
def handle_listcomp(self, listcomp_node):
elt = self.handle_expr(listcomp_node.children[0])
comps = self.comprehension_helper(listcomp_node.children[1],
"handle_testlist",
syms.list_for, syms.list_if,
syms.list_iter,
comp_fix_unamed_tuple_location=True)
return ast.ListComp(elt, comps, listcomp_node.lineno,
listcomp_node.column)
def handle_setcomp(self, set_maker):
elt = self.handle_expr(set_maker.children[0])
comps = self.comprehension_helper(set_maker.children[1],
comp_fix_unamed_tuple_location=True)
return ast.SetComp(elt, comps, set_maker.lineno, set_maker.column)
def handle_dictcomp(self, dict_maker):
key = self.handle_expr(dict_maker.children[0])
value = self.handle_expr(dict_maker.children[2])
comps = self.comprehension_helper(dict_maker.children[3],
comp_fix_unamed_tuple_location=True)
return ast.DictComp(key, value, comps, dict_maker.lineno,
dict_maker.column)
def handle_exprlist(self, exprlist, context):
exprs = []
for i in range(0, len(exprlist.children), 2):
child = exprlist.children[i]
expr = self.handle_expr(child)
self.set_context(expr, context)
exprs.append(expr)
return exprs
|
#!/bin/bash
# Script to run particle filter!
#
#
# Run particle filter
cd ./build
./particle_filter
|
<filename>tests/lib/api/index.js
exports.error = require('./error.js')
exports.path = require('./path.js')
exports.response = require('./response.js')
|
#!/bin/bash
java -classpath "/usr/share/java/*" druzy.jmita.JMita2 "$@"
|
#!/bin/bash
# if your program creates an output file (e.g., output.txt) compare it to the file created just now and store the difference in diff.log
touch diff.log
##################################
export PYTHONPATH=${APP_DIR}/../../common/python:$PYTHONPATH
${APP_DIR}/tools/compare-output ${APP_DIR}/../../datasets/lbm/short/output/reference.dat ${APP_DIR}/run/short/reference.dat > pass.txt
if ! grep -q "Pass" pass.txt; then
mv pass.txt diff.log
fi
#diff <(sed 's/:::Injecting.*::://g' stdout.txt) ${APP_DIR}/golden_stdout.txt > diff.log
touch stdout_diff.log
# comparing stderr generated by your program
touch stderr_diff.log
# Application specific output: The following check will be performed only if at least one of diff.log, stdout_diff.log, and stderr_diff.log is different
#grep "Checking computed" stdout.txt > selected_output.txt
#grep "Checking computed" ${APP_DIR}/golden_stdout.txt > selected_golden_output.txt
#diff selected_output.txt selected_golden_output.txt > special_check.log
|
# There's no need to chroot and do this during initial
# install, since there is a post-install script that
# does the same thing, saving time.
# Update X font indexes and the font cache:
if [ -x /usr/bin/mkfontdir ]; then
/usr/bin/mkfontscale /usr/share/fonts/TTF
/usr/bin/mkfontdir /usr/share/fonts/TTF
fi
if [ -x /usr/bin/fc-cache ]; then
/usr/bin/fc-cache /usr/share/fonts/TTF
fi
|
<filename>node_modules/react-icons-kit/md/ic_local_movies.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ic_local_movies = void 0;
var ic_local_movies = {
"viewBox": "0 0 24 24",
"children": [{
"name": "path",
"attribs": {
"d": "M0 0h24v24H0z",
"fill": "none"
},
"children": []
}, {
"name": "path",
"attribs": {
"d": "M18 3v2h-2V3H8v2H6V3H4v18h2v-2h2v2h8v-2h2v2h2V3h-2zM8 17H6v-2h2v2zm0-4H6v-2h2v2zm0-4H6V7h2v2zm10 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V7h2v2z"
},
"children": []
}]
};
exports.ic_local_movies = ic_local_movies;
|
@manager.command
def run():
"""
Run the server.
"""
# Start the server
start_server()
# Print a message indicating that the server has started
print('[+] Server started successfully.')
|
<gh_stars>0
from django.apps import AppConfig
class AdmzoneConfig(AppConfig):
name = 'admZone'
|
function getNextSunday(date) {
let curr = new Date(date);
let weekDayNum = curr.getDay();
let diff = 7 - weekDayNum;
curr.setDate(curr.getDate() + diff);
let nextSunday = curr.toISOString().split('T')[0];
return nextSunday;
}
let result = getNextSunday(new Date("December 25, 2020"));
console.log(result); // output: "2021-01-03"
|
def validate_token(password: str) -> bool:
encrypted_token = "MjM4NDk0NzU2NTIxMzc3Nzky.CunGFQ.wUILz7z6HoJzVeq6pyHPmVgQgV4"
decrypted_token = ""
shift = len(password) # Use the length of the password as the shift value
for char in encrypted_token:
if char.isalpha():
if char.islower():
decrypted_token += chr((ord(char) - shift - 97) % 26 + 97)
else:
decrypted_token += chr((ord(char) - shift - 65) % 26 + 65)
else:
decrypted_token += char
return decrypted_token == password
|
//
// Created by Zhukov on 2020/7/23.
//
#ifndef MODBUSMASTER_FRAME_CONVERSION_H
#define MODBUSMASTER_FRAME_CONVERSION_H
uint8_t char_to_number(const uint8_t ch);
uint8_t number_to_char(const uint8_t ch);
void ascii_frame_to_standard_modbus(uint8_t* rx, uint16_t length, uint8_t* result, uint16_t* result_length);
void standard_modbus_to_ascii_frame(uint8_t* rx, uint16_t length, uint8_t* result, uint16_t* result_length);
#endif //MODBUSMASTER_FRAME_CONVERSION_H
|
def print_unique_characters(string):
unique_characters = []
for char in string:
if char not in unique_characters:
unique_characters.append(char)
unique_characters.sort()
for char in unique_characters:
print(char, end="")
|
<form action = "submit.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="email">Email Address:</label>
<input type="email" id="email" name="email"><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age"><br>
<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select><br>
<label for="color">Favorite Color:</label>
<input type="text" id="color" name="color"><br>
<input type="submit" value="Submit">
</form>
|
#!/usr/bin/env sh
set -e
python -m validate $@
|
package io.github.pmckeown.dependencytrack.score;
import io.github.pmckeown.dependencytrack.CommonConfig;
import io.github.pmckeown.dependencytrack.AbstractDependencyTrackMojo;
import io.github.pmckeown.dependencytrack.DependencyTrackException;
import io.github.pmckeown.util.Logger;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import javax.inject.Inject;
import static java.lang.String.format;
/**
* Provides the capability to find the current Inherited Risk Score as determined by the Dependency Track Server.
*
* Specific configuration options are:
* <ol>
* <li>inheritedRiskScoreThreshold</li>
* </ol>
*
* @author <NAME>
*/
@Mojo(name = "score", defaultPhase = LifecyclePhase.VERIFY)
public class ScoreMojo extends AbstractDependencyTrackMojo {
@Parameter
private Integer inheritedRiskScoreThreshold;
private ScoreAction scoreAction;
@Inject
public ScoreMojo(ScoreAction scoreAction, CommonConfig commonConfig, Logger logger) {
super(commonConfig, logger);
this.scoreAction = scoreAction;
}
@Override
public void performAction() throws MojoFailureException, MojoExecutionException {
try {
Integer inheritedRiskScore = scoreAction.determineScore(inheritedRiskScoreThreshold);
failBuildIfThresholdIsBreached(inheritedRiskScore);
} catch (DependencyTrackException ex) {
handleFailure(format("Failed to determine score for: %s-%s", commonConfig.getProjectName(),
commonConfig.getProjectVersion()));
}
}
private void failBuildIfThresholdIsBreached(Integer inheritedRiskScore) throws MojoFailureException {
logger.debug("Inherited Risk Score Threshold set to: %s",
inheritedRiskScoreThreshold == null ? "Not set" : inheritedRiskScoreThreshold);
if (inheritedRiskScoreThreshold != null && inheritedRiskScore > inheritedRiskScoreThreshold) {
throw new MojoFailureException(format("Inherited Risk Score [%d] was greater than the " +
"configured threshold [%d]", inheritedRiskScore, inheritedRiskScoreThreshold));
}
}
/*
* Setters for dependency injection in tests
*/
void setInheritedRiskScoreThreshold(Integer threshold) {
this.inheritedRiskScoreThreshold = threshold;
}
}
|
// https://codeforces.com/contest/922/problem/D
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
cin.tie(0), ios::sync_with_stdio(0);
int n;
cin >> n;
vector<string> t(n);
for (int i = 0; i < n; i++) cin >> t[i];
sort(t.begin(), t.end(), [&](string &i, string &j) -> bool {
ll si = 0, hi = 0, sj = 0, hj = 0;
for (char c : i) if (c == 's') si++; else hi++;
for (char c : j) if (c == 's') sj++; else hj++;
if (!si && !sj) return i.size() < j.size();
if (!hi && !hj) return i.size() < j.size();
if (!si) return 0;
if (!sj) return 1;
if (!hi) return 1;
if (!hj) return 0;
return si*hj > sj*hi;
});
ll s = 0, sum = 0;
for (int i = 0; i < n; i++)
for (char c : t[i])
if (c == 's') s++;
else sum += s;
cout << sum << '\n';
}
|
<filename>packages/friends/src/index.ts
export * from './FriendsList';
|
#!/usr/bin/env bash
# this will create a directory '/etc/vagrant' if it doesn't exist
# each vagrant provision step will create a file within this folder
# to determine if it needs to run again
# if you want to run a particular step on a subsequent 'vagrant up', simply remove the file
# if you want to run all steps on a subsequent 'vagrant up', simple remove the /etc/vagrant folder
if [ ! -e /etc/vagrant ]
then
mkdir /etc/vagrant
fi
# make some of our helper scripts executable
chmod a+x /vagrant/vagrant/scripts/reset
chmod a+x /vagrant/vagrant/scripts/run
|
<reponame>Jerrypiglet/Total3DUnderstanding
import numpy as np
import os.path as osp
def read_cam_params(camFile):
assert osp.isfile(str(camFile))
with open(str(camFile), 'r') as camIn:
# camNum = int(camIn.readline().strip() )
cam_data = camIn.read().splitlines()
cam_num = int(cam_data[0])
cam_params = np.array([x.split(' ') for x in cam_data[1:]]).astype(np.float)
assert cam_params.shape[0] == cam_num * 3
cam_params = np.split(cam_params, cam_num, axis=0) # [[origin, lookat, up], ...]
return cam_params
def normalize(x):
return x / np.linalg.norm(x)
def project_v(v, cam_R, cam_t, cam_K, if_only_proj_front_v=True, if_return_front_flags=False):
v_transformed = cam_R @ v.T + cam_t
# print(v_transformed[2:3, :])
if if_only_proj_front_v:
v_transformed = v_transformed * (v_transformed[2:3, :] > 0.)
p = cam_K @ v_transformed
if not if_return_front_flags:
return np.vstack([p[0, :]/(p[2, :]+1e-8), p[1, :]/(p[2, :]+1e-8)]).T
else:
return np.vstack([p[0, :]/(p[2, :]+1e-8), p[1, :]/(p[2, :]+1e-8)]).T, (v_transformed[2:3, :] > 0.).flatten().tolist()
def project_v_homo(v, cam_transformation4x4, cam_K):
# https://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/EPSRC_SSAZ/img30.gif
# https://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/EPSRC_SSAZ/node3.html
v_homo = np.hstack([v, np.ones((v.shape[0], 1))])
cam_K_homo = np.hstack([cam_K, np.zeros((3, 1))])
# v_transformed = cam_R @ v.T + cam_t
v_transformed = cam_transformation4x4 @ v_homo.T
v_transformed_nonhomo = np.vstack([v_transformed[0, :]/v_transformed[3, :], v_transformed[1, :]/v_transformed[3, :], v_transformed[2, :]/v_transformed[3, :]])
# print(v_transformed.shape, v_transformed_nonhomo.shape)
v_transformed = v_transformed * (v_transformed_nonhomo[2:3, :] > 0.)
p = cam_K_homo @ v_transformed
return np.vstack([p[0, :]/p[2, :], p[1, :]/p[2, :]]).T
|
<filename>js/sykepengesoknad/soknad-behandlingsdager/SoknadBehandlingsdager.js
import React from 'react';
import PropTypes from 'prop-types';
import beregnSteg, { KVITTERING } from '../utils/beregnSteg';
import SoknadKvitteringSjekker from '../felleskomponenter/SoknadKvitteringSjekker';
import { soknadPt } from '../../propTypes';
import { AVBRUTT, KORRIGERT, NY, SENDT, UTKAST_TIL_KORRIGERING } from '../enums/soknadstatuser';
import Feilmelding from '../../components/Feilmelding';
import EttSporsmalPerSideContainer from '../felleskomponenter/ett-sporsmal-per-side/EttSporsmalPerSideContainer';
import SendtSoknadBehandlingsdager from './SendtSoknadBehandlingsdager';
import AvbruttSoknadBehandlingsdager from './AvbruttSoknadBehandlingsdager';
const SoknadBehandlingsdagerSkjema = (props) => {
const { sti } = props;
const steg = beregnSteg(sti);
switch (steg) {
case KVITTERING: {
return <SoknadKvitteringSjekker soknad={props.soknad} />;
}
default: {
return <EttSporsmalPerSideContainer {...props} />;
}
}
};
SoknadBehandlingsdagerSkjema.propTypes = {
sti: PropTypes.string,
soknad: soknadPt,
};
const SoknadBehandlingsdager = (props) => {
const { soknad, sti } = props;
switch (soknad.status) {
case NY:
case UTKAST_TIL_KORRIGERING: {
return <SoknadBehandlingsdagerSkjema {...props} />;
}
case SENDT:
case KORRIGERT: {
if (beregnSteg(sti) === KVITTERING) {
return <SoknadKvitteringSjekker {...props} />;
}
return <SendtSoknadBehandlingsdager {...props} />;
}
case AVBRUTT: {
return <AvbruttSoknadBehandlingsdager {...props} />;
}
default: {
return <Feilmelding melding="Sรธknaden har ukjent status" />;
}
}
};
SoknadBehandlingsdager.propTypes = {
sti: PropTypes.string,
soknad: soknadPt,
};
export default SoknadBehandlingsdager;
|
def solveNQueens(n):
# An empty board
board = [[0 for x in range(n)] for y in range(n)]
# Initialize result
result = []
# Solve the problem
solveNQueensUtil(board, 0, result)
return result
def solveNQueensUtil(board, col, result):
if col >= len(board):
result.append(board) # Add solution
return
# Consider the rows
for i in range(len(board)):
# If this row can be used
if isSafe(board, i, col):
board[i][col] = 1 # Place the queen
solveNQueensUtil(board, col + 1, result)
board[i][col] = 0 # Backtrack
def isSafe(board, row, col):
# For the column
for i in range(col):
if board[row][i] == 1:
return False
# For the upper left diagonal
i, j = row, col
while i >=0 and j >= 0:
if board[i][j] == 1:
return False
i, j = i-1, j-1
# For the lower left diagonal
i, j = row, col
while j >= 0 and i < len(board):
if board[i][j] == 1:
return False
i, j = i+1, j-1
return True
|
import {MDCFormField} from '@material/form-field';
import {MDCCheckbox} from '@material/checkbox';
const checkbox = new MDCCheckbox(document.querySelector('.mdc-checkbox'));
const formField = new MDCFormField(document.querySelector('.mdc-form-field'));
formField.input = checkbox;
|
import { StyleSheet } from 'react-native'
export const blue1 = '#d1dfed'
export const darkBlue1 = '#146dc7'
export const theme = StyleSheet.create({
background: {
flex: 1,
width: '100%',
resizeMode: "cover",
backgroundColor: blue1,
},
header: {
backgroundColor: darkBlue1,
},
content: {
padding: 15,
},
sidebarIcon: {
color: darkBlue1,
},
headerIcon: {
color: 'black',
},
errorText: {
color: 'red',
},
dangerIcon:{
color: 'red',
},
warningIcon: {
color: 'orange',
}
})
|
def modify_statement(stocks):
""" Modify the financial statement according to the new stocks. """
new_stocks = []
for stock in stocks:
new_stocks.append(stock + 5)
return new_stocks
modify_statement(stocks)
|
/**
* MailSlurp API
* MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://www.mailslurp.com) - Get an [API KEY](https://app.mailslurp.com/sign-up/) - Generated [SDK Clients](https://www.mailslurp.com/docs/) - [Examples](https://github.com/mailslurp/examples) repository
*
* OpenAPI spec version: 6.5.2
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { HttpFile } from '../http/http.ts';
/**
* Options for replying to an alias email using the alias inbox
*/
export class ReplyToAliasEmailOptions {
/**
* Body of the reply email you want to send
*/
'body': string;
/**
* Is the reply HTML
*/
'isHTML': boolean;
/**
* The charset that your message should be sent with. Optional. Default is UTF-8
*/
'charset'?: string;
/**
* List of uploaded attachments to send with the reply. Optional.
*/
'attachments'?: Array<string>;
/**
* Template variables if using a template
*/
'templateVariables'?: { [key: string]: any; };
/**
* Template ID to use instead of body. Will use template variable map to fill defined variable slots.
*/
'template'?: string;
/**
* How an email should be sent based on its recipients
*/
'sendStrategy'?: ReplyToAliasEmailOptionsSendStrategyEnum;
/**
* Optionally use inbox name as display name for sender email address
*/
'useInboxName'?: boolean;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{
"name": "body",
"baseName": "body",
"type": "string",
"format": ""
},
{
"name": "isHTML",
"baseName": "isHTML",
"type": "boolean",
"format": ""
},
{
"name": "charset",
"baseName": "charset",
"type": "string",
"format": ""
},
{
"name": "attachments",
"baseName": "attachments",
"type": "Array<string>",
"format": ""
},
{
"name": "templateVariables",
"baseName": "templateVariables",
"type": "{ [key: string]: any; }",
"format": ""
},
{
"name": "template",
"baseName": "template",
"type": "string",
"format": "uuid"
},
{
"name": "sendStrategy",
"baseName": "sendStrategy",
"type": "ReplyToAliasEmailOptionsSendStrategyEnum",
"format": ""
},
{
"name": "useInboxName",
"baseName": "useInboxName",
"type": "boolean",
"format": ""
} ];
static getAttributeTypeMap() {
return ReplyToAliasEmailOptions.attributeTypeMap;
}
public constructor() {
}
}
export type ReplyToAliasEmailOptionsSendStrategyEnum = "SINGLE_MESSAGE" ;
|
def countLicenseComments(file_path: str) -> int:
with open(file_path, 'r') as file:
content = file.read()
license_comment_count = content.count('// http://www.apache.org/licenses/LICENSE-2.0')
return license_comment_count
|
#!/bin/bash
FN="breastCancerNKI_1.24.0.tar.gz"
URLS=(
"https://bioconductor.org/packages/3.10/data/experiment/src/contrib/breastCancerNKI_1.24.0.tar.gz"
"https://bioarchive.galaxyproject.org/breastCancerNKI_1.24.0.tar.gz"
"https://depot.galaxyproject.org/software/bioconductor-breastcancernki/bioconductor-breastcancernki_1.24.0_src_all.tar.gz"
)
MD5="9ad9f4370b9b1dfc1f03ce49d07c32fb"
# Use a staging area in the conda dir rather than temp dirs, both to avoid
# permission issues as well as to have things downloaded in a predictable
# manner.
STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM
mkdir -p $STAGING
TARBALL=$STAGING/$FN
SUCCESS=0
for URL in ${URLS[@]}; do
curl $URL > $TARBALL
[[ $? == 0 ]] || continue
# Platform-specific md5sum checks.
if [[ $(uname -s) == "Linux" ]]; then
if md5sum -c <<<"$MD5 $TARBALL"; then
SUCCESS=1
break
fi
else if [[ $(uname -s) == "Darwin" ]]; then
if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then
SUCCESS=1
break
fi
fi
fi
done
if [[ $SUCCESS != 1 ]]; then
echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:"
printf '%s\n' "${URLS[@]}"
exit 1
fi
# Install and clean up
R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL
rm $TARBALL
rmdir $STAGING
|
<filename>restapi/src/main/java/io/stargate/web/docsapi/service/query/search/db/impl/SubDocumentSearchQueryBuilder.java
/*
* Copyright The Stargate Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.stargate.web.docsapi.service.query.search.db.impl;
import io.stargate.db.query.Predicate;
import io.stargate.db.query.builder.BuiltCondition;
import io.stargate.web.docsapi.service.query.DocsApiConstants;
import java.util.Collection;
import java.util.List;
/**
* Search query builder that matches all rows on the given #subDocumentsPath for a single document.
*/
public class SubDocumentSearchQueryBuilder extends PathSearchQueryBuilder {
/** Doc id to target. */
private final String documentId;
public SubDocumentSearchQueryBuilder(String documentId, List<String> subDocumentsPath) {
super(subDocumentsPath);
this.documentId = documentId;
}
/** {@inheritDoc} */
@Override
public Collection<BuiltCondition> getPredicates() {
Collection<BuiltCondition> predicates = super.getPredicates();
predicates.add(BuiltCondition.of(DocsApiConstants.KEY_COLUMN_NAME, Predicate.EQ, documentId));
return predicates;
}
}
|
#!/bin/bash
# This script parses in the command line parameters from runCust,
# maps them to the correct command line parameters for DispNet training script and launches that task
# The last line of runCust should be: bash $CONFIG_FILE --data-dir $DATA_DIR --log-dir $LOG_DIR
# Parse the command line parameters
# that runCust will give out
DATA_DIR=NONE
LOG_DIR=NONE
CONFIG_DIR=NONE
MODEL_DIR=NONE
# Parsing command line arguments:
while [[ $# > 0 ]]
do
key="$1"
case $key in
-h|--help)
echo "Usage: run_dispnet_training_philly.sh [run_options]"
echo "Options:"
echo " -d|--data-dir <path> - directory path to input data (default NONE)"
echo " -l|--log-dir <path> - directory path to save the log files (default NONE)"
echo " -p|--config-file-dir <path> - directory path to config file directory (default NONE)"
echo " -m|--model-dir <path> - directory path to output model file (default NONE)"
exit 1
;;
-d|--data-dir)
DATA_DIR="$2"
shift # pass argument
;;
-p|--config-file-dir)
CONFIG_DIR="$2"
shift # pass argument
;;
-m|--model-dir)
MODEL_DIR="$2"
shift # pass argument
;;
-l|--log-dir)
LOG_DIR="$2"
shift
;;
*)
echo Unkown option $key
;;
esac
shift # past argument or value
done
# Prints out the arguments that were passed into the script
echo "DATA_DIR=$DATA_DIR"
echo "LOG_DIR=$LOG_DIR"
echo "CONFIG_DIR=$CONFIG_DIR"
echo "MODEL_DIR=$MODEL_DIR"
# Run training on philly
# Add the root folder of the code to the PYTHONPATH
export PYTHONPATH=$PYTHONPATH:$CONFIG_DIR
# Run the actual job
python $CONFIG_DIR/examples/AnytimeNetwork/resnet-ann.py \
--data_dir=$DATA_DIR \
--log_dir=$LOG_DIR \
--model_dir=$MODEL_DIR \
--load=${MODEL_DIR}/checkpoint \
-f=4 --opt_at=-1 -n=9 -c=32 -s=3 --samloss=0 --ds_name=cifar10 --batch_size=128 --nr_gpu=4 --resnet_version=resnext --exp_gamma=0.3 --sum_rand_ratio=2 --last_reward_rate=0.8
|
export interface IStorageService {
/**
* Store a buffer in the storage system.
* @param name The name of the item to store.
* @param buffer The buffer of data to store.
*/
set(name: string, buffer: Buffer): Promise<void>;
/**
* Get a buffer from the storage system.
* @param name The name of the item to retrieve.
* @returns The buffer retrieved.
*/
get(name: string): Promise<Buffer | undefined>;
/**
* Remove a buffer from the storage system.
* @param name The name of the item to remove.
*/
remove(name: string): Promise<void>;
}
|
sudo /etc/init.d/mysql restart
|
#!/bin/bash
# j: ๅ ้คๆๅฎ็ฎๅฝไธๆๆไนฑ็ ๆไปถ,ไนฑ็ ๆไปถไธ่ฌๅคงๅฐ้ฝไธบ0
# ่ทๅๆไปถๅคนไธๆๆๆไปถ
folder="/root/java-service"
soft_files=$(ls $folder)
for sfile in ${soft_files}
do
if [ ! -s "${sfile}" ]
then
echo "soft: ${sfile}"
rm ${sfile}
fi
done
|
#!/bin/sh
#rm -rf src/test/resources/gold/lexer/expected/*
rm -rf src/test/resources/gold/parser/current/*.psi
rm -rf out
|
#!/bin/sh
git submodule init
git submodule update
test -x .setup_hook.sh && ./.setup_hook.sh
cd hardware/esp8266com/esp8266
git submodule init
git submodule update
cd tools
./get.py
|
<gh_stars>10-100
package com.yoga.utility.qr.service;
import com.alibaba.fastjson.TypeReference;
import com.yoga.utility.qr.dto.UploadedFileBean;
import com.yoga.utility.qr.model.QRBindInfo;
import com.yoga.core.base.BaseService;
import com.yoga.core.exception.BusinessException;
import com.yoga.core.utils.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class QRCodeService extends BaseService {
private final static String RedisKey_Qr_Common = "QR.Common";
private final static String RedisKey_Qr_file = "Qr.File";
public interface ActionQueryEntry {
String actionQuery(String code);
}
private List<ActionQueryEntry> actionQueryEntries = new ArrayList<>();
public void registerQueryEntry(ActionQueryEntry entry) {
actionQueryEntries.add(entry);
}
public void unregisterQueryEntry(ActionQueryEntry entry) {
actionQueryEntries.remove(entry);
}
@PostConstruct
public void registerEntry() {
registerQueryEntry(code-> {
QRBindInfo info = redisOperator.get(RedisKey_Qr_Common + code, QRBindInfo.class);
if (info == null) return null;
return info.getUrl() + "?code=" + code;
});
}
public String actionQuery(String code) {
for (ActionQueryEntry entry : actionQueryEntries) {
String url = entry.actionQuery(code);
if (StringUtil.isNotBlank(url)) return url;
}
return null;
}
public void bindToQr(String code, HttpServletRequest request, String url, Map<String, Object> params) {
org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
Session session = subject == null ? null : subject.getSession();
String token = session == null ? null : session.getId().toString();
QRBindInfo bindInfo = new QRBindInfo(request, url, params, token);
redisOperator.set(RedisKey_Qr_Common + code, bindInfo, 600);
}
public void bindToQr(String code, HttpServletRequest request, String url, Map<String, Object> params, String token) {
QRBindInfo bindInfo = new QRBindInfo(request, url, params, token);
redisOperator.set(RedisKey_Qr_Common + code, bindInfo, 600);
}
public QRBindInfo unbindFromQr(String code) {
String key = RedisKey_Qr_Common + code;
QRBindInfo info = redisOperator.get(key, QRBindInfo.class);
if (info == null) throw new BusinessException("ๆชๆพๅฐไบ็ปด็ ไฟกๆฏ");
redisOperator.remove(key);
return info;
}
public QRBindInfo pickFromQr(String code) {
String key = RedisKey_Qr_Common + code;
QRBindInfo info = redisOperator.get(key, QRBindInfo.class);
if (info == null) throw new BusinessException("ๆชๆพๅฐไบ็ปด็ ไฟกๆฏ");
return info;
}
public void bindFilesToQr(String code, List<UploadedFileBean> files) {
redisOperator.set(RedisKey_Qr_file + code, files, 60);
}
public List<UploadedFileBean> unbindFilesFromQr(String code) {
String key = RedisKey_Qr_file + code;
return redisOperator.get(key, new TypeReference<List<UploadedFileBean>>(){});
}
}
|
/* mbed Microcontroller Library
*******************************************************************************
* Copyright (c) 2015 WIZnet Co.,Ltd. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of ARM Limited nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************
*/
#include <stddef.h>
#include "cmsis.h"
#include "gpio_irq_api.h"
#include "pinmap.h"
#include "mbed_error.h"
#define EDGE_NONE (0)
#define EDGE_RISE (1)
#define EDGE_FALL (2)
#define EDGE_BOTH (3)
static gpio_irq_handler irq_handler;
static uint32_t channel_ids[4][16];
#ifdef __cplusplus
extern "C"{
#endif
void port_generic_handler(GPIO_TypeDef* GPIOx, uint32_t port_num);
void PORT0_Handler(void)
{
NVIC_ClearPendingIRQ(PORT0_IRQn);
port_generic_handler(GPIOA, 0);
}
void PORT1_Handler(void)
{
port_generic_handler(GPIOB, 1);
}
void PORT2_Handler(void)
{
port_generic_handler(GPIOC, 2);
}
void PORT3_Handler(void)
{
port_generic_handler(GPIOD, 3);
}
void port_generic_handler(GPIO_TypeDef* GPIOx, uint32_t port_num)
{
int i = 0;
int loop = 16;
if(GPIOx == GPIOD) loop = 5;
for(i=0; i<loop; i++)
{
if(GPIOx->Interrupt.INTSTATUS & (1 << i))
{
GPIOx->Interrupt.INTCLEAR |= (1 << i);
if(GPIOx->INTPOLSET >> i) //rising
irq_handler(channel_ids[port_num][i], IRQ_RISE);
else //falling
irq_handler(channel_ids[port_num][i], IRQ_FALL);
}
}
}
#ifdef __cplusplus
}
#endif
int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32_t id)
{
obj->port_num = WIZ_PORT(pin);
obj->pin_num = WIZ_PIN_NUM(pin);
obj->pin_index = WIZ_PIN_INDEX(pin);
//gpio_irq_disable(obj);
if (pin == NC) return -1;
if(obj->port_num == 0)
obj->irq_n = PORT0_IRQn;
else if(obj->port_num == 1)
obj->irq_n = PORT1_IRQn;
else if(obj->port_num == 2)
obj->irq_n = PORT2_IRQn;
else
obj->irq_n = PORT3_IRQn;
obj->pin = pin;
obj->event = EDGE_NONE;
// Enable EXTI interrupt
NVIC_ClearPendingIRQ(obj->irq_n);
NVIC_EnableIRQ(obj->irq_n);
channel_ids[obj->port_num][obj->pin_num] = id;
irq_handler = handler;
return 0;
}
void gpio_irq_free(gpio_irq_t *obj)
{
channel_ids[obj->port_num][obj->pin_num] = 0;
obj->event = EDGE_NONE;
}
void gpio_irq_set(gpio_irq_t *obj, gpio_irq_event event, uint32_t enable)
{
GPIO_TypeDef *gpio = (GPIO_TypeDef *)Get_GPIO_BaseAddress(obj->port_num);
if (enable) {
if (event == IRQ_RISE) {
gpio->INTPOLSET |= obj->pin_index;
obj->event = EDGE_RISE;
obj->rise_null = 0;
}
else if (event == IRQ_FALL) {
gpio->INTPOLCLR |= obj->pin_index;
obj->event = EDGE_FALL;
obj->fall_null = 0;
}
gpio->INTENCLR |= obj->pin_index;
gpio->INTTYPESET |= obj->pin_index;
gpio->INTENSET |= obj->pin_index;
} else {
if (event == IRQ_RISE) {
obj->rise_null = 1;
if(obj->fall_null)
gpio->INTENCLR |= obj->pin_index;
}
else if (event == IRQ_FALL) {
obj->fall_null = 1;
if(obj->rise_null)
gpio->INTENCLR |= obj->pin_index;
}
}
}
void gpio_irq_enable(gpio_irq_t *obj)
{
NVIC_EnableIRQ(obj->irq_n);
}
void gpio_irq_disable(gpio_irq_t *obj)
{
NVIC_DisableIRQ(obj->irq_n);
obj->event = EDGE_NONE;
}
|
/*
* MIT License
*
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.jamsimulator.jams.gui.mips.simulator.flow.multicycle;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import net.jamsimulator.jams.event.Listener;
import net.jamsimulator.jams.gui.mips.simulator.flow.FlowTable;
import net.jamsimulator.jams.gui.mips.simulator.flow.SegmentedFlowEntry;
import net.jamsimulator.jams.mips.architecture.MultiCycleArchitecture;
import net.jamsimulator.jams.mips.simulation.MIPSSimulation;
import net.jamsimulator.jams.mips.simulation.event.SimulationResetEvent;
import net.jamsimulator.jams.mips.simulation.event.SimulationStopEvent;
import net.jamsimulator.jams.mips.simulation.event.SimulationUndoStepEvent;
import net.jamsimulator.jams.mips.simulation.multicycle.event.MultiCycleStepEvent;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class MultiCycleFlowTable extends FlowTable {
private LinkedList<MultiCycleStepEvent.After> toAdd;
private Map<Long, SegmentedFlowEntry> entries;
private long firstCycle;
public MultiCycleFlowTable(MIPSSimulation<? extends MultiCycleArchitecture> simulation) {
super(simulation);
firstCycle = 0;
if (simulation.getData().canCallEvents()) {
toAdd = new LinkedList<>();
entries = new HashMap<>();
simulation.registerListeners(this, true);
} else {
flows.setAlignment(Pos.CENTER);
flows.getChildren().add(new Label("Events are disabled."));
}
}
@SuppressWarnings("unchecked")
@Override
public MIPSSimulation<? extends MultiCycleArchitecture> getSimulation() {
return (MIPSSimulation<? extends MultiCycleArchitecture>) super.getSimulation();
}
@Override
public void setStepSize(double stepSize) {
super.setStepSize(stepSize);
refresh();
}
private void flushEvents() {
if (toAdd.isEmpty()) return;
String start = String.valueOf(simulation.getRegisters().getValidRegistersStarts()
.stream().findAny().orElse('$'));
MultiCycleStepEvent.After event;
SegmentedFlowEntry entry;
while (!toAdd.isEmpty()) {
event = toAdd.pop();
entry = entries.get(event.getInstructionNumber());
if (entry == null) {
entry = new SegmentedFlowEntry(flows.getChildren().size(), this,
event.getInstruction(), start, event.getInstructionNumber(), event.getCycle());
entries.put(event.getInstructionNumber(), entry);
flows.getChildren().add(entry);
}
if (entries.size() > maxItems) {
SegmentedFlowEntry toRemove = (SegmentedFlowEntry) flows.getChildren().remove(0);
entries.remove(toRemove.getInstructionNumber());
}
entry.addStep(event.getCycle(), event.getExecutedStep(), stepSize, firstCycle, false);
}
long localCycle = firstCycle;
firstCycle = ((SegmentedFlowEntry) flows.getChildren().get(0)).getStartingCycle();
if (localCycle != firstCycle) {
refresh();
}
refreshVisualizer();
}
@Override
public long getFirstCycle() {
return firstCycle;
}
@Override
public long getLastCycle() {
if (flows.getChildren().isEmpty()) return 0;
var last = (SegmentedFlowEntry) flows.getChildren().get(flows.getChildren().size() - 1);
return last.getLastCycle();
}
public void refresh() {
int index = 0;
for (Node child : flows.getChildren()) {
if (child instanceof SegmentedFlowEntry) {
((SegmentedFlowEntry) child).refresh(index++, stepSize, firstCycle);
}
}
}
@Listener
private void onInstructionExecuted(MultiCycleStepEvent.After event) {
//Adding items to a separate list prevents the app to block.
toAdd.add(event);
if (event.getInstructionNumber() - toAdd.getFirst().getInstructionNumber() >= maxItems) {
long number = toAdd.removeFirst().getInstructionNumber();
while (toAdd.getFirst().getInstructionNumber() == number) {
toAdd.removeFirst();
}
}
}
@Listener
private void onSimulationStop(SimulationStopEvent event) {
Platform.runLater(this::flushEvents);
}
@Listener
private void onSimulationReset(SimulationResetEvent event) {
flows.getChildren().clear();
entries.clear();
refreshVisualizer();
}
@Listener
private void onSimulationUndo(SimulationUndoStepEvent.After event) {
SegmentedFlowEntry cycle = ((SegmentedFlowEntry) flows.getChildren().get(flows.getChildren().size() - 1));
if (cycle.removeCycle(event.getUndoCycle()) && cycle.isEmpty()) {
entries.remove(cycle.getInstructionNumber());
flows.getChildren().remove(flows.getChildren().size() - 1);
}
refreshVisualizer();
}
}
|
<filename>javascript-version/bot/events/onready.js
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require('../files/config.json')
const {servers, presence} = require("../utils/util.js")
const chalk = require("chalk")
module.exports = (client) => {
const { status, games, interval } = config.presence;
presence(status, games, interval, client)
async function startup() {
console.log(chalk.blue('โ โ( login )โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ'))
console.log(chalk.blue("โ โ( Amount's )โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ"))
console.log(chalk.blue(`โ Trickedbot > Active in ${client.guilds.cache.size} servers! โ\nโ Trickedbot > ${client.users.cache.size} People, thats alot โ\nโ Trickedbot > ${client.channels.cache.size} different channels, thats alot โ`))
console.log(chalk.blue('โ โ( Servers )โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ'))
console.log(chalk.blue(servers(client)))
}
startup(); // โ โ
};
module.exports.config = {
displayName: 'onready',
dbName: 'onready',
loadDBFirst: true,
}
|
#!/bin/bash
# Copyright 2021 Collate
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#cd ..
echo "Maven clean package"
mvn -DskipTests clean package
echo "Docker compose up"
cd docker/local-metadata/
docker-compose up -d --build
echo "docker build done"
echo "waiting for data ingestion"
while ! wget -O /dev/null -o /dev/null localhost:8585/api/v1/teams/name/Finance; do sleep 5; done
|
<gh_stars>1-10
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package models.fe.tcsp
import models.des.SubscriptionView
import play.api.libs.json._
import utils.CommonMethods
case class TcspTypes(serviceProviders: Set[ServiceProvider])
sealed trait ServiceProvider {
val value: String =
this match {
case NomineeShareholdersProvider => "01"
case TrusteeProvider => "02"
case RegisteredOfficeEtc => "03"
case CompanyDirectorEtc => "04"
case CompanyFormationAgent => "05"
}
}
case object NomineeShareholdersProvider extends ServiceProvider
case object TrusteeProvider extends ServiceProvider
case object RegisteredOfficeEtc extends ServiceProvider
case object CompanyDirectorEtc extends ServiceProvider
case object CompanyFormationAgent extends ServiceProvider
object TcspTypes {
implicit val jsonReads: Reads[TcspTypes] = {
import play.api.libs.json.Reads._
import play.api.libs.json._
(__ \ "serviceProviders").read[Set[String]].flatMap { x: Set[String] =>
x.map {
case "01" => Reads(_ => JsSuccess(NomineeShareholdersProvider)) map identity[ServiceProvider]
case "02" => Reads(_ => JsSuccess(TrusteeProvider)) map identity[ServiceProvider]
case "03" => Reads(_ => JsSuccess(RegisteredOfficeEtc)) map identity[ServiceProvider]
case "04" => Reads(_ => JsSuccess(CompanyDirectorEtc)) map identity[ServiceProvider]
case "05" => Reads(_ => JsSuccess(CompanyFormationAgent)) map identity[ServiceProvider]
case _ =>
Reads(_ => JsError((JsPath \ "serviceProviders") -> JsonValidationError("error.invalid")))
}.foldLeft[Reads[Set[ServiceProvider]]](
Reads[Set[ServiceProvider]](_ => JsSuccess(Set.empty))
) {
(result, data) =>
data flatMap { m =>
result.map { n =>
n + m
}
}
} map TcspTypes.apply
}
}
implicit val jsonWrite = Writes[TcspTypes] {
case TcspTypes(services) =>
Json.obj(
"serviceProviders" -> (services map {
_.value
}).toSeq
) ++ services.foldLeft[JsObject](Json.obj()) {
case (m, _) =>
m
}
}
implicit def conv(view: SubscriptionView): Option[TcspTypes] = {
val serviceProviders: Option[Set[ServiceProvider]] = view.businessActivities.tcspServicesOffered match {
case Some(svcsProviders) => Some(Set(
CommonMethods.getSpecificType(svcsProviders.nomineeShareholders, NomineeShareholdersProvider),
CommonMethods.getSpecificType(svcsProviders.trusteeProvider, TrusteeProvider),
CommonMethods.getSpecificType(svcsProviders.regOffBusinessAddrVirtualOff, RegisteredOfficeEtc),
CommonMethods.getSpecificType(svcsProviders.compDirSecPartnerProvider, CompanyDirectorEtc),
CommonMethods.getSpecificType(svcsProviders.trustOrCompFormAgent, CompanyFormationAgent)
).flatten)
case None => None
}
Some(TcspTypes(serviceProviders.getOrElse(Set())))
}
}
|
#include <iostream>
using namespace std;
int findMinMax(int arr[], int n) {
int min = arr[0];
int max = arr[0];
for (int i=1; i<n; ++i) {
if (arr[i] < min)
min = arr[i];
if (arr[i] > max)
max = arr[i];
}
cout << "Min: " << min << " Max: " << max;
return 0;
}
int main()
{
int arr[] = {3, 5, 6, 7, 1, 2, 10};
int arr_size = sizeof(arr)/sizeof(arr[0]);
findMinMax(arr, arr_size);
return 0;
}
|
python scripts/preprocess.py \
--input_txt data/largePHP_UTF-8.txt \
--output_h5 data/largePHP.h5 \
--output_json data/largePHP.json
# --input_txt data/tiny-shakespeare.txt \
# --output_h5 data/tiny-shakespeare.h5 \
# --output_json data/tiny-shakespeare.json
th train.lua -input_h5 data/largePHP.h5 -input_json data/largePHP.json -gpu_backend opencl -max_epochs 50 -num_layers 2
# th train.lua -input_h5 data/tiny-shakespeare.h5 -input_json data/tiny-shakespeare.json -gpu_backend opencl -max_epochs 50 -num_layers 2
|
package string_handle;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
*
* @author minchoba
* ๋ฐฑ์ค 14405๋ฒ: ํผ์นด์ธ
*
* @see https://www.acmicpc.net/problem/14405/
*
*/
public class Boj14405 {
private static final String[] POKE = {"pi", "ka", "chu"};
private static final String SPACE = " ";
public static void main(String[] args) throws Exception{
// ๋ฒํผ๋ฅผ ํตํ ๊ฐ ์
๋ ฅ
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String word = br.readLine();
boolean res = true;
for(final String REMOVE : POKE) { // ํด๋น ์์ ์ ๊ฑฐ
word = word.replaceAll(REMOVE, SPACE);
}
for(char tmp: word.toCharArray()) {
if(tmp >= 'a' && tmp <= 'z') { // ์ ๊ฑฐ๋ ์์ ์ ์์ง ์ํ๋ฒณ ์๋ฌธ์๊ฐ ํฌํจ๋์๋ค๋ฉด
res = false; // ๊ฒฐ๊ณผ ๋ณ์์ ๊ฑฐ์ง์ ๋ด๊ณ ๋ฐ๋ณต๋ฌธ ์ข
๋ฃ
break;
}
}
System.out.println(res ? "YES" : "NO"); // ๊ฒฐ๊ณผ ๋ณ์์ ๋ฐ๋ฅธ ๊ฒฐ๊ณผ๊ฐ ์ถ๋ ฅ
}
}
|
<gh_stars>1-10
/*
* Copyright (C) 2005-2015 <NAME> (<EMAIL>).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "0root/root.h"
// Always verify that a file of level N does not include headers > N!
#include "1errorinducer/errorinducer.h"
#ifndef HAM_ROOT_H
# error "root.h was not included"
#endif
namespace hamsterdb {
ErrorInducer ErrorInducer::ms_instance;
bool ErrorInducer::ms_is_active = false;
} // namespace hamsterdb
|
#!/bin/bash
# Use Glue to create the template file
# First parameter is file name with path - best practise: located in /cre
# Also a dummy file of the destination file must be located at same path
# Rest of parameters is command and parameters to execute on change
# Every container should have it's own set of files inside glue
hostname=$(cat /etc/hostname | tr -d '\n' )
file_tmpl=$1
file_result=$(echo "$file_tmpl" | rev | cut -f 2- -d '.' | rev)
host_tmpl="${hostname}_$(basename $file_tmpl)"
host_result="${hostname}_$(basename $file_result)"
if [ ! -f $file_tmpl ]; then
echo "[FAIL]: File $file_tmpl not found !"
exit 1
fi
if [ ! ${file_tmpl: -5} == ".tmpl" ]; then
echo "[FAIL]: Filename must end with *.tmpl"
exit 1
fi
if [ ! -d /cre/glue ]; then
echo "[FAIL]: Directory /cre/glue not found! Use volumes_from cre-glue to fix"
exit 1
fi
if [ ! -f $file_result ]; then
echo "[WARNING]: File $file_result not found !"
touch /cre/glue/$host_result
else
cp $file_result /cre/glue/$host_result
fi
## shift to get rid of first parameter - only the rest is needed
shift
while true; do
inotifywait -q --format %e /cre/glue/$host_result | while read EVENT
do
echo "$EVENT has triggered for File $host_result - copy back"
sleep 0.20
touch /cre/glue/$host_result
cp -f /cre/glue/$host_result $file_result
sleep 0.05
echo "Execute $@"
$@
done
echo "Restart inotifywait for /cre/glue/$host_result"
done &
sleep 1
echo "Now to copy file: $file_tmpl to ..."
# Add code to add CurrentContainer and GlueContainer in front of file.
{ echo -n '{{ $CurrentContainer := where $ "Hostname" "';
cat /etc/hostname | tr -d '\n';
echo -n -e '" | first }} \n';
echo '{{ $GlueContainer := where $ "ID" .Docker.CurrentContainerID | first }}';
cat $file_tmpl; } > /cre/$host_tmpl
mv /cre/$host_tmpl /cre/glue/$host_tmpl
echo "... to destination: /cre/glue/$host_tmpl " &
wait
echo "Upps - finished, but should not..."
|
#!/bin/bash
echo "Install calico"
curl https://docs.projectcalico.org/manifests/calico.yaml -O
kubectl apply -f calico.yaml
|
def search_substring(string, n):
substrings = []
for i in range(len(string)-n+1):
substrings.append(string[i:i+n])
return substrings
|
public function getRecordsByTypeAndStatus($type, $status){
$this->db->where('tipo', $type);
$this->db->where('status', $status);
$query = $this->db->get($this->tabela);
return $query->result(); // Assuming the result should be returned as an array of objects
}
|
<filename>src/mainwindow/actions/MessageActions.js
import { APPEND_MESSAGE, CLEAR_MESSAGE } from './types'
export const appendMessage = (message) => {
return {
type: APPEND_MESSAGE,
payload: message
}
}
export const clearMessage = () => {
return {
type: CLEAR_MESSAGE
}
}
|
import pandas as pd
def generate_heatmap_df(pucks):
# Truncate full time-series to [arrival_time, departure_time_0]
def trunc_ts(series):
return series.truncate(series['arrival_time'], series['departure_time_0'])
# Apply truncation function to each row and transpose the result
heatmapdf = pucks.apply(trunc_ts, axis=1).T
# Convert columns from index to turn_no
heatmapdf.columns = pucks['turn_no'].values
# Fill NaN values with 0 and cast to integer
heatmapdf = heatmapdf.fillna(0).astype(int)
return heatmapdf
|
import numpy as np
import matplotlib.pyplot as plt
def bayesian_inference(data, prior):
c1 = data.count(1)
c0 = data.count(0)
p1 = c1 / len(data)
p0 = c0 / len(data)
likelihood_c1 = np.random.binomial(len(data), p1, 10000) / len(data)
likelihood_c0 = np.random.binomial(len(data), p0, 10000) / len(data)
p_grid = np.linspace(0, 1, 1000)
prior_prob = np.ones(1000) * prior
likelihood = (likelihood_c1 * p1) + (likelihood_c0 * p0)
unstd_posterior = likelihood * prior_prob
posterior = unstd_posterior / sum(unstd_posterior)
return p_grid, posterior
# Example usage
up_down = [1, 0, 1, 1, 0, 1, 0, 1, 1, 1]
prior_prob = 0.7
p_grid, posterior = bayesian_inference(up_down, prior_prob)
plt.plot(p_grid, posterior)
plt.xlabel('Probability of Success')
plt.ylabel('Posterior Probability')
plt.title('Posterior Distribution')
plt.show()
|
/*
* Copyright 2017 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.examples.realmmultiprocessexample;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import io.realm.Realm;
public class AnotherProcessService extends Service {
Handler handler;
@Override
public void onCreate() {
super.onCreate();
handler = new Handler(Looper.myLooper());
final Runnable runnable = new Runnable() {
@Override
public void run() {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealmOrUpdate(Utils.createStandaloneProcessInfo(AnotherProcessService.this));
realm.commitTransaction();
realm.close();
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
|
#!/bin/bash
if [ $# -ge 1 ]; then
xrandr | awk "/$1/,/connected/ {} {if (\$2 ~ /\*/) { for(i=2;i<=NF;i++) {gsub(\"[+*]\",\"\");print \$i}}}"
else
# Hardwired for my screen... bc this should never be used.
xrandr | awk "/eDP-1/,/connected/ {} {if (\$2 ~ /\*/) { for(i=2;i<=NF;i++) {gsub(\"[+*]\",\"\");print \$i}}}"
fi
# I want to leave this here as a reminder of why Stack Overflow must be used in moderation.
# xrandr | awk " / connected/ {on=1}; {if(on==1) {a[NR]=\$0}}; /^[[:alpha:]]/ {p=0; for (i in a) print a[i]; delete a}" | grep *+ | awk '// {first=$1;$1="";gsub("[*+]","");print $0}' 2>/dev/null | cut -d ' ' -f 2- | sed 's/ /\n/g'
|
<reponame>woonsan/incubator-freemarker
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package freemarker.ext.beans;
// FMPP template source:
// ----
// package freemarker.ext.beans;
//
// // FMPP template source:
// // ----
// <#assign src><#include "ManyObjectsOfDifferentClasses.java.ftl" parse=false></#assign>
// ${src?trim?replace('(.*\r?\n)|.+', r'// $0', 'r')}
// // ----
//
// <#assign MAX_CLA = 8 - 1>
// <#assign MAX_MET = 10 - 1>
// <#assign MAX_PRO = 10 - 1>
//
// public class ManyObjectsOfDifferentClasses {
//
// public static final Object[] OBJECTS = new Object[] {
// <#list 0..MAX_CLA as claI>
// new C${claI}(),
// </#list>
// };
//
// <#list 0..MAX_CLA as claI>
// static public class C${claI} {
// <#list 0..MAX_PRO as proI>
// public int getP${proI}() { return ${claI} * 1000 + ${proI}; }
// </#list>
// <#list 0..MAX_MET as metI>
// public int m${metI}() { return ${claI} * 1000 + ${metI}; };
// </#list>
// }
// </#list>
//
// }
// ----
public class ManyObjectsOfDifferentClasses {
public static final Object[] OBJECTS = new Object[] {
new C0(),
new C1(),
new C2(),
new C3(),
new C4(),
new C5(),
new C6(),
new C7(),
};
static public class C0 {
public int getP0() { return 0 * 1000 + 0; }
public int getP1() { return 0 * 1000 + 1; }
public int getP2() { return 0 * 1000 + 2; }
public int getP3() { return 0 * 1000 + 3; }
public int getP4() { return 0 * 1000 + 4; }
public int getP5() { return 0 * 1000 + 5; }
public int getP6() { return 0 * 1000 + 6; }
public int getP7() { return 0 * 1000 + 7; }
public int getP8() { return 0 * 1000 + 8; }
public int getP9() { return 0 * 1000 + 9; }
public int m0() { return 0 * 1000 + 0; };
public int m1() { return 0 * 1000 + 1; };
public int m2() { return 0 * 1000 + 2; };
public int m3() { return 0 * 1000 + 3; };
public int m4() { return 0 * 1000 + 4; };
public int m5() { return 0 * 1000 + 5; };
public int m6() { return 0 * 1000 + 6; };
public int m7() { return 0 * 1000 + 7; };
public int m8() { return 0 * 1000 + 8; };
public int m9() { return 0 * 1000 + 9; };
}
static public class C1 {
public int getP0() { return 1 * 1000 + 0; }
public int getP1() { return 1 * 1000 + 1; }
public int getP2() { return 1 * 1000 + 2; }
public int getP3() { return 1 * 1000 + 3; }
public int getP4() { return 1 * 1000 + 4; }
public int getP5() { return 1 * 1000 + 5; }
public int getP6() { return 1 * 1000 + 6; }
public int getP7() { return 1 * 1000 + 7; }
public int getP8() { return 1 * 1000 + 8; }
public int getP9() { return 1 * 1000 + 9; }
public int m0() { return 1 * 1000 + 0; };
public int m1() { return 1 * 1000 + 1; };
public int m2() { return 1 * 1000 + 2; };
public int m3() { return 1 * 1000 + 3; };
public int m4() { return 1 * 1000 + 4; };
public int m5() { return 1 * 1000 + 5; };
public int m6() { return 1 * 1000 + 6; };
public int m7() { return 1 * 1000 + 7; };
public int m8() { return 1 * 1000 + 8; };
public int m9() { return 1 * 1000 + 9; };
}
static public class C2 {
public int getP0() { return 2 * 1000 + 0; }
public int getP1() { return 2 * 1000 + 1; }
public int getP2() { return 2 * 1000 + 2; }
public int getP3() { return 2 * 1000 + 3; }
public int getP4() { return 2 * 1000 + 4; }
public int getP5() { return 2 * 1000 + 5; }
public int getP6() { return 2 * 1000 + 6; }
public int getP7() { return 2 * 1000 + 7; }
public int getP8() { return 2 * 1000 + 8; }
public int getP9() { return 2 * 1000 + 9; }
public int m0() { return 2 * 1000 + 0; };
public int m1() { return 2 * 1000 + 1; };
public int m2() { return 2 * 1000 + 2; };
public int m3() { return 2 * 1000 + 3; };
public int m4() { return 2 * 1000 + 4; };
public int m5() { return 2 * 1000 + 5; };
public int m6() { return 2 * 1000 + 6; };
public int m7() { return 2 * 1000 + 7; };
public int m8() { return 2 * 1000 + 8; };
public int m9() { return 2 * 1000 + 9; };
}
static public class C3 {
public int getP0() { return 3 * 1000 + 0; }
public int getP1() { return 3 * 1000 + 1; }
public int getP2() { return 3 * 1000 + 2; }
public int getP3() { return 3 * 1000 + 3; }
public int getP4() { return 3 * 1000 + 4; }
public int getP5() { return 3 * 1000 + 5; }
public int getP6() { return 3 * 1000 + 6; }
public int getP7() { return 3 * 1000 + 7; }
public int getP8() { return 3 * 1000 + 8; }
public int getP9() { return 3 * 1000 + 9; }
public int m0() { return 3 * 1000 + 0; };
public int m1() { return 3 * 1000 + 1; };
public int m2() { return 3 * 1000 + 2; };
public int m3() { return 3 * 1000 + 3; };
public int m4() { return 3 * 1000 + 4; };
public int m5() { return 3 * 1000 + 5; };
public int m6() { return 3 * 1000 + 6; };
public int m7() { return 3 * 1000 + 7; };
public int m8() { return 3 * 1000 + 8; };
public int m9() { return 3 * 1000 + 9; };
}
static public class C4 {
public int getP0() { return 4 * 1000 + 0; }
public int getP1() { return 4 * 1000 + 1; }
public int getP2() { return 4 * 1000 + 2; }
public int getP3() { return 4 * 1000 + 3; }
public int getP4() { return 4 * 1000 + 4; }
public int getP5() { return 4 * 1000 + 5; }
public int getP6() { return 4 * 1000 + 6; }
public int getP7() { return 4 * 1000 + 7; }
public int getP8() { return 4 * 1000 + 8; }
public int getP9() { return 4 * 1000 + 9; }
public int m0() { return 4 * 1000 + 0; };
public int m1() { return 4 * 1000 + 1; };
public int m2() { return 4 * 1000 + 2; };
public int m3() { return 4 * 1000 + 3; };
public int m4() { return 4 * 1000 + 4; };
public int m5() { return 4 * 1000 + 5; };
public int m6() { return 4 * 1000 + 6; };
public int m7() { return 4 * 1000 + 7; };
public int m8() { return 4 * 1000 + 8; };
public int m9() { return 4 * 1000 + 9; };
}
static public class C5 {
public int getP0() { return 5 * 1000 + 0; }
public int getP1() { return 5 * 1000 + 1; }
public int getP2() { return 5 * 1000 + 2; }
public int getP3() { return 5 * 1000 + 3; }
public int getP4() { return 5 * 1000 + 4; }
public int getP5() { return 5 * 1000 + 5; }
public int getP6() { return 5 * 1000 + 6; }
public int getP7() { return 5 * 1000 + 7; }
public int getP8() { return 5 * 1000 + 8; }
public int getP9() { return 5 * 1000 + 9; }
public int m0() { return 5 * 1000 + 0; };
public int m1() { return 5 * 1000 + 1; };
public int m2() { return 5 * 1000 + 2; };
public int m3() { return 5 * 1000 + 3; };
public int m4() { return 5 * 1000 + 4; };
public int m5() { return 5 * 1000 + 5; };
public int m6() { return 5 * 1000 + 6; };
public int m7() { return 5 * 1000 + 7; };
public int m8() { return 5 * 1000 + 8; };
public int m9() { return 5 * 1000 + 9; };
}
static public class C6 {
public int getP0() { return 6 * 1000 + 0; }
public int getP1() { return 6 * 1000 + 1; }
public int getP2() { return 6 * 1000 + 2; }
public int getP3() { return 6 * 1000 + 3; }
public int getP4() { return 6 * 1000 + 4; }
public int getP5() { return 6 * 1000 + 5; }
public int getP6() { return 6 * 1000 + 6; }
public int getP7() { return 6 * 1000 + 7; }
public int getP8() { return 6 * 1000 + 8; }
public int getP9() { return 6 * 1000 + 9; }
public int m0() { return 6 * 1000 + 0; };
public int m1() { return 6 * 1000 + 1; };
public int m2() { return 6 * 1000 + 2; };
public int m3() { return 6 * 1000 + 3; };
public int m4() { return 6 * 1000 + 4; };
public int m5() { return 6 * 1000 + 5; };
public int m6() { return 6 * 1000 + 6; };
public int m7() { return 6 * 1000 + 7; };
public int m8() { return 6 * 1000 + 8; };
public int m9() { return 6 * 1000 + 9; };
}
static public class C7 {
public int getP0() { return 7 * 1000 + 0; }
public int getP1() { return 7 * 1000 + 1; }
public int getP2() { return 7 * 1000 + 2; }
public int getP3() { return 7 * 1000 + 3; }
public int getP4() { return 7 * 1000 + 4; }
public int getP5() { return 7 * 1000 + 5; }
public int getP6() { return 7 * 1000 + 6; }
public int getP7() { return 7 * 1000 + 7; }
public int getP8() { return 7 * 1000 + 8; }
public int getP9() { return 7 * 1000 + 9; }
public int m0() { return 7 * 1000 + 0; };
public int m1() { return 7 * 1000 + 1; };
public int m2() { return 7 * 1000 + 2; };
public int m3() { return 7 * 1000 + 3; };
public int m4() { return 7 * 1000 + 4; };
public int m5() { return 7 * 1000 + 5; };
public int m6() { return 7 * 1000 + 6; };
public int m7() { return 7 * 1000 + 7; };
public int m8() { return 7 * 1000 + 8; };
public int m9() { return 7 * 1000 + 9; };
}
}
|
#!/usr/bin/env sh
# generated from catkin/cmake/template/local_setup.sh.in
# since this file is sourced either use the provided _CATKIN_SETUP_DIR
# or fall back to the destination set at configure time
: ${_CATKIN_SETUP_DIR:=/home/nimesh/dev/anscer_PS/devel/.private/navloc}
CATKIN_SETUP_UTIL_ARGS="--extend --local"
. "$_CATKIN_SETUP_DIR/setup.sh"
unset CATKIN_SETUP_UTIL_ARGS
|
// Main Tab Bar Controller
import UIKit
class MainTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
let homeVC = HomeViewController()
let settingsVC = SettingsViewController()
let apiSettingsVC = ApiSettingsViewController()
let controllers = [
homeVC,
settingsVC,
apiSettingsVC
]
viewControllers = controllers.map { UINavigationController(rootViewController: $0) }
for (index, controller) in viewControllers.enumerated() {
controller.tabBarItem.title = titles[index]
controller.tabBarItem.image = UIImage(named: images[index])
}
}
/// Private
private let titles = ["Home", "Settings", "API Settings"]
private let images = ["home", "settings", "apisettings"]
}
|
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Station } from '../entities/station.entity';
@Injectable()
export class UserService {
constructor(
@InjectRepository(Station, 'readonly') private readonly stationRepository: Repository<Station>,
) { }
async myIp(ip: string): Promise<Object> {
const data = {
ipAddress: ip,
stations: []
};
data.stations = await this.stationRepository.find({
where: { ipAddress: ip }
});
return data;
}
}
|
#include <iostream>
using namespace std;
int main()
{
int num1, num2, sum;
cout<<"Enter first number: ";
cin>>num1;
cout<<"Enter second number: ";
cin>>num2;
sum = num1 + num2;
cout<<"Sum of two numbers is "<<sum;
return 0;
}
|
#!/usr/bin/env bash
export PATH=$PATH:$(pwd -P)/ci
source header.sh
${PROJECT_ROOT_DIR}/ci/build-rhoscala-rbls.sh
${PROJECT_ROOT_DIR}/ci/test-rholang-rbls.sh
${PROJECT_ROOT_DIR}/ci/clean-up.sh
cd ${PROJECT_ROOT_DIR}
|
#!/bin/bash
DOTPATH=~/git/MyDotFiles
# Create local zhrc config
touch ~/zshrc.local.sh
rm ~/.zshrc
ln -s $DOTPATH/zshrc ~/.zshrc
rm ~/.vimrc
ln -s $DOTPATH/vimrc ~/.vimrc
rm -r ~/.vim
ln -s $DOTPATH/vim ~/.vim
rm ~/.gvimrc
ln -s $DOTPATH/gvimrc ~/.gvimrc
rm ~/.dircolors
ln -s $DOTPATH/extras/dircolors ~/.dircolors
rm ~/.gitconfig
ln -s $DOTPATH/gitconfig ~/.gitconfig
rm ~/.lessfilter
ln -s $DOTPATH/zsh/lessfilter ~/.lessfilter
rm ~/.vifm
ln -s $DOTPATH/.vifm ~/.vifm
rm ~/LESS_TERMCAP
ln -s $DOTPATH/zsh/LESS_TERMCAP ~/
rm -rf ~/bin
ln -s $DOTPATH/extras/bin ~/
rm -rf ~/.fzf.zsh
ln -s $DOTPATH/fzf.zsh ~/.fzf.zsh
rm -rf ~/.grc
ln -s $DOTPATH/configs/grc ~/.grc
touch ~/.stCommitMsg
cp $DOTPATH/gitconfig.user ~/.gitconfig.user
# Only add NO_ZSH_THEME to zshrc.local.sh if it hasn't been added before
if [ "$(grep "NO_ZSH_THEME" ~/zshrc.local.sh|wc -c)" == "0" ]; then
echo "${bG}adding${cZ} NO_ZSH_THEME to ~/zshrc.local.sh"
cat >> ~/zshrc.local.sh << EOF
# export NO_ZSH_THEME=true
EOF
fi
# Add proxy if proxy env is present
if [ -n $http_proxy ]; then
# only add it once
if [ "$(grep "http_proxy" ~/zshrc.local.sh|wc -c)" == "0" ]; then
echo "${bG}adding${cZ} http_proxy to ~/zshrc.local.sh"
cat >> ~/zshrc.local.sh << EOF
export http_proxy="$http_proxy"
export https_proxy="$https_proxy"
EOF
fi
fi
|
#!/usr/bin/env bash
pip3 install -r requirements.txt
|
'use strict'
const fs = require('fs')
const fetch = require('node-fetch')
/**
* Download a Cemu release (zip) to a given path
* @param {Release(2)} release - Release to download
* @param {string} path - Download path
* @param {function} [callback] - Callback, receives an error object if an error occurs
* @return {Promise}
* @memberOf module:release
*/
function download (release, path, callback) {
function checkStatus (res) {
if (res.ok) {
return res
} else {
throw new Error(res.statusText)
}
}
return new Promise((resolve, reject) => {
fetch(release.download)
.then(checkStatus)
.then(res => {
res.body.pipe(
fs.createWriteStream(path)
.on('finish', () => {
if (callback) callback()
resolve()
})
.on('error', err => {
throw err
})
)
})
.catch(err => {
if (callback) callback(err)
reject(err)
})
})
}
module.exports = download
|
#!/bin/bash
export NODE_ENV=production
# bigsurfshop
(node bin/provider/reindex --provider=bigsurfshop --seller=used --path=sails)
(node bin/provider/reindex --provider=bigsurfshop --seller=used --path=boards --no-checkHosts)
(node bin/provider/reindex --provider=bigsurfshop --seller=used --path=masts --no-checkHosts)
(node bin/provider/reindex --provider=bigsurfshop --seller=used --path=booms --no-checkHosts)
(node bin/provider/reindex --provider=bigsurfshop --seller=used --path=fins --no-checkHosts)
|
#include "Config.h"
#include "BNetReqEmail.h"
namespace Packets
{
namespace BNet
{
bool BNetReqEmail::Pack()
{
return true;
}
}
}
|
#!/bin/bash
#COBALT -t 3:00:00
#COBALT -n 1
#COBALT -A OceanClimate_2
# This software is open source software available under the BSD-3 license.
#
# Copyright (c) 2020 Triad National Security, LLC. All rights reserved.
# Copyright (c) 2020 Lawrence Livermore National Security, LLC. All rights
# reserved.
# Copyright (c) 2020 UT-Battelle, LLC. All rights reserved.
#
# Additional copyright and license information can be found in the LICENSE file
# distributed with this code, or at
# https://raw.githubusercontent.com/MPAS-Dev/MPAS-Analysis/master/LICENSE
source /lus/theta-fs0/projects/ccsm/acme/tools/e3sm-unified/load_latest_e3sm_unified_cooley.sh
# MPAS/ACME job to be analyzed, including paths to simulation data and
# observations. Change this name and path as needed
run_config_file="config.20180410.A_WCYCL1950_HR.ne120_oRRS18v3_ICG.theta"
# NOTE: the following section will OVERWRITE values specified within the config file named above
# one parallel task per node by default
parallel_task_count=8
# ncclimo can run with 1 (serial) or 12 (bck) threads
ncclimo_mode=serial
if [ ! -f $run_config_file ]; then
echo "File $run_config_file not found!"
exit 1
fi
# This is a config file generated just for this job with the output directory,
# command prefix and parallel task count from above.
job_config_file=config.output.$COBALT_JOBID
# write out the config file specific to this job
cat <<EOF > $job_config_file
[execute]
# options related to executing parallel tasks
# the number of parallel tasks (1 means tasks run in serial, the default)
parallelTaskCount = $parallel_task_count
# the parallelism mode in ncclimo ("serial" or "bck")
# Set this to "bck" (background parallelism) if running on a machine that can
# handle 12 simultaneous processes, one for each monthly climatology.
ncclimoParallelMode = $ncclimo_mode
EOF
mpas_analysis $run_config_file $job_config_file
|
#!/bin/sh
set -e
# create namespace
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Namespace
metadata:
name: netdata
EOF
# set kubectl namespace
kubectl config set-context --current --namespace=netdata
# deploy netdata
kubectl apply -f https://raw.githubusercontent.com/digitalocean/marketplace-kubernetes/master/stacks/netdata/yaml/netdata.yaml
# ensure services are running
kubectl rollout status statefulset/netdata-master
kubectl rollout status daemonset/netdata-slave
|
package com.nils.engine.main;
import java.awt.Graphics;
public abstract class Game {
protected GameContainer gc;
public Game(GameContainer gc) {
this.gc = gc;
}
public abstract void update(double dt);
public abstract void render(Graphics g);
public GameContainer getGc() {
return gc;
}
public void setGc(GameContainer gc) {
this.gc = gc;
}
}
|
package utils.assets.loader;
import com.badlogic.gdx.graphics.g2d.Gdx2DPixmap;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import arc.Core;
import arc.assets.*;
import arc.assets.loaders.FileHandleResolver;
import arc.assets.loaders.TextureLoader;
import arc.graphics.g2d.TextureAtlas;
import arc.graphics.g2d.TextureRegion;
import arc.struct.*;
import arc.files.*;
import arc.graphics.Pixmap.*;
import arc.graphics.*;
import arc.graphics.Texture.*;
import arc.util.io.Streams;
import arc.util.serialization.XmlReader;
import mindustry.Vars;
import temp.Debug;
import utils.assets.Pack;
import z.debug.assets.Coding;
import z.debug.assets.ResourceMappingClass;
public class PackLoader extends DecodeAsynchronousAssetLoader<Pack, PackLoader.PackParameter> {
class SyncData {
Class classtype;
String path;
Pixmap pixmap;
ResourceMappingClass para;
// TextureFilter minFilter;
// TextureFilter magFilter;
}
private XmlReader reader;
public PackLoader (FileHandleResolver resolver) {
super(resolver);
reader = new XmlReader();
}
private SyncData[] syncDataArray;
@Override
public void loadAsync (AssetManager manager, String fileName, Fi file, PackParameter parameter) {
Coding coding = Coding.values()[Integer.parseInt(file.extension().substring(1)) - 1];
byte[] xmlbytes = getZonesAssets(coding, file.readBytes());
XmlReader.Element root = reader.parse(new String(xmlbytes));
syncDataArray = new SyncData[root.getChildCount()];
Fi packfile = Core.files.internal(file.pathWithoutExtension() + ".pack");
byte[] bytes = packfile.readBytes();
InputStream inputStream = null;
try {
inputStream = new GZIPInputStream(new ByteArrayInputStream(bytes), bytes.length);
for (int i = 0; i < root.getChildCount(); i++) {
XmlReader.Element node = root.getChild(i);
int nodeSize = node.getIntAttribute("size", 0);
Coding nodeCoding = Coding.valueOf(node.getAttribute("coding").toUpperCase());
String nodeStrPar = node.getAttribute("parameter", null);
ResourceMappingClass nodeParEnu = null;
if (nodeStrPar != null) {
nodeParEnu = ResourceMappingClass.valueOf(nodeStrPar.toUpperCase());
// nodeParameter = (TextureLoaderZones.TextureParameter) PARAMETERS[nodeParEnu.ordinal()];
}
String nodePath = node.getAttribute("path");
ResourceMappingClass nodeTypeEnu = ResourceMappingClass.valueOf(node.getAttribute("type").toUpperCase());
Class nodeTypeClass = CLASSES[nodeTypeEnu.ordinal()];
byte[] nodBytes = new byte[nodeSize];
inputStream.read(nodBytes);
nodBytes = getZonesAssets(nodeCoding, nodBytes);
syncDataArray[i] = new SyncData();
syncDataArray[i].path = nodePath;
syncDataArray[i].classtype = nodeTypeClass;
syncDataArray[i].para = nodeParEnu != null ? nodeParEnu : (parameter != null ? parameter.textureFilter : null);
syncDataArray[i].pixmap = new Pixmap(new Gdx2DPixmap(nodBytes, 0, nodBytes.length, 0));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
Streams.close(inputStream);
}
}
@Override
public Pack loadSync (AssetManager manager, String fileName, Fi file, PackParameter parameter) {
for (SyncData syncData : syncDataArray) {
Texture nodeTexture = new Texture(syncData.pixmap);
TextureRegion region = new TextureRegion(nodeTexture);
// byteManager.addAsset(syncData.path, syncData.classtype, region);
TextureAtlas atlas = Vars.atlasS;
// if (Debug.NOTE1)
// ;
atlas.addRegion(syncData.path, region);
if (syncData.para != null) {
TextureLoader.TextureParameter nodeParameter = (TextureLoader.TextureParameter) PARAMETERS[syncData.para.ordinal()];
nodeTexture.setFilter(nodeParameter.minFilter, nodeParameter.magFilter);
nodeTexture.setWrap(nodeParameter.wrapU, nodeParameter.wrapV);
}
}
syncDataArray = null;
return new Pack(true);
}
@Override
public Array<AssetDescriptor> getDependencies (String fileName, Fi file, PackParameter parameter) {
return null;
}
static public class PackParameter extends AssetLoaderParameters<Pack> {
public ResourceMappingClass textureFilter = null;
// public TextureFilter magFilter = null;
// public TextureWrap wrapU = null;
// public TextureWrap wrapV = null;
public PackParameter() {
}
public PackParameter(ResourceMappingClass textureFilter) {
this.textureFilter = textureFilter;
}
}
}
|
<reponame>Nirovision/mimiron
# -*- coding: utf-8 -*-
from mimiron.exceptions import BaseMimironException
class InvalidEnvironment(BaseMimironException):
def __init__(self, env):
message = '"%s" environment is invalid' % (env,)
super(InvalidEnvironment, self).__init__(message)
class UnexpectedCommand(BaseMimironException):
def __init__(self):
message = 'encountered unexpected command, input parser error'
super(UnexpectedCommand, self).__init__(message)
class InvalidOperatingBranch(BaseMimironException):
def __init__(self, branch):
message = 'operations only allowed on DEFAULT_GIT_BRANCH (current: "%s")' % (branch,)
super(InvalidOperatingBranch, self).__init__(message)
|
#!/bin/bash
#
# Copyright (c) 2019-2020 P3TERX <https://p3terx.com>
#
# This is free software, licensed under the MIT License.
# See /LICENSE for more information.
#
# https://github.com/P3TERX/Actions-OpenWrt
# File name: diy-part2.sh
# Description: OpenWrt DIY script part 2 (After Update feeds)
#
# Modify default IP
#sed -i 's/192.168.1.1/192.168.50.5/g' package/base-files/files/bin/config_generate
# ่ฎพ็ฝฎๅฏ็ ไธบ็ฉบ๏ผๅฎ่ฃ
ๅบไปถๆถๆ ้ๅฏ็ ็ป้๏ผ็ถๅ่ชๅทฑไฟฎๆนๆณ่ฆ็ๅฏ็ ๏ผ
sed -i 's@.*CYXluq4wUazHjmCDBCqXF*@#&@g' package/lean/default-settings/files/zzz-default-settings
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.