repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
betofigueiredo/carteirasDigitaisACEM
|
src/store/memberships/use_cases/storeCleared/index.js
|
export { default } from './storeCleared';
|
IUaenaSong/OnlineJudge
|
OnlineJudgeBE/Backend/src/main/java/com/iuaenasong/oj/manager/admin/role/AdminRoleManager.java
|
<gh_stars>0
/**
* @Author LengYun
* @Since 2022/01/13 14:28
* @Description
*/
package com.iuaenasong.oj.manager.admin.role;
import com.iuaenasong.oj.dao.user.RoleEntityService;
import com.iuaenasong.oj.pojo.entity.user.Auth;
import com.iuaenasong.oj.pojo.entity.user.Role;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@Component
public class AdminRoleManager {
@Autowired
private RoleEntityService roleEntityService;
public IPage<Role> getRoleList(Integer limit, Integer currentPage, String keyword) {
if (currentPage == null || currentPage < 1) currentPage = 1;
if (limit == null || limit < 1) limit = 10;
QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
IPage<Role> iPage = new Page<>(currentPage, limit);
if (!StringUtils.isEmpty(keyword)) {
final String key = keyword.trim();
queryWrapper.and(wrapper -> wrapper.like("name", key).or()
.like("permission", key).or());
}
return roleEntityService.page(iPage, queryWrapper);
}
}
|
lenxin/spring-security
|
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/authentication/package-info.java
|
/**
* Support classes and interfaces for authenticating and authorizing a client with an
* OpenID Connect 1.0 Provider using a specific authorization grant flow.
*/
package org.springframework.security.oauth2.client.oidc.authentication;
|
matcornic/cds
|
cli/cds/ui/monitoring.go
|
<reponame>matcornic/cds<filename>cli/cds/ui/monitoring.go
package ui
import (
"encoding/json"
"fmt"
"net/url"
"sort"
"strconv"
"strings"
"time"
"github.com/gizak/termui"
"github.com/ovh/cds/cli"
"github.com/ovh/cds/sdk"
)
func (ui *Termui) showMonitoring() {
termui.Body.Rows = nil
ui.queue = cli.NewScrollableList()
ui.queue.ItemFgColor = termui.ColorWhite
ui.queue.ItemBgColor = termui.ColorBlack
heightBottom := 18
heightQueue := ((termui.TermHeight() - heightBottom) / 2) - 3
if heightQueue <= 0 {
heightQueue = 4
}
ui.queue.BorderLabel = " Queue "
ui.queue.Height = heightQueue
ui.queue.Width = termui.TermWidth()
ui.queue.Items = []string{"Loading..."}
ui.queue.BorderBottom = false
ui.queue.BorderLeft = false
ui.queue.BorderRight = false
ui.selected = QueueSelected
ui.building = cli.NewScrollableList()
ui.building.ItemFgColor = termui.ColorWhite
ui.building.ItemBgColor = termui.ColorBlack
heightBuilding := ((termui.TermHeight() - heightBottom) / 2) + 3
if heightBuilding <= 0 {
heightBuilding = 3
}
ui.building.BorderLabel = " Building "
ui.building.Height = heightBuilding
ui.building.Width = termui.TermWidth()
ui.building.Items = []string{"Loading..."}
ui.building.BorderBottom = false
ui.building.BorderLeft = false
ui.building.BorderRight = false
ui.statusWorkerList = cli.NewScrollableList()
ui.statusWorkerList.ItemFgColor = termui.ColorWhite
ui.statusWorkerList.ItemBgColor = termui.ColorBlack
ui.statusWorkerList.BorderLabel = " Workers "
ui.statusWorkerList.Height = heightBottom
ui.statusWorkerList.Items = []string{"[select a job](fg-cyan,bg-default)"}
ui.statusWorkerList.BorderBottom = false
ui.statusWorkerList.BorderLeft = false
ui.statusWorkerModels = cli.NewScrollableList()
ui.statusWorkerModels.BorderLabel = " Worker Models "
ui.statusWorkerModels.Height = heightBottom
ui.statusWorkerModels.Items = []string{"[loading...](fg-cyan,bg-default)"}
ui.statusWorkerModels.BorderBottom = false
ui.statusWorkerModels.BorderLeft = false
ui.statusHatcheriesWorkers = cli.NewScrollableList()
ui.statusHatcheriesWorkers.BorderLabel = " Hatcheries "
ui.statusHatcheriesWorkers.Height = heightBottom
ui.statusHatcheriesWorkers.Items = []string{"[loading...](fg-cyan,bg-default)"}
ui.statusHatcheriesWorkers.BorderBottom = false
ui.statusHatcheriesWorkers.BorderLeft = false
ui.statusHatcheriesWorkers.BorderRight = false
ui.status = cli.NewScrollableList()
ui.status.BorderLabel = " Status "
ui.status.Height = heightBottom
ui.status.Items = []string{"[loading...](fg-cyan,bg-default)"}
ui.status.BorderBottom = false
ui.status.BorderLeft = true
ui.status.BorderRight = false
termui.Body.AddRows(
termui.NewRow(
termui.NewCol(12, 0, ui.header),
),
)
termui.Body.AddRows(
termui.NewCol(12, 0, ui.queue),
termui.NewCol(12, 0, ui.building),
)
termui.Body.AddRows(
termui.NewRow(
termui.NewCol(4, 0, ui.statusWorkerList),
termui.NewCol(2, 0, ui.statusWorkerModels),
termui.NewCol(3, 0, ui.statusHatcheriesWorkers),
termui.NewCol(3, 0, ui.status),
),
)
termui.Render()
baseURL := "http://cds.ui/"
urlUI, err := sdk.GetConfigUser()
if err != nil {
ui.msg = fmt.Sprintf("[%s](bg-red)", err.Error())
}
if b, ok := urlUI[sdk.ConfigURLUIKey]; ok {
baseURL = b
}
ticker := time.NewTicker(2 * time.Second).C
for {
var a, b, c, d string
select {
case <-ticker:
ui.monitoringColorSelected()
a = ui.updateQueue(baseURL)
b = ui.updateQueueWorkers()
c = ui.updateBuilding(baseURL)
d = ui.updateStatus()
}
ui.msg = fmt.Sprintf("%s | %s | %s | %s", a, b, c, d)
termui.Render()
}
}
func (ui *Termui) monitoringCursorDown() {
switch ui.selected {
case QueueSelected:
ui.queue.CursorDown()
case BuildingSelected:
ui.building.CursorDown()
case WorkersListSelected:
ui.statusWorkerList.CursorDown()
case WorkerModelsSelected:
ui.statusWorkerModels.CursorDown()
case HatcheriesWorkersSelected:
ui.statusHatcheriesWorkers.CursorDown()
case StatusSelected:
ui.status.CursorDown()
}
}
func (ui *Termui) monitoringCursorUp() {
switch ui.selected {
case QueueSelected:
ui.queue.CursorUp()
case BuildingSelected:
ui.building.CursorUp()
case WorkersListSelected:
ui.statusWorkerList.CursorUp()
case WorkerModelsSelected:
ui.statusWorkerModels.CursorUp()
case HatcheriesWorkersSelected:
ui.statusHatcheriesWorkers.CursorUp()
case StatusSelected:
ui.status.CursorUp()
}
}
func (ui *Termui) monitoringSelectNext() {
ui.currentURL = ""
switch ui.selected {
case QueueSelected:
ui.selected = BuildingSelected
ui.queue.Cursor = 0
case BuildingSelected:
ui.selected = WorkersListSelected
ui.building.Cursor = 0
case WorkersListSelected:
ui.selected = WorkerModelsSelected
ui.statusWorkerList.Cursor = 0
case WorkerModelsSelected:
ui.selected = HatcheriesWorkersSelected
ui.statusWorkerModels.Cursor = 0
case HatcheriesWorkersSelected:
ui.selected = StatusSelected
ui.statusHatcheriesWorkers.Cursor = 0
case StatusSelected:
ui.selected = QueueSelected
ui.status.Cursor = 0
}
ui.monitoringColorSelected()
}
func (ui *Termui) monitoringColorSelected() {
ui.queue.BorderFg = termui.ColorDefault
ui.building.BorderFg = termui.ColorDefault
ui.statusWorkerList.BorderFg = termui.ColorDefault
ui.statusWorkerModels.BorderFg = termui.ColorDefault
ui.statusHatcheriesWorkers.BorderFg = termui.ColorDefault
ui.status.BorderFg = termui.ColorDefault
switch ui.selected {
case QueueSelected:
ui.queue.BorderFg = termui.ColorRed
case BuildingSelected:
ui.building.BorderFg = termui.ColorRed
case WorkersListSelected:
ui.statusWorkerList.BorderFg = termui.ColorRed
case WorkerModelsSelected:
ui.statusWorkerModels.BorderFg = termui.ColorRed
case HatcheriesWorkersSelected:
ui.statusHatcheriesWorkers.BorderFg = termui.ColorRed
case StatusSelected:
ui.status.BorderFg = termui.ColorRed
}
termui.Render(ui.queue,
ui.building,
ui.statusWorkerList,
ui.statusWorkerModels,
ui.statusHatcheriesWorkers,
ui.status)
}
func (ui *Termui) updateStatus() string {
start := time.Now()
status, err := sdk.GetStatus()
if err != nil {
ui.msg = fmt.Sprintf("[%s](bg-red)", err.Error())
return ""
}
elapsed := time.Since(start)
msg := fmt.Sprintf("[status %s](fg-cyan,bg-default)", sdk.Round(elapsed, time.Millisecond).String())
selected := "fg-white,bg-default"
if ui.selected == StatusSelected {
selected = "fg-white"
}
items := []string{}
for _, l := range status.Lines {
if l.Status != sdk.MonitoringStatusOK {
items = append(items, fmt.Sprintf("[%s](bg-red)", l))
} else {
items = append(items, fmt.Sprintf("[%s](%s)", l, selected))
}
}
ui.status.Items = items
return msg
}
func (ui *Termui) updateBuilding(baseURL string) string {
start := time.Now()
pbs, err := sdk.GetBuildingPipelines()
if err != nil {
ui.msg = fmt.Sprintf("[%s](bg-red)", err.Error())
return ""
}
elapsed := time.Since(start)
msg := fmt.Sprintf("[buildingPipelines %s](fg-cyan,bg-default)", sdk.Round(elapsed, time.Millisecond).String())
statusTitle := []string{}
status := make(map[string]int)
items := []string{fmt.Sprintf("[ %s➤ %s ➤ %s ➤ %s](fg-cyan,bg-default)", pad("project/application", 35), pad("pipeline", 25), pad("branch/env", 19), "stage: jobs...")}
for i, pb := range pbs {
if _, ok := status[pb.Status.String()]; !ok {
statusTitle = append(statusTitle, pb.Status.String())
}
status[pb.Status.String()] = status[pb.Status.String()] + 1
t := ui.pipelineLine(pb.Application.ProjectKey, pb.Application, pb)
for _, s := range pb.Stages {
switch s.Status {
case sdk.StatusWaiting:
t += fmt.Sprintf("[ ➤ %s ](fg-yellow,bg-default)", s.Name)
case sdk.StatusBuilding:
t += fmt.Sprintf("[ ➤ %s ](fg-blue,bg-default)", s.Name)
if len(s.PipelineBuildJobs) > 0 {
t += "[:](fg-cyan,bg-default)"
}
for _, pbj := range s.PipelineBuildJobs {
t += jobLine(pbj.Job.Action.Name, pbj.Status)
}
case sdk.StatusSuccess:
t += fmt.Sprintf("[ ➤ %s ](fg-green,bg-default)", s.Name)
case sdk.StatusFail:
t += fmt.Sprintf("[ ➤ %s ](fg-red,bg-default)", s.Name)
default:
t += fmt.Sprintf("[ ➤ %s %s ](fg-cyan,bg-default)", s.Name, s.Status)
}
}
items = append(items, t)
if i == ui.building.Cursor-1 {
ui.currentURL = computeURL(baseURL, pb.Application.ProjectKey, pb.Application.Name, pb.Pipeline.Name, fmt.Sprintf("%d", pb.BuildNumber), pb.Environment.Name, pb.Trigger.VCSChangesBranch, strconv.FormatInt(pb.Version, 10))
}
}
ui.building.Items = items
sort.Strings(statusTitle)
title := " Pipelines "
for _, s := range statusTitle {
icon, color := statusShort(s)
title += fmt.Sprintf("[%d %s](%s) ", status[s], icon, color)
}
ui.building.BorderLabel = title
return msg
}
func (ui *Termui) pipelineLine(projKey string, app sdk.Application, pb sdk.PipelineBuild) string {
branch := pb.Trigger.VCSChangesBranch
selected := ",bg-default"
if ui.selected == BuildingSelected {
selected = "fg-white"
}
icon, color := statusShort(pb.Status.String())
return fmt.Sprintf("[%s](%s,%s)[ %s](bg-default)[➤ ](fg-cyan,bg-default)[%s ](bg-default)[➤ ](fg-cyan,bg-default)[%s](bg-default)", icon, color, selected, pad(projKey+"/"+app.Name, 35), pad(pb.Pipeline.Name, 25), pad(branch+"/"+pb.Environment.Name, 19))
}
func jobLine(name string, status string) string {
switch status {
case string(sdk.StatusSuccess):
return fmt.Sprintf("[ [%s]](fg-green,bg-default)", name)
case string(sdk.StatusFail):
return fmt.Sprintf("[ [%s]](fg-red,bg-default)", name)
case string(sdk.StatusBuilding):
return fmt.Sprintf("[ [%s]](fg-blue,bg-default)", name)
case string(sdk.StatusWaiting):
return fmt.Sprintf("[ [%s]](fg-yellow,bg-default)", name)
case string(sdk.StatusDisabled):
return fmt.Sprintf("[ [%s-%s]](fg-cyan,bg-default)", name, status)
default:
return fmt.Sprintf("[ [%s-%s]](fg-white,bg-default)", name, status)
}
}
func (ui *Termui) updateQueueWorkers() string {
start := time.Now()
workers, err := sdk.GetWorkers()
if err != nil {
ui.msg = fmt.Sprintf("[%s](bg-red)", err.Error())
return ""
}
elapsed := time.Since(start)
msg := fmt.Sprintf("[workers %s](fg-cyan,bg-default)", sdk.Round(elapsed, time.Millisecond).String())
ui.computeStatusHatcheriesWorkers(workers)
msga, wmodels := ui.computeStatusWorkerModels(workers)
ui.computeStatusWorkersList(workers, wmodels)
return msg + msga
}
func (ui *Termui) computeStatusHatcheriesWorkers(workers []sdk.Worker) {
hatcheryNames, statusTitle := []string{}, []string{}
hatcheries := make(map[string]map[string]int64)
status := make(map[string]int)
for _, w := range workers {
var name string
if w.HatcheryID == 0 {
name = "Without hatchery"
} else {
name = w.HatcheryName
}
if _, ok := hatcheries[name]; !ok {
hatcheries[name] = make(map[string]int64)
hatcheryNames = append(hatcheryNames, name)
}
hatcheries[name][w.Status.String()] = hatcheries[name][w.Status.String()] + 1
if _, ok := status[w.Status.String()]; !ok {
statusTitle = append(statusTitle, w.Status.String())
}
status[w.Status.String()] = status[w.Status.String()] + 1
}
selected := ",bg-default"
if ui.selected == HatcheriesWorkersSelected {
selected = ""
}
items := []string{}
sort.Strings(hatcheryNames)
for _, name := range hatcheryNames {
v := hatcheries[name]
var t string
for _, status := range statusTitle {
if v[status] > 0 {
icon, color := statusShort(status)
t += fmt.Sprintf("[ %d %s ](%s%s)", v[status], icon, color, selected)
}
}
t += fmt.Sprintf("[ %s](fg-white%s)", name, selected)
items = append(items, t)
}
ui.statusHatcheriesWorkers.Items = items
sort.Strings(statusTitle)
title := " Hatcheries "
for _, s := range statusTitle {
icon, color := statusShort(s)
title += fmt.Sprintf("[%d %s](%s) ", status[s], icon, color)
}
ui.statusHatcheriesWorkers.BorderLabel = title
}
func (ui *Termui) computeStatusWorkersList(workers []sdk.Worker, wModels map[int64]sdk.Model) {
titles, items := []string{}, []string{}
values := map[string]sdk.Worker{}
selected := ",bg-default"
statusTitle := []string{}
status := make(map[string]int)
if ui.selected == WorkersListSelected {
selected = ""
}
for _, w := range workers {
n := wModels[w.ModelID].Type + " " + wModels[w.ModelID].Name + " " + w.Name
titles = append(titles, n)
values[n] = w
if _, ok := status[w.Status.String()]; !ok {
statusTitle = append(statusTitle, w.Status.String())
}
status[w.Status.String()] = status[w.Status.String()] + 1
}
sort.Strings(titles)
for _, t := range titles {
w := values[t]
icon, color := statusShort(w.Status.String())
items = append(items, fmt.Sprintf("[%s ](%s%s)[ %s](%s)", icon, color, selected, pad(t, 70), selected))
}
var s string
if len(workers) > 1 {
s = "s"
}
sort.Strings(statusTitle)
title := fmt.Sprintf(" %d Worker%s ", len(workers), s)
for _, s := range statusTitle {
icon, color := statusShort(s)
title += fmt.Sprintf("[%d %s](%s) ", status[s], icon, color)
}
ui.statusWorkerList.BorderLabel = title
ui.statusWorkerList.Items = items
}
func (ui *Termui) computeStatusWorkerModels(workers []sdk.Worker) (string, map[int64]sdk.Model) {
start := time.Now()
workerModels, errwm := sdk.GetWorkerModels()
if errwm != nil {
ui.msg = fmt.Sprintf("[%s](bg-red)", errwm.Error())
return "", nil
}
elapsed := time.Since(start)
msg := fmt.Sprintf(" | [wModels %s](fg-cyan,bg-default)", sdk.Round(elapsed, time.Millisecond).String())
wModels := make(map[int64]sdk.Model, len(workerModels))
for w := range workerModels {
wModels[workerModels[w].ID] = workerModels[w]
}
statusTitle, items, idsModels := []string{}, []string{}, []string{}
models := make(map[string]map[string]int64)
status := make(map[string]int)
for _, w := range workers {
idModel := fmt.Sprintf("%s", wModels[w.ModelID].Type+" "+wModels[w.ModelID].Name)
if _, ok := models[idModel]; !ok {
models[idModel] = make(map[string]int64)
idsModels = append(idsModels, idModel)
}
models[idModel][w.Status.String()] = models[idModel][w.Status.String()] + 1
if _, ok := status[w.Status.String()]; !ok {
statusTitle = append(statusTitle, w.Status.String())
}
status[w.Status.String()] = status[w.Status.String()] + 1
}
selected := ",bg-default"
if ui.selected == WorkerModelsSelected {
selected = ""
}
sort.Strings(idsModels)
for _, id := range idsModels {
v := models[id]
var t string
for _, status := range statusTitle {
if v[status] > 0 {
icon, color := statusShort(status)
t += fmt.Sprintf("[%d %s ](%s%s)", v[status], icon, color, selected)
}
}
t += fmt.Sprintf("[ %s](fg-white%s)", pad(id, 28), selected)
items = append(items, t)
}
ui.statusWorkerModels.Items = items
sort.Strings(statusTitle)
title := " Models "
for _, s := range statusTitle {
icon, color := statusShort(s)
title += fmt.Sprintf("[%d %s](%s) ", status[s], icon, color)
}
ui.statusWorkerModels.BorderLabel = title
return msg, wModels
}
func (ui *Termui) updateQueue(baseURL string) string {
start := time.Now()
var pbJobs []sdk.PipelineBuildJob
data, code, err := sdk.Request("GET", "/queue?status=all", nil)
if err != nil {
ui.msg = fmt.Sprintf("[%s](bg-red)", err.Error())
return ""
}
if code >= 300 {
ui.msg = fmt.Sprintf("[%s](bg-red)", err.Error())
return ""
}
if err = json.Unmarshal(data, &pbJobs); err != nil {
ui.msg = fmt.Sprintf("[%s](bg-red)", err.Error())
return ""
}
elapsed := time.Since(start)
msg := fmt.Sprintf("[queue %s](fg-cyan,bg-default)", sdk.Round(elapsed, time.Millisecond).String())
var maxQueued time.Duration
booked := make(map[string]int)
items := []string{
fmt.Sprintf("[ %s %s%s %s ➤ %s ➤ %s](fg-cyan,bg-default)", pad("since", 9), pad("booked", 27), pad("job", 7), pad("project/application", 35), pad("pipeline/branch/env", 33), "requirements"),
}
for i, job := range pbJobs {
req := ""
for _, r := range job.Job.Action.Requirements {
req += fmt.Sprintf("%s(%s):%s ", r.Name, r.Type, r.Value)
}
prj := getVarsInPbj("cds.project", job.Parameters)
app := getVarsInPbj("cds.application", job.Parameters)
pip := getVarsInPbj("cds.pipeline", job.Parameters)
build := getVarsInPbj("cds.buildNumber", job.Parameters)
env := getVarsInPbj("cds.environment", job.Parameters)
bra := getVarsInPbj("git.branch", job.Parameters)
version := getVarsInPbj("cds.version", job.Parameters)
duration := time.Since(job.Queued)
if maxQueued < duration {
maxQueued = duration
}
row := make([]string, 5)
var c string
if duration > 60*time.Second {
c = "bg-red"
} else if duration > 15*time.Second {
c = "bg-yellow"
} else {
c = "bg-default"
}
row[0] = pad(fmt.Sprintf(sdk.Round(duration, time.Second).String()), 9)
if job.BookedBy.ID != 0 {
row[1] = pad(fmt.Sprintf(" %s.%d ", job.BookedBy.Name, job.BookedBy.ID), 27)
booked[fmt.Sprintf("%s.%d", job.BookedBy.Name, job.BookedBy.ID)] = booked[job.BookedBy.Name] + 1
} else {
row[1] = pad("", 27)
}
row[2] = pad(fmt.Sprintf("%d", job.ID), 7)
row[3] = fmt.Sprintf("%s ➤ %s", pad(prj+"/"+app, 35), pad(pip+"/"+bra+"/"+env, 33))
row[4] = fmt.Sprintf("➤ %s", req)
item := fmt.Sprintf(" [%s](%s)[%s %s %s %s](bg-default)", row[0], c, row[1], row[2], row[3], row[4])
items = append(items, item)
if i == ui.queue.Cursor-1 {
ui.currentURL = computeURL(baseURL, prj, app, pip, build, env, bra, version)
}
}
ui.queue.Items = items
t := fmt.Sprintf(" Queue:%d Max Waiting:%s ", len(pbJobs), sdk.Round(maxQueued, time.Second).String())
for name, total := range booked {
t += fmt.Sprintf("%s:%d ", name, total)
}
ui.queue.BorderLabel = t
return msg
}
func statusShort(status string) (string, string) {
switch status {
case sdk.StatusWaiting.String():
return "☕", "fg-cyan"
case sdk.StatusBuilding.String():
return "▶", "fg-blue"
case sdk.StatusDisabled.String():
return "⏏", "fg-grey"
case sdk.StatusChecking.String():
return "♻", "fg-yellow"
case sdk.StatusSuccess.String():
return "✔", "fg-green"
case sdk.StatusFail.String():
return "✖", "fg-red"
}
return status, "fg-default"
}
func computeURL(baseURL, prj, app, pip, build, env, branch, version string) string {
return fmt.Sprintf("%s/project/%s/application/%s/pipeline/%s/build/%s?envName=%s&branch=%s&version=%s",
baseURL, prj, app, pip, build, url.QueryEscape(env), url.QueryEscape(branch), version,
)
}
func pad(t string, size int) string {
if len(t) > size {
return t[0:size-3] + "..."
}
return t + strings.Repeat(" ", size-len(t))
}
func getVarsInPbj(key string, ps []sdk.Parameter) string {
for _, p := range ps {
if p.Name == key {
return p.Value
}
}
return ""
}
|
MantledIllusion/hura
|
hura-web/src/main/java/com/mantledillusion/injection/hura/web/HuraWebEnvironment.java
|
<filename>hura-web/src/main/java/com/mantledillusion/injection/hura/web/HuraWebEnvironment.java<gh_stars>0
package com.mantledillusion.injection.hura.web;
import com.mantledillusion.injection.hura.core.Blueprint;
import com.mantledillusion.injection.hura.core.annotation.instruction.Define;
class HuraWebEnvironment implements Blueprint {
private final String applicationBasePackage;
private final String applicationInitializerClass;
HuraWebEnvironment(String applicationBasePackage, String applicationInitializerClass) {
this.applicationBasePackage = applicationBasePackage;
this.applicationInitializerClass = applicationInitializerClass;
}
@Define
PropertyAllocation defineApplicationBasePackage() {
return PropertyAllocation.of(HuraWebApplicationInitializer.PKEY_BASEPACKAGE, this.applicationBasePackage);
}
@Define
PropertyAllocation defineApplicationInitializerClass() {
return PropertyAllocation.of(HuraWebApplicationInitializer.PKEY_INITIALIZER, this.applicationInitializerClass);
}
}
|
fredxfred/pinot
|
pinot-core/src/test/java/com/linkedin/pinot/core/data/partition/PartitionFunctionTest.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.linkedin.pinot.core.data.partition;
import java.util.Random;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Unit test for {@link PartitionFunction}
*/
public class PartitionFunctionTest {
/**
* Unit test for {@link ModuloPartitionFunction}.
* <ul>
* <li> Builds an instance of the {@link ModuloPartitionFunction}. </li>
* <li> Performs modulo operations on random numbers and asserts results returned by the partition function
* are as expected. </li>
* </ul>
*/
@Test
public void testModulo() {
long seed = System.currentTimeMillis();
Random random = new Random(seed);
for (int i = 0; i < 1000; i++) {
int expectedNumPartitions = Math.abs(random.nextInt());
// Avoid divide-by-zero.
if (expectedNumPartitions == 0) {
expectedNumPartitions = 1;
}
String functionName = "MoDuLo";
PartitionFunction partitionFunction =
PartitionFunctionFactory.getPartitionFunction(functionName, expectedNumPartitions);
Assert.assertEquals(partitionFunction.toString().toLowerCase(), functionName.toLowerCase());
Assert.assertEquals(partitionFunction.getNumPartitions(), expectedNumPartitions);
for (int j = 0; j < 1000; j++) {
int value = random.nextInt();
Assert.assertEquals(partitionFunction.getPartition(value), (value % expectedNumPartitions));
}
}
}
/**
* Unit test for {@link MurmurPartitionFunction}.
* <ul>
* <li> Tests that partition values are in expected range. </li>
* <li> Tests that toString returns expected string. </li>
* </ul>
*/
@Test
public void testMurmurPartitioner() {
long seed = System.currentTimeMillis();
Random random = new Random(seed);
for (int i = 0; i < 1000; i++) {
int expectedNumPartitions = Math.abs(random.nextInt());
// Avoid divide-by-zero.
if (expectedNumPartitions == 0) {
expectedNumPartitions = 1;
}
String functionName = "mUrmur";
PartitionFunction partitionFunction =
PartitionFunctionFactory.getPartitionFunction(functionName, expectedNumPartitions);
Assert.assertEquals(partitionFunction.toString().toLowerCase(), functionName.toLowerCase());
Assert.assertEquals(partitionFunction.getNumPartitions(), expectedNumPartitions);
for (int j = 0; j < 1000; j++) {
Integer value = random.nextInt();
Assert.assertTrue(partitionFunction.getPartition(value.toString()) < expectedNumPartitions,
"Illegal: " + partitionFunction.getPartition(value.toString()) + " " + expectedNumPartitions);
}
}
}
/**
* Unit test for {@link MurmurPartitionFunction}.
* <ul>
* <li> Tests that partition values are in expected range. </li>
* <li> Tests that toString returns expected string. </li>
* </ul>
*/
@Test
public void testByteArrayPartitioner() {
long seed = System.currentTimeMillis();
Random random = new Random(seed);
for (int i = 0; i < 1000; i++) {
int expectedNumPartitions = Math.abs(random.nextInt());
// Avoid divide-by-zero.
if (expectedNumPartitions == 0) {
expectedNumPartitions = 1;
}
String functionName = "bYteArray";
PartitionFunction partitionFunction =
PartitionFunctionFactory.getPartitionFunction(functionName, expectedNumPartitions);
Assert.assertEquals(partitionFunction.toString().toLowerCase(), functionName.toLowerCase());
Assert.assertEquals(partitionFunction.getNumPartitions(), expectedNumPartitions);
for (int j = 0; j < 1000; j++) {
Integer value = random.nextInt();
Assert.assertTrue(partitionFunction.getPartition(value) < expectedNumPartitions,
"Illegal: " + partitionFunction.getPartition(value) + " " + expectedNumPartitions);
}
}
}
}
|
jonggyup/RequestOrganizer
|
Code/drivers/media/i2c/adv748x/adv748x-core.c
|
/*
* Driver for Analog Devices ADV748X HDMI receiver with AFE
*
* Copyright (C) 2017 Renesas Electronics Corp.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* Authors:
* <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
*/
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/of_graph.h>
#include <linux/regmap.h>
#include <linux/slab.h>
#include <linux/v4l2-dv-timings.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-device.h>
#include <media/v4l2-dv-timings.h>
#include <media/v4l2-ioctl.h>
#include "adv748x.h"
/* -----------------------------------------------------------------------------
* Register manipulation
*/
#define ADV748X_REGMAP_CONF(n) \
{ \
.name = n, \
.reg_bits = 8, \
.val_bits = 8, \
.max_register = 0xff, \
.cache_type = REGCACHE_NONE, \
}
static const struct regmap_config adv748x_regmap_cnf[] = {
ADV748X_REGMAP_CONF("io"),
ADV748X_REGMAP_CONF("dpll"),
ADV748X_REGMAP_CONF("cp"),
ADV748X_REGMAP_CONF("hdmi"),
ADV748X_REGMAP_CONF("edid"),
ADV748X_REGMAP_CONF("repeater"),
ADV748X_REGMAP_CONF("infoframe"),
ADV748X_REGMAP_CONF("cbus"),
ADV748X_REGMAP_CONF("cec"),
ADV748X_REGMAP_CONF("sdp"),
ADV748X_REGMAP_CONF("txa"),
ADV748X_REGMAP_CONF("txb"),
};
static int adv748x_configure_regmap(struct adv748x_state *state, int region)
{
int err;
if (!state->i2c_clients[region])
return -ENODEV;
state->regmap[region] =
devm_regmap_init_i2c(state->i2c_clients[region],
&adv748x_regmap_cnf[region]);
if (IS_ERR(state->regmap[region])) {
err = PTR_ERR(state->regmap[region]);
adv_err(state,
"Error initializing regmap %d with error %d\n",
region, err);
return -EINVAL;
}
return 0;
}
struct adv748x_register_map {
const char *name;
u8 default_addr;
};
static const struct adv748x_register_map adv748x_default_addresses[] = {
[ADV748X_PAGE_IO] = { "main", 0x70 },
[ADV748X_PAGE_DPLL] = { "dpll", 0x26 },
[ADV748X_PAGE_CP] = { "cp", 0x22 },
[ADV748X_PAGE_HDMI] = { "hdmi", 0x34 },
[ADV748X_PAGE_EDID] = { "edid", 0x36 },
[ADV748X_PAGE_REPEATER] = { "repeater", 0x32 },
[ADV748X_PAGE_INFOFRAME] = { "infoframe", 0x31 },
[ADV748X_PAGE_CBUS] = { "cbus", 0x30 },
[ADV748X_PAGE_CEC] = { "cec", 0x41 },
[ADV748X_PAGE_SDP] = { "sdp", 0x79 },
[ADV748X_PAGE_TXB] = { "txb", 0x48 },
[ADV748X_PAGE_TXA] = { "txa", 0x4a },
};
static int adv748x_read_check(struct adv748x_state *state,
int client_page, u8 reg)
{
struct i2c_client *client = state->i2c_clients[client_page];
int err;
unsigned int val;
err = regmap_read(state->regmap[client_page], reg, &val);
if (err) {
adv_err(state, "error reading %02x, %02x\n",
client->addr, reg);
return err;
}
return val;
}
int adv748x_read(struct adv748x_state *state, u8 page, u8 reg)
{
return adv748x_read_check(state, page, reg);
}
int adv748x_write(struct adv748x_state *state, u8 page, u8 reg, u8 value)
{
return regmap_write(state->regmap[page], reg, value);
}
/* adv748x_write_block(): Write raw data with a maximum of I2C_SMBUS_BLOCK_MAX
* size to one or more registers.
*
* A value of zero will be returned on success, a negative errno will
* be returned in error cases.
*/
int adv748x_write_block(struct adv748x_state *state, int client_page,
unsigned int init_reg, const void *val,
size_t val_len)
{
struct regmap *regmap = state->regmap[client_page];
if (val_len > I2C_SMBUS_BLOCK_MAX)
val_len = I2C_SMBUS_BLOCK_MAX;
return regmap_raw_write(regmap, init_reg, val, val_len);
}
static int adv748x_set_slave_addresses(struct adv748x_state *state)
{
struct i2c_client *client;
unsigned int i;
u8 io_reg;
for (i = ADV748X_PAGE_DPLL; i < ADV748X_PAGE_MAX; ++i) {
io_reg = ADV748X_IO_SLAVE_ADDR_BASE + i;
client = state->i2c_clients[i];
io_write(state, io_reg, client->addr << 1);
}
return 0;
}
static void adv748x_unregister_clients(struct adv748x_state *state)
{
unsigned int i;
for (i = 1; i < ARRAY_SIZE(state->i2c_clients); ++i)
i2c_unregister_device(state->i2c_clients[i]);
}
static int adv748x_initialise_clients(struct adv748x_state *state)
{
unsigned int i;
int ret;
for (i = ADV748X_PAGE_DPLL; i < ADV748X_PAGE_MAX; ++i) {
state->i2c_clients[i] = i2c_new_secondary_device(
state->client,
adv748x_default_addresses[i].name,
adv748x_default_addresses[i].default_addr);
if (state->i2c_clients[i] == NULL) {
adv_err(state, "failed to create i2c client %u\n", i);
return -ENOMEM;
}
ret = adv748x_configure_regmap(state, i);
if (ret)
return ret;
}
return adv748x_set_slave_addresses(state);
}
/**
* struct adv748x_reg_value - Register write instruction
* @page: Regmap page identifier
* @reg: I2C register
* @value: value to write to @page at @reg
*/
struct adv748x_reg_value {
u8 page;
u8 reg;
u8 value;
};
static int adv748x_write_regs(struct adv748x_state *state,
const struct adv748x_reg_value *regs)
{
int ret;
while (regs->page != ADV748X_PAGE_EOR) {
if (regs->page == ADV748X_PAGE_WAIT) {
msleep(regs->value);
} else {
ret = adv748x_write(state, regs->page, regs->reg,
regs->value);
if (ret < 0) {
adv_err(state,
"Error regs page: 0x%02x reg: 0x%02x\n",
regs->page, regs->reg);
return ret;
}
}
regs++;
}
return 0;
}
/* -----------------------------------------------------------------------------
* TXA and TXB
*/
static const struct adv748x_reg_value adv748x_power_up_txa_4lane[] = {
{ADV748X_PAGE_TXA, 0x00, 0x84}, /* Enable 4-lane MIPI */
{ADV748X_PAGE_TXA, 0x00, 0xa4}, /* Set Auto DPHY Timing */
{ADV748X_PAGE_TXA, 0x31, 0x82}, /* ADI Required Write */
{ADV748X_PAGE_TXA, 0x1e, 0x40}, /* ADI Required Write */
{ADV748X_PAGE_TXA, 0xda, 0x01}, /* i2c_mipi_pll_en - 1'b1 */
{ADV748X_PAGE_WAIT, 0x00, 0x02},/* delay 2 */
{ADV748X_PAGE_TXA, 0x00, 0x24 },/* Power-up CSI-TX */
{ADV748X_PAGE_WAIT, 0x00, 0x01},/* delay 1 */
{ADV748X_PAGE_TXA, 0xc1, 0x2b}, /* ADI Required Write */
{ADV748X_PAGE_WAIT, 0x00, 0x01},/* delay 1 */
{ADV748X_PAGE_TXA, 0x31, 0x80}, /* ADI Required Write */
{ADV748X_PAGE_EOR, 0xff, 0xff} /* End of register table */
};
static const struct adv748x_reg_value adv748x_power_down_txa_4lane[] = {
{ADV748X_PAGE_TXA, 0x31, 0x82}, /* ADI Required Write */
{ADV748X_PAGE_TXA, 0x1e, 0x00}, /* ADI Required Write */
{ADV748X_PAGE_TXA, 0x00, 0x84}, /* Enable 4-lane MIPI */
{ADV748X_PAGE_TXA, 0xda, 0x01}, /* i2c_mipi_pll_en - 1'b1 */
{ADV748X_PAGE_TXA, 0xc1, 0x3b}, /* ADI Required Write */
{ADV748X_PAGE_EOR, 0xff, 0xff} /* End of register table */
};
static const struct adv748x_reg_value adv748x_power_up_txb_1lane[] = {
{ADV748X_PAGE_TXB, 0x00, 0x81}, /* Enable 1-lane MIPI */
{ADV748X_PAGE_TXB, 0x00, 0xa1}, /* Set Auto DPHY Timing */
{ADV748X_PAGE_TXB, 0x31, 0x82}, /* ADI Required Write */
{ADV748X_PAGE_TXB, 0x1e, 0x40}, /* ADI Required Write */
{ADV748X_PAGE_TXB, 0xda, 0x01}, /* i2c_mipi_pll_en - 1'b1 */
{ADV748X_PAGE_WAIT, 0x00, 0x02},/* delay 2 */
{ADV748X_PAGE_TXB, 0x00, 0x21 },/* Power-up CSI-TX */
{ADV748X_PAGE_WAIT, 0x00, 0x01},/* delay 1 */
{ADV748X_PAGE_TXB, 0xc1, 0x2b}, /* ADI Required Write */
{ADV748X_PAGE_WAIT, 0x00, 0x01},/* delay 1 */
{ADV748X_PAGE_TXB, 0x31, 0x80}, /* ADI Required Write */
{ADV748X_PAGE_EOR, 0xff, 0xff} /* End of register table */
};
static const struct adv748x_reg_value adv748x_power_down_txb_1lane[] = {
{ADV748X_PAGE_TXB, 0x31, 0x82}, /* ADI Required Write */
{ADV748X_PAGE_TXB, 0x1e, 0x00}, /* ADI Required Write */
{ADV748X_PAGE_TXB, 0x00, 0x81}, /* Enable 4-lane MIPI */
{ADV748X_PAGE_TXB, 0xda, 0x01}, /* i2c_mipi_pll_en - 1'b1 */
{ADV748X_PAGE_TXB, 0xc1, 0x3b}, /* ADI Required Write */
{ADV748X_PAGE_EOR, 0xff, 0xff} /* End of register table */
};
int adv748x_txa_power(struct adv748x_state *state, bool on)
{
int val;
val = txa_read(state, ADV748X_CSI_FS_AS_LS);
if (val < 0)
return val;
/*
* This test against BIT(6) is not documented by the datasheet, but was
* specified in the downstream driver.
* Track with a WARN_ONCE to determine if it is ever set by HW.
*/
WARN_ONCE((on && val & ADV748X_CSI_FS_AS_LS_UNKNOWN),
"Enabling with unknown bit set");
if (on)
return adv748x_write_regs(state, adv748x_power_up_txa_4lane);
return adv748x_write_regs(state, adv748x_power_down_txa_4lane);
}
int adv748x_txb_power(struct adv748x_state *state, bool on)
{
int val;
val = txb_read(state, ADV748X_CSI_FS_AS_LS);
if (val < 0)
return val;
/*
* This test against BIT(6) is not documented by the datasheet, but was
* specified in the downstream driver.
* Track with a WARN_ONCE to determine if it is ever set by HW.
*/
WARN_ONCE((on && val & ADV748X_CSI_FS_AS_LS_UNKNOWN),
"Enabling with unknown bit set");
if (on)
return adv748x_write_regs(state, adv748x_power_up_txb_1lane);
return adv748x_write_regs(state, adv748x_power_down_txb_1lane);
}
/* -----------------------------------------------------------------------------
* Media Operations
*/
static const struct media_entity_operations adv748x_media_ops = {
.link_validate = v4l2_subdev_link_validate,
};
/* -----------------------------------------------------------------------------
* HW setup
*/
static const struct adv748x_reg_value adv748x_sw_reset[] = {
{ADV748X_PAGE_IO, 0xff, 0xff}, /* SW reset */
{ADV748X_PAGE_WAIT, 0x00, 0x05},/* delay 5 */
{ADV748X_PAGE_IO, 0x01, 0x76}, /* ADI Required Write */
{ADV748X_PAGE_IO, 0xf2, 0x01}, /* Enable I2C Read Auto-Increment */
{ADV748X_PAGE_EOR, 0xff, 0xff} /* End of register table */
};
/* Supported Formats For Script Below */
/* - 01-29 HDMI to MIPI TxA CSI 4-Lane - RGB888: */
static const struct adv748x_reg_value adv748x_init_txa_4lane[] = {
/* Disable chip powerdown & Enable HDMI Rx block */
{ADV748X_PAGE_IO, 0x00, 0x40},
{ADV748X_PAGE_REPEATER, 0x40, 0x83}, /* Enable HDCP 1.1 */
{ADV748X_PAGE_HDMI, 0x00, 0x08},/* Foreground Channel = A */
{ADV748X_PAGE_HDMI, 0x98, 0xff},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0x99, 0xa3},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0x9a, 0x00},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0x9b, 0x0a},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0x9d, 0x40},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0xcb, 0x09},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0x3d, 0x10},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0x3e, 0x7b},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0x3f, 0x5e},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0x4e, 0xfe},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0x4f, 0x18},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0x57, 0xa3},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0x58, 0x04},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0x85, 0x10},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0x83, 0x00},/* Enable All Terminations */
{ADV748X_PAGE_HDMI, 0xa3, 0x01},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0xbe, 0x00},/* ADI Required Write */
{ADV748X_PAGE_HDMI, 0x6c, 0x01},/* HPA Manual Enable */
{ADV748X_PAGE_HDMI, 0xf8, 0x01},/* HPA Asserted */
{ADV748X_PAGE_HDMI, 0x0f, 0x00},/* Audio Mute Speed Set to Fastest */
/* (Smallest Step Size) */
{ADV748X_PAGE_IO, 0x04, 0x02}, /* RGB Out of CP */
{ADV748X_PAGE_IO, 0x12, 0xf0}, /* CSC Depends on ip Packets, SDR 444 */
{ADV748X_PAGE_IO, 0x17, 0x80}, /* Luma & Chroma can reach 254d */
{ADV748X_PAGE_IO, 0x03, 0x86}, /* CP-Insert_AV_Code */
{ADV748X_PAGE_CP, 0x7c, 0x00}, /* ADI Required Write */
{ADV748X_PAGE_IO, 0x0c, 0xe0}, /* Enable LLC_DLL & Double LLC Timing */
{ADV748X_PAGE_IO, 0x0e, 0xdd}, /* LLC/PIX/SPI PINS TRISTATED AUD */
/* Outputs Enabled */
{ADV748X_PAGE_IO, 0x10, 0xa0}, /* Enable 4-lane CSI Tx & Pixel Port */
{ADV748X_PAGE_TXA, 0x00, 0x84}, /* Enable 4-lane MIPI */
{ADV748X_PAGE_TXA, 0x00, 0xa4}, /* Set Auto DPHY Timing */
{ADV748X_PAGE_TXA, 0xdb, 0x10}, /* ADI Required Write */
{ADV748X_PAGE_TXA, 0xd6, 0x07}, /* ADI Required Write */
{ADV748X_PAGE_TXA, 0xc4, 0x0a}, /* ADI Required Write */
{ADV748X_PAGE_TXA, 0x71, 0x33}, /* ADI Required Write */
{ADV748X_PAGE_TXA, 0x72, 0x11}, /* ADI Required Write */
{ADV748X_PAGE_TXA, 0xf0, 0x00}, /* i2c_dphy_pwdn - 1'b0 */
{ADV748X_PAGE_TXA, 0x31, 0x82}, /* ADI Required Write */
{ADV748X_PAGE_TXA, 0x1e, 0x40}, /* ADI Required Write */
{ADV748X_PAGE_TXA, 0xda, 0x01}, /* i2c_mipi_pll_en - 1'b1 */
{ADV748X_PAGE_WAIT, 0x00, 0x02},/* delay 2 */
{ADV748X_PAGE_TXA, 0x00, 0x24 },/* Power-up CSI-TX */
{ADV748X_PAGE_WAIT, 0x00, 0x01},/* delay 1 */
{ADV748X_PAGE_TXA, 0xc1, 0x2b}, /* ADI Required Write */
{ADV748X_PAGE_WAIT, 0x00, 0x01},/* delay 1 */
{ADV748X_PAGE_TXA, 0x31, 0x80}, /* ADI Required Write */
{ADV748X_PAGE_EOR, 0xff, 0xff} /* End of register table */
};
/* 02-01 Analog CVBS to MIPI TX-B CSI 1-Lane - */
/* Autodetect CVBS Single Ended In Ain 1 - MIPI Out */
static const struct adv748x_reg_value adv748x_init_txb_1lane[] = {
{ADV748X_PAGE_IO, 0x00, 0x30}, /* Disable chip powerdown Rx */
{ADV748X_PAGE_IO, 0xf2, 0x01}, /* Enable I2C Read Auto-Increment */
{ADV748X_PAGE_IO, 0x0e, 0xff}, /* LLC/PIX/AUD/SPI PINS TRISTATED */
{ADV748X_PAGE_SDP, 0x0f, 0x00}, /* Exit Power Down Mode */
{ADV748X_PAGE_SDP, 0x52, 0xcd}, /* ADI Required Write */
{ADV748X_PAGE_SDP, 0x0e, 0x80}, /* ADI Required Write */
{ADV748X_PAGE_SDP, 0x9c, 0x00}, /* ADI Required Write */
{ADV748X_PAGE_SDP, 0x9c, 0xff}, /* ADI Required Write */
{ADV748X_PAGE_SDP, 0x0e, 0x00}, /* ADI Required Write */
/* ADI recommended writes for improved video quality */
{ADV748X_PAGE_SDP, 0x80, 0x51}, /* ADI Required Write */
{ADV748X_PAGE_SDP, 0x81, 0x51}, /* ADI Required Write */
{ADV748X_PAGE_SDP, 0x82, 0x68}, /* ADI Required Write */
{ADV748X_PAGE_SDP, 0x03, 0x42}, /* Tri-S Output , PwrDwn 656 pads */
{ADV748X_PAGE_SDP, 0x04, 0xb5}, /* ITU-R BT.656-4 compatible */
{ADV748X_PAGE_SDP, 0x13, 0x00}, /* ADI Required Write */
{ADV748X_PAGE_SDP, 0x17, 0x41}, /* Select SH1 */
{ADV748X_PAGE_SDP, 0x31, 0x12}, /* ADI Required Write */
{ADV748X_PAGE_SDP, 0xe6, 0x4f}, /* V bit end pos manually in NTSC */
/* Enable 1-Lane MIPI Tx, */
/* enable pixel output and route SD through Pixel port */
{ADV748X_PAGE_IO, 0x10, 0x70},
{ADV748X_PAGE_TXB, 0x00, 0x81}, /* Enable 1-lane MIPI */
{ADV748X_PAGE_TXB, 0x00, 0xa1}, /* Set Auto DPHY Timing */
{ADV748X_PAGE_TXB, 0xd2, 0x40}, /* ADI Required Write */
{ADV748X_PAGE_TXB, 0xc4, 0x0a}, /* ADI Required Write */
{ADV748X_PAGE_TXB, 0x71, 0x33}, /* ADI Required Write */
{ADV748X_PAGE_TXB, 0x72, 0x11}, /* ADI Required Write */
{ADV748X_PAGE_TXB, 0xf0, 0x00}, /* i2c_dphy_pwdn - 1'b0 */
{ADV748X_PAGE_TXB, 0x31, 0x82}, /* ADI Required Write */
{ADV748X_PAGE_TXB, 0x1e, 0x40}, /* ADI Required Write */
{ADV748X_PAGE_TXB, 0xda, 0x01}, /* i2c_mipi_pll_en - 1'b1 */
{ADV748X_PAGE_WAIT, 0x00, 0x02},/* delay 2 */
{ADV748X_PAGE_TXB, 0x00, 0x21 },/* Power-up CSI-TX */
{ADV748X_PAGE_WAIT, 0x00, 0x01},/* delay 1 */
{ADV748X_PAGE_TXB, 0xc1, 0x2b}, /* ADI Required Write */
{ADV748X_PAGE_WAIT, 0x00, 0x01},/* delay 1 */
{ADV748X_PAGE_TXB, 0x31, 0x80}, /* ADI Required Write */
{ADV748X_PAGE_EOR, 0xff, 0xff} /* End of register table */
};
static int adv748x_reset(struct adv748x_state *state)
{
int ret;
ret = adv748x_write_regs(state, adv748x_sw_reset);
if (ret < 0)
return ret;
ret = adv748x_set_slave_addresses(state);
if (ret < 0)
return ret;
/* Init and power down TXA */
ret = adv748x_write_regs(state, adv748x_init_txa_4lane);
if (ret)
return ret;
adv748x_txa_power(state, 0);
/* Init and power down TXB */
ret = adv748x_write_regs(state, adv748x_init_txb_1lane);
if (ret)
return ret;
adv748x_txb_power(state, 0);
/* Disable chip powerdown & Enable HDMI Rx block */
io_write(state, ADV748X_IO_PD, ADV748X_IO_PD_RX_EN);
/* Enable 4-lane CSI Tx & Pixel Port */
io_write(state, ADV748X_IO_10, ADV748X_IO_10_CSI4_EN |
ADV748X_IO_10_CSI1_EN |
ADV748X_IO_10_PIX_OUT_EN);
/* Use vid_std and v_freq as freerun resolution for CP */
cp_clrset(state, ADV748X_CP_CLMP_POS, ADV748X_CP_CLMP_POS_DIS_AUTO,
ADV748X_CP_CLMP_POS_DIS_AUTO);
return 0;
}
static int adv748x_identify_chip(struct adv748x_state *state)
{
int msb, lsb;
lsb = io_read(state, ADV748X_IO_CHIP_REV_ID_1);
msb = io_read(state, ADV748X_IO_CHIP_REV_ID_2);
if (lsb < 0 || msb < 0) {
adv_err(state, "Failed to read chip revision\n");
return -EIO;
}
adv_info(state, "chip found @ 0x%02x revision %02x%02x\n",
state->client->addr << 1, lsb, msb);
return 0;
}
/* -----------------------------------------------------------------------------
* i2c driver
*/
void adv748x_subdev_init(struct v4l2_subdev *sd, struct adv748x_state *state,
const struct v4l2_subdev_ops *ops, u32 function,
const char *ident)
{
v4l2_subdev_init(sd, ops);
sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
/* the owner is the same as the i2c_client's driver owner */
sd->owner = state->dev->driver->owner;
sd->dev = state->dev;
v4l2_set_subdevdata(sd, state);
/* initialize name */
snprintf(sd->name, sizeof(sd->name), "%s %d-%04x %s",
state->dev->driver->name,
i2c_adapter_id(state->client->adapter),
state->client->addr, ident);
sd->entity.function = function;
sd->entity.ops = &adv748x_media_ops;
}
static int adv748x_parse_dt(struct adv748x_state *state)
{
struct device_node *ep_np = NULL;
struct of_endpoint ep;
bool out_found = false;
bool in_found = false;
for_each_endpoint_of_node(state->dev->of_node, ep_np) {
of_graph_parse_endpoint(ep_np, &ep);
adv_info(state, "Endpoint %pOF on port %d", ep.local_node,
ep.port);
if (ep.port >= ADV748X_PORT_MAX) {
adv_err(state, "Invalid endpoint %pOF on port %d",
ep.local_node, ep.port);
continue;
}
if (state->endpoints[ep.port]) {
adv_err(state,
"Multiple port endpoints are not supported");
continue;
}
of_node_get(ep_np);
state->endpoints[ep.port] = ep_np;
/*
* At least one input endpoint and one output endpoint shall
* be defined.
*/
if (ep.port < ADV748X_PORT_TXA)
in_found = true;
else
out_found = true;
}
return in_found && out_found ? 0 : -ENODEV;
}
static void adv748x_dt_cleanup(struct adv748x_state *state)
{
unsigned int i;
for (i = 0; i < ADV748X_PORT_MAX; i++)
of_node_put(state->endpoints[i]);
}
static int adv748x_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct adv748x_state *state;
int ret;
/* Check if the adapter supports the needed features */
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -EIO;
state = kzalloc(sizeof(struct adv748x_state), GFP_KERNEL);
if (!state)
return -ENOMEM;
mutex_init(&state->mutex);
state->dev = &client->dev;
state->client = client;
state->i2c_clients[ADV748X_PAGE_IO] = client;
i2c_set_clientdata(client, state);
/*
* We can not use container_of to get back to the state with two TXs;
* Initialize the TXs's fields unconditionally on the endpoint
* presence to access them later.
*/
state->txa.state = state->txb.state = state;
state->txa.page = ADV748X_PAGE_TXA;
state->txb.page = ADV748X_PAGE_TXB;
state->txa.port = ADV748X_PORT_TXA;
state->txb.port = ADV748X_PORT_TXB;
/* Discover and process ports declared by the Device tree endpoints */
ret = adv748x_parse_dt(state);
if (ret) {
adv_err(state, "Failed to parse device tree");
goto err_free_mutex;
}
/* Configure IO Regmap region */
ret = adv748x_configure_regmap(state, ADV748X_PAGE_IO);
if (ret) {
adv_err(state, "Error configuring IO regmap region");
goto err_cleanup_dt;
}
ret = adv748x_identify_chip(state);
if (ret) {
adv_err(state, "Failed to identify chip");
goto err_cleanup_dt;
}
/* Configure remaining pages as I2C clients with regmap access */
ret = adv748x_initialise_clients(state);
if (ret) {
adv_err(state, "Failed to setup client regmap pages");
goto err_cleanup_clients;
}
/* SW reset ADV748X to its default values */
ret = adv748x_reset(state);
if (ret) {
adv_err(state, "Failed to reset hardware");
goto err_cleanup_clients;
}
/* Initialise HDMI */
ret = adv748x_hdmi_init(&state->hdmi);
if (ret) {
adv_err(state, "Failed to probe HDMI");
goto err_cleanup_clients;
}
/* Initialise AFE */
ret = adv748x_afe_init(&state->afe);
if (ret) {
adv_err(state, "Failed to probe AFE");
goto err_cleanup_hdmi;
}
/* Initialise TXA */
ret = adv748x_csi2_init(state, &state->txa);
if (ret) {
adv_err(state, "Failed to probe TXA");
goto err_cleanup_afe;
}
/* Initialise TXB */
ret = adv748x_csi2_init(state, &state->txb);
if (ret) {
adv_err(state, "Failed to probe TXB");
goto err_cleanup_txa;
}
return 0;
err_cleanup_txa:
adv748x_csi2_cleanup(&state->txa);
err_cleanup_afe:
adv748x_afe_cleanup(&state->afe);
err_cleanup_hdmi:
adv748x_hdmi_cleanup(&state->hdmi);
err_cleanup_clients:
adv748x_unregister_clients(state);
err_cleanup_dt:
adv748x_dt_cleanup(state);
err_free_mutex:
mutex_destroy(&state->mutex);
kfree(state);
return ret;
}
static int adv748x_remove(struct i2c_client *client)
{
struct adv748x_state *state = i2c_get_clientdata(client);
adv748x_afe_cleanup(&state->afe);
adv748x_hdmi_cleanup(&state->hdmi);
adv748x_csi2_cleanup(&state->txa);
adv748x_csi2_cleanup(&state->txb);
adv748x_unregister_clients(state);
adv748x_dt_cleanup(state);
mutex_destroy(&state->mutex);
kfree(state);
return 0;
}
static const struct i2c_device_id adv748x_id[] = {
{ "adv7481", 0 },
{ "adv7482", 0 },
{ },
};
MODULE_DEVICE_TABLE(i2c, adv748x_id);
static const struct of_device_id adv748x_of_table[] = {
{ .compatible = "adi,adv7481", },
{ .compatible = "adi,adv7482", },
{ }
};
MODULE_DEVICE_TABLE(of, adv748x_of_table);
static struct i2c_driver adv748x_driver = {
.driver = {
.name = "adv748x",
.of_match_table = adv748x_of_table,
},
.probe = adv748x_probe,
.remove = adv748x_remove,
.id_table = adv748x_id,
};
module_i2c_driver(adv748x_driver);
MODULE_AUTHOR("<NAME> <<EMAIL>>");
MODULE_DESCRIPTION("ADV748X video decoder");
MODULE_LICENSE("GPL v2");
|
SakthivelMKS/finezoom-java-may2018
|
Java_Trainning/src/com/bluescope/java/training/JavaClassObjectExample.java
|
package com.bluescope.java.training;
import java.util.ArrayList;
public class JavaClassObjectExample {
public static void main(String args[]) {
excute ex =new excute();
ex.auther="Balagurusamy";
ex.bookname="J2EE";
ex.price=3000;
String jj=ex.bookDetails();
System.out.println("The return value:"+jj);
}
}
class excute{
String bookname;
String auther;
int price;
public String bookDetails() {
return bookname.concat(auther)+price;
}
@SuppressWarnings("rawtypes")
public ArrayList<Comparable> bookDetails1(int a,int b) {
ArrayList<Comparable> list=new ArrayList<Comparable>();
list.add(a);
list.add(b);
String Result;
Result=""+(a+b);
list.add(Result);
return list;
}
}
|
salamanderrex/CSE291DS
|
project2/conformance/rmi/SkeletonTest.java
|
<filename>project2/conformance/rmi/SkeletonTest.java
package conformance.rmi;
import test.*;
import rmi.*;
import java.net.*;
/** Performs basic tests on the public interface of {@link rmi.Skeleton}.
<p>
The tests performed are:
<ul>
<li>Both <code>Skeleton</code> constructors reject classes.</li>
<li>Both constructors reject non-remote interfaces.</li>
<li>Both constructors require the first two arguments to be
non-<code>null</code>.</li>
<li>The skeleton can be started and stopped, and accepts connections while
started.</li>
</ul>
*/
public class SkeletonTest extends Test
{
/** Test notice. */
public static final String notice = "checking skeleton public interface";
/** Socket address used for the creation of skeletons. */
private final InetSocketAddress address;
/** Dummy object used for testing calls to <code>Skeleton</code>
constructors. */
private final BadInterfaceImplementation dummy_server;
/** Regular server object. */
private final TestServer server;
/** The main skeleton used for testing. */
private final TestSkeleton skeleton;
/** Indicates whether the skeleton has stopped. */
private boolean stopped;
/** Creates a <code>SkeletonTest</code> object. */
public SkeletonTest()
{
address = new InetSocketAddress(7000);
dummy_server = new BadInterfaceImplementation();
server = new TestServer();
skeleton = new TestSkeleton();
stopped = false;
}
/** Performs the test. */
@Override
protected void perform() throws TestFailed
{
ensureClassRejected();
ensureNonRemoteInterfaceRejected();
ensureNullPointerExceptions();
ensureSkeletonRuns();
}
/** Performs tests with a running skeleton.
<p>
This method starts the skeleton and then stops it. In between, it probes
to see if the skeleton is accepting connections.
*/
private void ensureSkeletonRuns() throws TestFailed
{
if(probe())
throw new TestFailed("skeleton accepts connections before start");
try
{
skeleton.start();
}
catch(RMIException e)
{
throw new TestFailed("unable to start skeleton", e);
}
if(!probe())
throw new TestFailed("skeleton refuses connections after start");
skeleton.stop();
synchronized(this)
{
while(!stopped)
{
try
{
wait();
}
catch(InterruptedException e) { }
}
}
if(probe())
throw new TestFailed("skeleton accepts connections after stop");
}
/** Wakes <code>ensureSkeletonRuns</code>. */
private synchronized void wake()
{
stopped = true;
notifyAll();
}
/** Checks that it is possible to connect to the server.
@return <code>true</code> if the connection can be established, and
<code>false</code> if it cannot be.
*/
private boolean probe()
{
Socket socket = new Socket();
try
{
socket.connect(address);
}
catch(Exception e)
{
return false;
}
try
{
socket.close();
}
catch(Exception e) { }
return true;
}
/** Stops the skeleton server, if it is running, and attempts to wake the
test main thread. */
@Override
protected void clean()
{
skeleton.stop();
wake();
}
/** Ensures that a <code>Skeleton</code> cannot be constructed from a class
rather than an interface.
@throws TestFailed If a <code>Skeleton</code> is constructed from a
class, or if an unexpected exception occurs.
*/
private void ensureClassRejected() throws TestFailed
{
try
{
Skeleton<Object> bad_skeleton =
new Skeleton<Object>(Object.class, dummy_server);
throw new TestFailed("Skeleton(Class<T>, T) constructor has " +
"accepted a class");
}
catch(TestFailed e) { throw e; }
catch(Error e) { }
catch(Throwable t)
{
throw new TestFailed("Skeleton(Class<T>, T) constructor threw " +
"an unexpected exception when given a " +
"class", t);
}
try
{
Skeleton<Object> bad_skeleton =
new Skeleton<Object>(Object.class, dummy_server, address);
throw new TestFailed("Skeleton(Class<T>, T, InetSocketAddress) " +
"constructor has accepted a class");
}
catch(TestFailed e) { throw e; }
catch(Error e) { }
catch(Throwable t)
{
throw new TestFailed("Skeleton(Class<T>, T, InetSocketAddress) " +
"constructor threw an unexpected exception " +
"when given a class", t);
}
}
/** Ensures that a <code>Skeleton</code> cannot be constructed from a
non-remote interface.
@throws TestFailed If a <code>Skeleton</code> is constructed from a
non-remote interface, or if an unexpected exception
occurs.
*/
private void ensureNonRemoteInterfaceRejected() throws TestFailed
{
try
{
Skeleton<BadInterface> bad_skeleton =
new Skeleton<BadInterface>(BadInterface.class, dummy_server);
throw new TestFailed("Skeleton(Class<T>, T) constructor has " +
"accepted a non-remote interface");
}
catch(TestFailed e) { throw e; }
catch(Error e) { }
catch(Throwable t)
{
throw new TestFailed("Skeleton(Class<T>, T) constructor threw " +
"an unexpected exception when given a " +
"non-remote interface", t);
}
try
{
Skeleton<BadInterface> bad_skeleton =
new Skeleton<BadInterface>(BadInterface.class, dummy_server,
address);
throw new TestFailed("Skeleton(Class<T>, T, InetSocketAddress) " +
"constructor has accepted a non-remote " +
"interface");
}
catch(TestFailed e) { throw e; }
catch(Error e) { }
catch(Throwable t)
{
throw new TestFailed("Skeleton(Class<T>, T, InetSocketAddress) " +
"constructor threw an unexpected exception " +
"when given a non-remote interface", t);
}
}
/** Ensures that <code>Skeleton</code> constructors throw
<code>NullPointerException</code> when given <code>null</code> for the
class or server parameters.
@throws TestFailed If <code>null</code> is given as a parameter but the
correct exception is not thrown.
*/
private void ensureNullPointerExceptions() throws TestFailed
{
// Make sure that null for the first argument is rejected.
try
{
Skeleton<TestInterface> bad_skeleton =
new Skeleton<TestInterface>(null, server);
throw new TestFailed("Skeleton(Class<T>, T) constructor " +
"accepted null for first argument");
}
catch(TestFailed e) { throw e; }
catch(NullPointerException e) { }
catch(Throwable t)
{
throw new TestFailed("Skeleton(Class<T>, T) constructor threw " +
"an unexpected exception when given null " +
"for first argument", t);
}
try
{
Skeleton<TestInterface> bad_skeleton =
new Skeleton<TestInterface>(null, server, address);
throw new TestFailed("Skeleton(Class<T>, T, InetSocketAddress) " +
"constructor accepted null for first " +
"argument");
}
catch(TestFailed e) { throw e; }
catch(NullPointerException e) { }
catch(Throwable t)
{
throw new TestFailed("Skeleton(Class<T>, T, InetSocketAddress) " +
"constructor threw an unexpected exception " +
"when given null for first argument", t);
}
// Make sure that null for the second argument is rejected.
try
{
Skeleton<TestInterface> bad_skeleton =
new Skeleton<TestInterface>(TestInterface.class, null);
throw new TestFailed("Skeleton(Class<T>, T) constructor " +
"accepted null for second argument");
}
catch(TestFailed e) { throw e; }
catch(NullPointerException e) { }
catch(Throwable t)
{
throw new TestFailed("Skeleton(Class<T>, T) constructor threw " +
"an unexpected exception when given null " +
"for second argument", t);
}
try
{
Skeleton<TestInterface> bad_skeleton =
new Skeleton<TestInterface>(TestInterface.class, null,
address);
throw new TestFailed("Skeleton(Class<T>, T, InetSocketAddress) " +
"constructor accepted null for second " +
"argument");
}
catch(TestFailed e) { throw e; }
catch(NullPointerException e) { }
catch(Throwable t)
{
throw new TestFailed("Skeleton(Class<T>, T, InetSocketAddress) " +
"constructor threw an unexpected exception " +
"when given null for second argument", t);
}
}
/** Derivative of <code>Skeleton</code> which notifies the test when it
stops.
<p>
Service thread errors are ignored because, in this test, their source is
generally the <code>probe</code> method.
*/
private class TestSkeleton extends Skeleton<TestInterface>
{
/** Creates a <code>TestSkeleton</code> */
TestSkeleton()
{
super(TestInterface.class, server, address);
}
/** Wakes the testing main thread. */
@Override
protected void stopped(Throwable cause)
{
wake();
}
/** Handles an error in the listening thread. */
@Override
protected boolean listen_error(Exception e)
{
failure(new TestFailed("error in skeleton listening thread", e));
return false;
}
}
/** Dummy implementation of <code>BadInterface</code>. */
private class BadInterfaceImplementation implements BadInterface
{
/** Returns its argument. */
@Override
public Object method(int argument)
{
return argument;
}
}
}
|
Sakshi14-code/CompetitiveCodingQuestions
|
Backtracking/Word Break.cpp
|
<filename>Backtracking/Word Break.cpp
#include<bits/stdc++.h>
#include<cmath>
#include<climits>
#define test ll t; cin>>t; while(t--)
#define rep0(n) for(ll i=0;i<(n);i++)
#define rep1(n) for(ll i=1;i<=(n);i++)
using namespace std;
typedef long long ll;
ll len,n;
unordered_set<string> dict;
bool searchInDict(string word)
{
if(dict.find(word)!=dict.end())
return true;
return false;
}
/*variable length denotes the summation of lengths of all previously formed words.
For eg i am a boyandgirl. so there are 4 strings in the vector vs that are ["i","am","a","boyandgirl"].
Therefore length = len("i") + len("am") + len("a") = 1+2+1 = 4.
Note that we will not consider the length of last string because this the word which we are supposed
to split now and has not yet been split.*/
void WordBreak(string lastWord,ll spacePos,string result,ll length)
{
if(spacePos>len)
{
if(searchInDict(lastWord))
cout<<result+lastWord<<endl;
return;
}
ll splitLen = spacePos - length;
WordBreak(lastWord,spacePos+1,result,length);//without giving space
/* splitting the last word into two words and inserting into result string if the first word is present in
dictionary*/
string split1(lastWord.begin(),lastWord.begin()+splitLen);
string split2(lastWord.begin()+splitLen,lastWord.end());
if(searchInDict(split1)) //if word formed is present in dictionary
/*deleting the last word and inserting the two spliited words formed from last word into the vector */
WordBreak(split2,spacePos+1,result+split1+" ",length+split1.length()); // giving space.
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
cin>>n;
string str;
rep0(n)
{
cin>>str;
dict.insert(str);
}
string sentence;
cin>>sentence;
len = sentence.length();
WordBreak(sentence,1,"",0);
return 0;
}
|
AkashSDas/DataStructures-and-Algorithms
|
data-structures/recursion/power.py
|
<gh_stars>0
def power(num, raised_to, count=1):
# Handling raised to 0 condition
if raised_to == 0:
return 1
if raised_to == count:
return num
return num * power(num, raised_to, count + 1)
print(power(2, 5))
# Another way
def power_2(num, raised_to):
if raised_to == 0:
return 1
return num * power_2(num, raised_to - 1)
print(power_2(2, 0))
print(power_2(2, 5))
|
ClearControl/ClearCLIJ
|
src/main/java/net/haesleinhuepf/clij/macro/modules/Crop2D.java
|
package net.haesleinhuepf.clij.macro.modules;
import net.haesleinhuepf.clij.clearcl.ClearCLBuffer;
import net.haesleinhuepf.clij.clearcl.ClearCLImage;
import net.haesleinhuepf.clij.kernels.Kernels;
import net.haesleinhuepf.clij.macro.AbstractCLIJPlugin;
import net.haesleinhuepf.clij.macro.CLIJMacroPlugin;
import net.haesleinhuepf.clij.macro.CLIJOpenCLProcessor;
import net.haesleinhuepf.clij.macro.documentation.OffersDocumentation;
import org.scijava.plugin.Plugin;
/**
* Author: @haesleinhuepf
* December 2018
*/
@Deprecated
@Plugin(type = CLIJMacroPlugin.class, name = "CLIJ_crop2D")
public class Crop2D extends AbstractCLIJPlugin implements CLIJMacroPlugin, CLIJOpenCLProcessor, OffersDocumentation {
@Override
public boolean executeCL() {
if (containsCLImageArguments() && clij.hasImageSupport()) {
return Kernels.crop(clij, (ClearCLImage)( args[0]), (ClearCLImage)(args[1]), asInteger(args[2]), asInteger(args[3]));
} else {
Object[] args = openCLBufferArgs();
boolean result = Kernels.crop(clij, (ClearCLBuffer)( args[0]), (ClearCLBuffer)(args[1]), asInteger(args[2]), asInteger(args[3]));
releaseBuffers(args);
return result;
}
}
@Override
public String getParameterHelpText() {
return "Image source, Image destination, Number startX, Number startY, Number width, Number height";
}
@Override
public ClearCLBuffer createOutputBufferFromSource(ClearCLBuffer input)
{
int width = asInteger(args[4]);
int height = asInteger(args[5]);
return clij.createCLBuffer(new long[]{width, height}, input.getNativeType());
}
@Override
public String getDescription() {
return "Crops a given rectangle out of a given image.\n\n" +
"Note: If the destination image pre-exists already, it will be overwritten and keep it's dimensions." +
"\n\nDEPRECATED: This method is deprecated. Use CLIJ2 instead.";
}
@Override
public String getAvailableForDimensions() {
return "3D";
}
}
|
exactpro/clearth
|
clearth-core/src/main/java/com/exactprosystems/clearth/Digester.java
|
<reponame>exactpro/clearth
/******************************************************************************
* Copyright 2009-2019 Exactpro Systems Limited
* https://www.exactpro.com
* Build Software to Test Software
*
* 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 com.exactprosystems.clearth;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
/**
* @author andrey.panarin
*
*/
public class Digester
{
/**
* Converts text data to an MD5 hash.
* @param data Input data to convert.
* @return The resulting MD5 hash, encoded as Base64.
* @throws NoSuchAlgorithmException If MD5 is not supported.
* @throws UnsupportedEncodingException If UTF-8 is not supported.
*/
public static String stringToMD5(String data) throws NoSuchAlgorithmException, UnsupportedEncodingException
{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digested = md.digest(data.getBytes("UTF-8"));
String base64 = Base64.encodeBase64String(digested).trim();
return base64;
}
/**
* Checks if the specified string looks like an MD5 hash.
* @param data The string to check.
* @return true if the length and the ending of the string looks
* like the ones of an MD5/Base64 hash. Otherwise, returns false.
*/
public static boolean isLikeMD5(String data)
{
return data.length() == 24 && data.endsWith("==");
}
/**
* Run this digester once when you want to encrypt (digest) your
* users' passwords.
* @param args Pass your salt here. If nothing is passed,
* a default salt will be applied.
* @throws IOException In case of any I/O error reading or writing the users file.
* @throws NoSuchAlgorithmException If digestion algorithm is not available.
*/
public static void main(String[] args) throws IOException, NoSuchAlgorithmException
{
String salt = ClearThCore.getDefaultSalt();
if (args.length > 0)
{
System.out.println("Setting custom salt...");
salt = args[0];
}
else
{
System.out.println("Using default core salt...");
}
File usersFile = new File("cfg/users.xml");
//Memorize file contents, modifying passwords
BufferedReader reader = new BufferedReader(new FileReader(usersFile));
List<String> lines = new ArrayList<String>();
Pattern pattern = Pattern.compile("(<\\s*password\\s*>)([^<]+)(<\\s*/\\s*password\\s*>)", Pattern.CASE_INSENSITIVE);
int totalChanges = 0, skipped = 0;
while (reader.ready())
{
String line = reader.readLine();
Matcher matcher = pattern.matcher(line);
StringBuffer buffer = new StringBuffer();
while (matcher.find())
{
String before = matcher.group(1);
String password = matcher.group(2);
String after = matcher.group(3);
if (isLikeMD5(password))
{
skipped++;
continue;
}
String digested = stringToMD5(password+salt);
matcher.appendReplacement(buffer, before+digested+after);
totalChanges++;
}
matcher.appendTail(buffer);
lines.add(buffer.toString());
}
reader.close();
System.out.println("Starting "+usersFile.getPath()+" file modification...");
BufferedWriter writer = new BufferedWriter(new FileWriter(usersFile));
for (String line : lines)
{
writer.write(line);
writer.write("\r\n");
}
writer.close();
System.out.println("Total changes: "+totalChanges);
System.out.println("Encrypted passwords skipped: "+skipped);
}
}
|
etaty/akka
|
akka-actor-tests/src/test/scala/akka/performance/trading/domain/Order.scala
|
<reponame>etaty/akka
package akka.performance.trading.domain
trait Order {
def orderbookSymbol: String
def price: Long
def volume: Long
def nanoTime: Long
def withNanoTime: Order
}
case class Bid(
orderbookSymbol: String,
price: Long,
volume: Long,
nanoTime: Long = 0L)
extends Order {
def split(newVolume: Long) = {
new Bid(orderbookSymbol, price, newVolume)
}
def withNanoTime: Bid = copy(nanoTime = System.nanoTime)
}
case class Ask(
orderbookSymbol: String,
price: Long,
volume: Long,
nanoTime: Long = 0L)
extends Order {
def split(newVolume: Long) = {
new Ask(orderbookSymbol, price, newVolume)
}
def withNanoTime: Ask = copy(nanoTime = System.nanoTime)
}
|
AlexeyMochalov/firebird
|
src/intl/lc_ascii.cpp
|
/*
* PROGRAM: InterBase International support
* MODULE: lc_ascii.cpp
* DESCRIPTION: Language Drivers in the binary collation family.
*
* The contents of this file are subject to the Interbase Public
* License Version 1.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.Inprise.com/IPL.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
* or implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code was created by Inprise Corporation
* and its predecessors. Portions created by Inprise Corporation are
* Copyright (C) Inprise Corporation.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*/
#include "firebird.h"
#include "../common/classes/alloc.h"
#include "../intl/ldcommon.h"
#include "../common/CharSet.h"
#include "../common/IntlUtil.h"
#include "ld_proto.h"
#include "lc_ascii.h"
static const ULONG UPPER_EXCEPTIONS_B5[] = {
0x00B5, // #MICRO SIGN
0
};
static const ULONG UPPER_EXCEPTIONS_FF[] = {
0x00FF, // #LATIN SMALL LETTER Y WITH DIAERESIS
0
};
static const ULONG UPPER_EXCEPTIONS_B5_FF[] = {
0x00B5, // #MICRO SIGN
0x00FF, // #LATIN SMALL LETTER Y WITH DIAERESIS
0
};
namespace {
struct TextTypeImpl
{
Jrd::CharSet* charSet;
charset cs;
const ULONG* lower_exceptions;
const ULONG* upper_exceptions;
};
} // namespace
static void famasc_destroy(texttype* obj)
{
TextTypeImpl* impl = static_cast<TextTypeImpl*>(obj->texttype_impl);
if (impl)
{
Firebird::IntlUtil::finiCharset(&impl->cs);
delete impl->charSet;
delete impl;
}
}
static ULONG famasc_str_to_lower(texttype* obj, ULONG iLen, const BYTE* pStr, ULONG iOutLen, BYTE *pOutStr)
{
try
{
TextTypeImpl* impl = static_cast<TextTypeImpl*>(obj->texttype_impl);
return Firebird::IntlUtil::toLower(impl->charSet, iLen, pStr, iOutLen, pOutStr,
impl->lower_exceptions);
}
catch (const Firebird::Exception&)
{
return INTL_BAD_STR_LENGTH;
}
}
static ULONG famasc_str_to_upper(texttype* obj, ULONG iLen, const BYTE* pStr, ULONG iOutLen, BYTE *pOutStr)
{
try
{
TextTypeImpl* impl = static_cast<TextTypeImpl*>(obj->texttype_impl);
return Firebird::IntlUtil::toUpper(impl->charSet, iLen, pStr, iOutLen, pOutStr,
impl->upper_exceptions);
}
catch (const Firebird::Exception&)
{
return INTL_BAD_STR_LENGTH;
}
}
static inline bool FAMILY_ASCII(texttype* cache,
SSHORT country,
const ASCII* POSIX,
USHORT attributes,
const UCHAR*, // specific_attributes,
ULONG specific_attributes_length,
const ASCII* cs_name,
const ASCII* config_info,
const ULONG* lower_exceptions,
const ULONG* upper_exceptions)
{
if ((attributes & ~TEXTTYPE_ATTR_PAD_SPACE) || specific_attributes_length)
return false;
cache->texttype_version = TEXTTYPE_VERSION_1;
cache->texttype_name = POSIX;
cache->texttype_country = country;
cache->texttype_pad_option = (attributes & TEXTTYPE_ATTR_PAD_SPACE) ? true : false;
cache->texttype_fn_key_length = famasc_key_length;
cache->texttype_fn_string_to_key= famasc_string_to_key;
cache->texttype_fn_compare = famasc_compare;
if (lower_exceptions || upper_exceptions)
{
cache->texttype_fn_destroy = famasc_destroy;
cache->texttype_fn_str_to_upper = famasc_str_to_upper;
cache->texttype_fn_str_to_lower = famasc_str_to_lower;
TextTypeImpl* impl = FB_NEW_POOL(*getDefaultMemoryPool()) TextTypeImpl;
cache->texttype_impl = impl;
memset(&impl->cs, 0, sizeof(impl->cs));
LD_lookup_charset(&impl->cs, cs_name, config_info);
impl->charSet = Jrd::CharSet::createInstance(*getDefaultMemoryPool(), 0, &impl->cs);
impl->lower_exceptions = lower_exceptions;
impl->upper_exceptions = upper_exceptions;
}
return true;
}
TEXTTYPE_ENTRY2(DOS101_init)
{
static const ASCII POSIX[] = "C.DOS437";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(DOS107_init)
{
static const ASCII POSIX[] = "C.DOS865";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(DOS160_init)
{
static const ASCII POSIX[] = "C.DOS850";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(ISO88591_cp_init)
{
static const ASCII POSIX[] = "C.ISO8859_1";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(ISO88592_cp_init)
{
static const ASCII POSIX[] = "C.ISO8859_2";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(ISO88593_cp_init)
{
static const ASCII POSIX[] = "C.ISO8859_3";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(ISO88594_cp_init)
{
static const ASCII POSIX[] = "C.ISO8859_4";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(ISO88595_cp_init)
{
static const ASCII POSIX[] = "C.ISO8859_5";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(ISO88596_cp_init)
{
static const ASCII POSIX[] = "C.ISO8859_6";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(ISO88597_cp_init)
{
static const ASCII POSIX[] = "C.ISO8859_7";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(ISO88598_cp_init)
{
static const ASCII POSIX[] = "C.ISO8859_8";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(ISO88599_cp_init)
{
static const ASCII POSIX[] = "C.ISO8859_9";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(ISO885913_cp_init)
{
static const ASCII POSIX[] = "C.ISO8859_13";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, NULL);
}
TEXTTYPE_ENTRY2(DOS852_c0_init)
{
static const ASCII POSIX[] = "C.DOS852";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(DOS857_c0_init)
{
static const ASCII POSIX[] = "C.DOS857";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(DOS860_c0_init)
{
static const ASCII POSIX[] = "C.DOS860";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(DOS861_c0_init)
{
static const ASCII POSIX[] = "C.DOS861";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(DOS863_c0_init)
{
static const ASCII POSIX[] = "C.DOS863";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(DOS737_c0_init)
{
static const ASCII POSIX[] = "C.DOS737";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(DOS775_c0_init)
{
static const ASCII POSIX[] = "C.DOS775";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(DOS858_c0_init)
{
static const ASCII POSIX[] = "C.DOS858";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(DOS862_c0_init)
{
static const ASCII POSIX[] = "C.DOS862";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(DOS864_c0_init)
{
static const ASCII POSIX[] = "C.DOS864";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(DOS866_c0_init)
{
static const ASCII POSIX[] = "C.DOS866";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(DOS869_c0_init)
{
static const ASCII POSIX[] = "C.DOS869";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(CYRL_c0_init)
{
static const ASCII POSIX[] = "C.CYRL";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(WIN1250_c0_init)
{
static const ASCII POSIX[] = "C.ISO8859_1";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(WIN1251_c0_init)
{
static const ASCII POSIX[] = "C.ISO8859_1";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(WIN1252_c0_init)
{
static const ASCII POSIX[] = "C.ISO8859_1";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5);
}
TEXTTYPE_ENTRY2(WIN1253_c0_init)
{
static const ASCII POSIX[] = "C.ISO8859_1";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_FF);
}
TEXTTYPE_ENTRY2(WIN1254_c0_init)
{
static const ASCII POSIX[] = "C.ISO8859_1";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5);
}
TEXTTYPE_ENTRY2(WIN1255_c0_init)
{
static const ASCII POSIX[] = "C.ISO8859_5";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(WIN1256_c0_init)
{
static const ASCII POSIX[] = "C.ISO8859_1";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(WIN1257_c0_init)
{
static const ASCII POSIX[] = "C.ISO8859_1";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(NEXT_c0_init)
{
static const ASCII POSIX[] = "C.ISO8859_1";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(KOI8R_c0_init)
{
static const ASCII POSIX[] = "C.KOI8R";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(KOI8U_c0_init)
{
static const ASCII POSIX[] = "C.KOI8U";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5_FF);
}
TEXTTYPE_ENTRY2(WIN1258_c0_init)
{
static const ASCII POSIX[] = "C.ISO8859_1";
return FAMILY_ASCII(cache, CC_C, POSIX, attributes, specific_attributes, specific_attributes_length,
cs_name, config_info, NULL, UPPER_EXCEPTIONS_B5);
}
const USHORT LANGASCII_MAX_KEY = MAX_KEY;
const BYTE ASCII_SPACE = 32; // ASCII code for space
/*
* key_length (in_len)
*
* For an input string of (in_len) bytes, return the maximum
* key buffer length.
*
* This is used for index buffer allocation within the
* Engine.
*/
USHORT famasc_key_length(texttype* /*obj*/, USHORT inLen)
{
// fb_assert (inLen <= LANGASCII_MAX_KEY); - possible upper logic error if true
return (MIN(inLen, LANGASCII_MAX_KEY));
}
/*
*
* Convert a user string to a sequence that will collate bytewise.
*
* For ASCII type collation (codepoint collation) this mearly
* involves stripping the space character off the key.
*
* RETURN:
* Length, in bytes, of returned key
*/
USHORT famasc_string_to_key(texttype* obj, USHORT iInLen, const BYTE* pInChar, USHORT iOutLen, BYTE *pOutChar,
USHORT /*key_type*/) // unused
{
fb_assert(pOutChar != NULL);
fb_assert(pInChar != NULL);
fb_assert(iInLen <= LANGASCII_MAX_KEY);
fb_assert(iOutLen <= LANGASCII_MAX_KEY);
fb_assert(iOutLen >= famasc_key_length(obj, iInLen));
// point inbuff at last character
const BYTE* inbuff = pInChar + iInLen - 1;
if (obj->texttype_pad_option)
{
// skip backwards over all spaces & reset input length
while ((inbuff >= pInChar) && (*inbuff == ASCII_SPACE))
inbuff--;
}
iInLen = (inbuff - pInChar + 1);
BYTE* outbuff = pOutChar;
while (iInLen-- && iOutLen--) {
*outbuff++ = *pInChar++;
}
return (outbuff - pOutChar);
}
static bool all_spaces(const BYTE* s, SLONG len)
{
fb_assert(s != NULL);
while (len-- > 0)
{
if (*s++ != ASCII_SPACE)
return false;
}
return true;
}
SSHORT famasc_compare(texttype* obj, ULONG l1, const BYTE* s1, ULONG l2, const BYTE* s2,
INTL_BOOL* error_flag)
{
fb_assert(obj != NULL);
fb_assert(s1 != NULL);
fb_assert(s2 != NULL);
fb_assert(error_flag != NULL);
*error_flag = false;
const ULONG len = MIN(l1, l2);
for (ULONG i = 0; i < len; i++)
{
if (s1[i] == s2[i])
continue;
if (all_spaces(&s1[i], (SLONG) (l1 - i)))
return -1;
if (all_spaces(&s2[i], (SLONG) (l2 - i)))
return 1;
if (s1[i] < s2[i])
return -1;
return 1;
}
if (l1 > len)
{
if (obj->texttype_pad_option && all_spaces(&s1[len], (SLONG) (l1 - len)))
return 0;
return 1;
}
if (l2 > len)
{
if (obj->texttype_pad_option && all_spaces(&s2[len], (SLONG) (l2 - len)))
return 0;
return -1;
}
return (0);
}
|
DigitalDataChainConsortium/vdi2770
|
vdi2770-core/src/test/java/de/vdi/vdi2770/metadata/xml/ExampleXmlReadXmlTest.java
|
/*******************************************************************************
* 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 de.vdi.vdi2770.metadata.xml;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.FilenameFilter;
import java.util.List;
import java.util.Locale;
import org.junit.jupiter.api.Test;
import de.vdi.vdi2770.metadata.common.FaultLevel;
import de.vdi.vdi2770.metadata.model.Document;
import de.vdi.vdi2770.metadata.model.ValidationFault;
/**
* Reading and validating XML files from the example folder.
*
* @author <NAME> (Leipzig University, Institute for Applied
* Informatics InfAI)
*/
public class ExampleXmlReadXmlTest {
private static final String EXAMPLES_FOLDER = "../examples/xml";
/**
* Read all example XML files.
*
* @throws XmlProcessingException
*/
@Test
public void readXmlExamples() throws XmlProcessingException {
final File dir = new File(EXAMPLES_FOLDER);
final File[] xmlFiles = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
return name.toLowerCase().endsWith(".xml")
&& !name.toLowerCase().contains("invalid");
}
});
if (xmlFiles != null && xmlFiles.length > 0) {
for (final File xmlFile : xmlFiles) {
final XmlReader reader = new XmlReader(Locale.getDefault());
final Document xmlDocument = reader.read(xmlFile);
// validate with strict mode
final List<ValidationFault> strictErrors = xmlDocument.validate(Locale.getDefault(),
true);
assertTrue(strictErrors.size() == 0 || strictErrors.stream()
.filter(f -> f.getLevel() == FaultLevel.ERROR).count() == 0);
final List<ValidationFault> NonStrictErrors = xmlDocument
.validate(Locale.getDefault(), false);
assertTrue(NonStrictErrors.size() == 0 || NonStrictErrors.stream()
.filter(f -> f.getLevel() == FaultLevel.ERROR).count() == 0);
}
}
}
}
|
htw0056/blog
|
java/code/scope-test/src/main/java/com/htw/study/scopetest/provider/SingletonProviderBean.java
|
package com.htw.study.scopetest.provider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.inject.Provider;
/**
* Created by htw on 2019/3/1.
*/
@Slf4j
@Component
public class SingletonProviderBean {
public SingletonProviderBean() {
log.info("Singleton instance created");
}
@Autowired
private Provider<PrototypeBean> prototypeBeanObjectFactory;
public PrototypeBean getPrototypeBean() {
return prototypeBeanObjectFactory.get();
}
}
|
shileiyu/ncore
|
ncore/algorithm/cityhash.cpp
|
// Copyright (c) 2011 Google, Inc.
//
// 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.
//
// CityHash, by <NAME> and <NAME>
//
// This file provides CityHash64() and related functions.
//
// It's probably possible to create even faster hash functions by
// writing a program that systematically explores some of the space of
// possible hash functions, by using SIMD instructions, or by
// compromising on hash quality.
#include <stdlib.h> // for size_t.
#include <stdint.h>
#include <string.h> // for memcpy and memset
#include <utility>
#include <algorithm>
#include "cityhash.h"
namespace ncore
{
// Hash 128 input bits down to 64 bits of output.
// This is intended to be a reasonably good hash function.
inline uint64_t Hash128to64(const uint128_t& x) {
// Murmur-inspired hashing.
const uint64_t kMul = 0x9ddfea08eb382d69ULL;
uint64_t a = (uint128_tLow64(x) ^ uint128_tHigh64(x)) * kMul;
a ^= (a >> 47);
uint64_t b = (uint128_tHigh64(x) ^ a) * kMul;
b ^= (b >> 47);
b *= kMul;
return b;
}
using namespace std;
static uint64_t UNALIGNED_LOAD64(const char *p) {
uint64_t result;
memcpy(&result, p, sizeof(result));
return result;
}
static uint32_t UNALIGNED_LOAD32(const char *p) {
uint32_t result;
memcpy(&result, p, sizeof(result));
return result;
}
#if !defined(WORDS_BIGENDIAN)
#define uint32_t_in_expected_order(x) (x)
#define uint64_t_in_expected_order(x) (x)
#else
#ifdef _MSC_VER
#include <stdlib.h>
#define bswap_32(x) _byteswap_ulong(x)
#define bswap_64(x) _byteswap_uint64_t(x)
#elif defined(__APPLE__)
// Mac OS X / Darwin features
#include <libkern/OSByteOrder.h>
#define bswap_32(x) OSSwapInt32(x)
#define bswap_64(x) OSSwapInt64(x)
#else
#include <byteswap.h>
#endif
#define uint32_t_in_expected_order(x) (bswap_32(x))
#define uint64_t_in_expected_order(x) (bswap_64(x))
#endif // WORDS_BIGENDIAN
#if !defined(LIKELY)
#if HAVE_BUILTIN_EXPECT
#define LIKELY(x) (__builtin_expect(!!(x), 1))
#else
#define LIKELY(x) (x)
#endif
#endif
static uint64_t Fetch64(const char *p) {
return uint64_t_in_expected_order(UNALIGNED_LOAD64(p));
}
static uint32_t Fetch32(const char *p) {
return uint32_t_in_expected_order(UNALIGNED_LOAD32(p));
}
// Some primes between 2^63 and 2^64 for various uses.
static const uint64_t k0 = 0xc3a5c85c97cb3127ULL;
static const uint64_t k1 = 0xb492b66fbe98f273ULL;
static const uint64_t k2 = 0x9ae16a3b2f90404fULL;
static const uint64_t k3 = 0xc949d7c7509e6557ULL;
// Bitwise right rotate. Normally this will compile to a single
// instruction, especially if the shift is a manifest constant.
static uint64_t Rotate(uint64_t val, int shift) {
// Avoid shifting by 64: doing so yields an undefined result.
return shift == 0 ? val : ((val >> shift) | (val << (64 - shift)));
}
// Equivalent to Rotate(), but requires the second arg to be non-zero.
// On x86-64, and probably others, it's possible for this to compile
// to a single instruction if both args are already in registers.
static uint64_t RotateByAtLeast1(uint64_t val, int shift) {
return (val >> shift) | (val << (64 - shift));
}
static uint64_t ShiftMix(uint64_t val) {
return val ^ (val >> 47);
}
static uint64_t HashLen16(uint64_t u, uint64_t v) {
return Hash128to64(uint128_t(u, v));
}
static uint64_t HashLen0to16(const char *s, size_t len) {
if (len > 8) {
uint64_t a = Fetch64(s);
uint64_t b = Fetch64(s + len - 8);
return HashLen16(a, RotateByAtLeast1(b + len, len)) ^ b;
}
if (len >= 4) {
uint64_t a = Fetch32(s);
return HashLen16(len + (a << 3), Fetch32(s + len - 4));
}
if (len > 0) {
uint8_t a = s[0];
uint8_t b = s[len >> 1];
uint8_t c = s[len - 1];
uint32_t y = static_cast<uint32_t>(a) + (static_cast<uint32_t>(b) << 8);
uint32_t z = len + (static_cast<uint32_t>(c) << 2);
return ShiftMix(y * k2 ^ z * k3) * k2;
}
return k2;
}
// This probably works well for 16-byte strings as well, but it may be overkill
// in that case.
static uint64_t HashLen17to32(const char *s, size_t len) {
uint64_t a = Fetch64(s) * k1;
uint64_t b = Fetch64(s + 8);
uint64_t c = Fetch64(s + len - 8) * k2;
uint64_t d = Fetch64(s + len - 16) * k0;
return HashLen16(Rotate(a - b, 43) + Rotate(c, 30) + d,
a + Rotate(b ^ k3, 20) - c + len);
}
// Return a 16-byte hash for 48 bytes. Quick and dirty.
// Callers do best to use "random-looking" values for a and b.
static pair<uint64_t, uint64_t> WeakHashLen32WithSeeds(
uint64_t w, uint64_t x, uint64_t y, uint64_t z, uint64_t a, uint64_t b) {
a += w;
b = Rotate(b + a + z, 21);
uint64_t c = a;
a += x;
a += y;
b += Rotate(a, 44);
return make_pair(a + z, b + c);
}
// Return a 16-byte hash for s[0] ... s[31], a, and b. Quick and dirty.
static pair<uint64_t, uint64_t> WeakHashLen32WithSeeds(
const char* s, uint64_t a, uint64_t b) {
return WeakHashLen32WithSeeds(Fetch64(s),
Fetch64(s + 8),
Fetch64(s + 16),
Fetch64(s + 24),
a,
b);
}
// Return an 8-byte hash for 33 to 64 bytes.
static uint64_t HashLen33to64(const char *s, size_t len) {
uint64_t z = Fetch64(s + 24);
uint64_t a = Fetch64(s) + (len + Fetch64(s + len - 16)) * k0;
uint64_t b = Rotate(a + z, 52);
uint64_t c = Rotate(a, 37);
a += Fetch64(s + 8);
c += Rotate(a, 7);
a += Fetch64(s + 16);
uint64_t vf = a + z;
uint64_t vs = b + Rotate(a, 31) + c;
a = Fetch64(s + 16) + Fetch64(s + len - 32);
z = Fetch64(s + len - 8);
b = Rotate(a + z, 52);
c = Rotate(a, 37);
a += Fetch64(s + len - 24);
c += Rotate(a, 7);
a += Fetch64(s + len - 16);
uint64_t wf = a + z;
uint64_t ws = b + Rotate(a, 31) + c;
uint64_t r = ShiftMix((vf + ws) * k2 + (wf + vs) * k0);
return ShiftMix(r * k0 + vs) * k2;
}
uint64_t CityHash64(const char *s, size_t len) {
if (len <= 32) {
if (len <= 16) {
return HashLen0to16(s, len);
} else {
return HashLen17to32(s, len);
}
} else if (len <= 64) {
return HashLen33to64(s, len);
}
// For strings over 64 bytes we hash the end first, and then as we
// loop we keep 56 bytes of state: v, w, x, y, and z.
uint64_t x = Fetch64(s);
uint64_t y = Fetch64(s + len - 16) ^ k1;
uint64_t z = Fetch64(s + len - 56) ^ k0;
pair<uint64_t, uint64_t> v = WeakHashLen32WithSeeds(s + len - 64, len, y);
pair<uint64_t, uint64_t> w = WeakHashLen32WithSeeds(s + len - 32, len * k1, k0);
z += ShiftMix(v.second) * k1;
x = Rotate(z + x, 39) * k1;
y = Rotate(y, 33) * k1;
// Decrease len to the nearest multiple of 64, and operate on 64-byte chunks.
len = (len - 1) & ~static_cast<size_t>(63);
do {
x = Rotate(x + y + v.first + Fetch64(s + 16), 37) * k1;
y = Rotate(y + v.second + Fetch64(s + 48), 42) * k1;
x ^= w.second;
y ^= v.first;
z = Rotate(z ^ w.first, 33);
v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first);
w = WeakHashLen32WithSeeds(s + 32, z + w.second, y);
std::swap(z, x);
s += 64;
len -= 64;
} while (len != 0);
return HashLen16(HashLen16(v.first, w.first) + ShiftMix(y) * k1 + z,
HashLen16(v.second, w.second) + x);
}
uint64_t CityHash64WithSeed(const char *s, size_t len, uint64_t seed) {
return CityHash64WithSeeds(s, len, k2, seed);
}
uint64_t CityHash64WithSeeds(const char *s, size_t len,
uint64_t seed0, uint64_t seed1) {
return HashLen16(CityHash64(s, len) - seed0, seed1);
}
// A subroutine for CityHash128(). Returns a decent 128-bit hash for strings
// of any length representable in ssize_t. Based on City and Murmur.
static uint128_t CityMurmur(const char *s, size_t len, uint128_t seed) {
uint64_t a = uint128_tLow64(seed);
uint64_t b = uint128_tHigh64(seed);
uint64_t c = 0;
uint64_t d = 0;
size_t l = len - 16;
if (l <= 0) { // len <= 16
a = ShiftMix(a * k1) * k1;
c = b * k1 + HashLen0to16(s, len);
d = ShiftMix(a + (len >= 8 ? Fetch64(s) : c));
} else { // len > 16
c = HashLen16(Fetch64(s + len - 8) + k1, a);
d = HashLen16(b + len, c + Fetch64(s + len - 16));
a += d;
do {
a ^= ShiftMix(Fetch64(s) * k1) * k1;
a *= k1;
b ^= a;
c ^= ShiftMix(Fetch64(s + 8) * k1) * k1;
c *= k1;
d ^= c;
s += 16;
l -= 16;
} while (l > 0);
}
a = HashLen16(a, c);
b = HashLen16(d, b);
return uint128_t(a ^ b, HashLen16(b, a));
}
uint128_t CityHash128WithSeed(const char *s, size_t len, uint128_t seed) {
if (len < 128) {
return CityMurmur(s, len, seed);
}
// We expect len >= 128 to be the common case. Keep 56 bytes of state:
// v, w, x, y, and z.
pair<uint64_t, uint64_t> v, w;
uint64_t x = uint128_tLow64(seed);
uint64_t y = uint128_tHigh64(seed);
uint64_t z = len * k1;
v.first = Rotate(y ^ k1, 49) * k1 + Fetch64(s);
v.second = Rotate(v.first, 42) * k1 + Fetch64(s + 8);
w.first = Rotate(y + z, 35) * k1 + x;
w.second = Rotate(x + Fetch64(s + 88), 53) * k1;
// This is the same inner loop as CityHash64(), manually unrolled.
do {
x = Rotate(x + y + v.first + Fetch64(s + 16), 37) * k1;
y = Rotate(y + v.second + Fetch64(s + 48), 42) * k1;
x ^= w.second;
y ^= v.first;
z = Rotate(z ^ w.first, 33);
v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first);
w = WeakHashLen32WithSeeds(s + 32, z + w.second, y);
std::swap(z, x);
s += 64;
x = Rotate(x + y + v.first + Fetch64(s + 16), 37) * k1;
y = Rotate(y + v.second + Fetch64(s + 48), 42) * k1;
x ^= w.second;
y ^= v.first;
z = Rotate(z ^ w.first, 33);
v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first);
w = WeakHashLen32WithSeeds(s + 32, z + w.second, y);
std::swap(z, x);
s += 64;
len -= 128;
} while (LIKELY(len >= 128));
y += Rotate(w.first, 37) * k0 + z;
x += Rotate(v.first + z, 49) * k0;
// If 0 < len < 128, hash up to 4 chunks of 32 bytes each from the end of s.
for (size_t tail_done = 0; tail_done < len; ) {
tail_done += 32;
y = Rotate(y - x, 42) * k0 + v.second;
w.first += Fetch64(s + len - tail_done + 16);
x = Rotate(x, 49) * k0 + w.first;
w.first += v.first;
v = WeakHashLen32WithSeeds(s + len - tail_done, v.first, v.second);
}
// At this point our 48 bytes of state should contain more than
// enough information for a strong 128-bit hash. We use two
// different 48-byte-to-8-byte hashes to get a 16-byte final result.
x = HashLen16(x, v.first);
y = HashLen16(y, w.first);
return uint128_t(HashLen16(x + v.second, w.second) + y,
HashLen16(x + w.second, y + v.second));
}
uint128_t CityHash128(const char *s, size_t len) {
if (len >= 16) {
return CityHash128WithSeed(s + 16,
len - 16,
uint128_t(Fetch64(s) ^ k3,
Fetch64(s + 8)));
} else if (len >= 8) {
return CityHash128WithSeed(NULL,
0,
uint128_t(Fetch64(s) ^ (len * k0),
Fetch64(s + len - 8) ^ k1));
} else {
return CityHash128WithSeed(s, len, uint128_t(k0, k1));
}
}
}
|
DimensionalRobos/InappExp
|
app/InappExp-Java/src/org/drobos/SentiAnalyzer.java
|
<filename>app/InappExp-Java/src/org/drobos/SentiAnalyzer.java
package org.drobos;
/**
* Analyzes Sentiments after being tagged and returns the main descriptor for inappropriateness
*/
import java.io.IOException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Daikaiser
*/
public class SentiAnalyzer {
public static Sentiment analyze(String taggedDoc) {
if (taggedDoc.trim() == "") {
return null;
}
try {
SentimentCorpus sentiWordNet = new SentimentCorpus(Config.SentiWordNetPath());
LinkedList<Sentiment> sentiments = new LinkedList<Sentiment>();
taggedDoc = taggedDoc.toLowerCase();
taggedDoc = taggedDoc.replace('_', '#');
String[] tokens = taggedDoc.split(" ");
for (String token : tokens) {
try {
sentiments.addLast(new Sentiment(token.split("#")[0], sentiWordNet.extract(token)));
} catch (Exception e) {
try {
LinkedList<String> stemList = Stemmer.stem(token.split("#")[0], token.split("#")[1]);
for (String stem : stemList) {
System.err.println(stem);
sentiments.addLast(new Sentiment(stem, sentiWordNet.extract(stem + "#" + token.split("#")[1])));
break;
}
} catch (Exception ex) {
}
}
}
for (Sentiment sentiment : sentiments) {
System.out.println(sentiment.word + "#" + sentiment.sentimentValue);
}
return getMainDescriptor(sentiments);
//PlotTool.threshPlot(sentiments);
//PlotTool.funcPlot(sentiments);
} catch (Exception ex) {
Logger.getLogger(SentiAnalyzer.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public static Sentiment getMainDescriptor(LinkedList<Sentiment> sentiments) {
try {
Sentiment mainDescriptor = sentiments.getFirst();
for (Sentiment descriptor : sentiments) {
if (descriptor.sentimentValue < mainDescriptor.sentimentValue) {
mainDescriptor = descriptor;
}
}
if (mainDescriptor.sentimentValue >= 0|String.valueOf(mainDescriptor.sentimentValue).equals("NaN")) {
throw new Exception();
} else {
System.err.println("<p>"+mainDescriptor.word + "#" + mainDescriptor.sentimentValue+"</p>");
return mainDescriptor;
}
} catch (Exception ex) {
}
return null;
}
public static double getMin(LinkedList<Sentiment> sentiments) {
try {
Sentiment mainDescriptor = sentiments.getFirst();
for (Sentiment descriptor : sentiments) {
if (descriptor.sentimentValue < mainDescriptor.sentimentValue) {
mainDescriptor = descriptor;
}
}
//System.err.println(mainDescriptor.word + "#" + mainDescriptor.sentimentValue);
return mainDescriptor.sentimentValue;
} catch (Exception ex) {
}
return 0;
}
public static double getMax(LinkedList<Sentiment> sentiments) {
try {
Sentiment mainDescriptor = sentiments.getFirst();
for (Sentiment descriptor : sentiments) {
if (descriptor.sentimentValue > mainDescriptor.sentimentValue) {
mainDescriptor = descriptor;
}
}
//System.err.println(mainDescriptor.word + "#" + mainDescriptor.sentimentValue);
return mainDescriptor.sentimentValue;
} catch (Exception ex) {
}
return 0;
}
public static double getMean(LinkedList<Sentiment> sentiments) {
double sum = 0;
for (Sentiment descriptor : sentiments) {
sum += descriptor.sentimentValue;
}
return sum/sentiments.size();
}
public static double getVariance(LinkedList<Sentiment> sentiments){
double sum=0;
for(Sentiment sentiment:sentiments){
sum+=Math.pow(sentiment.sentimentValue-getMean(sentiments), 2);
}
return sum/sentiments.size();
}
public static double getRMS(LinkedList<Sentiment> sentiments){
double sum=0;
for(Sentiment sentiment:sentiments){
sum+=Math.pow(sentiment.sentimentValue, 2);
}
return Math.sqrt(sum/sentiments.size());
}
}
|
Ryan-hou/leetcode
|
src/main/java/com/github/ryan/algorithm/leetcode/easy/easy414/Solution.java
|
package com.github.ryan.algorithm.leetcode.easy.easy414;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;
/**
* @author <EMAIL>
* @description
* @className Solution
* @date November 30,2018
*/
public class Solution {
public int thirdMax(int[] nums) {
assert nums != null && nums.length > 0;
Set<Integer> set = new HashSet<>();
for (int n : nums) {
set.add(n);
}
// 维护容量为3的小根堆,堆顶的数据即为本堆中最小的数据,也就是整个数组中第三大的数
PriorityQueue<Integer> pq = new PriorityQueue<>(3);
for (int n : set) {
pq.add(n);
if (pq.size() > 3) {
// 移除当前最小的数据
pq.poll();
}
}
// corner case
if (pq.size() == 2) {
pq.poll();
}
// else pq.size() == 1 || pq.size() == 3
return pq.peek();
}
}
|
Sam-Fuller/Game_workspace
|
Game/src/entity/enemy/staticMelee/Spikes.java
|
package entity.enemy.staticMelee;
import colour.Colour;
import entity.Player;
import graphics.Mesh;
import graphics.MeshBuilder;
import loader.TextureLoader;
import runnable.Graphics;
import state.World;
public class Spikes extends StaticMelee {
static final int dHeight = 1;
static final int dWidth = 1;
public static final int startHealth = 10;
public static final int healthScalar = 10;
static final int damage = 5;
static final long damageCooldown = 1000000000;
long lastDamage = 0;
Mesh colourMesh;
public Spikes(float posX, float posY, int level) {
super(dHeight, dWidth, posX, posY, level);
int health = startHealth + level * healthScalar;
setMaxHealth(health);
setHealth(health);
}
@Override
public void render() {
if (colourMesh == null) rerender();
colourMesh.render(getPosX()+World.getOffsetX(getChunkNo()), getPosY()+World.getOffsetY(getChunkNo()));
}
private void rerender() {
MeshBuilder meshBuilder = new MeshBuilder();
Colour enemyColour = Graphics.getColourScheme().enemySpikes();
meshBuilder.drawTriangle(0, 0, getHeight(), getWidth(), (float) Math.PI, enemyColour, enemyColour);
colourMesh = meshBuilder.asColourMesh(false);
}
@Override
public void action(float frameSpeed) {
long now = System.nanoTime();
if (now - lastDamage > damageCooldown) {
float x = getPosX() + World.getOffsetX(getChunkNo()) - Player.getPlayer().getPosX();
float y = getPosY() + World.getOffsetY(getChunkNo()) - Player.getPlayer().getPosY();
if (this.touchingSquarePlayer()) {
float a = Player.getPlayer().getPosX();
float b = Player.getPlayer().getPosY();
float c = getPosX();
float d = getPosY();
Player.getPlayer().decHealth(damage);
lastDamage = now;
Player.getPlayer().incVelocityX(x > 0? -2f/(x+1) : -2f/(x-1));
Player.getPlayer().incVelocityY(y > 0? -2f/(y+1) : -2f/(y-1));
}
}
}
@Override
public void onDestruction() {
World.getWorld().get(getChunkNo()).getEntities().remove(this);
colourMesh.cleanUp();
}
}
|
HackYourFuture-CPH/fp-class18
|
src/client/components/TotalPriceCard/TotalPriceCard.stories.js
|
import React from 'react';
import TotalPrice from './TotalPriceCard.component';
export default {
title: 'Components / TotalPriceCard',
component: TotalPrice,
};
// eslint-disable-next-line react/jsx-props-no-spreading
export const GrandTotalPrice = (args) => <TotalPrice {...args} />;
GrandTotalPrice.args = {
subTotal: 100,
};
|
readmeio/markdown
|
sanitize.schema.js
|
<filename>sanitize.schema.js<gh_stars>10-100
const { defaultSchema: sanitize } = require('hast-util-sanitize/lib/schema');
// Sanitization Schema Defaults
sanitize.clobberPrefix = '';
sanitize.tagNames.push('span', 'style');
sanitize.attributes['*'].push('class', 'className', 'align', 'style');
sanitize.tagNames.push('rdme-pin');
sanitize.tagNames.push('rdme-embed');
sanitize.attributes['rdme-embed'] = [
'url',
'provider',
'html',
'title',
'href',
'iframe',
'width',
'height',
'image',
'favicon',
];
sanitize.attributes.a = ['href', 'title', 'class', 'className', 'download'];
sanitize.tagNames.push('figure');
sanitize.tagNames.push('figcaption');
sanitize.tagNames.push('input'); // allow GitHub-style todo lists
sanitize.ancestors.input = ['li'];
module.exports = sanitize;
|
gublan24/umpleSPLFull
|
umpleSPL/src-gen-umple/cruise/umple/compiler/TemplateException.java
|
<reponame>gublan24/umpleSPLFull
/*PLEASE DO NOT EDIT THIS CODE*/
/*This code was generated using the UMPLE 1.31.1.5860.78bb27cc6 modeling language!*/
package cruise.umple.compiler;
import cruise.umple.parser.Token;
import cruise.umple.parser.Position;
import cruise.umple.parser.ErrorMessage;
/**
* class TemplateException {
* isA Exception;
* Token token;
* Integer errorCode;
* String errMsg;
*
* public TemplateException(Token aToken, int aErrorCode, String aErrMsg, Exception ex) {
* super(aErrMsg, ex);
* token = aToken;
* errorCode = aErrorCode;
* errMsg = aErrMsg;
* }
* public TemplateException(Token aToken, int aErrorCode, String aErrMsg) {
* super(aErrMsg, null);
* token = aToken;
* errorCode = aErrorCode;
* errMsg = aErrMsg;
* }
* }
*
*/
// line 82 "../../../../src/UmpleInternalParser_CodeTemplate.ump"
public class TemplateException extends Exception
{
//------------------------
// MEMBER VARIABLES
//------------------------
//TemplateException Attributes
private Position position;
private ErrorMessage errorMessage;
//------------------------
// CONSTRUCTOR
//------------------------
public TemplateException(String aMessage, Exception aParent, Position aPosition, ErrorMessage aErrorMessage)
{
super(aMessage, aParent);
position = aPosition;
errorMessage = aErrorMessage;
}
//------------------------
// INTERFACE
//------------------------
public boolean setPosition(Position aPosition)
{
boolean wasSet = false;
position = aPosition;
wasSet = true;
return wasSet;
}
public boolean setErrorMessage(ErrorMessage aErrorMessage)
{
boolean wasSet = false;
errorMessage = aErrorMessage;
wasSet = true;
return wasSet;
}
public Position getPosition()
{
return position;
}
public ErrorMessage getErrorMessage()
{
return errorMessage;
}
public void delete()
{}
// line 91 "../../../../src/UmpleInternalParser_CodeTemplate.ump"
public TemplateException(Position aPosition, ErrorMessage aErrorMessage){
super("", null);
position = aPosition;
errorMessage = aErrorMessage;
}
public String toString()
{
return super.toString() + "["+ "]" + System.getProperties().getProperty("line.separator") +
" " + "position" + "=" + (getPosition() != null ? !getPosition().equals(this) ? getPosition().toString().replaceAll(" "," ") : "this" : "null") + System.getProperties().getProperty("line.separator") +
" " + "errorMessage" + "=" + (getErrorMessage() != null ? !getErrorMessage().equals(this) ? getErrorMessage().toString().replaceAll(" "," ") : "this" : "null");
}
}
|
jeanbez/spack
|
var/spack/repos/builtin/packages/py-pytest-qt/package.py
|
<reponame>jeanbez/spack
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class PyPytestQt(PythonPackage):
"""A pytest plugin that allows programmers to write tests for
PySide, PySide2 and PyQt applications."""
homepage = "https://github.com/pytest-dev/pytest-qt"
pypi = "pytest-qt/pytest-qt-3.3.0.tar.gz"
version('3.3.0', sha256='714b0bf86c5313413f2d300ac613515db3a1aef595051ab8ba2ffe619dbe8925')
depends_on('python@2.7:2.8,3.4:', type=('build', 'run'))
depends_on('py-setuptools', type='build')
depends_on('py-setuptools-scm', type='build')
depends_on('py-pytest@3:', type=('build', 'run'))
|
franticsoftware/starports
|
Game/src/game/SFXManager.cpp
|
<reponame>franticsoftware/starports
/*
<NAME>
Created: May 18th 2013
*/
#include "Game.h"
#include "ExplosionVisitor.h"
#include "SequenceVisitor.h"
#include "DelayVisitor.h"
#include "RemoveEntityVisitor.h"
#include "AudioManager.h"
#include "ParticleGenerator.h"
#include "EffectEntity.h"
#include "GameCamera.h"
namespace shoot
{
DEFINE_OBJECT(SFXManager);
//! constructor
SFXManager::SFXManager()
: m_bSkyBoxAnim(false)
, m_fInterpolator(0.0f)
, m_fExplosionTracker(0.0f)
, m_bActorExplosionsEnabled(true)
// properties
, m_fExplosionIntensity(8.0f)
, m_fExplosionDuration(1.3f)
, m_fSkyBoxAnimDuration(1.5f)
, m_fCameraShakeIntensity(.5f)
, m_fCameraShakeFrequency(.02f)
{
}
//! destructor
SFXManager::~SFXManager()
{
}
//! serializes the entity to/from a PropertyStream
void SFXManager::Serialize(PropertyStream& stream)
{
super::Serialize(stream);
stream.Serialize("ExplosionIntensity", &m_fExplosionIntensity);
stream.Serialize("ExplosionDuration", &m_fExplosionDuration);
stream.Serialize("SkyBoxAnimDuration", &m_fSkyBoxAnimDuration);
stream.Serialize("CameraShakeIntensity", &m_fCameraShakeIntensity);
stream.Serialize("CameraShakeFrequency", &m_fCameraShakeFrequency);
stream.Serialize("ExplosionEntity", &m_ExplosionEntity);
stream.Serialize("ImpactEntity", &m_ImpactEntity);
stream.Serialize("HitEntity", &m_HitEntity);
stream.Serialize("NoHitEntity", &m_NoHitEntity);
stream.Serialize("ExplosionInfos", &m_ExplosionInfos);
}
//! called during the initialization of the entity
void SFXManager::Init()
{
super::Init();
m_Root = GetRoot();
m_PlayerPulseManager = static_cast<PulseManager*>(GetChildByName("PlayerPulseManager"));
m_PlayerLaserManager = static_cast<LaserManager*>(GetChildByName("PlayerLaserManager"));
m_PlayerPelletManager = static_cast<PelletManager*>(GetChildByName("PlayerPelletManager"));
m_EnemyPulseManager = static_cast<PulseManager*>(GetChildByName("EnemyPulseManager"));
m_EnemyLaserManager = static_cast<LaserManager*>(GetChildByName("EnemyLaserManager"));
m_EnemyPelletManager = static_cast<PelletManager*>(GetChildByName("EnemyPelletManager"));
m_FireDamage = static_cast<ParticleGenerator*>(GetChildByName("FireDamage"));
if(EffectEntity* pStencilEffectsEntity = static_cast<EffectEntity*>(GetChildByName("StencilEffectsEntity")))
m_StencilEffects = DYNAMIC_CAST(pStencilEffectsEntity->GetEffect(), StencilEffects);
if (Entity* pSkyBox = m_Root->GetChildByType("SkyBoxEntity"))
m_SkyBoxMaterial = pSkyBox->GetComponent<GraphicComponent>()->GetMaterial();
if (m_FireDamage.IsValid())
m_FireDamage->SetActive(false);
}
//! called during the update of the entity
void SFXManager::Update()
{
UpdateSkyBox();
m_fExplosionTracker += g_fDeltaTime;
}
//! called when a bullet collided
void SFXManager::OnBulletCollided(Bullet* pBullet)
{
Entity3D* pEntity = static_cast<Entity3D*>(m_NoHitEntity->Copy());
m_Root->AddChild(pEntity);
pEntity->SetPosition(pBullet->vPosition);
pEntity->Init();
}
//! called when a laser collided
void SFXManager::OnLaserCollided(const Vector3& vIntersection)
{
Entity3D* pEntity = static_cast<Entity3D*>(m_NoHitEntity->Copy());
m_Root->AddChild(pEntity);
pEntity->SetPosition(vIntersection);
pEntity->Init();
}
//! called when damage is done
void SFXManager::OnDamageDone(const Vector3& vPosition)
{
Entity3D* pEntity = static_cast<Entity3D*>(m_HitEntity->Copy());
m_Root->AddChild(pEntity);
pEntity->SetPosition(vPosition);
pEntity->Init();
}
//! OnBulletImpact
float SFXManager::OnBulletImpact(const Vector3& position, Object* shooter)
{
Entity3D* pEntity = static_cast<Entity3D*>(m_ImpactEntity->Copy());
m_Root->AddChild(pEntity);
pEntity->SetPosition(position);
pEntity->Init();
auto seq = m_ImpactEntity->GetComponent<SequenceVisitor>();
auto delay = DYNAMIC_CAST(seq->GetVisitor(0), DelayVisitor);
return delay->GetDuration();
}
//! called when an actor is destroyed
void SFXManager::OnActorDestroyed(Actor* pActor)
{
float duration = 0.0f;
if (m_bActorExplosionsEnabled)
duration = Explode(pActor);
else
{
Object* pBaseExplosionVisitor = GetExplosionVisitor(pActor->GetTemplatePath());
if (pBaseExplosionVisitor)
{
ExplosionVisitor* pExplosionVisitor = static_cast<ExplosionVisitor*>(pBaseExplosionVisitor->Copy());
duration = (pExplosionVisitor->GetDuration() < 0.0f) ? m_fExplosionDuration : pExplosionVisitor->GetDuration();
pExplosionVisitor->SetDefaultIntensity(m_fExplosionIntensity);
pExplosionVisitor->SetDefaultDuration(m_fExplosionDuration);
pActor->GetMeshEntity()->AddComponent(pExplosionVisitor);
}
}
DelayVisitor* pDelay = snew DelayVisitor();
pDelay->SetDuration(duration);
SequenceVisitor* pSequence = snew SequenceVisitor();
pSequence->AddVisitor(pDelay);
pSequence->AddVisitor(snew RemoveEntityVisitor());
pActor->AddComponent(pSequence);
}
//! Makes an Actor explode
float SFXManager::Explode(Actor* pActor)
{
Object* pBaseExplosionVisitor = GetExplosionVisitor(pActor->GetTemplatePath());
if(!pBaseExplosionVisitor)
return 0.0f;
ExplosionVisitor* pExplosionVisitor = static_cast<ExplosionVisitor*>(pBaseExplosionVisitor->Copy());
Entity3D* pExplosionEntity = static_cast<Entity3D*>(m_ExplosionEntity->Copy());
for (size_t i = 0; i<pActor->GetMeshEntity()->GetComponentCount(); ++i)
{
if(Visitor* pVisitor = DYNAMIC_CAST(pActor->GetMeshEntity()->GetComponent(i), Visitor))
pVisitor->Leave();
}
for (size_t i = 0; i<pActor->GetMeshEntity()->GetChildCount(); ++i)
{
Entity* pChild = pActor->GetMeshEntity()->GetChild(i);
if(!pChild->IsA(SubMesh::TypeID)
&& !pChild->IsA(ParticleGenerator::TypeID)
&& pChild->GetName() != "Explosion")
{
pActor->GetMeshEntity()->GetChild(i)->SetVisible(false);
}
}
// stop particle generation
std::vector< Handle<ParticleGenerator> > particleEmitters;
pActor->GetChildrenByType<ParticleGenerator>(particleEmitters);
for (size_t i=0; i<particleEmitters.size(); ++i)
particleEmitters[i]->SetActive(false);
// add explosion visitor
pExplosionVisitor->SetDefaultIntensity(m_fExplosionIntensity);
pExplosionVisitor->SetDefaultDuration(m_fExplosionDuration);
pActor->GetMeshEntity()->AddComponent(pExplosionVisitor);
// add explosion entity
pExplosionEntity->SetScale(Vector3::One * pActor->GetExplosionScaleFactor());
pActor->AddChild(pExplosionEntity);
pExplosionEntity->SetPosition(pActor->GetMeshEntity()->GetPosition());
AUDIOMGR->Play(AudioManager::S_Explosion);
float fExplosionDuration = (pExplosionVisitor->GetDuration() < 0.0f) ? m_fExplosionDuration : pExplosionVisitor->GetDuration();
// add camera shake
auto camera = EntityRenderer::Instance()->Get3DCamera();
if (camera == GAMECAM)
{
bool bMultipleExplosionsDetected = (m_fExplosionTracker < m_fExplosionDuration);
bool bForceShake = true; // bIsPlayer || bIsBoss || pActor->GetShakeOnExplode();
float fForceShakeFactor = 2.0f;
if (bMultipleExplosionsDetected || bForceShake)
{
float fIntFactor = bForceShake ? fForceShakeFactor : 1.0f;
float fFreqFactor = bForceShake ? (1.0f / fForceShakeFactor) : 1.0f;
GAMECAM->Shake(m_fCameraShakeIntensity*fIntFactor, m_fCameraShakeFrequency*fFreqFactor, fExplosionDuration / 2.0f);
}
}
m_fExplosionTracker = 0.0f;
pActor->SetRotation(Vector3::Zero);
pActor->SetRotationMatrix(Matrix44::Identity);
//WaveSimulator::Instance()->AddShockWave(pActor->GetAbsolutePosition(), m_fExplosionWaveIntensity);
return fExplosionDuration;
}
//! animates the skybox color
void SFXManager::SetSkyBoxColor(const Color& color)
{
m_SrcSkyBoxColor = m_SkyBoxMaterial->GetColor();
m_DestSkyBoxColor = color;
m_fInterpolator = 0.0f;
m_bSkyBoxAnim = true;
}
//! returns the ExplosionVisitor corresponding to a template
Object* SFXManager::GetExplosionVisitor(const std::string& templatePath)
{
for (size_t i=0; i<m_ExplosionInfos.GetSize(); ++i)
{
for (size_t j = 0; j<m_ExplosionInfos[i].m_TemplatePaths.GetSize(); ++j)
{
if(m_ExplosionInfos[i].m_TemplatePaths[j] == templatePath)
{
return m_ExplosionInfos[i].m_Explosion;
}
}
}
return NULL;
}
//! updates the skybox
void SFXManager::UpdateSkyBox()
{
if(m_bSkyBoxAnim)
{
if(m_fInterpolator < 1.0f)
{
Color color = Math::Lerp<Color>(m_SrcSkyBoxColor, m_DestSkyBoxColor, m_fInterpolator);
m_SkyBoxMaterial->SetColor(color);
m_fInterpolator += g_fDeltaTime/m_fSkyBoxAnimDuration;
}
else
{
m_SkyBoxMaterial->SetColor(m_DestSkyBoxColor);
m_bSkyBoxAnim = false;
}
}
}
//! clears all effects
void SFXManager::Clear()
{
m_PlayerPulseManager->Clear();
m_PlayerLaserManager->Clear();
m_PlayerPelletManager->Clear();
m_PlayerSidePulseManager->Clear();
m_PlayerSideLaserManager->Clear();
m_PlayerSidePelletManager->Clear();
m_EnemyPulseManager->Clear();
m_EnemyLaserManager->Clear();
m_EnemyPelletManager->Clear();
}
}
|
TsvetomirNikolov/swift
|
16. Regex, Lambda, JUnit/MavenProject/src/test/java/rpg_tests/AxeTests.java
|
package rpg_tests;
import SoftuniClasses.Axe;
import SoftuniClasses.Dummy;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class AxeTests {
@Test(expected = IllegalArgumentException.class)
public void weaponLosesDurabilirt() {
Axe axe = new Axe(10, 10);
Dummy dummy = new Dummy(10, 10);
axe.attack(dummy);
axe.attack(dummy);
Assert.assertTrue(axe.getAttackPoints() == 9);
}
@Test(expected = IllegalArgumentException.class)
public void brokenWeaponTest() {
Axe axe = new Axe(10, 10);
Dummy dummy = new Dummy(10, 10);
axe.attack(dummy);
axe.attack(dummy);
Assert.assertEquals(9, axe.getDurabilityPoints());
}
}
|
zhangpf/fuchsia-rs
|
src/developer/bugreport/client/main.cc
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <filesystem>
#include <fstream>
#include <iostream>
#include "src/developer/bugreport/client/bug_report_handler.h"
#include "src/lib/fxl/command_line.h"
namespace {
std::ifstream* OpenFile(const std::filesystem::path& path) {
std::error_code ec;
if (!std::filesystem::exists(path, ec)) {
FXL_LOG(ERROR) << "Could not open " << path;
return nullptr;
}
static std::ifstream iss;
iss.open(path, std::ifstream::in);
if (!iss.good()) {
FXL_LOG(ERROR) << "Could not read " << path;
return nullptr;
}
return &iss;
}
constexpr char kUsage[] = R"(bugreport
Process an incoming bugreport generated by a target device.
Will output several report files in a given output directory.
Usage:
bugreport [--input-file=<FILEPATH>] <OUTPUT_DIR>
Arguments:
--input_file Optional input file to be read. If not specified, will read
from stdin.
OUTPUT_DIR Where bugreport will store the files. Required.
)";
} // namespace
int main(int argc, char* argv[]) {
auto command_line = fxl::CommandLineFromArgcArgv(argc, argv);
// Check if an input file was given, use stdin otherwise.
std::istream* input;
if (command_line.HasOption("input-file")) {
std::string input_value;
command_line.GetOptionValue("input-file", &input_value);
input = OpenFile(input_value);
if (!input)
exit(1);
} else {
input = &std::cin;
}
FXL_DCHECK(input);
// Bugreport requires the caller to provide a valid directory to where output
// the report.
auto& pos_args = command_line.positional_args();
if (pos_args.size() != 1u) {
FXL_LOG(ERROR) << "A single output path should be given.";
std::cerr << kUsage;
exit(1);
}
// Output path should be valid.
std::filesystem::path output_path(pos_args[0]);
std::error_code ec;
if (!std::filesystem::is_directory(output_path, ec)) {
FXL_LOG(ERROR) << "Invalid output directory given: " << output_path;
exit(1);
}
auto targets = bugreport::HandleBugReport(output_path, input);
if (!targets) {
std::cerr << "Error processing input bug report. Exiting." << std::endl;
exit(1);
}
// Report the success.
std::cout << "Bug report processing successful." << std::endl;
for (auto& target : *targets) {
auto path = output_path / target.name;
std::cout << "Exported " << path << std::endl;
}
}
|
lechium/tvOS135Headers
|
System/Library/PrivateFrameworks/UIKitCore.framework/_UIScreenEdgePanRecognizerDwellSettings.h
|
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, June 7, 2020 at 11:45:26 AM Mountain Standard Time
* Operating System: Version 13.4.5 (Build 17L562)
* Image Source: /System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <UIKitCore/_UISettings.h>
@interface _UIScreenEdgePanRecognizerDwellSettings : _UISettings {
double _longPressTipPermittedHorizontalMovement;
double _longPressTipPermittedVerticalMovement;
double _longPressPermittedHorizontalMovement;
double _longPressPermittedVerticalMovement;
double _longPressRequiredDuration;
}
@property (assign,nonatomic) double longPressTipPermittedHorizontalMovement; //@synthesize longPressTipPermittedHorizontalMovement=_longPressTipPermittedHorizontalMovement - In the implementation block
@property (assign,nonatomic) double longPressTipPermittedVerticalMovement; //@synthesize longPressTipPermittedVerticalMovement=_longPressTipPermittedVerticalMovement - In the implementation block
@property (assign,nonatomic) double longPressPermittedHorizontalMovement; //@synthesize longPressPermittedHorizontalMovement=_longPressPermittedHorizontalMovement - In the implementation block
@property (assign,nonatomic) double longPressPermittedVerticalMovement; //@synthesize longPressPermittedVerticalMovement=_longPressPermittedVerticalMovement - In the implementation block
@property (assign,nonatomic) double longPressRequiredDuration; //@synthesize longPressRequiredDuration=_longPressRequiredDuration - In the implementation block
+(id)settingsControllerModule;
-(void)setDefaultValues;
-(void)setLongPressPermittedHorizontalMovement:(double)arg1 ;
-(void)setLongPressPermittedVerticalMovement:(double)arg1 ;
-(void)setLongPressTipPermittedHorizontalMovement:(double)arg1 ;
-(void)setLongPressTipPermittedVerticalMovement:(double)arg1 ;
-(void)setLongPressRequiredDuration:(double)arg1 ;
-(double)longPressTipPermittedHorizontalMovement;
-(double)longPressTipPermittedVerticalMovement;
-(double)longPressPermittedHorizontalMovement;
-(double)longPressPermittedVerticalMovement;
-(double)longPressRequiredDuration;
@end
|
JasperFloorBloomreach/gov-scot
|
site/components/src/main/java/scot/gov/www/components/RedirectComponent.java
|
<filename>site/components/src/main/java/scot/gov/www/components/RedirectComponent.java
package scot.gov.www.components;
import org.apache.commons.lang.StringUtils;
import org.hippoecm.hst.component.support.bean.BaseHstComponent;
import org.hippoecm.hst.content.beans.query.HstQuery;
import org.hippoecm.hst.content.beans.query.HstQueryResult;
import org.hippoecm.hst.content.beans.query.builder.Constraint;
import org.hippoecm.hst.content.beans.query.builder.HstQueryBuilder;
import org.hippoecm.hst.content.beans.query.exceptions.QueryException;
import org.hippoecm.hst.content.beans.standard.HippoBean;
import org.hippoecm.hst.core.component.HstRequest;
import org.hippoecm.hst.core.component.HstResponse;
import org.hippoecm.hst.core.linking.HstLink;
import org.hippoecm.hst.core.request.HstRequestContext;
import org.hippoecm.hst.util.HstResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scot.gov.www.beans.Publication;
import scot.gov.www.beans.PublicationPage;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.hippoecm.hst.content.beans.query.builder.ConstraintBuilder.constraint;
/**
* Component used to support the redirect behaviour of gov.scot: if the sitemap does not match any other entry then this
* component will check if a redirect id available before sending a 404.
*
* Redirects are checked in the following order:
* 1 - url aliases, stored under /content/redirects/Aliases/<requestpath> These are used to provide point to point redirects
* many of which came from Rubric url aliases
*
* 2 - if it is an old style publicaitons url (i.e. starts with /Publications/, then check imported publications and pages
* to see if the importer has recorded this url.
* Publication urls are stored in govscot:Publication and govscot:PublicationPage nodes.
*
* 3 - check to see if this is a historical url that can be sent to the archive / www2.gov,scot.
* Stored under /content/redirects/HistoricalUrls
*
*/
public class RedirectComponent extends BaseHstComponent {
private static final Logger LOG = LoggerFactory.getLogger(RedirectComponent.class);
public static final String GOVSCOT_URL = "govscot:url";
@Override
public void doBeforeRender(final HstRequest request, final HstResponse response) {
// check if this url is a known url alias
String url = findAlias(request);
if (url != null) {
LOG.info("Redirecting to url alias {} -> {}", request.getPathInfo(), url);
// if the incoming url has url paramaters and the outgoing one does nto then pass them on...
HstResponseUtils.sendPermanentRedirect(request, response, url);
return;
}
// if this is a publications url then check if we have a publication for it
if (isOldStylePublicationUrl(request)) {
HippoBean bean = findPublicationsByGovScotUrl(request);
if (bean != null) {
HstRequestContext context = request.getRequestContext();
final HstLink link = context.getHstLinkCreator().create(bean, context);
LOG.info("Redirecting govscot publication url {} to {}", request.getPathInfo(), link.getPath());
HstResponseUtils.sendPermanentRedirect(request, response, link.getPath());
return;
}
}
// we do not know this url, send a 404
HstRequestContext context = request.getRequestContext();
HippoBean document = context.getContentBean();
request.setAttribute("document", document);
request.setAttribute("isPageNotFound", true);
LOG.info("404 for {}", request.getRequestURL());
response.setStatus(404);
}
private String findAlias(HstRequest request) {
try {
return doFindAlias(request);
} catch (RepositoryException e) {
LOG.error("Failed to find url alias {}", request.getPathInfo(), e);
return null;
}
}
private String doFindAlias(HstRequest request) throws RepositoryException {
Session session = request.getRequestContext().getSession();
String path = String.format("/content/redirects/Aliases%s", ArchiveUtils.escapeJcrPath(request.getPathInfo()));
if (!session.nodeExists(path)) {
return null;
}
Node node = session.getNode(path);
if (!node.hasProperty(GOVSCOT_URL)) {
return null;
}
String url = node.getProperty(GOVSCOT_URL).getString();
// if the incoming url has parameters and the outgoing one does not then add
// the params to the redirect
if (!url.contains("?") && isNotBlank(request.getQueryString())) {
url = new StringBuilder(url).append('?').append(request.getQueryString()).toString();
}
return url;
}
private boolean isOldStylePublicationUrl(HstRequest request) {
String govscotUrl = request.getPathInfo();
return StringUtils.startsWith(govscotUrl, "/Publications/");
}
private HippoBean findPublicationsByGovScotUrl(HstRequest request) {
String govscotUrl = request.getPathInfo();
// remove any trailing slash since they are stored without a trailing slash
govscotUrl = StringUtils.removeEnd(govscotUrl, "/");
// if the url ends with /downloads then remove it since there is no downloads page in the new version
// of publications
if (govscotUrl.endsWith("/downloads")) {
govscotUrl = StringUtils.substringBeforeLast(govscotUrl, "/downloads");
}
HstQuery query = HstQueryBuilder
.create(request.getRequestContext().getSiteContentBaseBean())
.ofTypes(Publication.class, PublicationPage.class)
.where(urlConstraint(govscotUrl))
.build();
try {
HstQueryResult result = query.execute();
if (result.getTotalSize() == 0) {
return null;
}
return result.getHippoBeans().nextHippoBean();
} catch (QueryException e) {
LOG.error("Failed to get publication by govscotUrl slug {}", govscotUrl, e);
return null;
}
}
Constraint urlConstraint(String govscotUrl) {
return constraint("govscot:govscoturl").equalTo(govscotUrl);
}
}
|
stripe/tracer-objc
|
Tracer/TRCPlayer.h
|
<gh_stars>10-100
//
// TRCPlayer.h
// Tracer
//
// Created by <NAME> on 2/22/19.
// Copyright © 2019 tracer. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "TRCBlocks.h"
@class TRCTrace;
@protocol TRCFixtureProvider;
NS_ASSUME_NONNULL_BEGIN
/**
Trace player
*/
NS_SWIFT_NAME(TracePlayer)
@interface TRCPlayer : NSObject
/**
Plays a trace by performing recorded invocations on the main queue.
If playback fails, completes with an error.
If playback succeeds, completes with nil.
*/
- (void)playTrace:(TRCTrace *)trace
onTarget:(id)target
completion:(TRCErrorCompletionBlock)completion;
/**
Plays a trace by performing recorded invocations on the main queue.
If an unknown object is encountered in the recorded trace, the player asks
the fixture provider for a fixture.
If playback fails, completes with an error.
If playback succeeds, completes with nil.
*/
- (void)playTrace:(TRCTrace *)trace
onTarget:(id)target
withFixtureProvider:(id<TRCFixtureProvider>)fixtureProvider
completion:(TRCErrorCompletionBlock)completion;
@end
NS_ASSUME_NONNULL_END
|
bradh/skylight-uas
|
src/skylight-autopilot/src/main/java/br/skylight/uav/plugins/control/pids/SkylightPIDWorker.java
|
package br.skylight.uav.plugins.control.pids;
import br.skylight.commons.dli.skylight.PIDConfiguration;
import br.skylight.commons.dli.skylight.SkylightVehicleConfigurationMessage;
import br.skylight.commons.dli.vehicle.VehicleConfigurationMessage;
import br.skylight.uav.plugins.control.Pilot;
import br.skylight.uav.plugins.control.instruments.AdvancedInstrumentsService;
import br.skylight.uav.services.ActuatorsService;
import br.skylight.uav.services.GPSService;
import br.skylight.uav.services.InstrumentsService;
public abstract class SkylightPIDWorker extends PIDWorker {
//limit 20% more than specified to avoid reaching those limits due to dynamic characteristics of flight
public static final float LIMITS_MAX_FACTOR = 0.75F;
public static final float LIMITS_MIN_FACTOR = 1.25F;
public static final float ACTUATORS_RANGE_MIN = -127;
public static final float ACTUATORS_RANGE_MAX = 127;
public static final float ACTUATORS_INTEGRATOR_MIN = -70;
public static final float ACTUATORS_INTEGRATOR_MAX = 70;
public static final float THROTTLE_VALUE_MIN = 0;
public static final float THROTTLE_VALUE_MAX = 127;
public static final float DAMP_RANGE_MIN = -127;
public static final float DAMP_RANGE_MAX = 127;
protected float elevatorSurfaceGain = 0;
protected float rudderSurfaceGain = 0;
protected float pitchRateDamp = 0;
protected float rollRateDamp = 0;
protected float yawRateDamp = 0;
protected float maxPitch = (float)Math.toRadians(12);
protected float minPitch = (float)Math.toRadians(-12);
protected float maxRoll = (float)Math.toRadians(30);
protected float minRoll = (float)Math.toRadians(-30);
protected float maxKtias = 150;
protected float minKtias = 50;
protected InstrumentsService instrumentsService;
protected ActuatorsService actuatorsService;
protected GPSService gpsService;
protected Pilot pilot;
protected AdvancedInstrumentsService advancedInstrumentsService;
protected PIDControllers pidControllers;
public SkylightPIDWorker(PIDController pidController) {
super(pidController);
}
public final void setupPIDController(VehicleConfigurationMessage ac, SkylightVehicleConfigurationMessage sac) {
rudderSurfaceGain = sac.getRudderSurfaceGain();
elevatorSurfaceGain = sac.getElevatorSurfaceGain();
pitchRateDamp = sac.getPitchRateDamp();
rollRateDamp = sac.getRollRateDamp();
yawRateDamp = sac.getYawRateDamp();
maxPitch = (sac.getPitchMax()>Math.PI)?sac.getPitchMax():(sac.getPitchMax() * LIMITS_MAX_FACTOR);
minPitch = (sac.getPitchMin()<-Math.PI)?sac.getPitchMin():(sac.getPitchMin() * LIMITS_MAX_FACTOR);
maxRoll = (sac.getRollMax()>Math.PI)?sac.getRollMax():(sac.getRollMax() * LIMITS_MAX_FACTOR);
minRoll = (sac.getRollMin()<-Math.PI)?sac.getRollMin():(sac.getRollMin() * LIMITS_MAX_FACTOR);
minKtias = sac.getStallIndicatedAirspeed() * LIMITS_MIN_FACTOR;
maxKtias = ac.getMaximumIndicatedAirspeed() * LIMITS_MAX_FACTOR;
//common configuration for PID controllers
PIDConfiguration pc = sac.getPIDConfiguration(getPIDController().getPIDControl());
PIDController pcc = getPIDController();
pcc.setProportionalGain(pc.getKp());
pcc.setDifferentialGain(pc.getKd());
pcc.setIntegralGain(pc.getKi(), -Float.MAX_VALUE, Float.MAX_VALUE);
//specific configuration for each PID controller
setupPIDController(sac, pc);
}
public void setPidControllers(PIDControllers pidControllers) {
this.pidControllers = pidControllers;
}
public void setAdvancedInstrumentsService(AdvancedInstrumentsService advancedInstrumentsService) {
this.advancedInstrumentsService = advancedInstrumentsService;
}
public void setInstrumentsService(InstrumentsService instrumentsService) {
this.instrumentsService = instrumentsService;
}
public void setGpsService(GPSService gpsService) {
this.gpsService = gpsService;
}
public void setActuatorsService(ActuatorsService actuatorsService) {
this.actuatorsService = actuatorsService;
}
public void setPilot(Pilot pilot) {
this.pilot = pilot;
}
protected abstract void setupPIDController(SkylightVehicleConfigurationMessage ac, PIDConfiguration pc);
public float getMinKtias() {
return minKtias;
}
}
|
webersongao/WBSBlog
|
WBSBlog/Main/Controller/WBSHorizonalTableViewController.h
|
<reponame>webersongao/WBSBlog
//
// WBSHorizonalTableViewController.h
// WBSBlog
//
// Created by Weberson on 16/7/20.
// Copyright © 2016年 Weberson. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface WBSHorizonalTableViewController : UITableViewController
@property (nonatomic, strong) NSArray *controllers;
@property (nonatomic, copy) void (^changeIndex)(NSUInteger index);
@property (nonatomic, copy) void (^scrollView)(CGFloat offsetRatio, NSUInteger focusIndex, NSUInteger animationIndex);
@property (nonatomic, copy) void (^viewDidAppear)(NSInteger index);
- (instancetype)initWithViewControllers:(NSArray *)controllers;
- (void)scrollToViewAtIndex:(NSUInteger)index;
@end
|
ssinno28/Marionette.EntityView
|
views/reusableTypes/pager/PagerListView.js
|
var PagerListView;
(function ($, _, Backbone, Marionette, PagerItemView) {
PagerListView = Marionette.CollectionView.extend({
tagName: 'ul',
className: 'pagination',
initialize: function (options) {
_.extend(this, options);
},
childView: PagerItemView,
events: {
'click li': 'updateCurrent'
},
ui: {
'$pagerItems': 'li'
},
updateCurrent: function (e) {
e.preventDefault();
var $target = $(e.target),
channel = this.getChannel();
this.$el.find('li').removeClass('active');
$target.parent().addClass('active');
channel.trigger('page:changed:' + this.parentViewCid, e);
if (this.options.routing) {
location.hash = $target.attr('href');
} else {
channel.trigger('getAll', $target.data('number'));
}
},
getChannel: function () {
return Backbone.Radio.channel(this.route);
}
});
})(jQuery, _, Backbone, Marionette, PagerItemView);
|
m-wrona/gwt-medicapital
|
server/com/medicapital/server/access/gwtrpc/PatientEvaluationCommandExecutor.java
|
<gh_stars>0
package com.medicapital.server.access.gwtrpc;
import java.util.Set;
import com.medicapital.common.commands.entity.SelectCommand;
import com.medicapital.common.commands.entity.SelectCommandResp;
import com.medicapital.common.commands.entity.SelectCountCommand;
import com.medicapital.common.commands.entity.SelectCountCommandResp;
import com.medicapital.common.commands.evaluation.SelectDoctorEvaluationCommand;
import com.medicapital.common.commands.evaluation.SelectDoctorEvaluationCountCommand;
import com.medicapital.common.dao.ServerException;
import com.medicapital.common.entities.PatientEvaluation;
import com.medicapital.server.logic.PatientEvaluationFacade;
public class PatientEvaluationCommandExecutor extends CommandExecutor<PatientEvaluation> {
private static final long serialVersionUID = 711604574643924164L;
private PatientEvaluationFacade patientEvaluationFacade;
@Override
protected SelectCountCommandResp<PatientEvaluation> handleSelectCountCommand(final SelectCountCommand<PatientEvaluation> selectCountCommand) throws CommandExecutionException, ServerException {
if (selectCountCommand instanceof SelectDoctorEvaluationCountCommand) {
final SelectDoctorEvaluationCountCommand selectDoctorEvaluationCountCommand = (SelectDoctorEvaluationCountCommand) selectCountCommand;
final int count = patientEvaluationFacade.getDoctorEvaluationsCount(selectDoctorEvaluationCountCommand.getDoctorId());
return new SelectCountCommandResp<PatientEvaluation>(PatientEvaluation.class, count);
}
throw new CommandExecutionException("Unsuppored commnad: " + selectCountCommand.getClass());
}
@Override
protected SelectCommandResp<PatientEvaluation> handleSelectCommand(final SelectCommand<PatientEvaluation> selectCommand) throws CommandExecutionException, ServerException {
if (selectCommand instanceof SelectDoctorEvaluationCommand) {
final SelectDoctorEvaluationCommand selectDoctorEvaluationCommand = (SelectDoctorEvaluationCommand) selectCommand;
final Set<PatientEvaluation> evaluations = patientEvaluationFacade.getDoctorPatientEvaluations(selectDoctorEvaluationCommand.getDoctorId(), selectDoctorEvaluationCommand.getStartRow(), selectDoctorEvaluationCommand.getRowCount());
return new SelectCommandResp<PatientEvaluation>(PatientEvaluation.class, evaluations);
}
throw new CommandExecutionException("Unsuppored commnad: " + selectCommand.getClass());
}
@Override
protected Class<PatientEvaluation> getEntityClass() {
return PatientEvaluation.class;
}
public void setPatientEvaluationFacade(PatientEvaluationFacade patientEvaluationFacade) {
setFacade(patientEvaluationFacade);
this.patientEvaluationFacade = patientEvaluationFacade;
}
}
|
renaisaalves/Python-CursoemVideo
|
exercicios/ex007.py
|
#7: Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média.
n1 = float(input('Primeira nota: '))
n2 = float(input('Segunda nota: '))
m = (n1 + n2) / 2
print('A média entre {} e {} é igual a {:.1f}' . format(n1, n2, m))
|
maurizioabba/rose
|
tests/RunTests/PythonTests/test2011_034.py
|
<filename>tests/RunTests/PythonTests/test2011_034.py
def foo0(*args):
print args
def bar0(**kwargs):
print kwargs
def baz0(*args, **kwargs):
print args, kwargs
def foo1(x, *args):
print x, args
def bar1(x, **kwargs):
print x, kwargs
def baz1(x, *args, **kwargs):
print x, args, kwargs
def foo2(x, y, *args):
print x, y, args
def bar2(x, y, **kwargs):
print x, y, kwargs
def baz2(x, y, *args, **kwargs):
print x, y, args, kwargs
(zero, one, two, three, four) = (None, 1, 2.0, 'three', ['four'])
foo0(one, two)
bar0(first=one, second=two)
baz0(one, two, third=three, fourth=four)
foo1(zero, one, two)
bar1(zero, first=one, second=two)
baz1(zero, one, two, third=three, fourth=four)
foo2(zero, four, one, two)
bar2(zero, four, first=one, second=two)
baz2(zero, four, one, two, third=three, fourth=four)
args = (1, 2, 3)
kwargs = {'four': 4,
'five': 5,
'six': 6}
foo0(*args)
bar0(**kwargs)
baz0(*args, **kwargs)
foo1(8, *args)
bar1(9, **kwargs)
baz1(10, *args, **kwargs)
foo2(11, 115, *args)
bar2(12, 125, **kwargs)
baz2(13, 135, *args, **kwargs)
|
pile-contributors/pile-contributors.github.io
|
docpiles/grouplistwidget/html/search/functions_f.js
|
var searchData=
[
['wheelevent',['wheelEvent',['../class_group_list_widget.html#a64665c0495dcac59ba3166410e60ab1f',1,'GroupListWidget']]]
];
|
heng-gezhizou/gulimall
|
gulimall-coupon/src/main/java/com/adtec/gulimall/coupon/dao/SeckillSkuRelationDao.java
|
<gh_stars>0
package com.adtec.gulimall.coupon.dao;
import com.adtec.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 秒杀活动商品关联
*
* @author hgzz
* @email <EMAIL>
* @date 2020-09-15 21:42:21
*/
@Mapper
public interface SeckillSkuRelationDao extends BaseMapper<SeckillSkuRelationEntity> {
}
|
Xrysnow/cocos2d-x-gfx
|
backend/pipeline/PipelineSceneData.h
|
/****************************************************************************
Copyright (c) 2020-2022 <NAME> Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
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.
****************************************************************************/
#pragma once
#include "Define.h"
#include "scene/Define.h"
#include "scene/Light.h"
#include "scene/Sphere.h"
namespace cc {
namespace gfx {
class Framebuffer;
}
namespace pipeline {
class RenderPipeline;
class CC_DLL PipelineSceneData : public Object {
public:
PipelineSceneData() = default;
~PipelineSceneData() override = default;
void activate(gfx::Device *device, RenderPipeline *pipeline);
void setPipelineSharedSceneData(scene::PipelineSharedSceneData *data);
void destroy();
inline void setShadowFramebuffer(const scene::Light *light, gfx::Framebuffer *framebuffer) { _shadowFrameBufferMap.emplace(light, framebuffer); }
inline const std::unordered_map<const scene::Light *, gfx::Framebuffer *> &getShadowFramebufferMap() const { return _shadowFrameBufferMap; }
inline scene::PipelineSharedSceneData * getSharedData() const { return _sharedSceneData; }
inline const RenderObjectList & getRenderObjects() const { return _renderObjects; }
inline const RenderObjectList & getDirShadowObjects() const { return _dirShadowObjects; }
inline void setRenderObjects(RenderObjectList &&ro) { _renderObjects = std::forward<RenderObjectList>(ro); }
inline void setDirShadowObjects(RenderObjectList &&ro) { _dirShadowObjects = std::forward<RenderObjectList>(ro); }
inline const RenderObjectList & getCastShadowObjects() const { return _castShadowObjects; }
inline void setCastShadowObjects(RenderObjectList &&ro) { _castShadowObjects = std::forward<RenderObjectList>(ro); }
inline const vector<const scene::Light *> & getValidPunctualLights() const { return _validPunctualLights; }
inline void setValidPunctualLights(vector<const scene::Light *> &&validPunctualLights) { _validPunctualLights = std::forward<vector<const scene::Light *>>(validPunctualLights); }
inline float getShadowCameraFar() const { return _shadowCameraFar; }
inline void setShadowCameraFar(float shadowDistance) { _shadowCameraFar = shadowDistance; }
inline Mat4 getMatShadowView() const { return _matShadowView; }
inline void setMatShadowView(const Mat4 &matShadowView) { _matShadowView = matShadowView; }
inline Mat4 getMatShadowProj() const { return _matShadowProj; }
inline void setMatShadowProj(const Mat4 &matShadowProj) { _matShadowProj = matShadowProj; }
inline Mat4 getMatShadowViewProj() const { return _matShadowViewProj; }
inline void setMatShadowViewProj(const Mat4 &matShadowViewProj) { _matShadowViewProj = matShadowViewProj; }
inline void addRenderObject(RenderObject &&obj) { _renderObjects.emplace_back(obj); }
inline void clearRenderObjects() { _renderObjects.clear(); }
inline void addValidPunctualLight(scene::Light *light) { _validPunctualLights.emplace_back(light); }
inline void clearValidPunctualLights() { _validPunctualLights.clear(); }
private:
RenderObjectList _renderObjects;
RenderObjectList _dirShadowObjects;
RenderObjectList _castShadowObjects;
vector<const scene::Light *> _validPunctualLights;
scene::PipelineSharedSceneData *_sharedSceneData = nullptr;
RenderPipeline * _pipeline = nullptr;
gfx::Device * _device = nullptr;
float _shadowCameraFar = 0.0F;
Mat4 _matShadowView;
Mat4 _matShadowProj;
Mat4 _matShadowViewProj;
std::unordered_map<const scene::Light *, gfx::Framebuffer *> _shadowFrameBufferMap;
};
} // namespace pipeline
} // namespace cc
|
hallba/Sidekick
|
Sidekick_4.5/GenerateOligomerCGSystem.py
|
#!/usr/bin/python
from __future__ import with_statement
import sys,os,pdbio
from HAConf import configuration,programs,debug_status
from LipidBox import add_solvent_dppc, add_solvent_dlpc, add_solvent_dopc, add_solvent_popc
from MDPGenerator import replace_seed, replace_steps
import AutomatedPlot, PeptideBuild, GenerateCGSystem, GenerateDimerCGSystem
gromacs = configuration['gromacs_location']
scripts = configuration['misc_scripts']
#Lookup table for sizes
defined_system_sizes = {
"S" : {
"xy": 10,
"lipid": 4,
"xyz": 11.5
}
}
tail_lookup = { "DP" : add_solvent_dppc,
"DL" : add_solvent_dlpc,
"PO" : add_solvent_popc,
"DO" : add_solvent_dopc
}
allowed_lipids = [ "DPPC", "DPPG", "DPPE", "DLPC", "DLPG", "DLPE", "DOPC", "DOPG", "DOPE", "POPC", "POPG", "POPE" ]
class generic_oligomer_system(GenerateDimerCGSystem.generic_dimer_system):
def __init__(self,sequences,lipid_type="DPPC",topology_name="ioned_topol",pdb_name="ioned.pdb",bias=True,seed=None,angle=0,position=0.,system_size="XS",preformed_insertion=True,special=None,rotatebyangle=0,alternating=False):
self.sequences = sequences #expecting a list
self.lipid_type="DPPC" #No options at present
self.pdb_name = pdb_name
self.topology_name = topology_name
self.charge = 0
self.epsilon = 20
self.bias = bias
self.seed = seed
self.angle = angle % 360
self.rotatebyangle = rotatebyangle % 360
self.position = position
#self.system_size = defined_system_sizes[system_size]
self.system_xy = 9 # No options yet
self.preformed_insertion = True #No options at present
self.special = special
self.apolar = True
self.pme = False
self.number_lipid_types = 1
self.alternating = alternating
#First generate n helices and their itps
#Where to put everything? Best known packings of equal circles in a square from http://hydra.nat.uni-magdeburg.de/packing/csq/csq.html
#All are based on a 1AU square, with an origin in the center
#If you need more, you need to add them explicitly
self.best_packings ={ 3 : { "cart" : [[-0.246, -0.246],[0.246, -0.114],[-0.114, 0.246]],
"radi" : 0.254
},
4 : { "cart" : [[-0.25,-0.25],[0.25,-0.25],[-0.25,0.25],[0.25,0.25]],
"radi" : 0.25
},
5 : { "cart" : [[-0.293, -0.293],[0.293, -0.293],[0,0],[-0.293, 0.293],[0.293, 0.293]],
"radi" : 0.207
},
6 : { "cart" : [[-0.312, -0.312],[0.312, -0.312],[0, -0.104],[-0.312, 0.104],[0.312, 0.104],[0, 0.312]],
"radi" : 0.188
},
7 : { "cart" : [[-0.326, -0.326],[0.023, -0.326],[0.326, -0.151],[-0.326, 0.023],[0.023, 0.023],[0.3,0.3],[-0.151, 0.326]],
"radi" : 0.174
},
8 : { "cart" : [[-0.330,-0.330],[0.330,-0.330],[0,-0.241],[-0.241,0],[0.241,0],[0,0.241],[-0.330,0.330],[0.330,0.330]],
"radi" : 0.170
},
9 : { "cart" : [[-0.333,-0.333],[0,-0.333],[0.333,-0.333],[-0.333,0],[0,0],[0.333,0],[-0.333,0.333],[0,0.333],[0.333,0.333]],
"radi" : 0.167
}
}
if len(self.sequences) not in self.best_packings.keys():
print "No best packing has been coded for", len(self.sequences), "helices. Exiting"
sys.exit()
best_packing = self.best_packings[len(self.sequences)]
self.topology_header_generator()
self.radius = best_packing["radi"] * self.system_xy
if self.radius < 1.2:
print "WARNING: shortest distance between helices is shorter than the cut off"
else:
print "Shortest distance between helices is", self.radius
for item in range(len(self.sequences)):
self.initial_sequence = sequences[item]
self.generate_atomistic_helix()
self.CoarseGrain()
rotate = 180 * (item%2) if self.alternating else 0
self.PeptideEM(xrotate=rotate,zrotate=self.rotatebyangle,x_displacement=best_packing["cart"][item][0]*self.system_xy,y_displacement=best_packing["cart"][item][1]*self.system_xy)
self.RenameCGFiles("Helix"+str(item))
self.initial_sequence = self.sequences[0] #Initial sequence is the first sequence (A)
#Combine the peptides into a single PDB and prepare for a dimer
os.system("cat Helix*.pdb | grep ATOM >> prot_em.pdb")
self.oligomer_topology_header_generator()
with open("preion_topol.top","w") as preion_topology:
print >> preion_topology, self.topology_header
#Now reposition them, insert into a preformed bilayer/water system and add counter ions
self.BuildMe()
def PeptideEM(self,xrotate=0,zrotate=0,x_displacement=0,y_displacement=0):
topology = open("preion_topol.top","w")
topology.write(self.topology_header)
topology.flush()
os.system(gromacs+"grompp -f "+ configuration['mdp_files'] + "cg-em_extended.mdp -c protein_cg_box.pdb -o prot_em -p preion_topol >& grompp_protem.log")
os.system(gromacs+"mdrun -deffnm prot_em")
#os.system(gromacs+"genbox -cp prot_em.gro -cs "+ configuration['martini_systems'] + "solvent.pdb -o deionised_system.pdb -vdwd 0.24 >& genbox.log")
os.system(gromacs+"editconf -f prot_em.gro -o prot_em.gro -center 0 0 0")
os.system(gromacs+"editconf -f prot_em.gro -o prot_em_post_rot.pdb -rotate " + str(xrotate) + " 0 " + str(zrotate))
os.system(gromacs+"editconf -f prot_em_post_rot.pdb -o prot_em.pdb -translate " + str(x_displacement) + " " + str(y_displacement) + " " + str(self.position))
topology.close()
class generic_BondOligomer_System(generic_oligomer_system):
def oligomer_topology_header_generator(self):
self.topology_header = """#include "ff_v1.4_polar-backbone.itp"
#include "bond-dppg.itp"
"""
for item in range(len(self.sequences)):
self.topology_header += '#include "Helix'+ str(item) +'.itp"\n'
self.topology_header += """#include "special_ion.itp"
[ system ]
; Name
TM <NAME>
[ molecules ]
; Compound #mols
"""
for item in range(len(self.sequences)):
self.topology_header += 'Helix'+ str(item) +' 1\n'
class generic_MARTINIOligomer_System(generic_oligomer_system):
def oligomer_topology_header_generator(self):
self.topology_header = self.martini_base() + """#include "martini_v2.0_lipids.itp"
#include "martini_v2.0_ions.itp"
#include "martini-dppg-tieleman.itp"
"""
for item in range(len(self.sequences)):
self.topology_header += '#include "Helix'+ str(item) +'.itp"\n'
self.topology_header += """
[ system ]
; Name
TM Helix Dimer
[ molecules ]
; Compound #mols
"""
for item in range(len(self.sequences)):
self.topology_header += 'Helix'+ str(item) +' 1\n'
class MARTINIOligomer_System(generic_MARTINIOligomer_System,GenerateCGSystem.MARTINI_system):
pass
class BondOligomer_System(generic_BondOligomer_System,GenerateCGSystem.BOND_system):
pass
class BondOligomer_system_0_9_5(generic_BondOligomer_System,GenerateCGSystem.BOND_system_0_9_5):
pass
class BondOligomer_system_development(generic_BondOligomer_System,GenerateCGSystem.BOND_system_development):
pass
class BondOligomer_uncharged_DE(generic_BondOligomer_System,GenerateCGSystem.BOND_uncharged_DE):
pass
class MARTINIOligomer_system_1_1_1(generic_MARTINIOligomer_System,GenerateCGSystem.MARTINI_system_1_1_1):
pass
class MARTINIOligomer_system_1_1_2(generic_MARTINIOligomer_System,GenerateCGSystem.MARTINI_system_1_1_2):
pass
class MARTINIOligomer_system_1_1_2_b(generic_MARTINIOligomer_System,GenerateCGSystem.MARTINI_system_1_1_2_b):
pass
class MARTINIOligomer_system_112b_ENM(generic_MARTINIOligomer_System,GenerateCGSystem.MARTINI_system_112b_ENM):
pass
installed_models = { "MARTINI_1.1.1" : MARTINIOligomer_system_1_1_1,
"MARTINI_1.1.2" : MARTINIOligomer_system_1_1_2,
"MARTINI_1.1.2.b" : MARTINIOligomer_system_1_1_2_b,
"Bond" : BondOligomer_System,
"Bond0.9.5" : BondOligomer_system_0_9_5,
"MARTINI" : MARTINIOligomer_System,
"BondDev" : BondOligomer_system_development,
"BondUnchargedDE" : BondOligomer_uncharged_DE,
"MARTINI_1.1.2.b.ENM" : MARTINIOligomer_system_112b_ENM,
"Latest-Stable-MARTINI" : MARTINIOligomer_system_1_1_2_b,
"Latest-Stable-Bond" : BondOligomer_System
}
|
abaire/xbdm_gdb_bridge
|
src/xbox/xbox_interface.h
|
<gh_stars>1-10
#ifndef XBDM_GDB_BRIDGE_SRC_XBOX_XBOX_INTERFACE_H_
#define XBDM_GDB_BRIDGE_SRC_XBOX_XBOX_INTERFACE_H_
#include <boost/asio/thread_pool.hpp>
#include <future>
#include <list>
#include <memory>
#include <string>
#include "gdb/gdb_packet.h"
#include "net/ip_address.h"
class DelegatingServer;
class GDBBridge;
class GDBPacket;
class RDCPProcessedRequest;
class SelectThread;
class XBDMContext;
class XBDMDebugger;
class XBOXInterface {
public:
XBOXInterface(std::string name, IPAddress xbox_address);
void Start();
void Stop();
bool ReconnectXBDM();
bool AttachDebugger();
void DetachDebugger();
[[nodiscard]] std::shared_ptr<XBDMDebugger> Debugger() const {
return xbdm_debugger_;
}
[[nodiscard]] std::shared_ptr<XBDMContext> Context() const {
return xbdm_context_;
}
bool StartGDBServer(const IPAddress &address);
void StopGDBServer();
bool GetGDBListenAddress(IPAddress &ret) const;
bool StartNotificationListener(const IPAddress &address);
void AttachDebugNotificationHandler();
void DetachDebugNotificationHandler();
std::shared_ptr<RDCPProcessedRequest> SendCommandSync(
std::shared_ptr<RDCPProcessedRequest> command);
std::future<std::shared_ptr<RDCPProcessedRequest>> SendCommand(
std::shared_ptr<RDCPProcessedRequest> command);
private:
void OnGDBClientConnected(int sock, IPAddress &address);
void OnGDBPacketReceived(const std::shared_ptr<GDBPacket> &packet);
void DispatchGDBPacket(const std::shared_ptr<GDBPacket> &packet);
private:
std::string name_;
IPAddress xbox_address_;
std::shared_ptr<SelectThread> select_thread_;
std::shared_ptr<XBDMContext> xbdm_context_;
std::shared_ptr<XBDMDebugger> xbdm_debugger_;
std::shared_ptr<DelegatingServer> gdb_server_;
std::shared_ptr<GDBBridge> gdb_bridge_;
std::shared_ptr<boost::asio::thread_pool> gdb_executor_;
int debug_notification_handler_id_{0};
};
#endif // XBDM_GDB_BRIDGE_SRC_XBOX_XBOX_INTERFACE_H_
|
oshai/vertx-examples
|
core-examples/src/main/java/io/vertx/example/core/verticle/worker/WorkerVerticle.java
|
package io.vertx.example.core.verticle.worker;
import io.vertx.core.AbstractVerticle;
/**
* An example of worker verticle
*/
public class WorkerVerticle extends AbstractVerticle {
@Override
public void start() throws Exception {
System.out.println("[Worker] Starting in " + Thread.currentThread().getName());
vertx.eventBus().<String>consumer("sample.data", message -> {
System.out.println("[Worker] Consuming data in " + Thread.currentThread().getName());
String body = message.body();
message.reply(body.toUpperCase());
});
}
}
|
ScottKirvan/pinmame
|
src/cpu/i8051/i8051.c
|
/*****************************************************************************
*
* i8051.c
* Portable MCS-51 Family Emulator
*
* Chips in the family:
* 8051 Product Line (8031,8051,8751)
* 8052 Product Line (8032,8052,8752)
* 8054 Product Line (8054)
* 8058 Product Line (8058)
*
* Copyright (c) 2003 <NAME>, all rights reserved.
*
* - This source code is released as freeware for non-commercial purposes.
* - You are free to use and redistribute this code in modified or
* unmodified form, provided you list me in the credits.
* - If you modify this source code, you must add a notice to each modified
* source file that it has been changed. If you're a nice person, you
* will clearly mark each change too. :)
* - If you wish to use this for commercial purposes, please contact me at
* <EMAIL>
* - The author of this copywritten work reserves the right to change the
* terms of its usage and license at any time, including retroactively
* - This entire notice must remain in the source code.
*
* This work is based on:
* #1) 'Intel(tm) MC51 Microcontroller Family Users Manual' and
* #2) 8051 simulator by <NAME>
* #3) Portable UPI-41/8041/8741/8042/8742 emulator V0.1 by <NAME> (MAME CORE)
*
*****************************************************************************/
/******************************************************************************
* Notes:
* *Important*: Internal ROM needs to be treated the same as external rom by the programmer
* creating the driver (ie, use standard cpu rom region)
*
* The term cycles is used here to really refer to clock oscilations, because 1 machine cycle
* actually takes 12 oscilations.
*
* Read/Write/Modify Instruction -
* Data is read from the Port Latch (not the Port Pin!), possibly modified, and
* written back to (the pin? and) the latch!
*
* The following all perform this on a port address..
* (anl, orl, xrl, jbc, cpl, inc, dec, djnz, mov px.y,c, clr px.y, setb px.y)
*
* Serial UART emulation is not really accurate, but faked enough to work as far as i can tell
*
* August 27,2003: Currently support for only 8031/8051/8751 chips (ie 128 RAM)
* October 14,2003: Added initial support for the 8752 (ie 256 RAM)
* October 22,2003: Full support for the 8752 (ie 256 RAM)
* July 28,2004: Fixed MOVX command and added External Ram Paging Support
* July 31,2004: Added Serial Mode 0 Support & Fixed Interrupt Flags for Serial Port
*
* Todo: Full Timer support (all modes)
*
* NOW Implemented: RAM paging using hardware configured addressing...
* (July 28,2004) the "MOVX a,@R0/R1" and "MOVX @R0/R1,a" commands can use any of the other ports
* to output a page offset into external ram, but it is totally based on the hardware setup.
*
* Timing needs to be implemented via MAME timers perhaps?
*
*****************************************************************************/
#include <stdio.h>
#include "driver.h"
#include "state.h"
#include "mamedbg.h"
#include "i8051.h"
#define VERBOSE 0
#if VERBOSE
#define LOG(x) logerror x
#else
#define LOG(x)
#endif
#define FIXIRQ 1
//Prototypes
INLINE void push_pc(void);
INLINE void pop_pc(void);
INLINE void set_parity(void);
INLINE void do_add_flags(UINT8 a, UINT8 data, UINT8 c);
INLINE void do_sub_flags(UINT8 a, UINT8 data, UINT8 c);
INLINE UINT8 check_interrupts(void);
INLINE void update_timer(int cyc);
INLINE void update_serial(int cyc);
INLINE void serial_transmit(UINT8 data);
static READ_HANDLER(internal_ram_read);
static WRITE_HANDLER(internal_ram_write);
static READ_HANDLER(internal_ram_iread);
static READ32_HANDLER(external_ram_iaddr);
static WRITE_HANDLER(internal_ram_iwrite);
static READ_HANDLER(sfr_read);
static WRITE_HANDLER(sfr_write);
static WRITE_HANDLER( bit_address_w );
static READ_HANDLER( bit_address_r );
#if (HAS_I8052 || HAS_I8752)
static READ_HANDLER(i8052_internal_ram_iread);
static WRITE_HANDLER(i8052_internal_ram_iwrite);
#endif
//
typedef struct {
UINT8 timerbaud; //Flag set if timer overflow is controlling baud
UINT8 sending; //Flag set when uart is sending
UINT8 data_out; //Data to send out
UINT8 bits_to_send; //How many bits left to send when transmitting out the serial port
UINT8 bitcycles; //# of bitcycles passed since last bit was sent
} I8051_UART;
typedef struct {
//Internal stuff
UINT16 ppc; //previous pc
UINT16 pc; //current pc
UINT16 subtype; //specific version of the cpu, ie 8031, or 8051 for example
UINT8 cur_irq; //Holds value of any current IRQ being serviced
UINT8 irq_priority; //Holds value of the current IRQ Priority Level
UINT8 rwm; //Signals that the current instruction is a read/write/modify instruction
int prev_used_cycles; //Track previous # of used cycles
int last_int0; //Store state of int0
int last_int1; //Store state of int1
UINT8 int_vec; //Pending Interrupt Vector
int priority_request; //Priority level of incoming new irq
#if FIXIRQ
int intsBlocked; // interrupts blocked for one cycle by RETI
#endif
//SFR Registers (Note: Appear in order as they do in memory)
UINT8 po; //Port 0
UINT8 sp; //Stack Pointer
UINT8 dpl; //Data Pointer (DPTR) (Hi bit)
UINT8 dph; //Data Pointer (DPTR) (Lo bit)
UINT8 pcon; //Power Mode Control
UINT8 tcon; //Timer/Counter Control
UINT8 tmod; //Timer/Counter Mode Control
UINT8 tl0; //Timer 0 Lo
UINT8 tl1; //Timer 1 Lo
UINT8 th0; //Timer 0 Hi
UINT8 th1; //Timer 1 Hi
UINT8 p1; //Port 1
UINT8 scon; //Serial Control
UINT8 sbuf; //Serial Data Buffer
UINT8 p2; //Port 2
UINT8 ie; //Interrupt Enable
UINT8 p3; //Port 3
UINT8 ip; //Interrupt Priority
//8052 Only registers
#if (HAS_I8052 || HAS_I8752)
UINT8 t2con; //Timer/Counter 2 Control
UINT8 rcap2l; //Timer/Counter 2 Capture Register Lo
UINT8 rcap2h; //Timer/Counter 2 Capture Register Hi
UINT8 tl2; //Timer 2 Lo
UINT8 th2; //Timer 2 Hi
#endif
UINT8 psw; //Program Status Word
UINT8 acc; //Accumulator
UINT8 b; //Register B
//Internal Ram
UINT8 IntRam[0xff+1]; //Max 256 Bytes of Internal RAM (8031/51 have 128, 8032/52 have 256)
//Interrupt Callback
int (*irq_callback)(int irqline);
//Serial Port TX/RX Call backs
void (*serial_tx_callback)(int data); //Call back funciton when sending data out of serial port
int (*serial_rx_callback)(void); //Call back function to retrieve data when receiving serial port data
//Internal Indirect Read/Write Handlers
READ_HANDLER((*iram_iread));
WRITE_HANDLER((*iram_iwrite));
//External Ram Address Callback for generating the hardware specific access to external ram
READ32_HANDLER((*eram_iaddr_callback));
} I8051;
int i8051_icount;
static I8051 i8051;
static I8051_UART uart;
/* Layout of the registers in the debugger (-1 = end of a line, 0 = end of layout) */
static UINT8 i8051_reg_layout[] = {
I8051_PC, I8051_SP, I8051_PSW, I8051_ACC, I8051_B, I8051_DPH, I8051_DPL, I8051_IE, 0xFF,
I8051_R0, I8051_R1, I8051_R2, I8051_R3, I8051_R4, I8051_R5, I8051_R6, I8051_R7, I8051_RB, 0
};
/* Layout of the debugger windows x,y,w,h */
static UINT8 i8051_win_layout[] = {
0, 0,80, 2, /* register window (top rows) */
0, 3,24,19, /* disassembler window (left colums) */
25, 3,55,10, /* memory #1 window (right, upper middle) */
25,14,55, 8, /* memory #2 window (right, lower middle) */
0,23,80, 1, /* command line window (bottom rows) */
};
//Hold callback functions so they can be set by caller (before the cpu reset)
static void (*hold_serial_tx_callback)(int data);
static int (*hold_serial_rx_callback)(void);
static READ32_HANDLER((*hold_eram_iaddr_callback));
/*Short cuts*/
/***************************************************************
* Read Opcode/Opcode Arguments from Program Code
***************************************************************/
#define ROP(pc) cpu_readop(pc)
#define ROP_ARG(pc) cpu_readop_arg(pc)
/*****************************************************************************
* Read a byte from External Code Memory (Usually Program Rom(s) Space)
*****************************************************************************
This area is mapped from 0-FFFF internally (64K) */
#define CODEMEM_R(a) (UINT8)cpu_readmem20(a)
/*****************************************************************************
* Read/Write a byte from/to External Data Memory (Usually RAM or other I/O)
*****************************************************************************
This area is *ALSO* mapped from 0-FFFF internally (64K)
** HOWEVER **
We *FORCE* the address space into the range 10000-1FFFF to allow both
Code Memory and Data Memory to be pyshically separate while mapped @ the same
addresses, w/o any contention.
As far as the 8051 program code which is executing knows data memory still lives
in the 0-FFFF range.*/
#define DATAMEM_R(a) (UINT8)cpu_readmem20(a+0x10000)
#define DATAMEM_W(a,v) cpu_writemem20(a+0x10000,v)
/***************************************************************
* Read/Write a byte from/to the Internal RAM
***************************************************************/
#define IRAM_R(a) internal_ram_read(a)
#define IRAM_W(a,v) internal_ram_write(a,v)
/***************************************************************
* Read/Write a byte from/to the Internal RAM indirectly (called from indirect addressing)
***************************************************************/
#define IRAM_IR(a) internal_ram_iread(a)
#define IRAM_IW(a,v) internal_ram_iwrite(a,v)
/***************************************************************
* Form an Address to Read/Write to External RAM indirectly (called from indirect addressing)
***************************************************************/
#define ERAM_ADDR(a,m) external_ram_iaddr(a,m)
/***************************************************************
* Read/Write a byte from/to the SFR Registers
***************************************************************/
#define SFR_R(a) sfr_read(a)
#define SFR_W(a,v) sfr_write(a,v)
/***************************************************************
* Read/Write a bit from Bit Addressable Memory
***************************************************************/
#define BIT_R(a) bit_address_r(a)
#define BIT_W(a,v) bit_address_w(a,v)
/***************************************************************
* Input/Output a byte from given I/O port
***************************************************************/
#define IN(port) ((UINT8)cpu_readport16(port))
#define OUT(port,value) cpu_writeport16(port,value)
/***************************************************************
* Access the 4 banks of R registers (R0...R7)
***************************************************************/
#define R_R(n) i8051.IntRam[(GET_RS*8)+(n)]
/***************************************************************
* Easy macro for working with 16 bit DPTR
***************************************************************/
#define R_DPTR ((R_DPH<<8) | R_DPL)
#define DPTR_W(n) SFR_W(DPH, ((n)>>8)&0xff);\
SFR_W(DPL, ((n)&0xff));
/***************************************************************
* Easy macros for Setting Flags
***************************************************************/
/*PSW Flags*/
#define SET_CY(n) R_PSW = (R_PSW & 0x7f) | ((n)<<7); //Carry Flag
#define SET_AC(n) R_PSW = (R_PSW & 0xbf) | ((n)<<6); //Aux.Carry Flag
#define SET_FO(n) R_PSW = (R_PSW & 0xdf) | ((n)<<5); //User Flag
#define SET_RS(n) R_PSW = (R_PSW & 0xe7) | ((n)<<3); //R Bank Select
#define SET_OV(n) R_PSW = (R_PSW & 0xfb) | ((n)<<2); //Overflow Flag
#define SET_P(n) R_PSW = (R_PSW & 0xfe) | ((n)<<0); //Parity Flag
/*IE Flags*/
#define SET_EA(n) R_IE = (R_IE & 0x7f) | ((n)<<7); //Global Interrupt Enable/Disable
#if (HAS_I8052 || HAS_I8752)
#define SET_ET2(n) R_IE = (R_IE & 0xdf) | ((n)<<5); //Timer 2 Interrupt Enable/Disable
#endif
#define SET_ES(n) R_IE = (R_IE & 0xef) | ((n)<<4); //Serial Interrupt Enable/Disable
#define SET_ET1(n) R_IE = (R_IE & 0xf7) | ((n)<<3); //Timer 1 Interrupt Enable/Disable
#define SET_EX1(n) R_IE = (R_IE & 0xfb) | ((n)<<2); //External Int 1 Interrupt Enable/Disable
#define SET_ET0(n) R_IE = (R_IE & 0xfd) | ((n)<<1); //Timer 0 Interrupt Enable/Disable
#define SET_EX0(n) R_IE = (R_IE & 0xfe) | ((n)<<0); //External Int 0 Interrupt Enable/Disable
/*IP Flags*/
#if (HAS_I8052 || HAS_I8752)
#define SET_PT2(n) R_IP = (R_IP & 0xdf) | ((n)<<5); //Set Timer 2 Priority Level
#endif
#define SET_PS0(n) R_IP = (R_IP & 0xef) | ((n)<<4); //Set Serial Priority Level
#define SET_PT1(n) R_IP = (R_IP & 0xf7) | ((n)<<3); //Set Timer 1 Priority Level
#define SET_PX1(n) R_IP = (R_IP & 0xfb) | ((n)<<2); //Set External Int 1 Priority Level
#define SET_PT0(n) R_IP = (R_IP & 0xfd) | ((n)<<1); //Set Timer 0 Priority Level
#define SET_PX0(n) R_IP = (R_IP & 0xfe) | ((n)<<0); //Set External Int 0 Priority Level
/*TCON Flags*/
#define SET_TF1(n) R_TCON = (R_TCON & 0x7f) | ((n)<<7); //Indicated Timer 1 Overflow Int Triggered
#define SET_TR1(n) R_TCON = (R_TCON & 0xbf) | ((n)<<6); //IndicateS Timer 1 is running
#define SET_TF0(n) R_TCON = (R_TCON & 0xdf) | ((n)<<5); //Indicated Timer 0 Overflow Int Triggered
#define SET_TR0(n) R_TCON = (R_TCON & 0xef) | ((n)<<4); //IndicateS Timer 0 is running
#define SET_IE1(n) R_TCON = (R_TCON & 0xf7) | ((n)<<3); //Indicated External Int 1 Triggered
#define SET_IT1(n) R_TCON = (R_TCON & 0xfb) | ((n)<<2); //Indicates how External Int 1 is Triggered
#define SET_IE0(n) R_TCON = (R_TCON & 0xfd) | ((n)<<1); //Indicated External Int 0 Triggered
#define SET_IT0(n) R_TCON = (R_TCON & 0xfe) | ((n)<<0); //Indicates how External Int 0 is Triggered
/*SCON Flags*/
#define SET_SM0(n) R_SCON = (R_SCON & 0x7f) | ((n)<<7); //Sets Serial Port Mode
#define SET_SM1(n) R_SCON = (R_SCON & 0xbf) | ((n)<<6); //Sets Serial Port Mode
#define SET_SM2(n) R_SCON = (R_SCON & 0xdf) | ((n)<<5); //Sets Serial Port Mode (Multiprocesser mode)
#define SET_REN(n) R_SCON = (R_SCON & 0xef) | ((n)<<4); //Sets Serial Port Receive Enable
#define SET_TB8(n) R_SCON = (R_SCON & 0xf7) | ((n)<<3); //Transmit 8th Bit
#define SET_RB8(n) R_SCON = (R_SCON & 0xfb) | ((n)<<2); //Receive 8th Bit
#define SET_TI(n) R_SCON = (R_SCON & 0xfd) | ((n)<<1); //Indicates Transmit Interrupt Occurred
#define SET_RI(n) R_SCON = (R_SCON & 0xfe) | ((n)<<0); //Indicates Receive Interrupt Occurred
/*TMOD Flags*/
#define SET_GATE1(n) R_TMOD = (R_TMOD & 0x7f) | ((n)<<7); //Timer 1 Gate Mode
#define SET_CT1(n) R_TMOD = (R_TMOD & 0xbf) | ((n)<<6); //Timer 1 Counter Mode
#define SET_M1_1(n) R_TMOD = (R_TMOD & 0xdf) | ((n)<<5); //Timer 1 Timer Mode Bit 1
#define SET_M1_0(n) R_TMOD = (R_TMOD & 0xef) | ((n)<<4); //Timer 1 Timer Mode Bit 0
#define SET_GATE0(n) R_TMOD = (R_TMOD & 0xf7) | ((n)<<3); //Timer 0 Gate Mode
#define SET_CT0(n) R_TMOD = (R_TMOD & 0xfb) | ((n)<<2); //Timer 0 Counter Mode
#define SET_M0_1(n) R_TMOD = (R_TMOD & 0xfd) | ((n)<<1); //Timer 0 Timer Mode Bit 1
#define SET_M0_0(n) R_TMOD = (R_TMOD & 0xfe) | ((n)<<0); //Timer 0 Timer Mode Bit 0
#if (HAS_I8052 || HAS_I8752)
/*T2CON Flags*/
#define SET_TF2(n) R_T2CON = (R_T2CON & 0x7f) | ((n)<<7); //Indicated Timer 2 Overflow Int Triggered
#define SET_EXF2(n) R_T2CON = (R_T2CON & 0xbf) | ((n)<<6); //Indicates Timer 2 External Flag
#define SET_RCLK(n) R_T2CON = (R_T2CON & 0xdf) | ((n)<<5); //Receive Clock
#define SET_TCLK(n) R_T2CON = (R_T2CON & 0xef) | ((n)<<4); //Transmit Clock
#define SET_EXEN2(n) R_T2CON = (R_T2CON & 0xf7) | ((n)<<3); //Timer 2 External Interrupt Enable
#define SET_TR2(n) R_T2CON = (R_T2CON & 0xfb) | ((n)<<2); //Indicates Timer 2 is running
#define SET_CT2(n) R_T2CON = (R_T2CON & 0xfd) | ((n)<<1); //Sets Timer 2 Counter/Timer Mode
#define SET_CP(n) R_T2CON = (R_T2CON & 0xfe) | ((n)<<0); //Sets Timer 2 Capture/Reload Mode
#endif
/***************************************************************
* Easy macros for Getting Flags
***************************************************************/
/*PSW Flags*/
#define GET_CY ((R_PSW & 0x80)>>7)
#define GET_AC ((R_PSW & 0x40)>>6)
#define GET_FO ((R_PSW & 0x20)>>5)
#define GET_RS ((R_PSW & 0x18)>>3)
#define GET_OV ((R_PSW & 0x04)>>2)
#define GET_P ((R_PSW & 0x01)>>0)
/*IE Flags*/
#define GET_EA ((R_IE & 0x80)>>7)
#define GET_ET2 ((R_IE & 0x20)>>5)
#define GET_ES ((R_IE & 0x10)>>4)
#define GET_ET1 ((R_IE & 0x08)>>3)
#define GET_EX1 ((R_IE & 0x04)>>2)
#define GET_ET0 ((R_IE & 0x02)>>1)
#define GET_EX0 ((R_IE & 0x01)>>0)
/*IP Flags*/
#if (HAS_I8052 || HAS_I8752)
#define GET_PT2 ((R_IP & 0x20)>>5)
#endif
#define GET_PS ((R_IP & 0x10)>>4)
#define GET_PT1 ((R_IP & 0x08)>>3)
#define GET_PX1 ((R_IP & 0x04)>>2)
#define GET_PT0 ((R_IP & 0x02)>>1)
#define GET_PX0 ((R_IP & 0x01)>>0)
/*TCON Flags*/
#define GET_TF1 ((R_TCON & 0x80)>>7)
#define GET_TR1 ((R_TCON & 0x40)>>6)
#define GET_TF0 ((R_TCON & 0x20)>>5)
#define GET_TR0 ((R_TCON & 0x10)>>4)
#define GET_IE1 ((R_TCON & 0x08)>>3)
#define GET_IT1 ((R_TCON & 0x04)>>2)
#define GET_IE0 ((R_TCON & 0x02)>>1)
#define GET_IT0 ((R_TCON & 0x01)>>0)
/*SCON Flags*/
#define GET_SM0 ((R_SCON & 0x80)>>7)
#define GET_SM1 ((R_SCON & 0x40)>>6)
#define GET_SM2 ((R_SCON & 0x20)>>5)
#define GET_REN ((R_SCON & 0x10)>>4)
#define GET_TB8 ((R_SCON & 0x08)>>3)
#define GET_RB8 ((R_SCON & 0x04)>>2)
#define GET_TI ((R_SCON & 0x02)>>1)
#define GET_RI ((R_SCON & 0x01)>>0)
/*TMOD Flags*/
#define GET_GATE1 ((R_TMOD & 0x80)>>7)
#define GET_CT1 ((R_TMOD & 0x40)>>6)
#define GET_M1_1 ((R_TMOD & 0x20)>>5)
#define GET_M1_0 ((R_TMOD & 0x10)>>4)
#define GET_GATE0 ((R_TMOD & 0x08)>>3)
#define GET_CT0 ((R_TMOD & 0x04)>>2)
#define GET_M0_1 ((R_TMOD & 0x02)>>1)
#define GET_M0_0 ((R_TMOD & 0x01)>>0)
#if (HAS_I8052 || HAS_I8752)
/*T2CON Flags*/
#define GET_TF2 ((R_T2CON & 0x80)>>7)
#define GET_EXF2 ((R_T2CON & 0x40)>>6)
#define GET_RCLK ((R_T2CON & 0x20)>>5)
#define GET_TCLK ((R_T2CON & 0x10)>>4)
#define GET_EXEN2 ((R_T2CON & 0x08)>>3)
#define GET_TR2 ((R_T2CON & 0x04)>>2)
#define GET_CT2 ((R_T2CON & 0x02)>>1)
#define GET_CP ((R_T2CON & 0x01)>>0)
#endif
/*Add and Subtract Flag settings*/
#define DO_ADD_FLAGS(a,d,c) do_add_flags(a,d,c);
#define DO_SUB_FLAGS(a,d,c) do_sub_flags(a,d,c);
#define SET_PARITY set_parity();
#define PUSH_PC push_pc();
#define POP_PC pop_pc();
/* PC vectors */
#define V_RESET 0x000 /* power on address */
#define V_IE0 0x003 /* External Interrupt 0 */
#define V_TF0 0x00b /* Timer 0 Overflow */
#define V_IE1 0x013 /* External Interrupt 1 */
#define V_TF1 0x01b /* Timer 1 Overflow */
#define V_RITI 0x023 /* Serial Receive/Transmit */
#define V_TF2 0x02b /* Timer 2 Overflow */
/* Any pending IRQ */
#define SERIALPORT_IRQ ((R_SCON & 0x03) && GET_ES)
#if (HAS_I8052 || HAS_I8752)
#ifdef PINMAME // otherwise no sound on spinball games
#define NO_PENDING_IRQ !(R_TCON & 0xaa) && !(SERIALPORT_IRQ) && !GET_TF2 && !GET_EXF2
#else
#define NO_PENDING_IRQ !(R_TCON & 0xaa) && !(SERIALPORT_IRQ) && !GET_ET2 //!GET_TF2 && !GET_EXF2
#endif
#else
#define NO_PENDING_IRQ !(R_TCON & 0xaa) && !(SERIALPORT_IRQ)
#endif
/* Clear Current IRQ */
#define CLEAR_CURRENT_IRQ i8051.cur_irq = 0xff;\
i8051.irq_priority = 0;
#if FIXIRQ
/* block interrupts */
#define GET_INTS_BLOCKED i8051.intsBlocked
#define SET_INTS_BLOCKED i8051.intsBlocked=1
#define CLR_INTS_BLOCKED i8051.intsBlocked=0
#endif
/* shorter names for the I8051 structure elements */
//Internal stuff
#define PPC i8051.ppc
#define PC i8051.pc
#define TYPE i8051.subtype
#define RWM i8051.rwm
//SFR Registers
#define R_P0 i8051.po
#define R_SP i8051.sp
#define R_DPL i8051.dpl
#define R_DPH i8051.dph
#define R_PCON i8051.pcon
#define R_TCON i8051.tcon
#define R_TMOD i8051.tmod
#define R_TL0 i8051.tl0
#define R_TL1 i8051.tl1
#define R_TH0 i8051.th0
#define R_TH1 i8051.th1
#define R_P1 i8051.p1
#define R_SCON i8051.scon
#define R_SBUF i8051.sbuf
#define R_P2 i8051.p2
#define R_IE i8051.ie
#define R_P3 i8051.p3
#define R_IP i8051.ip
//8052 Only registers
#if (HAS_I8052 || HAS_I8752)
#define R_T2CON i8051.t2con
#define R_RCAP2L i8051.rcap2l
#define R_RCAP2H i8051.rcap2h
#define R_TL2 i8051.tl2
#define R_TH2 i8051.th2
#endif
#define R_PSW i8051.psw
#define R_ACC i8051.acc
#define R_B i8051.b
/* # of oscilations each opcode requires, tweaked based on pdf at http://www.oreganosystems.at/?page_id=96 (v1.6) */
static UINT8 i8051_cycles[] = {
12,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,
24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,
24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,
24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,
24,24,12,24,12,12,12,12,12,12,12,12,12,12,12,12,
24,24,12,24,12,12,12,12,12,12,12,12,12,12,12,12,
24,24,12,24,12,12,12,12,12,12,12,12,12,12,12,12,
24,24,24,24,12,24,12,12,12,12,12,12,12,12,12,12,
24,24,24,24,48,24,24,24,24,24,24,24,24,24,24,24,
24,24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,
24,24,12,24,48,12/*?*/,24,24,24,24,24,24,24,24,24,24,
24,24,12,12,24,24,24,24,24,24,24,24,24,24,24,24,
24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
24,24,12,12,12,24,12,12,24,24,24,24,24,24,24,24,
24,24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,
24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12
};
/* Include Opcode functions */
#include "i8051ops.c"
void i8051_init(void)
{
int cpu = cpu_getactivecpu();
//Internal stuff
state_save_register_UINT16("i8051", cpu, "PPC", &i8051.ppc, 1);
state_save_register_UINT16("i8051", cpu, "PC", &i8051.pc, 1);
state_save_register_UINT16("i8051", cpu, "SUBTYPE", &i8051.subtype,1);
state_save_register_UINT8 ("i8051", cpu, "RWM", &i8051.rwm ,1);
state_save_register_UINT8 ("i8051", cpu, "CUR_IRQ", &i8051.cur_irq ,1);
//SFR Registers
state_save_register_UINT8 ("i8051", cpu, "PO", &i8051.po, 1);
state_save_register_UINT8 ("i8051", cpu, "SP", &i8051.sp, 1);
state_save_register_UINT8 ("i8051", cpu, "DPL", &i8051.dpl, 1);
state_save_register_UINT8 ("i8051", cpu, "DPH", &i8051.dph, 1);
state_save_register_UINT8 ("i8051", cpu, "PCON", &i8051.pcon, 1);
state_save_register_UINT8 ("i8051", cpu, "TCON", &i8051.tcon, 1);
state_save_register_UINT8 ("i8051", cpu, "TMOD", &i8051.tmod, 1);
state_save_register_UINT8 ("i8051", cpu, "TL0", &i8051.tl0, 1);
state_save_register_UINT8 ("i8051", cpu, "TL1", &i8051.tl1, 1);
state_save_register_UINT8 ("i8051", cpu, "TH0", &i8051.th0, 1);
state_save_register_UINT8 ("i8051", cpu, "TH1", &i8051.th1, 1);
state_save_register_UINT8 ("i8051", cpu, "P1", &i8051.p1, 1);
state_save_register_UINT8 ("i8051", cpu, "SCON", &i8051.scon, 1);
state_save_register_UINT8 ("i8051", cpu, "SBUF", &i8051.sbuf, 1);
state_save_register_UINT8 ("i8051", cpu, "P2", &i8051.p2, 1);
state_save_register_UINT8 ("i8051", cpu, "IE", &i8051.ie, 1);
state_save_register_UINT8 ("i8051", cpu, "P3", &i8051.p3, 1);
state_save_register_UINT8 ("i8051", cpu, "IP", &i8051.ip, 1);
//8052 Only registers
#if (HAS_I8052 || HAS_I8752)
state_save_register_UINT8 ("i8051", cpu, "T2CON", &i8051.tcon, 1);
state_save_register_UINT8 ("i8051", cpu, "RCAP2L",&i8051.rcap2l, 1);
state_save_register_UINT8 ("i8051", cpu, "RCAP2H",&i8051.rcap2h, 1);
state_save_register_UINT8 ("i8051", cpu, "TL2", &i8051.tl2, 1);
state_save_register_UINT8 ("i8051", cpu, "TH2", &i8051.th2, 1);
#endif
state_save_register_UINT8 ("i8051", cpu, "PSW", &i8051.psw, 1);
state_save_register_UINT8 ("i8051", cpu, "ACC", &i8051.acc, 1);
state_save_register_UINT8 ("i8051", cpu, "B", &i8051.b, 1);
}
/* Reset registers to the initial values */
void i8051_reset(void *param)
{
memset(&i8051, 0, sizeof(I8051));
memset(&uart, 0, sizeof(I8051_UART));
i8051.subtype = 8051;
//Set up 8051 specific internal read/write (indirect) handlers..
i8051.iram_iread = internal_ram_read; //Indirect ram read/write handled the same as direct for 8051!
i8051.iram_iwrite = internal_ram_write; //Indirect ram read/write handled the same as direct for 8051!
//Set up serial call back handlers
i8051.serial_tx_callback = hold_serial_tx_callback;
hold_serial_tx_callback = NULL;
i8051.serial_rx_callback = hold_serial_rx_callback;
hold_serial_rx_callback = NULL;
//Setup External ram callback handlers
i8051.eram_iaddr_callback = hold_eram_iaddr_callback;
hold_eram_iaddr_callback = NULL;
//Clear Ram (w/0xff)
memset(&i8051.IntRam,0xff,sizeof(i8051.IntRam));
/* these are all defined reset states */
PC = 0;
SFR_W(SP, 0x7);
SFR_W(PSW, 0);
SFR_W(DPH, 0);
SFR_W(DPL, 0);
SFR_W(ACC, 0);
SFR_W(B, 0);
SFR_W(IP, 0);
SFR_W(IE, 0);
SFR_W(SCON, 0);
SFR_W(TCON, 0);
SFR_W(TMOD, 0);
SFR_W(TH1, 0);
SFR_W(TH0, 0);
SFR_W(TL1, 0);
SFR_W(TL0, 0);
/* set the port configurations to all 1's */
SFR_W(P3, 0xff);
SFR_W(P2, 0xff);
SFR_W(P1, 0xff);
SFR_W(P0, 0xff);
/* Flag as NO IRQ in Progress */
CLEAR_CURRENT_IRQ
#if FIXIRQ
CLR_INTS_BLOCKED;
#endif
}
/* Shut down CPU core */
void i8051_exit(void)
{
/* nothing to do */
}
/* Execute cycles - returns number of cycles actually run */
int i8051_execute(int cycles)
{
i8051_icount = cycles;
do
{
//Read next opcode
UINT8 op = cpu_readop(PC);
//Store previous PC
PPC = PC;
//Call Debugger
CALL_MAME_DEBUG;
//remove after testing
if(PC != PPC) op = cpu_readop(PC);
//Update Timer (if any timers are running)
if(R_TCON & 0x50)
update_timer(i8051.prev_used_cycles);
//Update Serial (if serial port sending data)
if(uart.sending)
update_serial(i8051.prev_used_cycles);
//Update PC
PC += 1;
//Decrement total count by # of cycles used for this opcode
i8051_icount -= (i8051_cycles[op]);
switch( op )
{
//NOP 12
case 0x00: /* 1: 0000 0000 */
nop();
break;
//AJMP code addr 24 /* 1: aaa0 0001 */
case 0x01:
ajmp();
break;
//LJMP code addr 24
case 0x02: /* 1: 0000 0010 */
ljmp();
break;
//RR A 12
case 0x03: /* 1: 0000 0011 */
rr_a();
break;
//INC A 12
case 0x04: /* 1: 0000 0100 */
inc_a();
break;
//INC data addr 12
case 0x05: /* 1: 0000 0101 */
RWM=1;
inc_mem();
RWM=0;
break;
//INC @R0/@R1 12 /* 1: 0000 011i */
case 0x06:
case 0x07:
inc_ir(op&1);
break;
//INC R0 to R7 12 /* 1: 0000 1rrr */
case 0x08:
case 0x09:
case 0x0a:
case 0x0b:
case 0x0c:
case 0x0d:
case 0x0e:
case 0x0f:
inc_r(op&7);
break;
//JBC bit addr, code addr 24
case 0x10: /* 1: 0001 0000 */
RWM=1;
jbc();
RWM=0;
break;
//ACALL code addr 24 /* 1: aaa1 0001 */
case 0x11:
acall();
break;
//LCALL code addr 24
case 0x12: /* 1: 0001 0010 */
lcall();
break;
//RRC A 12
case 0x13: /* 1: 0001 0011 */
rrc_a();
break;
//DEC A 12
case 0x14: /* 1: 0001 0100 */
dec_a();
break;
//DEC data addr 12
case 0x15: /* 1: 0001 0101 */
RWM=1;
dec_mem();
RWM=0;
break;
//DEC @R0/@R1 12 /* 1: 0001 011i */
case 0x16:
case 0x17:
dec_ir(op&1);
break;
//DEC R0 to R7 12 /* 1: 0001 1rrr */
case 0x18:
case 0x19:
case 0x1a:
case 0x1b:
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
dec_r(op&7);
break;
//JB bit addr, code addr 24
case 0x20: /* 1: 0010 0000 */
jb();
break;
//AJMP code addr 24 /* 1: aaa0 0001 */
case 0x21:
ajmp();
break;
//RET 24
case 0x22: /* 1: 0010 0010 */
ret();
break;
//RL A 12
case 0x23: /* 1: 0010 0011 */
rl_a();
break;
//ADD A, #data 12
case 0x24: /* 1: 0010 0100 */
add_a_byte();
break;
//ADD A, data addr 12
case 0x25: /* 1: 0010 0101 */
add_a_mem();
break;
//ADD A, @R0/@R1 12 /* 1: 0010 011i */
case 0x26:
case 0x27:
add_a_ir(op&1);
break;
//ADD A, R0 to R7 12 /* 1: 0010 1rrr */
case 0x28:
case 0x29:
case 0x2a:
case 0x2b:
case 0x2c:
case 0x2d:
case 0x2e:
case 0x2f:
add_a_r(op&7);
break;
//JNB bit addr, code addr 24
case 0x30: /* 1: 0011 0000 */
jnb();
break;
//ACALL code addr 24 /* 1: aaa1 0001 */
case 0x31:
acall();
break;
//RETI 24
case 0x32: /* 1: 0011 0010 */
reti();
break;
//RLC A 12
case 0x33: /* 1: 0011 0011 */
rlc_a();
break;
//ADDC A, #data 12
case 0x34: /* 1: 0011 0100 */
addc_a_byte();
break;
//ADDC A, data addr 12
case 0x35: /* 1: 0011 0101 */
addc_a_mem();
break;
//ADDC A, @R0/@R1 12 /* 1: 0011 011i */
case 0x36:
case 0x37:
addc_a_ir(op&1);
break;
//ADDC A, R0 to R7 12 /* 1: 0011 1rrr */
case 0x38:
case 0x39:
case 0x3a:
case 0x3b:
case 0x3c:
case 0x3d:
case 0x3e:
case 0x3f:
addc_a_r(op&7);
break;
//JC code addr 24
case 0x40: /* 1: 0100 0000 */
jc();
break;
//AJMP code addr 24 /* 1: aaa0 0001 */
case 0x41:
ajmp();
break;
//ORL data addr, A 12
case 0x42: /* 1: 0100 0010 */
RWM=1;
orl_mem_a();
RWM=0;
break;
//ORL data addr, #data 24
case 0x43: /* 1: 0100 0011 */
RWM=1;
orl_mem_byte();
RWM=0;
break;
//ORL A, #data 12
case 0x44: /* 1: 0100 0100 */
orl_a_byte();
break;
//ORL A, data addr 12
case 0x45: /* 1: 0100 0101 */
orl_a_mem();
break;
//ORL A, @RO/@R1 12 /* 1: 0100 011i */
case 0x46:
case 0x47:
orl_a_ir(op&1);
break;
//ORL A, RO to R7 12 /* 1: 0100 1rrr */
case 0x48:
case 0x49:
case 0x4a:
case 0x4b:
case 0x4c:
case 0x4d:
case 0x4e:
case 0x4f:
orl_a_r(op&7);
break;
//JNC code addr 24
case 0x50: /* 1: 0101 0000 */
jnc();
break;
//ACALL code addr 24 /* 1: aaa1 0001 */
case 0x51:
acall();
break;
//ANL data addr, A
case 0x52: /* 1: 0101 0010 */
RWM=1;
anl_mem_a();
RWM=0;
break;
//ANL data addr, #data 24
case 0x53: /* 1: 0101 0011 */
RWM=1;
anl_mem_byte();
RWM=0;
break;
//ANL A, #data 12
case 0x54: /* 1: 0101 0100 */
anl_a_byte();
break;
//ANL A, data addr 12
case 0x55: /* 1: 0101 0101 */
anl_a_mem();
break;
//ANL A, @RO/@R1 12 /* 1: 0101 011i */
case 0x56:
case 0x57:
anl_a_ir(op&1);
break;
//ANL A, RO to R7 12 /* 1: 0101 1rrr */
case 0x58:
case 0x59:
case 0x5a:
case 0x5b:
case 0x5c:
case 0x5d:
case 0x5e:
case 0x5f:
anl_a_r(op&7);
break;
//JZ code addr 24
case 0x60: /* 1: 0110 0000 */
jz();
break;
//AJMP code addr 24 /* 1: aaa0 0001 */
case 0x61:
ajmp();
break;
//XRL data addr, A 12
case 0x62: /* 1: 0110 0010 */
RWM=1;
xrl_mem_a();
RWM=0;
break;
//XRL data addr, #data 24
case 0x63: /* 1: 0110 0011 */
RWM=1;
xrl_mem_byte();
RWM=0;
break;
//XRL A, #data 12
case 0x64: /* 1: 0110 0100 */
xrl_a_byte();
break;
//XRL A, data addr 12
case 0x65: /* 1: 0110 0101 */
xrl_a_mem();
break;
//XRL A, @R0/@R1 12 /* 1: 0110 011i */
case 0x66:
case 0x67:
xrl_a_ir(op&1);
break;
//XRL A, R0 to R7 12 /* 1: 0110 1rrr */
case 0x68:
case 0x69:
case 0x6a:
case 0x6b:
case 0x6c:
case 0x6d:
case 0x6e:
case 0x6f:
xrl_a_r(op&7);
break;
//JNZ code addr 24
case 0x70: /* 1: 0111 0000 */
jnz();
break;
//ACALL code addr 24 /* 1: aaa1 0001 */
case 0x71:
acall();
break;
//ORL C, bit addr 24
case 0x72: /* 1: 0111 0010 */
orl_c_bitaddr();
break;
//JMP @A+DPTR 24
case 0x73: /* 1: 0111 0011 */
jmp_iadptr();
break;
//MOV A, #data 12
case 0x74: /* 1: 0111 0100 */
mov_a_byte();
break;
//MOV data addr, #data 24
case 0x75: /* 1: 0111 0101 */
mov_mem_byte();
break;
//MOV @R0/@R1, #data 12 /* 1: 0111 011i */
case 0x76:
case 0x77:
mov_ir_byte(op&1);
break;
//MOV R0 to R7, #data 12 /* 1: 0111 1rrr */
case 0x78:
case 0x79:
case 0x7a:
case 0x7b:
case 0x7c:
case 0x7d:
case 0x7e:
case 0x7f:
mov_r_byte(op&7);
break;
//SJMP code addr 24
case 0x80: /* 1: 1000 0000 */
sjmp();
break;
//AJMP code addr 24 /* 1: aaa0 0001 */
case 0x81:
ajmp();
break;
//ANL C, bit addr 24
case 0x82: /* 1: 1000 0010 */
anl_c_bitaddr();
break;
//MOVC A, @A + PC 24
case 0x83: /* 1: 1000 0011 */
movc_a_iapc();
break;
//DIV AB 48
case 0x84: /* 1: 1000 0100 */
div_ab();
break;
//MOV data addr, data addr 24
case 0x85: /* 1: 1000 0101 */
mov_mem_mem();
break;
//MOV data addr, @R0/@R1 24 /* 1: 1000 011i */
case 0x86:
case 0x87:
mov_mem_ir(op&1);
break;
//MOV data addr,R0 to R7 24 /* 1: 1000 1rrr */
case 0x88:
case 0x89:
case 0x8a:
case 0x8b:
case 0x8c:
case 0x8d:
case 0x8e:
case 0x8f:
mov_mem_r(op&7);
break;
//MOV DPTR, #data 24
case 0x90: /* 1: 1001 0000 */
mov_dptr_byte();
break;
//ACALL code addr 24 /* 1: aaa1 0001 */
case 0x91:
acall();
break;
//MOV bit addr, C 24
case 0x92: /* 1: 1001 0010 */
RWM = 1;
mov_bitaddr_c();
RWM = 0;
break;
//MOVC A, @A + DPTR 24
case 0x93: /* 1: 1001 0011 */
movc_a_iadptr();
break;
//SUBB A, #data 12
case 0x94: /* 1: 1001 0100 */
subb_a_byte();
break;
//SUBB A, data addr 12
case 0x95: /* 1: 1001 0101 */
subb_a_mem();
break;
//SUBB A, @R0/@R1 12 /* 1: 1001 011i */
case 0x96:
case 0x97:
subb_a_ir(op&1);
break;
//SUBB A, R0 to R7 12 /* 1: 1001 1rrr */
case 0x98:
case 0x99:
case 0x9a:
case 0x9b:
case 0x9c:
case 0x9d:
case 0x9e:
case 0x9f:
subb_a_r(op&7);
break;
//ORL C, /bit addr 24
case 0xa0: /* 1: 1010 0000 */
orl_c_nbitaddr();
break;
//AJMP code addr 24 /* 1: aaa0 0001 */
case 0xa1:
ajmp();
break;
//MOV C, bit addr 12
case 0xa2: /* 1: 1010 0010 */
mov_c_bitaddr();
break;
//INC DPTR 24
case 0xa3: /* 1: 1010 0011 */
inc_dptr();
break;
//MUL AB 48
case 0xa4: /* 1: 1010 0100 */
mul_ab();
break;
//reserved
case 0xa5: /* 1: 1010 0101 */
illegal();
break;
//MOV @R0/@R1, data addr 24 /* 1: 1010 011i */
case 0xa6:
case 0xa7:
mov_ir_mem(op&1);
break;
//MOV R0 to R7, data addr 24 /* 1: 1010 1rrr */
case 0xa8:
case 0xa9:
case 0xaa:
case 0xab:
case 0xac:
case 0xad:
case 0xae:
case 0xaf:
mov_r_mem(op&7);
break;
//ANL C,/bit addr 24
case 0xb0: /* 1: 1011 0000 */
anl_c_nbitaddr();
break;
//ACALL code addr 24 /* 1: aaa1 0001 */
case 0xb1:
acall();
break;
//CPL bit addr 12
case 0xb2: /* 1: 1011 0010 */
RWM=1;
cpl_bitaddr();
RWM=0;
break;
//CPL C 12
case 0xb3: /* 1: 1011 0011 */
cpl_c();
break;
//CJNE A, #data, code addr 24
case 0xb4: /* 1: 1011 0100 */
cjne_a_byte();
break;
//CJNE A, data addr, code addr 24
case 0xb5: /* 1: 1011 0101 */
cjne_a_mem();
break;
//CJNE @R0/@R1, #data, code addr 24 /* 1: 1011 011i */
case 0xb6:
case 0xb7:
cjne_ir_byte(op&1);
break;
//CJNE R0 to R7, #data, code addr 24 /* 1: 1011 1rrr */
case 0xb8:
case 0xb9:
case 0xba:
case 0xbb:
case 0xbc:
case 0xbd:
case 0xbe:
case 0xbf:
cjne_r_byte(op&7);
break;
//PUSH data addr 24
case 0xc0: /* 1: 1100 0000 */
push();
break;
//AJMP code addr 24 /* 1: aaa0 0001 */
case 0xc1:
ajmp();
break;
//CLR bit addr 12
case 0xc2: /* 1: 1100 0010 */
RWM=1;
clr_bitaddr();
RWM=0;
break;
//CLR C 12
case 0xc3: /* 1: 1100 0011 */
clr_c();
break;
//SWAP A 12
case 0xc4: /* 1: 1100 0100 */
swap_a();
break;
//XCH A, data addr 12
case 0xc5: /* 1: 1100 0101 */
xch_a_mem();
break;
//XCH A, @RO/@R1 12 /* 1: 1100 011i */
case 0xc6:
case 0xc7:
xch_a_ir(op&1);
break;
//XCH A, RO to R7 12 /* 1: 1100 1rrr */
case 0xc8:
case 0xc9:
case 0xca:
case 0xcb:
case 0xcc:
case 0xcd:
case 0xce:
case 0xcf:
xch_a_r(op&7);
break;
//POP data addr 24
case 0xd0: /* 1: 1101 0000 */
pop();
break;
//ACALL code addr 24 /* 1: aaa1 0001 */
case 0xd1:
acall();
break;
//SETB bit addr 12
case 0xd2: /* 1: 1101 0010 */
RWM=1;
setb_bitaddr();
RWM=0;
break;
//SETB C 12
case 0xd3: /* 1: 1101 0011 */
setb_c();
break;
//DA A 12
case 0xd4: /* 1: 1101 0100 */
da_a();
break;
//DJNZ data addr, code addr 24
case 0xd5: /* 1: 1101 0101 */
RWM=1;
djnz_mem();
RWM=0;
break;
//XCHD A, @R0/@R1 12 /* 1: 1101 011i */
case 0xd6:
case 0xd7:
xchd_a_ir(op&1);
break;
//DJNZ R0 to R7,code addr 24 /* 1: 1101 1rrr */
case 0xd8:
case 0xd9:
case 0xda:
case 0xdb:
case 0xdc:
case 0xdd:
case 0xde:
case 0xdf:
djnz_r(op&7);
break;
//MOVX A,@DPTR 24
case 0xe0: /* 1: 1110 0000 */
movx_a_idptr();
break;
//AJMP code addr 24 /* 1: aaa0 0001 */
case 0xe1:
ajmp();
break;
//MOVX A, @R0/@R1 24 /* 1: 1110 001i */
case 0xe2:
case 0xe3:
movx_a_ir(op&1);
break;
//CLR A 12
case 0xe4: /* 1: 1110 0100 */
clr_a();
break;
//MOV A, data addr 12
case 0xe5: /* 1: 1110 0101 */
mov_a_mem();
break;
//MOV A,@RO/@R1 12 /* 1: 1110 011i */
case 0xe6:
case 0xe7:
mov_a_ir(op&1);
break;
//MOV A,R0 to R7 12 /* 1: 1110 1rrr */
case 0xe8:
case 0xe9:
case 0xea:
case 0xeb:
case 0xec:
case 0xed:
case 0xee:
case 0xef:
mov_a_r(op&7);
break;
//MOVX @DPTR,A 24
case 0xf0: /* 1: 1111 0000 */
movx_idptr_a();
break;
//ACALL code addr 24 /* 1: aaa1 0001 */
case 0xf1:
acall();
break;
//MOVX @R0/@R1,A 12 /* 1: 1111 001i */
case 0xf2:
case 0xf3:
movx_ir_a(op&1);
break;
//CPL A 12
case 0xf4: /* 1: 1111 0100 */
cpl_a();
break;
//MOV data addr, A 12
case 0xf5: /* 1: 1111 0101 */
mov_mem_a();
break;
//MOV @R0/@R1, A 12 /* 1: 1111 011i */
case 0xf6:
case 0xf7:
mov_ir_a(op&1);
break;
//MOV R0 to R7, A 12 /* 1: 1111 1rrr */
case 0xf8:
case 0xf9:
case 0xfa:
case 0xfb:
case 0xfc:
case 0xfd:
case 0xfe:
case 0xff:
mov_r_a(op&7);
break;
default:
illegal();
}
//Store # of used cycles for this opcode (for timer & serial check at top of code)
i8051.prev_used_cycles = i8051_cycles[op];
//Check for pending interrupts & handle - remove cycles used
i8051_icount-=check_interrupts();
#if FIXIRQ
CLR_INTS_BLOCKED;
#endif
} while( i8051_icount > 0 );
return cycles - i8051_icount;
}
/* Get registers, return context size */
unsigned i8051_get_context(void *dst)
{
if( dst )
memcpy(dst, &i8051, sizeof(I8051));
return sizeof(I8051);
}
/* Set registers */
void i8051_set_context(void *src)
{
if( src )
memcpy(&i8051, src, sizeof(I8051));
}
/*NOTE: These are not used by the opcode functions, they are here only for MAME requirements*/
unsigned i8051_get_reg(int regnum)
{
switch( regnum )
{
case REG_PREVIOUSPC: return PPC;
case REG_PC:
case I8051_PC: return PC;
case REG_SP:
case I8051_SP: return R_SP;
case I8051_ACC: return R_ACC;
case I8051_PSW: return R_PSW;
case I8051_B: return R_B;
case I8051_DPH: return R_DPH;
case I8051_DPL: return R_DPL;
case I8051_IE: return R_IE;
//Not real registers
case I8051_R0: return R_R(0);
case I8051_R1: return R_R(1);
case I8051_R2: return R_R(2);
case I8051_R3: return R_R(3);
case I8051_R4: return R_R(4);
case I8051_R5: return R_R(5);
case I8051_R6: return R_R(6);
case I8051_R7: return R_R(7);
case I8051_RB: return GET_RS;
default:
return 0;
}
return 0;
}
/*NOTE: These are not used by the opcode functions, they are here only for MAME requirements*/
void i8051_set_reg (int regnum, unsigned val)
{
switch( regnum )
{
case REG_PC:
case I8051_PC: PC = val & 0xffff; break;
case REG_SP:
case I8051_SP: SFR_W(SP,val); break; //Use SFR to handle error checking
case I8051_ACC: SFR_W(ACC,val); break;
case I8051_PSW: SFR_W(PSW,val); break;
case I8051_B: SFR_W(B,val); break;
case I8051_DPH: SFR_W(DPH,val); break;
case I8051_DPL: SFR_W(DPL,val); break;
case I8051_IE: SFR_W(IE,val); break;
//Not real registers
case I8051_R0: R_R(0) = val; break;
case I8051_R1: R_R(1) = val; break;
case I8051_R2: R_R(2) = val; break;
case I8051_R3: R_R(3) = val; break;
case I8051_R4: R_R(4) = val; break;
case I8051_R5: R_R(5) = val; break;
case I8051_R6: R_R(6) = val; break;
case I8051_R7: R_R(7) = val; break;
case I8051_RB: SET_RS( (val&3) ); break;
default:
return;
}
}
void i8051_set_irq_line(int irqline, int state)
{
switch( irqline )
{
//External Interrupt 0
case I8051_INT0_LINE:
//Line Asserted?
if (state != CLEAR_LINE) {
//Is the enable flag for this interrupt set?
if(GET_EX0) {
//Need cleared->active line transition? (Logical 1-0 Pulse on the line) - CLEAR->ASSERT Transition since INT0 active lo!
if(GET_IT0){
if(i8051.last_int0 == CLEAR_LINE)
SET_IE0(1);
}
else
SET_IE0(1); //Nope, just set it..
}
}
else
SET_IE0(0); //Clear Int occurred flag
i8051.last_int0 = state;
//Do the interrupt & handle - remove machine cycles used
if(GET_IE0)
i8051_icount-=check_interrupts();
break;
//External Interrupt 1
case I8051_INT1_LINE:
//Line Asserted?
if (state != CLEAR_LINE) {
if(GET_EX1) {
//Need cleared->active line transition? (Logical 1-0 Pulse on the line) - CLEAR->ASSERT Transition since INT1 active lo!
if(GET_IT1){
if(i8051.last_int1 == CLEAR_LINE)
SET_IE1(1);
}
else
SET_IE1(1); //Nope, just set it..
}
}
else
SET_IE1(0); //Clear Int occurred flag
i8051.last_int1 = state;
//Do the interrupt & handle - remove machine cycles used
if(GET_IE1)
i8051_icount-=check_interrupts();
break;
//Serial Port Receive
case I8051_RX_LINE:
//Is the enable flags for this interrupt set?
if(GET_ES && GET_REN) {
int data = 0;
//Call our callball function to retrieve the data
if(i8051.serial_rx_callback)
data = i8051.serial_rx_callback();
//Update the register directly, since SFR_W() will trigger a serial transmit instead!
R_SBUF=data;
//Flag the IRQ
SET_RI(1);
}
break;
//Note: we won't call check interrupts, we'll let the main loop catch it
}
}
/***********************************************************************************
Check for pending Interrupts and process - returns # of cycles used for the int
Note about priority & interrupting interrupts..
1) A high priority interrupt cannot be interrupted by anything!
2) A low priority interrupt can ONLY be interrupted by a high priority interrupt
3) If more than 1 Interrupt Flag is set (ie, 2 simultaneous requests occur),
the following logic works as follows:
1) If two requests come in of different priority levels, the higher one is selected..
2) If the requests are of the same level, an internal order is used:
a) IEO
b) TFO
c) IE1
d) TF1
e) RI+TI
f) TF2+EXF2
**********************************************************************************/
INLINE UINT8 check_interrupts(void)
{
#if FIXIRQ
//Interrupts blocked by RETI or IE-/IP-write
if(GET_INTS_BLOCKED) return 0;
#endif
//If All Inerrupts Disabled or no pending abort..
if(!GET_EA) return 0;
//Any Interrupts Pending?
if(NO_PENDING_IRQ) return 0;
//Skip if current irq in progress is high priority!
if(i8051.irq_priority) { /* LOG(("high priority irq in progress, skipping irq request\n")); */ return 0; }
//Check which interrupt(s) requests have occurred..
//NOTE: The order of checking is based on the internal/default priority levels when levels are the same
//External Int 0
if(GET_IE0) {
//Set vector & priority level request
i8051.int_vec = V_IE0;
i8051.priority_request = GET_PX0;
}
//Timer 0 overflow
if(!i8051.priority_request && GET_TF0 && (!i8051.int_vec || (i8051.int_vec && GET_PT0))) {
//Set vector & priority level request
i8051.int_vec = V_TF0;
i8051.priority_request = GET_PT0;
}
//External Int 1
if(!i8051.priority_request && GET_IE1 && (!i8051.int_vec || (i8051.int_vec && GET_PX1))) {
//Set vector & priority level request
i8051.int_vec = V_IE1;
i8051.priority_request = GET_PX1;
}
//Timer 1 overflow
if(!i8051.priority_request && GET_TF1 && (!i8051.int_vec || (i8051.int_vec && GET_PT1))) {
//Set vector & priority level request
i8051.int_vec = V_TF1;
i8051.priority_request = GET_PT1;
}
//Serial Interrupt Transmit/Receive Interrupts (Note: ES Bit - Serial Interrupts must be enabled)
if(!i8051.priority_request && GET_ES && (GET_TI || GET_RI) && (!i8051.int_vec || (i8051.int_vec && GET_PS))) {
//Set vector & priority level request
i8051.int_vec = V_RITI;
i8051.priority_request = GET_PS;
}
#if (HAS_I8052 || HAS_I8752)
//Timer 2 overflow (Either Timer Overflow OR External Interrupt)
#ifdef PINMAME // otherwise no sound on spinball games
if(!i8051.priority_request && (GET_TF2 || GET_EXF2) && (!i8051.int_vec || (i8051.int_vec && GET_PT2))) {
#else
if(!i8051.priority_request && GET_ET2 && (GET_TF2 || GET_EXF2) && (!i8051.int_vec || (i8051.int_vec && GET_PT2))) {
#endif //Set vector & priority level request
i8051.int_vec = V_TF2;
i8051.priority_request = GET_PT2;
}
#endif
//Skip the interrupt request if currently processing is lo priority, and the new request IS NOT HI PRIORITY!
if(i8051.cur_irq < 0xff && !i8051.priority_request)
{ LOG(("low priority irq in progress already, skipping low irq request\n")); return 0; }
/*** --- Perform the interrupt --- ***/
//Save current pc to stack, set pc to new interrupt vector
push_pc();
PC = i8051.int_vec;
//Set current Irq & Priority being serviced
i8051.cur_irq = i8051.int_vec;
i8051.irq_priority = i8051.priority_request;
//Clear any interrupt flags that should be cleared since we're servicing the irq!
switch(i8051.cur_irq) {
case V_IE0:
//External Int Flag only cleared when configured as Edge Triggered..
//if(GET_IT0) - for some reason having this, breaks alving dmd games
SET_IE0(0);
break;
case V_TF0:
//Timer 0 - Always clear Flag
SET_TF0(0);
break;
case V_IE1:
//External Int Flag only cleared when configured as Edge Triggered..
//if(GET_IT1) - for some reason having this, breaks alving dmd games
SET_IE1(0);
break;
case V_TF1:
//Timer 0 - Always clear Flag
SET_TF1(0);
break;
case V_RITI:
// no flags are cleared, TI and RI remain set until reset by software
break;
case V_TF2:
// no flags are cleared according to manual
break;
}
//Clear vars.. (these are part of the 8051 structure for speed, so we don't have to dynamically allocate space each time)
i8051.int_vec = 0;
i8051.priority_request = 0;
//All interrupts use 2 machine cycles
return 24;
}
void i8051_set_irq_callback(int (*callback)(int irqline))
{
i8051.irq_callback = callback;
}
void i8051_set_serial_tx_callback(void (*callback)(int data))
{
//Hold in static variable since this function can get called before reset has run, which wipes i8051 memory clean
hold_serial_tx_callback = callback;
}
void i8051_set_serial_rx_callback(int (*callback)(void))
{
//Hold in static variable since this function can get called before reset has run, which wipes i8051 memory clean
hold_serial_rx_callback = callback;
}
void i8051_set_eram_iaddr_callback(READ32_HANDLER((*callback)))
{
//Hold in static variable since this function can get called before reset has run, which wipes i8051 memory clean
hold_eram_iaddr_callback = callback;
}
void i8051_state_save(void *file)
{
}
void i8051_state_load(void *file)
{
}
//This function is used to display the registers/flags, etc.. in the dissassembler window
//Note: Make sure to use r-> rather than direct references to the i8051 structure (contained in macros)
const char *i8051_info(void *context, int regnum)
{
static char buffer[19][20];
static int which = 0;
I8051 *r = (I8051*)context;
which = (which+1) % 19;
buffer[which][0] = '\0';
if( !context )
r = &i8051;
switch( regnum )
{
case CPU_INFO_REG+I8051_PC: sprintf(buffer[which], "PC:%04X", r->pc); break;
case CPU_INFO_REG+I8051_SP: sprintf(buffer[which], "SP:%02X", r->sp); break;
case CPU_INFO_REG+I8051_PSW:sprintf(buffer[which], "PSW:%02X", r->psw); break;
case CPU_INFO_REG+I8051_ACC:sprintf(buffer[which], "A:%02X", r->acc); break;
case CPU_INFO_REG+I8051_B: sprintf(buffer[which], "B:%02X", r->b); break;
case CPU_INFO_REG+I8051_DPH:sprintf(buffer[which], "DPH:%02X", r->dph); break;
case CPU_INFO_REG+I8051_DPL:sprintf(buffer[which], "DPL:%02X", r->dpl); break;
case CPU_INFO_REG+I8051_IE: sprintf(buffer[which], "IE:%02X", r->ie); break;
case CPU_INFO_REG+I8051_R0: sprintf(buffer[which], "R0:%02X", r->IntRam[0+(8*((r->psw & 0x18)>>3))]); break;
case CPU_INFO_REG+I8051_R1: sprintf(buffer[which], "R1:%02X", r->IntRam[1+(8*((r->psw & 0x18)>>3))]); break;
case CPU_INFO_REG+I8051_R2: sprintf(buffer[which], "R2:%02X", r->IntRam[2+(8*((r->psw & 0x18)>>3))]); break;
case CPU_INFO_REG+I8051_R3: sprintf(buffer[which], "R3:%02X", r->IntRam[3+(8*((r->psw & 0x18)>>3))]); break;
case CPU_INFO_REG+I8051_R4: sprintf(buffer[which], "R4:%02X", r->IntRam[4+(8*((r->psw & 0x18)>>3))]); break;
case CPU_INFO_REG+I8051_R5: sprintf(buffer[which], "R5:%02X", r->IntRam[5+(8*((r->psw & 0x18)>>3))]); break;
case CPU_INFO_REG+I8051_R6: sprintf(buffer[which], "R6:%02X", r->IntRam[6+(8*((r->psw & 0x18)>>3))]); break;
case CPU_INFO_REG+I8051_R7: sprintf(buffer[which], "R7:%02X", r->IntRam[7+(8*((r->psw & 0x18)>>3))]); break;
case CPU_INFO_REG+I8051_RB: sprintf(buffer[which], "RB:%02X", ((r->psw & 0x18)>>3)); break;
case CPU_INFO_FLAGS:
sprintf(buffer[which], "%c%c%c%c%c%c%c%c",
(r->psw & 0x80) ? 'C':'.',
(r->psw & 0x40) ? 'A':'.',
(r->psw & 0x20) ? 'F':'.',
(r->psw & 0x10) ? '0':'.',
(r->psw & 0x08) ? '1':'.',
(r->psw & 0x04) ? 'V':'.',
(r->psw & 0x02) ? '?':'.',
(r->psw & 0x01) ? 'P':'.');
break;
case CPU_INFO_NAME: return "I8051";
case CPU_INFO_FAMILY: return "Intel 8051";
case CPU_INFO_VERSION: return "0.1";
case CPU_INFO_FILE: return __FILE__;
case CPU_INFO_CREDITS: return "Copyright (c) 2003 <NAME>, all rights reserved.";
case CPU_INFO_REG_LAYOUT: return (const char*)i8051_reg_layout;
case CPU_INFO_WIN_LAYOUT: return (const char*)i8051_win_layout;
}
return buffer[which];
}
unsigned i8051_dasm(char *buffer, unsigned pc)
{
#ifdef MAME_DEBUG
return Dasm8051( buffer, pc );
#else
sprintf( buffer, "$%02X", cpu_readop(pc) );
return 1;
#endif
}
/* HELPER FUNCTIONS */
/*All writes to SFR are handled here*/
static WRITE_HANDLER(sfr_write)
{
data &= 0xff; //Ensure only 8 bits
switch (offset)
{
case P0:
R_P0 = data;
OUT(0,data);
break;
case SP:
//if(offset > 0xff) //!! wrong check
// LOG(("i8051 #%d: attemping to write value to SP past 256 bytes at 0x%04x\n", cpu_getactivecpu(), PC));
R_SP = data&0xff; //keep sp w/in 256 bytes
break;
case DPL: R_DPL = data; break;
case DPH: R_DPH = data; break;
case PCON: R_PCON= data; break;
case TCON: R_TCON= data; break;
case TMOD: R_TMOD= data; break;
case TL0: R_TL0 = data; break;
case TL1: R_TL1 = data; break;
case TH0: R_TH0 = data; break;
case TH1: R_TH1 = data; break;
case P1:
R_P1 = data;
OUT(1,data);
break;
case SCON: {
//Update register
R_SCON = data;
break;
}
case SBUF:
//R_SBUF = data; //This register is used only for "Receiving data coming in!"
serial_transmit(data); //Set up to transmit the data
break;
case P2:
R_P2 = data;
OUT(2,data);
break;
case IE:
R_IE = data;
#if FIXIRQ
SET_INTS_BLOCKED;
#endif
break;
case P3:
R_P3 = data;
OUT(3,data);
break;
case IP:
R_IP = data;
#if FIXIRQ
SET_INTS_BLOCKED;
#endif
break;
//8052 Only registers
#if (HAS_I8052 || HAS_I8752)
case T2CON: R_T2CON = data; break;
case RCAP2L: R_RCAP2L = data; break;
case RCAP2H: R_RCAP2H = data; break;
case TL2: R_TL2 = data; break;
case TH2: R_TH2 = data; break;
#endif
case PSW:
R_PSW = data;
SET_PARITY;
break;
case ACC:
R_ACC = data;
SET_PARITY;
break;
case B: R_B = data; break;
/* Illegal or non-implemented sfr */
default:
LOG(("i8051 #%d: attemping to write to an invalid/non-implemented SFR address: %x at 0x%04x, data=%x\n", cpu_getactivecpu(), offset,PC,data));
}
}
/*All reads to SFR are handled here*/
static READ_HANDLER(sfr_read)
{
switch (offset)
{
case P0:
if(RWM)
return R_P0; //Read directly from port latch
else
return IN(0); //Read from actual port
case SP: return R_SP;
case DPL: return R_DPL;
case DPH: return R_DPH;
case PCON: return R_PCON;
case TCON: return R_TCON;
case TMOD: return R_TMOD;
case TL0: return R_TL0;
case TL1: return R_TL1;
case TH0: return R_TH0;
case TH1: return R_TH1;
case P1:
if(RWM)
return R_P1; //Read directly from port latch
else
return IN(1); //Read from actual port
case SCON: return R_SCON;
case SBUF: return R_SBUF;
case P2:
if(RWM)
return R_P2; //Read directly from port latch
else
return IN(2); //Read from actual port
case IE: return R_IE;
case P3:
if(RWM)
return R_P3; //Read directly from port latch
else
return IN(3); //Read from actual port
case IP: return R_IP;
//8052 Only registers
#if (HAS_I8052 || HAS_I8752)
case T2CON: return R_T2CON;
case RCAP2L: return R_RCAP2L;
case RCAP2H: return R_RCAP2H;
case TL2: return R_TL2;
case TH2: return R_TH2;
#endif
case PSW: return R_PSW;
case ACC: return R_ACC;
case B: return R_B;
/* Illegal or non-implemented sfr */
default:
LOG(("i8051 #%d: attemping to read an invalid/non-implemented SFR address: %x at 0x%04x\n", cpu_getactivecpu(), offset,PC));
}
return 0xff;
}
/* Reads the contents of the Internal RAM memory */
/* Anything above 0x7f is a sfr/register */
static READ_HANDLER(internal_ram_read)
{
if (offset < 0x80)
return i8051.IntRam[offset];
else {
if (offset < 0x100)
return SFR_R(offset);
else
LOG(("i8051 #%d: attemping to read from an invalid Internal Ram address: %x at 0x%04x\n", cpu_getactivecpu(), offset,PC));
}
return 0xff;
}
/* Writes the contents of the Internal RAM memory */
/* Anything above 0x7f is a sfr/register */
static WRITE_HANDLER(internal_ram_write)
{
data &= 0xff; //Ensure it's only 8 bits
if (offset < 0x80)
i8051.IntRam[offset] = data;
else {
if (offset < 0x100)
SFR_W(offset,data);
else
LOG(("i8051 #%d: attemping to write to invalid Internal Ram address: %x at 0x%04x\n", cpu_getactivecpu(), offset,PC));
}
}
/* Reads the contents of the Internal RAM memory (BUT CALLED FROM AN INDIRECT ADDRESSING MODE) */
/* Different chip types handle differently, for speed, simply call the chip's handler */
static READ_HANDLER(internal_ram_iread)
{
return i8051.iram_iread(offset);
}
/* Writes the contents of the Internal RAM memory (BUT CALLED FROM AN INDIRECT ADDRESSING MODE) */
/* Different chip types handle differently, for speed, simply call the chip's handler */
static WRITE_HANDLER(internal_ram_iwrite)
{
i8051.iram_iwrite(offset,data);
}
/*Generate an external ram address for read/writing using indirect addressing mode */
/*The lowest 8 bits of the address are passed in (from the R0/R1 register), however
the hardware can be configured to set the rest of the address lines to any available output port pins, which
means the only way we can implement this is to allow the driver to setup a callback to generate the
address as defined by the specific hardware setup. We'll assume the address won't be bigger than 32 bits
*/
static READ32_HANDLER(external_ram_iaddr)
{
if(i8051.eram_iaddr_callback)
return i8051.eram_iaddr_callback(offset,mem_mask);
else
LOG(("i8051 #%d: external ram address requested (8 bit offset=%02x), but no callback available! at PC:%04x\n", cpu_getactivecpu(), offset, PC));
return offset;
}
/*Push the current PC to the stack*/
INLINE void push_pc()
{
UINT8 tmpSP = R_SP; //Grab and Increment Stack Pointer
tmpSP++; // ""
SFR_W(SP,tmpSP); // ""
if (tmpSP == R_SP) //Ensure it was able to write to new stack location
IRAM_IW(tmpSP, (PC & 0xff)); //Store low byte of PC to Internal Ram (Use IRAM_IW to store stack above 128 bytes)
tmpSP = R_SP; //Increment Stack Pointer
tmpSP++; // ""
SFR_W(SP,tmpSP); // ""
if (tmpSP == R_SP) //Ensure it was able to write to new stack location
IRAM_IW(tmpSP, ( (PC & 0xff00) >> 8)); //Store hi byte of PC to next address in Internal Ram (Use IRAM_IW to store stack above 128 bytes)
}
/*Pop the current PC off the stack and into the pc*/
INLINE void pop_pc()
{
UINT8 tmpSP = R_SP; //Grab Stack Pointer
PC = (IRAM_IR(tmpSP) & 0xff) << 8; //Store hi byte to PC (must use IRAM_IR to access stack pointing above 128 bytes)
tmpSP = R_SP-1; //Decrement Stack Pointer
SFR_W(SP,tmpSP); // ""
if (tmpSP == R_SP) //Ensure it was able to write to new stack location
PC = PC | IRAM_IR(tmpSP); //Store lo byte to PC (must use IRAM_IR to access stack pointing above 128 bytes)
SFR_W(SP,tmpSP-1); //Decrement Stack Pointer
}
//Set the PSW Parity Flag
INLINE void set_parity()
{
//This flag will be set when the accumulator contains an odd # of bits set..
int i,
p = 0;
for (i=1; i<=128; i=i*2) { //Test for each of the 8 bits in the ACC!
if ((R_ACC & i) != 0)
p++; //Keep track of how many bits are set
}
//Update the PSW Pairty bit
SET_P(p & 1);
}
static READ_HANDLER(bit_address_r)
{
int word;
int mask;
int bit_pos;
int base; /* base of bit space or sfr */
int distance; /* distance between bit addressable words */
/* 1 for normal bits, 8 for sfr bit addresses */
offset &= 0xff;
//User defined bit addresses 0x20-0x2f (values are 0x0-0x7f)
if (offset < 0x80) {
base = 0x20;
distance = 1;
}
//SFR bit addressable registers
else {
base = 0x80;
distance = 8;
}
word = ( (offset & 0x78) >> 3) * distance + base;
bit_pos = offset & 0x7;
mask = 0x1 << bit_pos;
return((IRAM_R(word) & mask) >> bit_pos); //Do not use IRAM_IR
}
static WRITE_HANDLER(bit_address_w)
{
int word;
int mask;
int bit_pos;
int result;
int base;
int distance;
offset &= 0xff;
//User defined bit addresses 0x20-0x2f (values are 0x0-0x7f)
if (offset < 0x80) {
base = 0x20;
distance = 1;
}
//SFR bit addressable registers
else {
base = 0x80;
distance = 8;
}
word = ((offset & 0x78) >> 3) * distance + base;
bit_pos = offset & 0x7;
data = (data & 0x1) << bit_pos;
mask = ~(1 << bit_pos) & 0xff;
result = IRAM_R(word) & mask; //Do not use IRAM_IR
result = result | data;
IRAM_W(word, result); //Do not use IRAM_IW
}
/* The following two handlers are used by the MAME Debugger Memory Window...
By keeping these functions separate from the internally used IRAM_W/IRAM_R functions,
we can manipulate and display internal memory in the debugger memory window in a layout
that is not necessarily how the real memory is.. this will be especially useful for
the 8052 chip where both the SFR and the upper 128 bytes of ram are mapped to the same
address, so we can handle that here by mapping the sfr to a different address */
READ_HANDLER(i8051_internal_r)
{
//Restrict internal ram to 256 Bytes max
if(offset < 0x100)
return IRAM_R(offset);
else
return 0;
}
WRITE_HANDLER(i8051_internal_w)
{
//Restrict internal ram to 256 Bytes max
if(offset < 0x100)
IRAM_W(offset,data);
}
INLINE void do_add_flags(UINT8 a, UINT8 data, UINT8 c)
{
UINT16 result = a+data+c;
INT16 result1 = (INT8)a+(INT8)data+c;
int cy, ac, ov;
cy = (result & 0x100) >> 8;
result = (a&0x0f)+(data&0x0f)+c;
ac = (result & 0x10) >> 4;
ov = (result1 < -128 || result1 > 127);
SET_CY(cy);
SET_AC(ac);
SET_OV(ov);
#ifdef MAME_DEBUG
// printf("add: result=%x, c=%x, ac=%x, ov=%x\n",a+data+c,cy,ac,ov);
#endif
}
INLINE void do_sub_flags(UINT8 a, UINT8 data, UINT8 c)
{
UINT16 result = a-(data+c);
INT16 result1 = (INT8)a-(INT8)(data+c);
int cy, ac, ov;
cy = (result & 0x100) >> 8;
result = (a&0x0f)-((data&0x0f)+c);
ac = (result & 0x10) >> 4;
ov = (result1 < -128 || result1 > 127);
SET_CY(cy);
SET_AC(ac);
SET_OV(ov);
#ifdef MAME_DEBUG
// printf("sub: a=%x, d=%x, c=%x, result=%x, cy=%x, ac=%x, ov=%x\n",a,data,c,a-data-c,cy,ac,ov);
#endif
}
INLINE void update_timer(int cyc)
{
//This code sucks, needs to be rewritten SJE
//Todo: Probably better to store the current mode of the timer on a write, so we don't waste time reading it.
//Note: Counting modes increment on 1 machine cycle (12 oscilator periods) - except Timer 2 in certain modes
//Update Timer 0
if(GET_TR0) {
//Determine Mode
int mode = (GET_M0_1<<1) | GET_M0_0;
int overflow;
UINT16 count = 0;
switch(mode) {
case 0: //13 Bit Timer Mode
case 1: //16 Bit Timer Mode
count = ((R_TH0<<8) | R_TL0);
if(mode == 0)
overflow = 0x3fff;
//Todo - really, we update HI counter when LO counter hits 0x20
else
overflow = 0xffff;
//Check for overflow
if((UINT32)(count+(cyc/12))>overflow) {
//Any overflow from cycles?
cyc-= (overflow-count)*12;
count = 0;
SET_TF0(1);
}
//Update the timer
if(cyc) {
int inctimer = 0;
//Gate Bit Set? Timer only incremented if Int0 is set!
if(GET_GATE0 && GET_IE0)
inctimer = (cyc/12);
//Counter Mode? Only increment on 1-0 transition of the Port 3's T0 Line
if(GET_CT0) {
//Not supported
}
//Neither, regular timer mode
if(!GET_GATE0 && !GET_CT0)
inctimer = (cyc/12);
count+=inctimer; //Increment counter
}
//Update new values of the counter
R_TH0 = (count>>8) & 0xff;
R_TL0 = count & 0xff;
break;
case 2: //8 Bit Autoreload
overflow = 0xff;
count = R_TL0;
//Check for overflow
if(count+(cyc/12)>overflow) {
SET_TF0(1);
//Reload
count = R_TH0+(overflow-count);
}
else
count+=(cyc/12);
//Update new values of the counter
R_TL0 = count & 0xff;
break;
case 3: //Split Timer
//Split Timer 1
overflow = 0xff;
count = R_TL0;
//Check for overflow
if(count+(cyc/12)>overflow) {
count = overflow-count;
SET_TF0(1);
}
else
count+=(cyc/12);
//Update new values of the counter
R_TL0 = count & 0xff;
//Split Timer 2
if(GET_TR1) {
overflow = 0xff;
count = R_TH0;
//Check for overflow
if(count+(cyc/12)>overflow) {
count = overflow-count;
SET_TF1(1);
}
else
count+=(cyc/12);
//Update new values of the counter
R_TH0 = count & 0xff;
}
break;
}
}
//Update Timer 1
if(GET_TR1) {
//Determine Mode
int mode = (GET_M1_1<<1) | GET_M1_0;
int overflow;
UINT16 count = 0;
switch(mode) {
case 0: //13 Bit Timer Mode
case 1: //16 Bit Timer Mode
count = ((R_TH1<<8) | R_TL1);
if(mode == 0)
overflow = 0x3fff;
//Todo - really, we update HI counter when LO counter hits 0x20
else
overflow = 0xffff;
//Check for overflow
if((UINT32)(count+(cyc/12))>overflow) {
//TODO: Timer 1 can be set as Serial Baud Rate in the 8051 only... process bits here..
//Any overflow from cycles?
cyc-= (overflow-count)*12;
count = 0;
SET_TF1(1);
}
//Update the timer
if(cyc) {
int inctimer = 0;
//Gate Bit Set? Timer only incremented if Int0 is set!
if(GET_GATE1 && GET_IE1)
inctimer = (cyc/12);
//Counter Mode? Only increment on 1-0 transition of the Port 3's T0 Line
if(GET_CT1) {
//Not supported
}
//Neither, regular timer mode
if(!GET_GATE1 && !GET_CT1)
inctimer = (cyc/12);
count+=inctimer; //Increment counter
}
//Update new values of the counter
R_TH1 = (count>>8) & 0xff;
R_TL1 = count & 0xff;
break;
case 2: //8 Bit Autoreload
overflow = 0xff;
count = R_TL1;
//Check for overflow
if(count+(cyc/12)>overflow) {
SET_TF1(1);
//Reload
count = R_TH1+(overflow-count);
}
else
count+=(cyc/12);
//Update new values of the counter
R_TL1 = count & 0xff;
break;
case 3: //Split Timer
break;
}
}
#if (HAS_I8052 || HAS_I8752)
//Update Timer 2
if(GET_TR2) {
int timerinc, overflow, isoverflow;
UINT16 count = ((R_TH2<<8) | R_TL2);
timerinc = overflow = isoverflow = 0;
//Are we in counter mode?
if(GET_CT2) {
//Not supported
}
//Are we in timer mode?
else {
//16 Bit Timer Mode
overflow = 0xffff;
//Timer 2 Used as Baud Generator? (For now, only *same* send/receive rates supported)
if(GET_TCLK || GET_RCLK)
timerinc = cyc/2; //Timer increments ever 1/2 cycle in baud mode
else
//REGULAR TIMER -
timerinc = cyc/12; //Timer increments ever 1/12 cycles in normal mode
//Check for overflow
if((UINT32)(count+timerinc)>overflow) {
//Set Interrupt flag *unless* used as baud generator
if(!GET_TCLK && !GET_RCLK) {
SET_TF2(1);
}
else {
//Update bits sent if sending & bits left to send!
if(uart.sending && uart.bits_to_send && uart.timerbaud)
uart.bits_to_send-=1;
}
//Auto reload?
if(!GET_CP)
count = ((R_RCAP2H<<8) | R_RCAP2L); //+(overflow-count);
else
count = overflow-count;
}
else {
//No overflow, just increment timer
count+=timerinc;
}
//Update flags
R_TH2 = (count>>8) & 0xff;
R_TL2 = count & 0xff;
}
}
#endif
}
//Set up to transmit data out of serial port
//NOTE: Enable Serial Port Interrupt bit is NOT required to send/receive data!
INLINE void serial_transmit(UINT8 data)
{
int mode = (GET_SM0<<1) | GET_SM1;
//Flag that we're sending data
uart.sending = 1;
uart.data_out = data;
switch(mode) {
//8 bit shifter ( + start,stop bit ) - baud set by clock freq / 12
case 0:
uart.timerbaud = 0;
uart.bitcycles = 0;
uart.bits_to_send = 8+2;
break;
//8 bit uart ( + start,stop bit ) - baud set by timer1 or timer2
case 1:
uart.timerbaud = 1;
uart.bits_to_send = 8+2;
break;
//9 bit uart
case 2:
case 3:
LOG(("Serial mode 2 & 3 not supported in i8051!\n"));
break;
}
}
//Check and update status of serial port
INLINE void update_serial(int cyc)
{
//Any bits left to send?
if(uart.bits_to_send) {
//Timer Generated baud?
if(uart.timerbaud) {
//Let Timer overflow handle removing bits
}
else {
//Oscillator Based baud rate = Osc/12 baud rate, however it also means 1 bit = 12 cycles.
uart.bitcycles+=cyc;
if(uart.bitcycles > 11) {
int bits_sent = uart.bitcycles / 12;
int diff = uart.bitcycles % 12;
//don't allow more bits sent than ready to send
if(bits_sent > uart.bits_to_send) {
bits_sent = uart.bits_to_send;
diff = 0;
}
uart.bits_to_send-=bits_sent;
uart.bitcycles = diff;
}
}
}
//If no bits left to send - flag the interrupt & call the callback
if(!uart.bits_to_send) {
//Clear sending flag
uart.sending = 0;
uart.bitcycles = 0;
//Call the callback function
if(i8051.serial_tx_callback)
i8051.serial_tx_callback(uart.data_out);
//Set Interrupt Flag
SET_TI(1);
//Note: we'll let the main loop catch the interrupt
}
}
/****************************************************************************
* 8752 Section
****************************************************************************/
#if (HAS_I8752)
void i8752_init (void) { i8051_init(); }
void i8752_reset (void *param)
{
memset(&i8051, 0, sizeof(I8051));
memset(&uart, 0, sizeof(I8051_UART));
i8051.subtype = 8752;
//Set up 8052 specific internal read/write (indirect) handlers..
i8051.iram_iread = i8052_internal_ram_iread;
i8051.iram_iwrite = i8052_internal_ram_iwrite;
//Set up serial call back handlers
i8051.serial_tx_callback = hold_serial_tx_callback;
hold_serial_tx_callback = NULL;
i8051.serial_rx_callback = hold_serial_rx_callback;
hold_serial_rx_callback = NULL;
//Setup External ram callback handlers
i8051.eram_iaddr_callback = hold_eram_iaddr_callback;
hold_eram_iaddr_callback = NULL;
//Clear Ram (w/0xff)
memset(&i8051.IntRam,0xff,sizeof(i8051.IntRam));
/* these are all defined reset states */
PC = 0;
SFR_W(SP, 0x7);
SFR_W(PSW, 0);
SFR_W(DPH, 0);
SFR_W(DPL, 0);
SFR_W(ACC, 0);
SFR_W(B, 0);
SFR_W(IP, 0);
SFR_W(IE, 0);
SFR_W(SCON, 0);
SFR_W(TCON, 0);
SFR_W(TMOD, 0);
SFR_W(TH1, 0);
SFR_W(TH0, 0);
SFR_W(TL1, 0);
SFR_W(TL0, 0);
//8052 Only registers
SFR_W(T2CON, 0);
SFR_W(RCAP2L, 0);
SFR_W(RCAP2H, 0);
SFR_W(TL2, 0);
SFR_W(TH2, 0);
/* set the port configurations to all 1's */
SFR_W(P3, 0xff);
SFR_W(P2, 0xff);
SFR_W(P1, 0xff);
SFR_W(P0, 0xff);
/* Flag as NO IRQ in Progress */
CLEAR_CURRENT_IRQ
}
void i8752_exit (void) { i8051_exit(); }
int i8752_execute(int cycles) { return i8051_execute(cycles); }
unsigned i8752_get_context (void *dst) { return i8051_get_context(dst); }
void i8752_set_context (void *src) { i8051_set_context(src); }
unsigned i8752_get_reg (int regnum) { return i8051_get_reg(regnum); }
void i8752_set_reg (int regnum, unsigned val) { i8051_set_reg(regnum,val); }
void i8752_set_irq_line(int irqline, int state) { i8051_set_irq_line(irqline,state); }
void i8752_set_irq_callback(int (*callback)(int irqline)) { i8051_set_irq_callback(callback); }
void i8752_set_serial_tx_callback(void (*callback)(int data)) { i8051_set_serial_tx_callback(callback); }
void i8752_set_serial_rx_callback(int (*callback)(void)) { i8051_set_serial_rx_callback(callback); }
void i8752_state_save(void *file) { i8051_state_save(file); }
void i8752_state_load(void *file) { i8051_state_load(file); }
const char *i8752_info(void *context, int regnum)
{
switch( regnum )
{
case CPU_INFO_NAME: return "I8752";
}
return i8051_info(context,regnum);
}
unsigned i8752_dasm(char *buffer, unsigned pc)
{
#ifdef MAME_DEBUG
return Dasm8051(buffer,pc);
#else
sprintf( buffer, "$%02X", cpu_readop(pc) );
return 1;
#endif
}
/* The following two handlers are used by the MAME Debugger Memory Window...
By keeping these functions separate from the internally used IRAM_W/IRAM_R functions,
we can manipulate and display internal memory in the debugger memory window in a layout
that is not necessarily how the real memory is.. this will be especially useful for
the 8052 chip where both the SFR and the upper 128 bytes of ram are mapped to the same
address, so we can handle that here by mapping the sfr to a different address */
READ_HANDLER(i8752_internal_r)
{
//USE INDIRECT READ TO ALLOW FULL 256 Bytes of RAM to show in the debugger
if(offset < 0x100)
return IRAM_IR(offset);
else
//MAP SFR registers starting at 256 (they are only 128 bytes in size)
if(offset < 0x100+0x80)
return SFR_R(offset-0x80);
else
//Everything else is 0 (and invalid)
return 0;
}
WRITE_HANDLER(i8752_internal_w)
{
//USE INDIRECT WRITE TO ALLOW FULL 256 Bytes of RAM to show in the debugger
if(offset < 0x100)
IRAM_IW(offset,data);
else
if(offset < 0x100+0x80)
SFR_W(offset-0x80,data);
}
/* Reads the contents of the Internal RAM memory INDIRECTLY */
/* Anything above 0x7f is NOT sfr/register, but rather UPPER 128K OF INTERNAL RAM */
static READ_HANDLER(i8052_internal_ram_iread)
{
if (offset < 0x100)
return i8051.IntRam[offset];
else
LOG(("i8051 #%d: attemping to read from an invalid Internal Ram address: %x at 0x%04x\n", cpu_getactivecpu(), offset,PC));
return 0xff;
}
/* Writes the contents of the Internal RAM memory INDIRECTLY */
/* Anything above 0x7f is NOT sfr/register, but rather UPPER 128K OF INTERNAL RAM */
static WRITE_HANDLER(i8052_internal_ram_iwrite)
{
data &= 0xff; //Ensure it's only 8 bits
if (offset < 0x100)
i8051.IntRam[offset] = data;
else
LOG(("i8051 #%d: attemping to write to an invalid Internal Ram address: %x at 0x%04x\n", cpu_getactivecpu(), offset,PC));
}
#endif //(HAS_8752)
|
vsuzarte/ekoob
|
src/main/java/com/aztec/koob/validadores/ValidadorData.java
|
<gh_stars>0
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.aztec.koob.validadores;
import java.sql.Date;
import java.text.SimpleDateFormat;
/**
*
* @author gabriel.sleal1
*/
public class ValidadorData {
public static Date formatarData(String dataNasc) {
try {
//FORMATANDO A DATA EM STRING PARA DATE
String ano = dataNasc.substring(0, 4);
String mes = dataNasc.substring(5, 7);
String dia = dataNasc.substring(8, 10);
String data = dia + "/" + mes + "/" + ano;
SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date dataFormatada = null;
try {
dataFormatada = formato.parse(data);
} catch (Exception E) {
}
java.sql.Date dataSql = new java.sql.Date(dataFormatada.getTime());
return dataSql;
} catch (Exception E) {
return null;
}
}
}
|
almmessias/CursoPython
|
ex035.py
|
<gh_stars>0
r1 = float (input ('Primeiro lado: '))
r2 = float (input ('Segundo lado: '))
r3 = float (input ('Terceiro lado: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print ('Os lados acima podem formar triangulo')
else:
print ('Os lados acima não podem formar triangulo')
|
Kuruka/editor-framework
|
lib/share/ipc.js
|
'use strict';
const Electron = require('electron');
let _ipc = null;
if ( Editor.isCoreLevel ) {
_ipc = Electron.ipcMain;
} else {
_ipc = Electron.ipcRenderer;
}
/**
* @module Editor
*/
/**
* This option is used to indicate that the channel should not send to self.
* It must be supplied as the last argument of your channel if you want.
* @property selfExcluded
* @type {Object}
*/
Editor.selfExcluded = {
'__is_ipc_option__': true,
'self-excluded': true,
};
class EditorIpc {
/**
* Ipc class for easily manage ipc events
* @class Editor.Ipc
* @constructor
*/
constructor () {
this.listeningIpcs = [];
}
/**
* Register ipc channel and respond it with the callback function
* @method on
* @param {string} ipc channel name
* @param {function} callback
*/
on (channel, callback) {
_ipc.on( channel, callback );
this.listeningIpcs.push( [channel, callback] );
}
/**
* Register ipc channel and respond it once with the callback function
* @method once
* @param {string} ipc channel name
* @param {function} callback
*/
once (channel, callback) {
_ipc.once( channel, callback );
this.listeningIpcs.push( [channel, callback] );
}
/**
* Clear all registered ipc messages in this ipc listener
* @method clear
*/
clear () {
for (let i = 0; i < this.listeningIpcs.length; i++) {
let pair = this.listeningIpcs[i];
_ipc.removeListener( pair[0], pair[1] );
}
this.listeningIpcs.length = 0;
}
}
module.exports = EditorIpc;
|
leszekbednorz/miru
|
miru-writer-deployable/src/main/java/com/jivesoftware/os/miru/writer/deployable/MiruWriterEndpoints.java
|
package com.jivesoftware.os.miru.writer.deployable;
import javax.inject.Singleton;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
*
*/
@Singleton
@Path("/ui")
public class MiruWriterEndpoints {
private final MiruWriterUIService writerUIService;
public MiruWriterEndpoints(@Context MiruWriterUIService writerUIService) {
this.writerUIService = writerUIService;
}
@GET
@Produces(MediaType.TEXT_HTML)
public Response get(@HeaderParam("rb_session_redir_url") @DefaultValue("") String redirUrl) {
String rendered = writerUIService.render(redirUrl);
return Response.ok(rendered).build();
}
}
|
sainsk/99-problems
|
java8/src/main/java/com/saikiran/ninetynine_problems/_02_arithmetic/P32.java
|
package com.saikiran.ninetynine_problems._02_arithmetic;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
/**
* (**) Determine the prime factors of a given positive integer.
*/
public class P32 {
public static List<Integer> primeFactors(int number) {
List<Integer> fs = new ArrayList<>();
IntStream.rangeClosed(2, number / 2).filter(P31::isPrime).forEach(f -> {
int n = number;
while (n % f == 0) {
n = n / f;
fs.add(f);
}
});
return fs;
}
}
|
recallsong/sogw
|
sogw/proxy/core/lambda.go
|
<filename>sogw/proxy/core/lambda.go
package core
func (a *Api) EvalLambda(ctx *RequestContext, text string) error {
// not implement yet
ctx.ReqCtx.WriteString("lambda expression is not implement yet.")
return nil
}
|
XEOCORP/eniobot
|
node_modules/dbd.js/package/functions/funcs/awaitMessages.js
|
const interpreter = require("../../interpreter")
const ms = require("ms")
const embed = require("../../handlers/errors")
module.exports = async d => {
const code = d.command.code
const r = code.split("$awaitMessages").length - 1
const inside = code.split("$awaitMessages[")[r].split("]")[0]
const [userFilter, time, responseOrResponses, commandOrCommands, error] = inside.split(";")
const filter = m => {
return (userFilter === "everyone" ? true : userFilter === m.author.id) && (responseOrResponses === "everything" ? true : responseOrResponses.toLowerCase().split(" ").join("").split(",").includes(m.content.toLowerCase())) && !m.author.bot
}
d.message.channel.awaitMessages(filter, {
max: 1,
time: ms(time),
errors: ["time"]
}).then(collected => {
const m = collected.first()
const cmd = responseOrResponses === "everything" ? d.client.awaited_commands.find(c => c.name === commandOrCommands) : d.client.awaited_commands.find(c => c.name === commandOrCommands.split(" ").join("").split(",")[responseOrResponses.split(" ").join("").split(",").findIndex(e => e.toLowerCase() === m.content.toLowerCase())])
if (!cmd) return d.error(`❌ Awaited command ${m.content} does not exist`)
interpreter(d.client, m, m.content.split(" "), cmd)
}).catch(err => {
if (!err || !err.message) embed(d, error)
else if (err.message) return d.error(`❌ ${err.message}`)
})
return {
code: d.command.code.replaceLast(`$awaitMessages[${inside}]`, "")
}
}
|
somish/padlock-pilot
|
padlock-master/frontend/src/Components/LoginForm.js
|
<filename>padlock-master/frontend/src/Components/LoginForm.js<gh_stars>1-10
import React, { useContext, useRef, useState } from 'react'
import { Alert, Button, Modal, Spinner } from 'react-bootstrap'
import { useHistory } from 'react-router-dom'
import { MenuItem, Paper, Grow, Popper, MenuList, ClickAwayListener } from '@material-ui/core'
import { AuthContext } from './Auth'
import { useUser } from '../api'
function LoginButton({ open }) {
return (
<Button className="login-button" onClick={open}>
<img className="padLogo1" src={require('../Images/clipart-key-large-1.png')} alt="Padlock logo" />| Login
</Button>
)
}
function LoginForm({ close, visible }) {
let history = useHistory()
let { error, loading, login } = useContext(AuthContext)
let emailEl = useRef(null)
let handleSubmit = async (e) => {
e.preventDefault()
if (loading) return
const email = emailEl.current.value.trim()
await login(email)
window.location = '/dashboard/projects'
}
return (
<Modal show={visible} onHide={close}>
<form onSubmit={handleSubmit}>
<Modal.Header closeButton>Log In</Modal.Header>
{error && <Alert variant="danger">{error.message}</Alert>}
<Modal.Body>
<label>
Email:
<input type="text" ref={emailEl} />
</label>
</Modal.Body>
<Modal.Footer>
<input type="submit" value="Login via Email" disabled={loading} />
</Modal.Footer>
</form>
</Modal>
)
}
function Logout() {
let { logout } = useContext(AuthContext)
const history = useHistory()
return (
<>
<Button onClick={logout}>Log out</Button>
</>
)
}
export default function Login() {
let { ready, logout } = useContext(AuthContext)
let user = useUser()
let anchorRef = useRef(null)
let [modalVisible, setModalVisible] = useState(false)
let [menuOpen, setMenuOpen] = useState(false)
const handleClose = (event) => {
if (anchorRef.current && anchorRef.current.contains(event.target)) {
return
}
setMenuOpen(false)
}
const handleToggle = () => {
setMenuOpen((prevOpen) => !prevOpen)
}
if (!ready) return <Spinner animation="border" variant="primary" />
if (user) {
return (
<>
<Button
className="logged-in-button"
ref={anchorRef}
aria-controls={menuOpen ? 'menu-list-grow' : undefined}
aria-haspopup="true"
onClick={handleToggle}
>
Logged in as {user.name}
</Button>
<Popper className="logged-in-popper" open={menuOpen} anchorEl={anchorRef.current} transition disablePortal>
{({ TransitionProps, placement }) => (
<Grow {...TransitionProps} style={{ transformOrigin: 'left top' }}>
<Paper>
<ClickAwayListener onClickAway={handleClose}>
<MenuList autoFocusItem={menuOpen} id="menu-list-grow">
<MenuItem onClick={() => (window.location = '/dashboard/projects')}>Go To Dashboard</MenuItem>
<MenuItem onClick={logout}>Logout</MenuItem>
</MenuList>
</ClickAwayListener>
</Paper>
</Grow>
)}
</Popper>
</>
)
}
return (
<>
<LoginButton open={() => setModalVisible(true)} />
<LoginForm close={() => setModalVisible(false)} visible={modalVisible} />
</>
)
}
|
Songner/image_classfication
|
ImageProcessing-Python/blog25-lvjing/blog25-image05.py
|
<reponame>Songner/image_classfication<gh_stars>0
#coding:utf-8
import cv2
import numpy as np
#获取滤镜颜色
def getBGR(img, table, i, j):
#获取图像颜色
b, g, r = img[i][j]
#计算标准颜色表中颜色的位置坐标
x = int(g/4 + int(b/32) * 64)
y = int(r/4 + int((b%32) / 4) * 64)
#返回滤镜颜色表中对应的颜色
return lj_map[x][y]
#读取原始图像
img = cv2.imread('scenery.png')
lj_map = cv2.imread('table.png')
print img.shape
#获取图像行和列
rows, cols = img.shape[:2]
#新建目标图像
dst = np.zeros((rows, cols, 3), dtype="uint8")
#循环设置滤镜颜色
for i in range(rows):
for j in range(cols):
dst[i][j] = getBGR(img, lj_map, i, j)
#显示图像
cv2.imshow('src', img)
cv2.imshow('dst', dst)
cv2.waitKey()
cv2.destroyAllWindows()
|
wuguowei19880907/cas
|
core/cas-server-core-authentication/src/test/java/org/apereo/cas/authentication/policy/RestfulAuthenticationPolicyTests.java
|
<reponame>wuguowei19880907/cas
package org.apereo.cas.authentication.policy;
import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.authentication.exceptions.AccountDisabledException;
import org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException;
import org.apereo.cas.config.CasCoreHttpConfiguration;
import org.apereo.cas.config.CasCoreServicesConfiguration;
import org.apereo.cas.config.CasCoreTicketCatalogConfiguration;
import org.apereo.cas.config.CasCoreTicketIdGeneratorsConfiguration;
import org.apereo.cas.config.CasCoreTicketsConfiguration;
import org.apereo.cas.config.CasCoreUtilConfiguration;
import org.apereo.cas.config.CasCoreWebConfiguration;
import org.apereo.cas.config.CasDefaultServiceTicketIdGeneratorsConfiguration;
import org.apereo.cas.config.support.CasWebApplicationServiceFactoryConfiguration;
import org.apereo.cas.util.MockWebServer;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpStatus;
import org.springframework.test.annotation.DirtiesContext;
import javax.security.auth.login.AccountExpiredException;
import javax.security.auth.login.AccountLockedException;
import javax.security.auth.login.AccountNotFoundException;
import javax.security.auth.login.FailedLoginException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.LinkedHashSet;
import static org.apereo.cas.util.junit.Assertions.assertThrowsWithRootCause;
import static org.junit.jupiter.api.Assertions.*;
/**
* This is {@link RestfulAuthenticationPolicyTests}.
*
* @author Misagh Moayyed
* @since 5.2.0
*/
@SpringBootTest(classes = {
RefreshAutoConfiguration.class,
CasCoreTicketIdGeneratorsConfiguration.class,
CasDefaultServiceTicketIdGeneratorsConfiguration.class,
CasCoreServicesConfiguration.class,
CasCoreTicketsConfiguration.class,
CasCoreWebConfiguration.class,
CasCoreUtilConfiguration.class,
CasCoreHttpConfiguration.class,
CasWebApplicationServiceFactoryConfiguration.class,
CasCoreTicketCatalogConfiguration.class
})
@DirtiesContext
@Tag("RestfulApi")
public class RestfulAuthenticationPolicyTests {
@Autowired
private ConfigurableApplicationContext applicationContext;
@Test
public void verifyAllowedOperation() {
try (val webServer = new MockWebServer(9200,
new ByteArrayResource(StringUtils.EMPTY.getBytes(StandardCharsets.UTF_8), "Output"), HttpStatus.OK)) {
webServer.start();
val policy = new RestfulAuthenticationPolicy("http://localhost:9200");
assertTrue(policy.isSatisfiedBy(CoreAuthenticationTestUtils.getAuthentication("casuser"), new LinkedHashSet<>(), applicationContext));
} catch (final Exception e) {
throw new AssertionError(e.getMessage(), e);
}
}
@Test
public void verifyStatusCodeUnAuthz() {
assertPolicyFails(9201, HttpStatus.UNAUTHORIZED, FailedLoginException.class);
assertPolicyFails(9202, HttpStatus.LOCKED, AccountLockedException.class);
assertPolicyFails(9203, HttpStatus.METHOD_NOT_ALLOWED, AccountDisabledException.class);
assertPolicyFails(9204, HttpStatus.FORBIDDEN, AccountDisabledException.class);
assertPolicyFails(9205, HttpStatus.NOT_FOUND, AccountNotFoundException.class);
assertPolicyFails(9206, HttpStatus.PRECONDITION_FAILED, AccountExpiredException.class);
assertPolicyFails(9207, HttpStatus.PRECONDITION_REQUIRED, AccountPasswordMustChangeException.class);
assertPolicyFails(9208, HttpStatus.INTERNAL_SERVER_ERROR, FailedLoginException.class);
}
private void assertPolicyFails(final int port, final HttpStatus status,
final Class<? extends Throwable> exceptionClass) {
try (val webServer = new MockWebServer(port,
new ByteArrayResource(StringUtils.EMPTY.getBytes(StandardCharsets.UTF_8), "Output"), status)) {
webServer.start();
val policy = new RestfulAuthenticationPolicy("http://localhost:" + port);
assertThrowsWithRootCause(GeneralSecurityException.class, exceptionClass,
() -> assertTrue(policy.isSatisfiedBy(CoreAuthenticationTestUtils.getAuthentication("casuser"),
new LinkedHashSet<>(), applicationContext)));
} catch (final Exception e) {
throw new AssertionError(e.getMessage(), e);
}
}
}
|
diasbruno/mout
|
tests/spec/string/spec-removeNonASCII.js
|
<gh_stars>100-1000
define(['mout/string/removeNonASCII'], function (removeNonASCII) {
describe('string/removeNonASCII()', function(){
it('should remove non-printable chars', function(){
var accents = 'áÁâÂàÀåÅãÃäÄçÇéÉêÊèÈëËíÍîÎìÌïÏñÑóÓôÔòÒØõÕöÖÐþúÚûÛùÙüÜýÝÿ';
var printable = 'lorem ~!@#$%^&*()_+`-={}[]|\\:";\'/?><., ipsum';
var str = accents + printable;
expect( removeNonASCII( str ) ).toEqual( printable );
});
it('should treat null as empty string', function(){
expect( removeNonASCII(null) ).toBe('');
});
it('should treat undefined as empty string', function(){
expect( removeNonASCII(void 0) ).toBe('');
});
});
});
|
stevekaeser/daisycms
|
applications/daisywiki/frontend/src/main/java/org/outerj/daisy/books/publisher/impl/publicationprocess/AssembleBookTask.java
|
/*
* Copyright 2004 Outerthought bvba and Schaubroeck nv
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.outerj.daisy.books.publisher.impl.publicationprocess;
import org.outerj.daisy.books.publisher.impl.bookmodel.SectionContainer;
import org.outerj.daisy.books.publisher.impl.bookmodel.Section;
import org.outerj.daisy.books.publisher.impl.BookInstanceLayout;
import org.outerj.daisy.xmlutil.ForwardingContentHandler;
import org.outerj.daisy.xmlutil.XmlSerializer;
import org.outerj.daisy.xmlutil.HtmlBodyRemovalHandler;
import org.outerj.daisy.frontend.PreparedDocuments;
import org.outerj.daisy.frontend.PreparedIncludeHandler;
import org.apache.cocoon.xml.AttributesImpl;
import org.apache.cocoon.xml.SaxBuffer;
import org.apache.cocoon.xml.ContentHandlerWrapper;
import org.xml.sax.ContentHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import java.io.OutputStream;
import java.util.Stack;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class AssembleBookTask implements PublicationProcessTask {
private final String output;
public AssembleBookTask(String output) {
this.output = output;
}
public void run(PublicationContext context) throws Exception {
context.getPublicationLog().info("Running assemble book task.");
String outputPath = BookInstanceLayout.getPublicationOutputPath(context.getPublicationOutputName()) + output;
OutputStream os = context.getBookInstance().getResourceOutputStream(outputPath);
try {
XmlSerializer xmlSerializer = new XmlSerializer(os);
xmlSerializer.startDocument();
xmlSerializer.startElement("", "html", "html", new AttributesImpl());
xmlSerializer.startElement("", "body", "body", new AttributesImpl());
processSections(context.getBook(), context, xmlSerializer, 1);
xmlSerializer.endElement("", "body", "body");
xmlSerializer.endElement("", "html", "html");
xmlSerializer.endDocument();
} finally {
os.close();
}
}
private void processSections(SectionContainer sectionContainer, PublicationContext context, ContentHandler consumer, int level) throws Exception {
Section[] sections = sectionContainer.getSections();
for (int i = 0; i < sections.length; i++) {
if (sections[i].getBookStorePath() != null) {
String location = BookInstanceLayout.getDocumentInPublicationStorePath(sections[i].getBookStorePath(), context.getPublicationOutputName());
PreparedDocuments preparedDocuments = PreparedDocumentsBuilder.build(context.getBookInstance().getResource(location));
HeaderShifterHandler headerShifterHandler = new HeaderShifterHandler(consumer, level - 1);
PreparedIncludeHandler preparedIncludeHandler = new PreparedIncludeHandler(new ContentHandlerWrapper(headerShifterHandler), preparedDocuments, true);
SaxBuffer buffer = preparedDocuments.getPreparedDocument(1).getSaxBuffer();
buffer.toSAX(new HtmlBodyRemovalHandler(preparedIncludeHandler));
} else if (sections[i].getTitle() != null) {
String headerTag = "h" + level;
AttributesImpl attrs = new AttributesImpl();
if (sections[i].getType() != null) {
attrs.addCDATAAttribute("daisySectionType", sections[i].getType());
}
consumer.startElement("", headerTag, headerTag, attrs);
char[] title = sections[i].getTitle().toCharArray();
consumer.characters(title, 0, title.length);
consumer.endElement("", headerTag, headerTag);
}
processSections(sections[i], context, consumer, level + 1);
}
}
static class HeaderShifterHandler extends ForwardingContentHandler {
private Stack headerStack = new Stack();
private final int shiftAmount;
private static final Pattern headerPattern = Pattern.compile("h([0-9]+)");
public HeaderShifterHandler(ContentHandler consumer, int shiftAmount) {
super(consumer);
this.shiftAmount = shiftAmount;
}
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
Matcher matcher = headerPattern.matcher(localName);
if (matcher.matches() && namespaceURI.equals("")) {
int currentLevel = Integer.parseInt(matcher.group(1));
int newLevel = currentLevel + shiftAmount + 1;
consumer.startElement(namespaceURI, "h" + newLevel, "h" + newLevel, atts);
headerStack.push(new Integer(newLevel));
} else {
consumer.startElement(namespaceURI, localName, qName, atts);
}
}
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
Matcher matcher = headerPattern.matcher(localName);
if (matcher.matches() && namespaceURI.equals("")) {
int level = ((Integer)headerStack.pop()).intValue();
consumer.endElement(namespaceURI, "h" + level, "h" + level);
} else {
consumer.endElement(namespaceURI, localName, qName);
}
}
}
}
|
TidalPaladin/combustion
|
src/combustion/util/validation.py
|
<reponame>TidalPaladin/combustion
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import Any, List, Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
from .typing import Array
@torch.jit.ignore
def check_shapes_match(x: Array, y: Array, x_name: str, y_name: str) -> None:
r"""Raises a :class:`ValueError` if two tensors do not have the same shape
Args:
x (numpy array or :class:`torch.Tensor`):
One of the two tensors to check
y (numpy array or :class:`torch.Tensor`):
One of the two tensors to check
x_name (str):
Variable name for tensor ``x`` in the :class:`ValueError` text
y_name (str):
Variable name for tensor ``y`` in the :class:`ValueError` text
"""
assert isinstance(x, (Tensor, np.ndarray))
assert isinstance(y, (Tensor, np.ndarray))
assert isinstance(x_name, str)
assert isinstance(y_name, str)
if x.shape != y.shape:
raise ValueError(f"expected {x_name}.shape == {y_name}.shape:\n" f"{x.shape} vs {y.shape}")
@torch.jit.ignore
def check_ndim_match(x: Array, y: Array, x_name: str, y_name: str) -> None:
r"""Raises a :class:`ValueError` if two tensors do not have the same number of dimensions
Args:
x (numpy array or :class:`torch.Tensor`):
One of the two tensors to check
y (numpy array or :class:`torch.Tensor`):
One of the two tensors to check
x_name (str):
Variable name for tensor ``x`` in the :class:`ValueError` text
y_name (str):
Variable name for tensor ``y`` in the :class:`ValueError` text
"""
assert isinstance(x, (Tensor, np.ndarray))
assert isinstance(y, (Tensor, np.ndarray))
assert isinstance(x_name, str)
assert isinstance(y_name, str)
if x.ndim != y.ndim:
raise ValueError(f"expected {x_name}.ndim == {y_name}.ndim:\n" f"{x.shape} vs {y.shape}")
def check_is_tensor(x: Any, name: str) -> None:
r"""Raises a :class:`TypeError` if the input is not a :class:`torch.Tensor`
Args:
x (Any):
Input to check
name (str):
Variable name for input ``x`` in the :class:`TypeError` text
"""
assert isinstance(name, str)
if not isinstance(x, Tensor):
raise TypeError(f"{name} must be type Tensor,\n" f"got {type(x)}")
@torch.jit.ignore
def check_is_array(x: Array, name: str) -> None:
r"""Raises a :class:`TypeError` if the input is not a :class:`torch.Tensor` or
:class:`numpy.ndarray`
Args:
x (Any):
Input to check
name (str):
Variable name for input ``x`` in the :class:`TypeError` text
"""
assert isinstance(name, str)
if not isinstance(x, (Tensor, np.ndarray)):
raise TypeError(f"{name} must be type Tensor or np.ndarray,\n" f"got {type(x)}")
@torch.jit.ignore
def check_shape(x: Array, shape: Union[Tuple[int, ...], List[int]], name: str) -> None:
r"""Raises a :class:`ValueError` if the input does not have the expected shape.
Args:
x (numpy array or :class:`torch.Tensor`):
Input to check
shape (iterable of ``Optional[int]``):
Expected shape of the tensor, or ``None`` for a dimension that should not be checked
name (str):
Variable name for input ``x`` in the :class:`ValueError` text
"""
assert isinstance(x, (Tensor, np.ndarray))
assert isinstance(shape, (list, tuple, torch.Size))
assert isinstance(name, str)
# check tensor rank mismatch first
if x.ndim != len(shape):
raise ValueError(f"expected {name}.shape == {shape}:\n" f"{x.shape} vs {shape}")
# check each dim, skip None entries in shape
for i, (actual, expected) in enumerate(zip(x.shape, shape)):
if expected is None:
continue
elif expected != actual:
raise ValueError(f"expected {name}.shape == {shape}:\n" f"mismatch in dim {i}: {x.shape} vs {shape}")
@torch.jit.ignore
def check_dimension(x: Array, dim: int, size: int, name: str) -> None:
r"""Raises a :class:`ValueError` if a given dimension does not have the expected size.
Args:
x (numpy array or :class:`torch.Tensor`):
Input to check
dim (int):
Dimension to check
size (int):
Expected dimension size
name (str):
Variable name for input ``x`` in the :class:`ValueError` text
"""
assert isinstance(x, (Tensor, np.ndarray))
dim = int(dim)
size = int(size)
assert isinstance(name, str)
if x.shape[dim] != size:
raise ValueError(f"expected {name}.shape[{dim}] == {size}\n" f"found shape {x.shape}")
@torch.jit.ignore
def check_ndim(x: Array, ndim: int, name: str) -> None:
r"""Raises a :class:`ValueError` if a given dimension does not have the expected size.
Args:
x (numpy array or :class:`torch.Tensor`):
Input to check
ndim (int):
Expected number of dimensions
name (str):
Variable name for input ``x`` in the :class:`ValueError` text
"""
assert isinstance(x, (Tensor, np.ndarray))
ndim = int(ndim)
assert isinstance(name, str)
if x.ndim != ndim:
raise ValueError(f"expected {name}.ndim == {ndim}\n" f"found shape {x.ndim}")
@torch.jit.ignore
def check_dimension_within_range(x: Array, dim: int, bounds: Tuple[Optional[int], Optional[int]], name: str) -> None:
r"""Raises a :class:`ValueError` if the size of a given dimension does not fall within
an expected range.
Args:
x (numpy array or :class:`torch.Tensor`):
Input to check
dim (int):
Dimension to check
bounds (tuple of two ints):
Lower and upper bound of expected dimension sizes. Bounds can be ``None`` for
no constraint
name (str):
Variable name for input ``x`` in the :class:`ValueError` text
"""
assert isinstance(x, (Tensor, np.ndarray))
dim = int(dim)
assert isinstance(name, str)
low = bounds[0] if bounds[0] is not None else 0
high = bounds[1] if bounds[1] is not None else float("inf")
if x.shape[dim] < low or x.shape[dim] > high:
raise ValueError(f"expected {low} < {name}.shape[{dim}] < {high}\n" f"found shape {x.shape}")
@torch.jit.ignore
def check_ndim_within_range(x: Array, bounds: Tuple[Optional[int], Optional[int]], name: str) -> None:
r"""Raises a :class:`ValueError` if a given dimension does not have the expected size.
Args:
x (numpy array or :class:`torch.Tensor`):
Input to check
bounds (tuple of two ints):
Lower and upper bound of expected number of dimensions. Bounds can be ``None`` for
no constraint
name (str):
Variable name for input ``x`` in the :class:`ValueError` text
"""
assert isinstance(x, (Tensor, np.ndarray))
assert isinstance(name, str)
low = bounds[0] if bounds[0] is not None else 0
high = bounds[1] if bounds[1] is not None else float("inf")
if x.ndim < low or x.ndim > high:
raise ValueError(f"expected {low} < {name}.ndim < {high}\n" f"found shape {x.ndim}")
@torch.jit.ignore
def check_dimension_match(x: Array, y: Array, dim: int, x_name: str, y_name: str) -> None:
r"""Raises a :class:`ValueError` if two tensors have different sizes for a given dimension.
Args:
x (numpy array or :class:`torch.Tensor`):
One of the two tensors to check
y (numpy array or :class:`torch.Tensor`):
One of the two tensors to check
dim (int):
Dimension to check
x_name (str):
Variable name for tensor ``x`` in the :class:`ValueError` text
y_name (str):
Variable name for tensor ``y`` in the :class:`ValueError` text
"""
assert isinstance(x, (Tensor, np.ndarray))
assert isinstance(y, (Tensor, np.ndarray))
dim = int(dim)
assert isinstance(x_name, str)
assert isinstance(y_name, str)
if x.shape[dim] != y.shape[dim]:
raise ValueError(f"expected {x_name}.shape[{dim}] == {y_name}.shape[{dim}]\n" f"{x.shape} vs {y.shape}")
@torch.jit.ignore
def check_names(x: Tensor, names: Union[List[str], Tuple[str, ...]], var_name) -> None:
assert isinstance(x, Tensor)
assert isinstance(names, (list, tuple))
assert isinstance(var_name, str)
expected = sorted(names)
actual = sorted(x.names)
if not actual == expected:
raise ValueError(f"expected {var_name}.names == {names}:\n" f"{actual} vs {expected}")
@torch.jit.ignore
def check_names_match(x: Tensor, y: Tensor, x_name: str, y_name: str):
assert isinstance(x, Tensor)
assert isinstance(y, Tensor)
assert isinstance(x_name, str)
assert isinstance(y_name, str)
x_names = sorted(x.names)
y_names = sorted(y.names)
if not x_names == y_names:
raise ValueError(f"expected {x_name}.names == {y_name}.names:\n" f"{x_names} vs {y_names}")
|
mlaggner/tmdb-java
|
src/main/java/com/uwetrottmann/tmdb2/entities/MovieResultsPage.java
|
<filename>src/main/java/com/uwetrottmann/tmdb2/entities/MovieResultsPage.java
package com.uwetrottmann.tmdb2.entities;
public class MovieResultsPage extends BaseResultsPage<BaseMovie> {
}
|
henrikhorbovyi/URI
|
src/beginner/1153.py
|
<filename>src/beginner/1153.py
N = int(input())
f = 1
for i in range(2,N+1):
f = f * i
print(f)
|
benjaminliu/leetcode-java
|
src/main/java/com/test/leetcode/medium/_338_CountingBits.java
|
<filename>src/main/java/com/test/leetcode/medium/_338_CountingBits.java
package com.test.leetcode.medium;
/**
* Created by ben on 2017/5/15.
*/
public class _338_CountingBits {
//[0,1,1,2,2]
public int[] countBits(int num) {
if (num == 0) {
return new int[]{0};
}
if (num == 1) {
return new int[]{0, 1};
}
int[] result = new int[num + 1];
result[0] = 0;
result[1] = 1;
int pow = 2;
int index = 0;
int i = 2;
int j = 0;
while (i <= num) {
if (j < pow) {
result[i] = result[index] + 1;
index++;
i++;
j++;
} else {
pow *= 2;
index = 0;
j = 0;
}
}
return result;
}
}
|
fastjrun/ciHelper
|
MybatisEx/src/main/java/com/fastjrun/mybatis/declare/UpdateDeclare.java
|
package com.fastjrun.mybatis.declare;
public class UpdateDeclare extends Declare {
private String table;
private Settings settings;
private Condition condition;
public UpdateDeclare()
{
this.settings = new Settings();
this.condition = new Condition();
}
public UpdateDeclare(String table)
{
this.table = table;
this.settings = new Settings();
this.condition = new Condition();
}
public UpdateDeclare addSet(String key, Object value)
{
this.settings.add(key, value);
return this;
}
public UpdateDeclare and(String key, Object ... value)
{
this.condition.and(key, value);
return this;
}
public UpdateDeclare table(String table)
{
this.table = table;
return this;
}
@Override
public void createSql()
{
this.sql = "update "+ table+ " set " + settings.toString();
if(null != condition && !condition.equals(""))
{
sql = sql + " where 1 = 1 " + condition ;
}
}
}
|
nilsvu/spectre
|
src/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/HarmonicSchwarzschild.cpp
|
<filename>src/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/HarmonicSchwarzschild.cpp
// Distributed under the MIT License.
// See LICENSE.txt for details.
#include "PointwiseFunctions/AnalyticSolutions/GeneralRelativity/HarmonicSchwarzschild.hpp"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <ostream>
#include <pup.h>
#include <utility>
#include "DataStructures/CachedTempBuffer.hpp"
#include "DataStructures/DataBox/Prefixes.hpp"
#include "DataStructures/DataVector.hpp"
#include "DataStructures/Tensor/EagerMath/Determinant.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "Options/Options.hpp"
#include "PointwiseFunctions/AnalyticSolutions/AnalyticSolution.hpp"
#include "PointwiseFunctions/GeneralRelativity/ExtrinsicCurvature.hpp"
#include "PointwiseFunctions/GeneralRelativity/Tags.hpp"
#include "Utilities/ConstantExpressions.hpp"
#include "Utilities/GenerateInstantiations.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/MakeWithValue.hpp"
namespace gr::Solutions {
HarmonicSchwarzschild::HarmonicSchwarzschild(
const double mass, const std::array<double, volume_dim>& center,
const Options::Context& context)
: mass_(mass), center_(center) {
if (mass_ < 0.0) {
PARSE_ERROR(context, "Mass must be non-negative. Given mass: " << mass_);
}
}
void HarmonicSchwarzschild::pup(PUP::er& p) {
p | mass_;
p | center_;
}
template <typename DataType, typename Frame>
HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::
IntermediateComputer(const HarmonicSchwarzschild& solution,
const tnsr::I<DataType, 3, Frame>& x)
: solution_(solution), x_(x) {}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<tnsr::I<DataType, 3, Frame>*> x_minus_center,
const gsl::not_null<CachedBuffer*> /*cache*/,
internal_tags::x_minus_center<DataType, Frame> /*meta*/) const {
for (size_t i = 0; i < 3; ++i) {
x_minus_center->get(i) = x_.get(i) - gsl::at(solution_.center(), i);
}
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> r,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::r<DataType> /*meta*/) const {
const auto& x_minus_center =
cache->get_var(*this, internal_tags::x_minus_center<DataType, Frame>{});
get(*r) =
sqrt(square(get<0>(x_minus_center)) + square(get<1>(x_minus_center)) +
square(get<2>(x_minus_center)));
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> one_over_r,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::one_over_r<DataType> /*meta*/) const {
const auto& r = cache->get_var(*this, internal_tags::r<DataType>{});
get(*one_over_r) = 1.0 / get(r);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<tnsr::I<DataType, 3, Frame>*> x_over_r,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::x_over_r<DataType, Frame> /*meta*/) const {
const auto& one_over_r =
cache->get_var(*this, internal_tags::one_over_r<DataType>{});
const auto& x_minus_center =
cache->get_var(*this, internal_tags::x_minus_center<DataType, Frame>{});
tenex::evaluate<ti::I>(x_over_r, x_minus_center(ti::I) * one_over_r());
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> m_over_r,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::m_over_r<DataType> /*meta*/) const {
const auto& one_over_r =
cache->get_var(*this, internal_tags::one_over_r<DataType>{});
get(*m_over_r) = solution_.mass() * get(one_over_r);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> sqrt_f_0,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::sqrt_f_0<DataType> /*meta*/) const {
const auto& m_over_r =
cache->get_var(*this, internal_tags::m_over_r<DataType>{});
get(*sqrt_f_0) = 1.0 + get(m_over_r);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> f_0,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::f_0<DataType> /*meta*/) const {
const auto& sqrt_f_0 =
cache->get_var(*this, internal_tags::sqrt_f_0<DataType>{});
get(*f_0) = square(get(sqrt_f_0));
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> two_m_over_m_plus_r,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::two_m_over_m_plus_r<DataType> /*meta*/) const {
const auto& r = cache->get_var(*this, internal_tags::r<DataType>{});
get(*two_m_over_m_plus_r) =
2.0 * solution_.mass() / (solution_.mass() + get(r));
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> two_m_over_m_plus_r_squared,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::two_m_over_m_plus_r_squared<DataType> /*meta*/) const {
const auto& two_m_over_m_plus_r =
cache->get_var(*this, internal_tags::two_m_over_m_plus_r<DataType>{});
get(*two_m_over_m_plus_r_squared) = square(get(two_m_over_m_plus_r));
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> two_m_over_m_plus_r_cubed,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::two_m_over_m_plus_r_cubed<DataType> /*meta*/) const {
const auto& two_m_over_m_plus_r =
cache->get_var(*this, internal_tags::two_m_over_m_plus_r<DataType>{});
const auto& two_m_over_m_plus_r_squared = cache->get_var(
*this, internal_tags::two_m_over_m_plus_r_squared<DataType>{});
get(*two_m_over_m_plus_r_cubed) =
get(two_m_over_m_plus_r) * get(two_m_over_m_plus_r_squared);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> spatial_metric_rr,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::spatial_metric_rr<DataType> /*meta*/) const {
const auto& two_m_over_m_plus_r =
cache->get_var(*this, internal_tags::two_m_over_m_plus_r<DataType>{});
const auto& two_m_over_m_plus_r_squared = cache->get_var(
*this, internal_tags::two_m_over_m_plus_r_squared<DataType>{});
const auto& two_m_over_m_plus_r_cubed = cache->get_var(
*this, internal_tags::two_m_over_m_plus_r_cubed<DataType>{});
get(*spatial_metric_rr) = 1.0 + get(two_m_over_m_plus_r) +
get(two_m_over_m_plus_r_squared) +
get(two_m_over_m_plus_r_cubed);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> one_over_spatial_metric_rr,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::one_over_spatial_metric_rr<DataType> /*meta*/) const {
const auto& spatial_metric_rr =
cache->get_var(*this, internal_tags::spatial_metric_rr<DataType>{});
get(*one_over_spatial_metric_rr) = 1.0 / get(spatial_metric_rr);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> spatial_metric_rr_minus_f_0,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::spatial_metric_rr_minus_f_0<DataType> /*meta*/) const {
const auto& spatial_metric_rr =
cache->get_var(*this, internal_tags::spatial_metric_rr<DataType>{});
const auto& f_0 = cache->get_var(*this, internal_tags::f_0<DataType>{});
get(*spatial_metric_rr_minus_f_0) = get(spatial_metric_rr) - get(f_0);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> d_spatial_metric_rr,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::d_spatial_metric_rr<DataType> /*meta*/) const {
const auto& two_m_over_m_plus_r_squared = cache->get_var(
*this, internal_tags::two_m_over_m_plus_r_squared<DataType>{});
const auto& two_m_over_m_plus_r_cubed = cache->get_var(
*this, internal_tags::two_m_over_m_plus_r_cubed<DataType>{});
get(*d_spatial_metric_rr) =
(0.5 * get(two_m_over_m_plus_r_squared) + get(two_m_over_m_plus_r_cubed) +
1.5 * square(get(two_m_over_m_plus_r_squared))) /
(-solution_.mass());
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> d_f_0,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::d_f_0<DataType> /*meta*/) const {
const auto& sqrt_f_0 =
cache->get_var(*this, internal_tags::sqrt_f_0<DataType>{});
const auto& m_over_r =
cache->get_var(*this, internal_tags::m_over_r<DataType>{});
const auto& one_over_r =
cache->get_var(*this, internal_tags::one_over_r<DataType>{});
get(*d_f_0) = -2.0 * get(sqrt_f_0) * get(m_over_r) * get(one_over_r);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<tnsr::i<DataType, 3, Frame>*> d_f_0_times_x_over_r,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::d_f_0_times_x_over_r<DataType, Frame> /*meta*/) const {
const auto& d_f_0 = cache->get_var(*this, internal_tags::d_f_0<DataType>{});
const auto& x_over_r =
cache->get_var(*this, internal_tags::x_over_r<DataType, Frame>{});
get<0>(*d_f_0_times_x_over_r) = get(d_f_0) * get<0>(x_over_r);
get<1>(*d_f_0_times_x_over_r) = get(d_f_0) * get<1>(x_over_r);
get<2>(*d_f_0_times_x_over_r) = get(d_f_0) * get<2>(x_over_r);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> f_1,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::f_1<DataType> /*meta*/) const {
const auto& one_over_r =
cache->get_var(*this, internal_tags::one_over_r<DataType>{});
const auto& spatial_metric_rr =
cache->get_var(*this, internal_tags::spatial_metric_rr<DataType>{});
const auto& f_0 = cache->get_var(*this, internal_tags::f_0<DataType>{});
get(*f_1) = get(one_over_r) * (get(spatial_metric_rr) - get(f_0));
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<tnsr::i<DataType, 3, Frame>*> f_1_times_x_over_r,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::f_1_times_x_over_r<DataType, Frame> /*meta*/) const {
const auto& f_1 = cache->get_var(*this, internal_tags::f_1<DataType>{});
const auto& x_over_r =
cache->get_var(*this, internal_tags::x_over_r<DataType, Frame>{});
get<0>(*f_1_times_x_over_r) = get(f_1) * get<0>(x_over_r);
get<1>(*f_1_times_x_over_r) = get(f_1) * get<1>(x_over_r);
get<2>(*f_1_times_x_over_r) = get(f_1) * get<2>(x_over_r);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> f_2,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::f_2<DataType> /*meta*/) const {
const auto& d_spatial_metric_rr =
cache->get_var(*this, internal_tags::d_spatial_metric_rr<DataType>{});
const auto& d_f_0 = cache->get_var(*this, internal_tags::d_f_0<DataType>{});
const auto& f_1 = cache->get_var(*this, internal_tags::f_1<DataType>{});
get(*f_2) = get(d_spatial_metric_rr) - get(d_f_0) - 2.0 * get(f_1);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<tnsr::iii<DataType, 3, Frame>*>
f_2_times_xxx_over_r_cubed,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::f_2_times_xxx_over_r_cubed<DataType, Frame> /*meta*/) const {
const auto& f_2 = cache->get_var(*this, internal_tags::f_2<DataType>{});
const auto& x_over_r =
cache->get_var(*this, internal_tags::x_over_r<DataType, Frame>{});
for (size_t i = 0; i < 3; i++) {
for (size_t j = i; j < 3; j++) {
for (size_t k = j; k < 3; k++) {
f_2_times_xxx_over_r_cubed->get(i, j, k) =
get(f_2) * x_over_r.get(i) * x_over_r.get(j) * x_over_r.get(k);
}
}
}
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> f_3,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::f_3<DataType> /*meta*/) const {
const auto& one_over_r =
cache->get_var(*this, internal_tags::one_over_r<DataType>{});
const auto& two_m_over_m_plus_r_squared = cache->get_var(
*this, internal_tags::two_m_over_m_plus_r_squared<DataType>{});
const auto& one_over_spatial_metric_rr = cache->get_var(
*this, internal_tags::one_over_spatial_metric_rr<DataType>{});
get(*f_3) = get(one_over_r) * get(two_m_over_m_plus_r_squared) *
get(one_over_spatial_metric_rr);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> f_4,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::f_4<DataType> /*meta*/) const {
const auto& f_3 = cache->get_var(*this, internal_tags::f_3<DataType>{});
const auto& two_m_over_m_plus_r_squared = cache->get_var(
*this, internal_tags::two_m_over_m_plus_r_squared<DataType>{});
const auto& two_m_over_m_plus_r_cubed = cache->get_var(
*this, internal_tags::two_m_over_m_plus_r_cubed<DataType>{});
const auto& d_spatial_metric_rr =
cache->get_var(*this, internal_tags::d_spatial_metric_rr<DataType>{});
const auto& one_over_spatial_metric_rr = cache->get_var(
*this, internal_tags::one_over_spatial_metric_rr<DataType>{});
get(*f_4) = -get(f_3) -
get(two_m_over_m_plus_r_cubed) * get(one_over_spatial_metric_rr) /
solution_.mass() -
get(d_spatial_metric_rr) * get(two_m_over_m_plus_r_squared) *
square(get(one_over_spatial_metric_rr));
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> lapse,
const gsl::not_null<CachedBuffer*> cache,
gr::Tags::Lapse<DataType> /*meta*/) const {
const auto& one_over_spatial_metric_rr = cache->get_var(
*this, internal_tags::one_over_spatial_metric_rr<DataType>{});
get(*lapse) = sqrt(get(one_over_spatial_metric_rr));
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*>
neg_half_lapse_cubed_times_d_spatial_metric_rr,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::neg_half_lapse_cubed_times_d_spatial_metric_rr<
DataType> /*meta*/) const {
const auto& lapse = cache->get_var(*this, gr::Tags::Lapse<DataType>{});
const auto& d_spatial_metric_rr =
cache->get_var(*this, internal_tags::d_spatial_metric_rr<DataType>{});
get(*neg_half_lapse_cubed_times_d_spatial_metric_rr) =
-0.5 * cube(get(lapse)) * get(d_spatial_metric_rr);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<tnsr::I<DataType, 3, Frame>*> shift,
const gsl::not_null<CachedBuffer*> cache,
gr::Tags::Shift<3, Frame, DataType> /*meta*/) const {
const auto& two_m_over_m_plus_r_squared = cache->get_var(
*this, internal_tags::two_m_over_m_plus_r_squared<DataType>{});
const auto& x_over_r =
cache->get_var(*this, internal_tags::x_over_r<DataType, Frame>{});
const auto& one_over_spatial_metric_rr = cache->get_var(
*this, internal_tags::one_over_spatial_metric_rr<DataType>{});
::tenex::evaluate<ti::I>(shift, two_m_over_m_plus_r_squared() *
x_over_r(ti::I) *
one_over_spatial_metric_rr());
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<tnsr::iJ<DataType, 3, Frame>*> deriv_shift,
const gsl::not_null<CachedBuffer*> cache,
DerivShift<DataType, Frame> /*meta*/) const {
const auto& x_over_r =
cache->get_var(*this, internal_tags::x_over_r<DataType, Frame>{});
const auto& f_3 = cache->get_var(*this, internal_tags::f_3<DataType>{});
const auto& f_4 = cache->get_var(*this, internal_tags::f_4<DataType>{});
for (size_t k = 0; k < 3; ++k) {
for (size_t i = k; i < 3; ++i) {
if (i != k) {
deriv_shift->get(k, i) = get(f_4) * x_over_r.get(i) * x_over_r.get(k);
deriv_shift->get(i, k) = deriv_shift->get(k, i); // symmetry
} else {
deriv_shift->get(k, i) = get(f_4) * square(x_over_r.get(i)) + get(f_3);
}
}
}
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<tnsr::ii<DataType, 3, Frame>*> spatial_metric,
const gsl::not_null<CachedBuffer*> cache,
gr::Tags::SpatialMetric<3, Frame, DataType> /*meta*/) const {
const auto& f_0 = cache->get_var(*this, internal_tags::f_0<DataType>{});
const auto& spatial_metric_rr_minus_f_0 = cache->get_var(
*this, internal_tags::spatial_metric_rr_minus_f_0<DataType>{});
const auto& x_over_r =
cache->get_var(*this, internal_tags::x_over_r<DataType, Frame>{});
for (size_t i = 0; i < 3; ++i) {
for (size_t j = i; j < 3; ++j) {
spatial_metric->get(i, j) =
get(spatial_metric_rr_minus_f_0) * x_over_r.get(i) * x_over_r.get(j);
if (i == j) {
spatial_metric->get(i, j) += get(f_0);
}
}
}
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<tnsr::ijj<DataType, 3, Frame>*> deriv_spatial_metric,
const gsl::not_null<CachedBuffer*> cache,
DerivSpatialMetric<DataType, Frame> /*meta*/) const {
const auto& d_f_0_times_x_over_r = cache->get_var(
*this, internal_tags::d_f_0_times_x_over_r<DataType, Frame>{});
const auto& f_1_times_x_over_r = cache->get_var(
*this, internal_tags::f_1_times_x_over_r<DataType, Frame>{});
const auto& f_2_times_xxx_over_r_cubed = cache->get_var(
*this, internal_tags::f_2_times_xxx_over_r_cubed<DataType, Frame>{});
for (size_t k = 0; k < 3; ++k) {
for (size_t i = 0; i < 3; ++i) {
for (size_t j = i; j < 3; ++j) {
deriv_spatial_metric->get(k, i, j) =
f_2_times_xxx_over_r_cubed.get(k, i, j);
if (i == j) {
deriv_spatial_metric->get(k, i, j) += d_f_0_times_x_over_r.get(k);
}
if (j == k) {
deriv_spatial_metric->get(k, i, j) += f_1_times_x_over_r.get(i);
}
if (i == k) {
deriv_spatial_metric->get(k, i, j) += f_1_times_x_over_r.get(j);
}
}
}
}
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<tnsr::ii<DataType, 3, Frame>*> dt_spatial_metric,
const gsl::not_null<CachedBuffer*> /*cache*/,
::Tags::dt<gr::Tags::SpatialMetric<3, Frame, DataType>> /*meta*/) const {
std::fill(dt_spatial_metric->begin(), dt_spatial_metric->end(), 0.);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> det_spatial_metric,
const gsl::not_null<CachedBuffer*> cache,
gr::Tags::DetSpatialMetric<DataType> /*meta*/) const {
const auto& spatial_metric =
cache->get_var(*this, gr::Tags::SpatialMetric<3, Frame, DataType>{});
*det_spatial_metric = determinant(spatial_metric);
}
template <typename DataType, typename Frame>
void HarmonicSchwarzschild::IntermediateComputer<DataType, Frame>::operator()(
const gsl::not_null<Scalar<DataType>*> one_over_det_spatial_metric,
const gsl::not_null<CachedBuffer*> cache,
internal_tags::one_over_det_spatial_metric<DataType> /*meta*/) const {
const auto& det_spatial_metric =
cache->get_var(*this, gr::Tags::DetSpatialMetric<DataType>{});
get(*one_over_det_spatial_metric) = 1.0 / get(det_spatial_metric);
}
template <typename DataType, typename Frame>
tnsr::i<DataType, 3, Frame>
HarmonicSchwarzschild::IntermediateVars<DataType, Frame>::get_var(
const IntermediateComputer<DataType, Frame>& computer,
DerivLapse<DataType, Frame> /*meta*/) {
const auto& neg_half_lapse_cubed_times_d_spatial_metric_rr = get_var(
computer, internal_tags::neg_half_lapse_cubed_times_d_spatial_metric_rr<
DataType>{});
const auto& x_over_r =
get_var(computer, internal_tags::x_over_r<DataType, Frame>{});
tnsr::i<DataType, 3, Frame> deriv_lapse{};
for (size_t i = 0; i < 3; i++) {
deriv_lapse.get(i) =
get(neg_half_lapse_cubed_times_d_spatial_metric_rr) * x_over_r.get(i);
}
return deriv_lapse;
}
template <typename DataType, typename Frame>
Scalar<DataType>
HarmonicSchwarzschild::IntermediateVars<DataType, Frame>::get_var(
const IntermediateComputer<DataType, Frame>& computer,
::Tags::dt<gr::Tags::Lapse<DataType>> /*meta*/) {
const auto& r = get(get_var(computer, internal_tags::r<DataType>{}));
return make_with_value<Scalar<DataType>>(r, 0.);
}
template <typename DataType, typename Frame>
tnsr::I<DataType, 3, Frame>
HarmonicSchwarzschild::IntermediateVars<DataType, Frame>::get_var(
const IntermediateComputer<DataType, Frame>& computer,
::Tags::dt<gr::Tags::Shift<3, Frame, DataType>> /*meta*/) {
const auto& r = get(get_var(computer, internal_tags::r<DataType>{}));
return make_with_value<tnsr::I<DataType, 3, Frame>>(r, 0.);
}
template <typename DataType, typename Frame>
Scalar<DataType>
HarmonicSchwarzschild::IntermediateVars<DataType, Frame>::get_var(
const IntermediateComputer<DataType, Frame>& computer,
gr::Tags::SqrtDetSpatialMetric<DataType> /*meta*/) {
const auto& det_spatial_metric =
get_var(computer, gr::Tags::DetSpatialMetric<DataType>{});
return Scalar<DataType>(sqrt(get(det_spatial_metric)));
}
template <typename DataType, typename Frame>
tnsr::II<DataType, 3, Frame>
HarmonicSchwarzschild::IntermediateVars<DataType, Frame>::get_var(
const IntermediateComputer<DataType, Frame>& computer,
gr::Tags::InverseSpatialMetric<3, Frame, DataType> /*meta*/) {
const auto& spatial_metric =
get_var(computer, gr::Tags::SpatialMetric<3, Frame, DataType>{});
const DataType& spatial_metric_00 = get<0, 0>(spatial_metric);
const DataType& spatial_metric_01 = get<0, 1>(spatial_metric);
const DataType& spatial_metric_02 = get<0, 2>(spatial_metric);
const DataType& spatial_metric_11 = get<1, 1>(spatial_metric);
const DataType& spatial_metric_12 = get<1, 2>(spatial_metric);
const DataType& spatial_metric_22 = get<2, 2>(spatial_metric);
const auto& one_over_det_spatial_metric =
get_var(computer, internal_tags::one_over_det_spatial_metric<DataType>{});
tnsr::II<DataType, 3, Frame> inverse_spatial_metric{};
get<0, 0>(inverse_spatial_metric) =
(spatial_metric_11 * spatial_metric_22 - square(spatial_metric_12)) *
get(one_over_det_spatial_metric);
get<0, 1>(inverse_spatial_metric) = (spatial_metric_12 * spatial_metric_02 -
spatial_metric_22 * spatial_metric_01) *
get(one_over_det_spatial_metric);
get<0, 2>(inverse_spatial_metric) = (spatial_metric_01 * spatial_metric_12 -
spatial_metric_02 * spatial_metric_11) *
get(one_over_det_spatial_metric);
get<1, 1>(inverse_spatial_metric) = (spatial_metric_22 * spatial_metric_00 -
spatial_metric_02 * spatial_metric_02) *
get(one_over_det_spatial_metric);
get<1, 2>(inverse_spatial_metric) = (spatial_metric_02 * spatial_metric_01 -
spatial_metric_00 * spatial_metric_12) *
get(one_over_det_spatial_metric);
get<2, 2>(inverse_spatial_metric) = (spatial_metric_00 * spatial_metric_11 -
spatial_metric_01 * spatial_metric_01) *
get(one_over_det_spatial_metric);
return inverse_spatial_metric;
}
template <typename DataType, typename Frame>
tnsr::ii<DataType, 3, Frame>
HarmonicSchwarzschild::IntermediateVars<DataType, Frame>::get_var(
const IntermediateComputer<DataType, Frame>& computer,
gr::Tags::ExtrinsicCurvature<3, Frame, DataType> /*meta*/) {
return gr::extrinsic_curvature(
get_var(computer, gr::Tags::Lapse<DataType>{}),
get_var(computer, gr::Tags::Shift<3, Frame, DataType>{}),
get_var(computer, DerivShift<DataType, Frame>{}),
get_var(computer, gr::Tags::SpatialMetric<3, Frame, DataType>{}),
get_var(computer,
::Tags::dt<gr::Tags::SpatialMetric<3, Frame, DataType>>{}),
get_var(computer, DerivSpatialMetric<DataType, Frame>{}));
}
#define DTYPE(data) BOOST_PP_TUPLE_ELEM(0, data)
#define FRAME(data) BOOST_PP_TUPLE_ELEM(1, data)
#define INSTANTIATE(_, data) \
template class HarmonicSchwarzschild::IntermediateVars<DTYPE(data), \
FRAME(data)>; \
template class HarmonicSchwarzschild::IntermediateComputer<DTYPE(data), \
FRAME(data)>;
GENERATE_INSTANTIATIONS(INSTANTIATE, (DataVector, double),
(::Frame::Inertial, ::Frame::Grid))
#undef INSTANTIATE
#undef DTYPE
#undef FRAME
} // namespace gr::Solutions
|
degulab/FALCON-SEED
|
src/FALCONSEED/runner/src/ssac/falconseed/module/swing/tree/MExecDefTree.java
|
/*
* 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.
*
* Copyright 2007-2015 SSAC(Systems of Social Accounting Consortium)
* <author> <NAME> (PieCake,Inc.)
* <author> <NAME> (TOKYO INSTITUTE OF TECHNOLOGY)
* <author> <NAME> (Statistics Bureau)
* <author> <NAME> (Tokyo University of Technology)
* <author> <NAME> (HOSEI UNIVERSITY)
* <author> <NAME> (TOKYO INSTITUTE OF TECHNOLOGY)
*/
/*
* @(#)MExecDefTree.java 3.2.1 2015/07/08
* - modified by Y.Ishizuka(PieCake.inc,)
* @(#)MExecDefTree.java 2.0.0 2012/11/02
* - modified by Y.Ishizuka(PieCake.inc,)
* @(#)MExecDefTree.java 1.22 2012/07/12
* - modified by Y.Ishizuka(PieCake.inc,)
* @(#)MExecDefTree.java 1.20 2012/03/16
* - modified by Y.Ishizuka(PieCake.inc,)
* @(#)MExecDefTree.java 1.10 2011/02/15
* - modified by Y.Ishizuka(PieCake.inc,)
* @(#)MExecDefTree.java 1.00 2010/12/20
* - created by Y.Ishizuka(PieCake.inc,)
*/
package ssac.falconseed.module.swing.tree;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Window;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DropTargetDragEvent;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.Icon;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import ssac.aadl.common.CommonMessages;
import ssac.aadl.common.CommonResources;
import ssac.aadl.module.ModuleFileManager;
import ssac.falconseed.module.MExecDefFileTransferable;
import ssac.falconseed.module.swing.MExecDefFileProgressMonitorTask;
import ssac.falconseed.runner.RunnerResources;
import ssac.util.Strings;
import ssac.util.io.VirtualFile;
import ssac.util.io.VirtualFileOperationException;
import ssac.util.logging.AppLogger;
import ssac.util.swing.Application;
import ssac.util.swing.FrameWindow;
import ssac.util.swing.tree.DnDTree;
import ssac.util.swing.tree.IDnDTreeHandler;
/**
* モジュール実行定義を表示するツリーコンポーネント。
*
* @version 3.2.1
*/
public class MExecDefTree extends DnDTree implements TreeWillExpandListener, TreeSelectionListener
{
//------------------------------------------------------------
// Constants
//------------------------------------------------------------
private static final long serialVersionUID = 1L;
//------------------------------------------------------------
// Fields
//------------------------------------------------------------
private final FocusRequester _hFocusRequester = new FocusRequester();
//------------------------------------------------------------
// Constructions
//------------------------------------------------------------
public MExecDefTree() {
this(null, null);
}
public MExecDefTree(MExecDefTreeModel newModel) {
this(newModel, null);
}
public MExecDefTree(MExecDefTreeModel newModel, IDnDTreeHandler newHandler) {
super(newModel==null ? new MExecDefTreeModel() : newModel);
setTreeHandler(newHandler);
setRootVisible(false); // ルートノードは表示しない
setShowsRootHandles(true); // 最上位にハンドルを表示する
setTooltipEnabled(true); // ツールチップを表示する
addTreeSelectionListener(this);
addTreeWillExpandListener(this);
}
//------------------------------------------------------------
// Public interfaces
//------------------------------------------------------------
/**
* このコンポーネントに設定されているモデルを取得する。
* このツリーコンポーネントのモデルは、{@link MExecDefTreeModel} クラスの
* インスタンスに限定される。
* @return このモデルに設定されている <code>MExecDefTreeModel</code> オブジェクト
*/
@Override
public MExecDefTreeModel getModel() {
return (MExecDefTreeModel)super.getModel();
}
@Override
public String getToolTipText(Object value, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus)
{
if (value == getModel().getUserRootNode()) {
// 選択されたノードがユーザールートの場合のみ、パスを表示する
return ((MExecDefTreeNode)value).getFileObject().getAbsolutePath();
} else {
return null;
}
}
public String getTreeNodeFileProperty(TreePath treepath) {
if (treepath != null) {
return getTreeNodeFileProperty((MExecDefTreeNode)treepath.getLastPathComponent());
} else {
return null;
}
}
public String getTreeNodeFileProperty(MExecDefTreeNode node) {
String strProperty = null;
if (node == getModel().getUserRootNode() || node == getModel().getSystemRootNode()) {
// システムルートディレクトリもしくはユーザールートディレクトリなら,絶対パスを表示
String dirprop = getTreeNodeFileInfo(node);
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(node.getFilePath());
sb.append("] ");
if (dirprop != null)
sb.append(dirprop);
strProperty = sb.toString();
}
else {
strProperty = getTreeNodeFileInfo(node);
if (strProperty != null) {
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(node.getDisplayName());
sb.append("] ");
sb.append(strProperty);
strProperty = sb.toString();
}
}
return strProperty;
}
public String getTreeNodeFileInfo(MExecDefTreeNode node) {
if (node == null || node.getFileObject() == null) {
return null;
}
// 最終更新日を表示する
long lastmodified;
if (node.isExecDefData()) {
lastmodified = ((MExecDefDataFile)node.getUserObject()).getDataFile().lastModified();
}
else {
lastmodified = node.lastModified();
}
// フォーマット
DateFormat frmDate = DateFormat.getDateTimeInstance();
Date dtModified = new Date(lastmodified);
return frmDate.format(dtModified);
}
/**
* このコンポーネントに指定されたツリーモデルを設定する。
* 設定可能なツリーモデルは、{@link MExecDefTreeModel} クラスのインスタンスに
* 限定される。
* @param newModel 設定する <code>MExecDefTreeModel</code> オブジェクト
* @throws NullPointerException <em>newModel</em> が <tt>null</tt> の場合
* @throws ClassCastException <em>newModel</em> が <code>MExecDefTreeModel</code> の
* インスタンスではない場合
*/
@Override
public void setModel(TreeModel newModel) {
if (newModel == null)
throw new NullPointerException("newModel argument is null.");
super.setModel((MExecDefTreeModel)newModel);
}
/**
* 現在のシステムルートとなるディレクトリの抽象パスを返す。
* @return システムルートディレクトリの抽象パス。設定されていない場合は <tt>null</tt>
*/
public VirtualFile getSystemRootDirectory() {
return getModel().getSystemRootDirectory();
}
/**
* 現在のユーザールートとなるディレクトリの抽象パスを返す。
* @return ユーザールートディレクトリの抽象パス。設定されていない場合は <tt>null</tt>
*/
public VirtualFile getUserRootDirectory() {
return getModel().getUserRootDirectory();
}
/**
* このコンポーネントにフォーカスを設定する。
*/
public void setFocus() {
if (!hasFocus()) {
SwingUtilities.invokeLater(_hFocusRequester);
}
}
/**
* このビューを格納するフレームウィンドウを取得する。
* @return このビューを格納するフレームウィンドウのインスタンス。
* このビューがフレームに格納されていない場合は <tt>null</tt> を返す。
*/
public FrameWindow getFrame() {
Window parentFrame = SwingUtilities.windowForComponent(this);
if (parentFrame instanceof FrameWindow)
return (FrameWindow)parentFrame;
else
return null;
}
/**
* 選択されているノードがすべて同じ階層にある場合に <tt>true</tt> を返す。
* 選択されていない場合は <tt>false</tt> を返す。
*/
public boolean isSelectedAllSameLevels() {
if (getSelectionCount() > 0) {
// 複数選択なら、同じレベルか判定する
TreePath[] paths = getSelectionPaths();
return isTreePathAllSameLevels(paths);
}
else {
// no selection
return false;
}
}
/**
* 指定されたツリーパスがすべて同じ階層のものであるかを検証する。
* このメソッドでは、指定されたツリーパスの要素数がすべて同じ場合に同じ階層とみなす。
* @param paths 検証するパスの配列
* @return すべて同じ階層のパスであれば <tt>true</tt> を返す。
* 指定された配列の要素が空である場合は <tt>false</tt> を返す。
* @throws NullPointerException 引数が <tt>null</tt> の場合
*/
public boolean isTreePathAllSameLevels(TreePath[] paths) {
int len = paths.length;
if (len == 1) {
// 要素が一つなら、同一階層
return true;
}
else if (len > 0) {
int level = paths[0].getPathCount();
for (int i = 1; i < len; i++) {
if (paths[i].getPathCount() != level) {
// not same level
return false;
}
}
// all same levels
return true;
}
else {
// 要素が空なら判定不可
return false;
}
}
/**
* 現在選択されている一つのノードに関連付けられている抽象パスを取得する。
* このメソッドが返す抽象パスは、{@link javax.swing.JTree#getSelectionPath()} メソッドが
* 返すノードのものとなる。
* @return 選択されているノードの一つからそのノードに関連付けられている
* 抽象パスを返す。選択されていない場合は <tt>null</tt> を返す。
*/
public VirtualFile getSelectionFile() {
TreePath path = getSelectionPath();
if (path == null) {
return null;
} else {
return ((MExecDefTreeNode)path.getLastPathComponent()).getFileObject();
}
}
/**
* 現在選択されているすべてのノードに関連付けられている抽象パスを取得する。
* このメソッドが返す抽象パスは、{@link javax.swing.JTree#getSelectionPaths()} メソッドが
* 返すノードのものとなる。
* @return 選択されているすべてのノードに関連付けられている抽象パスの配列を返す。
* 選択されていない場合は <tt>null</tt> を返す。
*/
public VirtualFile[] getSelectionFiles() {
TreePath[] paths = getSelectionPaths();
if (paths == null) {
return null;
} else {
VirtualFile[] files = new VirtualFile[paths.length];
for (int i = 0; i < paths.length; i++) {
files[i] = ((MExecDefTreeNode)paths[i].getLastPathComponent()).getFileObject();
}
return files;
}
}
/**
* 現在選択されている一つのノードに関連付けられているファイルモデルを取得する。
* このメソッドが返すオブジェクトは、{@link javax.swing.JTree#getSelectionPath()} メソッドが
* 返すノードのものとなる。
* @return 選択されているノードの一つからそのノードに関連付けられている
* ファイルモデルを返す。選択されていない場合は <tt>null</tt> を返す。
* @since 1.10
*/
public IMExecDefFile getSelectionNodeData() {
TreePath path = getSelectionPath();
if (path == null) {
return null;
} else {
return ((MExecDefTreeNode)path.getLastPathComponent()).getUserObject();
}
}
/**
* 現在選択されているすべてのノードに関連付けられているファイルモデルを取得する。
* このメソッドが返すオブジェクトは、{@link javax.swing.JTree#getSelectionPaths()} メソッドが
* 返すノードのものとなる。
* @return 選択されているすべてのノードに関連付けられているファイルモデルの配列を返す。
* 選択されていない場合は <tt>null</tt> を返す。
* @since 1.10
*/
public IMExecDefFile[] getSelectionNodeDatas() {
TreePath[] paths = getSelectionPaths();
if (paths == null) {
return null;
} else {
IMExecDefFile[] datas = new IMExecDefFile[paths.length];
for (int i = 0; i < paths.length; i++) {
datas[i] = ((MExecDefTreeNode)paths[i].getLastPathComponent()).getUserObject();
}
return datas;
}
}
/**
* 現在選択されているノードから、最初のモジュール実行定義設定ファイルを取得する。
* モジュール実行定義が選択されていない場合、このメソッドは <tt>null</tt> を返す。
* @return 選択されている最初のモジュール実行定義設定ファイルの抽象パスを返す。
* モジュール実行定義が選択されていない場合は <tt>null</tt> を返す。
*/
public VirtualFile getSelectionMExecDefPrefsFile() {
VirtualFile vfPrefs = null;
TreePath[] paths = getSelectionPaths();
if (paths != null) {
for (TreePath tp : paths) {
MExecDefTreeNode node = (MExecDefTreeNode)tp.getLastPathComponent();
if (node.isExecDefData()) {
vfPrefs = ((MExecDefDataFile)node.getUserObject()).getDataFile();
break;
}
}
}
return vfPrefs;
}
/**
* 現在選択されているノードから、すべてのモジュール実行定義設定ファイルを取得する。
* モジュール実行定義が一つも選択されていない場合、このメソッドは <tt>null</tt> を返す。
* @return 選択されているすべてのモジュール実行定義設定ファイルの抽象パスを格納する配列を返す。
* モジュール実行定義が一つも選択されていない場合は <tt>null</tt> を返す。
*/
public VirtualFile[] getSelectionMExecDefPrefsFiles() {
VirtualFile[] vfPrefsArray = null;
TreePath[] paths = getSelectionPaths();
if (paths != null) {
ArrayList<VirtualFile> filelist = new ArrayList<VirtualFile>();
for (TreePath tp : paths) {
MExecDefTreeNode node = (MExecDefTreeNode)tp.getLastPathComponent();
if (node.isExecDefData()) {
filelist.add( ((MExecDefDataFile)node.getUserObject()).getDataFile() );
}
}
if (!filelist.isEmpty()) {
vfPrefsArray = filelist.toArray(new VirtualFile[filelist.size()]);
}
}
return vfPrefsArray;
}
/**
* 現在選択されているノードのツリー構造を最新の情報に更新する。
* 選択されていない場合は、ルートノードから最新情報に更新する。
*/
public void refreshTree() {
if (getSelectionCount() > 0) {
TreePath[] paths = getSelectionPaths();
for (TreePath path : paths) {
refreshTree(path);
}
} else {
// for Root node
Object rootNode = getModel().getRoot();
if (rootNode != null) {
refreshTree(new TreePath(rootNode));
}
}
}
/**
* 指定されたツリーパスが示す最終ノードを起点に、ツリー構造を最新の情報に更新する。
* この更新では、ツリーコンポーネントに表示されているノードの情報のみを更新する。
* @param path 更新するノードの位置を示すツリーパス
* @throws NullPointerException <em>path</em> が <tt>null</tt> の場合
* @throws ClassCastException <em>path</em> の終端ノードが {@link MExecDefTreeNode} の
* インスタンスではない場合
*/
public void refreshTree(TreePath path) {
MExecDefTreeNode node = (MExecDefTreeNode)path.getLastPathComponent();
if (!node.exists()) {
// 指定のノードが示すファイルが存在しない場合は、親のレベルで更新する。
if (!node.isRoot()) {
refreshTree(path.getParentPath());
}
return;
}
// refresh
//node.refreshProperties();
if (isExpanded(path)) {
getModel().refreshChildren(node);
int numChildren = node.getChildCount();
for (int i = 0; i < numChildren; i++) {
TreePath childPath = path.pathByAddingChild(node.getChildAt(i));
refreshTree(childPath);
}
} else {
getModel().reload(node);
}
}
@Override
public Icon convertValueToIcon(Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
if (value instanceof MExecDefTreeNode) {
MExecDefTreeNode node = (MExecDefTreeNode)value;
if (node.exists()) {
// 存在するファイル
if (node.isRoot()) {
// root node icon
return CommonResources.ICON_DISKUNIT;
} else if (node.isDirectory()) {
if (expanded) {
return CommonResources.ICON_DIR_OPEN;
} else {
return CommonResources.ICON_DIR_CLOSE;
}
} else if (node.isExecDefGenericFilter()) {
//--- 汎用フィルタ定義のルートディレクトリ
return RunnerResources.ICON_GENERICFILTER;
} else if (node.isExecDefFilterMacro()) {
//--- フィルタマクロ定義のルートディレクトリ
return RunnerResources.ICON_MACROFILTER;
} else if (node.isExecDefData()) {
//--- モジュール実行定義のルートディレクトリ
return RunnerResources.ICON_FILTER;
} else {
return CommonResources.ICON_FILE;
}
} else {
// 存在しないファイルなら、×アイコン
return CommonResources.ICON_DELETE;
}
}
return null;
}
@Override
public String convertValueToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
if (value == null) {
return "";
}
else if (value instanceof MExecDefTreeNode) {
return ((MExecDefTreeNode)value).getDisplayName();
}
else {
return value.toString();
}
}
//------------------------------------------------------------
// File operations
//------------------------------------------------------------
public TreePath createDirectory(Component parentComponent, TreePath parentDir, String newDirName) {
MExecDefTreeModel model = getModel();
MExecDefTreeNode ndParent = (MExecDefTreeNode)parentDir.getLastPathComponent();
MExecDefTreeNode ndNewDir = null;
//--- check
if (!ndParent.isNodeAncestor(getModel().getUserRootNode())) {
throw new IllegalArgumentException("This parent node is delived from User root directory.");
}
//--- create
try {
ndNewDir = model.createDirectory(ndParent, newDirName);
} catch (VirtualFileOperationException ex) {
AppLogger.error(ex);
String errmsg = CommonMessages.getErrorMessage(CommonMessages.MessageID.ERR_FILE_CREATE, ex, "'" + String.valueOf(newDirName) + "'");
Application.showErrorMessage(parentComponent, errmsg);
return null;
}
TreePath retPath = new TreePath(model.getPathToRoot(ndNewDir));
setSelectionPath(retPath);
return retPath;
}
public TreePath createMExecDef(Component parentComponent, TreePath parentDir, String newName) {
MExecDefTreeModel model = getModel();
MExecDefTreeNode ndParent = (MExecDefTreeNode)parentDir.getLastPathComponent();
MExecDefTreeNode ndNewDir = null;
//--- check
if (!ndParent.isNodeAncestor(getModel().getUserRootNode())) {
throw new IllegalArgumentException("This parent node is delived from User root directory.");
}
//--- create
try {
ndNewDir = model.createMExecDef(ndParent, newName);
} catch (VirtualFileOperationException ex) {
AppLogger.error(ex);
String errmsg = CommonMessages.getErrorMessage(CommonMessages.MessageID.ERR_FILE_CREATE, ex, "'" + String.valueOf(newName) + "'");
Application.showErrorMessage(parentComponent, errmsg);
return null;
}
TreePath retPath = new TreePath(model.getPathToRoot(ndNewDir));
setSelectionPath(retPath);
return retPath;
}
/**
* <em>sourcePath</em> が示すファイルもしくはディレクトリの名称を <em>newName</em> に
* 変更する。このメソッドでは名称の正当性については検証しない。
* <em>watchFiles</em> にエントリが存在する場合、そのファイルと移動先との対応を
* 保持するマップを返す。
* 通知するメッセージがある場合は、<em>ownerFrame</em> を基準として
* メッセージボックスを表示する。
* @param ownerFrame メッセージボックスのオーナーフレーム
* @param sourcePath 名前を変更する対象の位置を示すツリーパス
* @param newName 新しい名前を表す文字列
* @return <em>watchFiles</em> にエントリが存在する場合は、そのファイルと変更後の抽象パスとの
* 対応を保持するマップを返す。<em>watchFiles</em> が <tt>null</tt> もしくは
* 空の場合は、空のマップを返す。
* @throws NullPointerException <em>sourcePath</em> が <tt>null</tt> の場合
* @throws IllegalArgumentException <em>sourcePath</em> が示すノードがルートのノードの場合、
* <em>newName</em> が <tt>null</tt> もしくは空文字列の場合
*/
public Map<VirtualFile,VirtualFile> renameFile(FrameWindow ownerFrame, TreePath sourcePath, String newName,
Collection<? extends VirtualFile> watchFiles)
{
if (sourcePath == null)
throw new NullPointerException("'sourcePath' argument is null.");
if (sourcePath.getPathCount() < 2)
throw new IllegalArgumentException("'sourcePath' argument is root node.");
if (Strings.isNullOrEmpty(newName))
throw new IllegalArgumentException("'newName' argument is null or empty.");
HashMap<VirtualFile,VirtualFile> watchMap = new HashMap<VirtualFile, VirtualFile>();
if (watchFiles != null && !watchFiles.isEmpty()) {
for (VirtualFile f : watchFiles) {
watchMap.put(f, null);
}
}
// rename
MExecDefTreeNode node = (MExecDefTreeNode)sourcePath.getLastPathComponent();
VirtualFile sourceFile = node.getFileObject();
VirtualFile targetFile = sourceFile.getParentFile().getChildFile(newName);
VirtualFile sourcePrefsFile = null;
VirtualFile targetPrefsFile = null;
if (sourceFile.isFile() && !Strings.endsWithIgnoreCase(sourceFile.getName(), ModuleFileManager.EXT_FILE_PREFS)) {
// ターゲットが設定ファイルではないファイルの場合、
// 同名の設定ファイルも自動的に処理対象とする
// *.aadl.pref, *.jar.prefs, *.amf.prefs
VirtualFile fPrefs = ModuleFileManager.getPrefsFile(sourceFile);
if (fPrefs.exists() && fPrefs.isFile()) {
sourcePrefsFile = fPrefs;
targetPrefsFile = ModuleFileManager.getPrefsFile(targetFile);
}
}
String errmsg = null;
try {
if (!sourceFile.renameTo(targetFile)) {
errmsg = String.format(CommonMessages.getInstance().msgCouldNotRenameTo,
sourceFile.getName(), newName);
AppLogger.error(errmsg);
}
}
catch (SecurityException ex) {
errmsg = String.format(CommonMessages.getInstance().msgCouldNotRenameTo,
sourceFile.getName(), newName);
AppLogger.error(errmsg, ex);
}
if (errmsg != null) {
Application.showErrorMessage(ownerFrame, errmsg);
return watchMap;
}
// rename with prefs
if (sourcePrefsFile != null) {
errmsg = null;
try {
if (!sourcePrefsFile.renameTo(targetPrefsFile)) {
errmsg = String.format(CommonMessages.getInstance().msgCouldNotRenameTo,
sourcePrefsFile.getName(), targetPrefsFile.getName());
AppLogger.warn(errmsg);
}
else {
// success
if (watchMap.containsKey(sourcePrefsFile)) {
watchMap.put(sourcePrefsFile, targetPrefsFile);
}
}
}
catch (SecurityException ex) {
errmsg = String.format(CommonMessages.getInstance().msgCouldNotRenameTo,
sourcePrefsFile.getName(), targetPrefsFile.getName());
AppLogger.warn(errmsg, ex);
}
}
// update watch map
if (!watchMap.isEmpty()) {
for (VirtualFile from : watchMap.keySet()) {
if (from.equals(sourceFile)) {
watchMap.put(from, targetFile);
}
else if (from.isDescendingFrom(sourceFile)) {
String relpath = from.relativePathFrom(sourceFile);
VirtualFile toFile = targetFile.getChildFile(relpath);
watchMap.put(from, toFile);
}
}
}
// update tree nodes
getModel().changeFileObject(node, targetFile);
getModel().sortChildren((MExecDefTreeNode)node.getParent());
//refreshTree(sourcePath);
setSelectionPath(sourcePath);
// completed
return watchMap;
}
/**
* <em>sourcePaths</em> のファイルを <em>targetPath</em> の示す位置に移動する。
* <em>watchFiles</em> にエントリが存在する場合、そのファイルと移動先との対応を
* 保持するマップを返す。
* 通知するメッセージがある場合は、<em>ownerFrame</em> を基準として
* メッセージボックスを表示する。
* @param ownerFrame メッセージボックスのオーナーフレーム
* @param sourcePaths 移動するファイルの位置を示すツリーパス
* @param targetPath 移動先ディレクトリの位置を示すツリーパス
* @param watchFiles 移動先を監視するファイルのコレクション
* @return <em>watchFiles</em> にエントリが存在する場合は、そのファイルと移動先との
* 対応を保持するマップを返す。<em>watchFiles</em> が <tt>null</tt> もしくは
* 空の場合は、空のマップを返す。
* @throws NullPointerException <em>sourcePath</em> もしくは <em>targetPath</em> が <tt>null</tt> の場合
*/
public Map<VirtualFile,VirtualFile> moveFiles(FrameWindow ownerFrame, TreePath[] sourcePaths, TreePath targetPath,
Collection<? extends VirtualFile> watchFiles)
{
if (sourcePaths == null)
throw new NullPointerException("'sourcePaths' argument is null.");
if (targetPath == null)
throw new NullPointerException("'targetPath' argument is null.");
MoveProgressMonitor task = new MoveProgressMonitor(watchFiles, sourcePaths, targetPath);
task.execute(ownerFrame);
refreshAfterProgressTask(task);
showErrorForProgressTask(ownerFrame, task);
return task.watchFiles;
}
/**
* <em>sourceFiles</em> に含まれるすべてのファイルを <em>targetPath</em> の示す位置にコピーする。
* コピー先の直下に <em>sourceFiles</em> に含まれるファイルが存在する場合は、名前を変更して
* コピーする。
* 通知するメッセージがある場合は、<em>ownerFrame</em> を基準として
* メッセージボックスを表示する。
* @param ownerFrame メッセージボックスのオーナーフレーム
* @param sourceFiles コピーするファイルを示す抽象パスの配列
* @param targetPath コピー先となるディレクトリを示すツリーパス
* @throws NullPointerException <em>sourceFiles</em> もしくは <em>targetPath</em> が <tt>null</tt> の場合
*/
public void copyFiles(FrameWindow ownerFrame, VirtualFile[] sourceFiles, TreePath targetPath) {
if (sourceFiles == null)
throw new NullPointerException("'sourceFiles' argument is null.");
if (targetPath == null)
throw new NullPointerException("'targetPath' argument is null.");
CopyProgressMonitor task = new CopyProgressMonitor(sourceFiles, targetPath);
task.execute(ownerFrame);
refreshAfterProgressTask(task);
showErrorForProgressTask(ownerFrame, task);
}
/**
* 指定されたツリーパスのファイルもしくはディレクトリを削除する。
* 通知するメッセージがある場合は、<em>ownerFrame</em> を基準として
* メッセージボックスを表示する。
* @param ownerFrame メッセージボックスのオーナーフレーム
* @param deletePaths 削除するファイルの位置を示すツリーパス
* @throws NullPointerException <em>deletePaths</em> が <tt>null</tt> の場合
*/
public void deleteFiles(FrameWindow ownerFrame, TreePath[] deletePaths) {
if (deletePaths == null)
throw new NullPointerException("'deletePaths' argument is null.");
DeleteProgressMonitor task = new DeleteProgressMonitor(deletePaths);
task.execute(ownerFrame);
refreshAfterProgressTask(task);
showErrorForProgressTask(ownerFrame, task);
}
//------------------------------------------------------------
// Event handlers
//------------------------------------------------------------
public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException
{
// no implementation
}
public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException
{
// ツリーが展開されるときに、ノードの情報を最新に更新する
MExecDefTreeNode node = (MExecDefTreeNode)event.getPath().getLastPathComponent();
((MExecDefTree)event.getSource()).getModel().refreshNode(node);
}
/**
* ツリーコンポーネントのノード選択状態が変更されたときに呼び出されるハンドラ
*/
public void valueChanged(TreeSelectionEvent tse) {
/*--- for test codes ---*
// check Event
ModuleTree _eventTree = (ModuleTree)tse.getSource();
TreeSelectionModel _selModel = _eventTree.getSelectionModel();
_selModel.getLeadSelectionPath();
TreePath[] _eventPaths = tse.getPaths();
TreePath _anchorPath = _eventTree.getAnchorSelectionPath();
TreePath _newLeadPath = tse.getNewLeadSelectionPath();
TreePath _oldLeadPath = tse.getOldLeadSelectionPath();
StringBuilder sb = new StringBuilder();
sb.append("[Debug] ModuleTree#valueChanged(TreeSelectionEvent)");
sb.append("\n <TreeSelectionEvent> path count : " + _eventPaths.length);
if (_anchorPath != null) {
sb.append("\n Anchor <row:" + _eventTree.getRowForPath(_anchorPath) + "> ");
sb.append(_anchorPath);
} else {
sb.append("\n Anchor nothing.");
}
if (_oldLeadPath != null) {
sb.append("\n Old Lead <row:" + _eventTree.getRowForPath(_oldLeadPath) + "> ");
sb.append(_oldLeadPath);
} else {
sb.append("\n Old Lead nothing.");
}
if (_newLeadPath != null) {
sb.append("\n New Lead <row:" + _eventTree.getRowForPath(_newLeadPath) + "> ");
sb.append(_newLeadPath);
} else {
sb.append("\n New Lead nothing.");
}
for (int i = 0; i < _eventPaths.length; i++) {
int row = _eventTree.getRowForPath(_eventPaths[i]);
sb.append("\n [" + i + "] <row:" + row + "> ");
if (tse.isAddedPath(i)) {
sb.append("(add) ");
} else {
sb.append("(remove) ");
}
if (_eventPaths[i].equals(_anchorPath)) {
sb.append("(Anchor) ");
}
if (_eventPaths[i].equals(_oldLeadPath)) {
sb.append("(Old Lead) ");
}
if (_eventPaths[i].equals(_newLeadPath)) {
sb.append("(New Lead) ");
}
sb.append(_eventPaths[i]);
}
int eventTreeLeadRow = _eventTree.getSelectionModel().getLeadSelectionRow();
TreePath eventTreeLeadPath = _eventTree.getSelectionModel().getLeadSelectionPath();
sb.append("\n <Event source Tree info> selection count : " + _eventTree.getSelectionCount());
sb.append("\n Lead selection <row:" + eventTreeLeadRow + "> ");
sb.append(eventTreeLeadPath);
System.err.println(sb.toString());
/**--- end of test codes ---*/
//SwingUtilities.invokeLater(_hInvoker);
//DefaultTreeSelectionModel model;
//((BasicTreeUI)getUI()).
/**/
// 選択数の判定
if (getSelectionModel().getSelectionMode() == TreeSelectionModel.SINGLE_TREE_SELECTION) {
// 単一選択の場合は調整の必要なし
onTreeSelectionAdjusted();
return;
}
MExecDefTree srcTree = (MExecDefTree)tse.getSource();
int numSelection = srcTree.getSelectionCount();
if (numSelection <= 1) {
// 選択がない場合や単一選択の場合は、調整の必要なし
onTreeSelectionAdjusted();
return;
}
// 選択パスの取得
TreePath[] eventPaths = tse.getPaths();
TreePath anchorPath = getAnchorSelectionPath();
TreePath newLeadPath = tse.getNewLeadSelectionPath();
int numEventPaths = eventPaths.length;
int numAddedPaths = 0;
int addedMinIndex = -1; // 追加された選択の最小インデックス
int addedMaxIndex = -1; // 追加された選択の最大インデックス
int addedAnchorIndex = -1; // 追加された選択の中で現在のアンカーとなるインデックス
int addedLeadIndex = -1; // 追加された選択の中で現在のリードとなるインデックス
for (int i = 0; i < numEventPaths; i++) {
if (tse.isAddedPath(i)) {
++numAddedPaths;
if ((addedMinIndex < 0) || (i < addedMinIndex)) {
addedMinIndex = i;
}
if (i > addedMaxIndex) {
addedMaxIndex = i;
}
if (eventPaths[i].equals(anchorPath)) {
addedAnchorIndex = i;
}
if (eventPaths[i].equals(newLeadPath)) {
addedLeadIndex = i;
}
}
}
if (numAddedPaths == 0) {
// 追加された選択が一つもない場合は、選択の調整は不要
onTreeSelectionAdjusted();
return;
}
// 選択状態の調整
int originIndex;
if (addedLeadIndex >= 0) {
// 追加された選択にリードが含まれている場合、そのノードが
// ユーザーに選択されたものとみなす。ただし、リードとアンカーが
// 同一の場合は、最小インデックスがユーザーにより選択された
// ものとみなす。
originIndex = (addedLeadIndex==addedAnchorIndex ? addedMinIndex : addedLeadIndex);
} else {
// 追加された選択にリードが含まれていない場合は、上方向に
// 選択範囲が拡張されたことを示すため、追加された選択の
// 最小インデックスが示すパスを基準とする。
originIndex = addedMinIndex;
}
TreeNode originParentNode = ((TreeNode)eventPaths[originIndex].getLastPathComponent()).getParent();
TreePath[] selectionPaths = srcTree.getSelectionPaths();
TreeNode parentNode;
numSelection = selectionPaths.length;
int numRemoveSelection = numSelection;
for (int i = 0; i < numSelection; i++) {
parentNode = ((TreeNode)selectionPaths[i].getLastPathComponent()).getParent();
if (parentNode == originParentNode) {
//--- 同じ親ノードを持つものは同一階層なので選択を維持
--numRemoveSelection;
selectionPaths[i] = null;
}
}
if (numRemoveSelection > 0) {
// 削除する選択が存在する場合は、選択を解除
removeSelectionPaths(selectionPaths);
//--- この場合、再度選択変更イベントが呼び出されるため、
//--- 選択確定メソッドの呼び出しは行わない
} else {
// 削除する選択が存在しない場合は、選択を確定
onTreeSelectionAdjusted();
}
/**/
}
/**
* ツリーコンポーネントの選択状態が変更され、その変更が確定された
* ときに呼び出される。
* <p>
* このツリーコンポーネントでは、ツリーノードの複数選択は同一階層のみに
* 限定するため、選択状態を調整する。選択変更確定とは、この調整が
* 完了した状態を指す。単一選択や、選択が解除される場合は、調整は
* 行われずに、このメソッドが即座に呼び出される。
*/
protected void onTreeSelectionAdjusted() {
}
//------------------------------------------------------------
// Internal methods
//------------------------------------------------------------
/**
* コピー、移動、削除など、プログレスモニタータスクの処理後に
* ツリー表示を更新する。
* @param task 実行したプログレスモニタータスク
*/
protected void refreshAfterProgressTask(FileProgressMonitor task) {
MExecDefTreeModel model = getModel();
// ソースのツリー表示を更新
for (TreePath sPath : task._sources.values()) {
if (sPath != null) {
MExecDefTreeNode node = (MExecDefTreeNode)sPath.getLastPathComponent();
if (node.exists()) {
refreshTree(sPath);
} else {
model.removeNodeFromParent(node);
}
}
}
// ターゲットのツリー表示を更新
if (task._targetPath != null) {
refreshTree(task._targetPath);
}
}
/**
* コピー、移動、削除など、プログレスモニタータスクの処理中に発生した
* エラーに関するメッセージを表示する。
* エラーが発生していない場合は、処理しない。
*
* @param owner メッセージボックスのオーナー
* @param task 実行したプログレスモニタータスク
*/
protected void showErrorForProgressTask(Frame owner, FileProgressMonitor task) {
task.showError(owner);
}
//------------------------------------------------------------
// Inner classes
//------------------------------------------------------------
/**
* このビューのメインコンポーネントとなるツリーコンポーネントに
* フォーカスを設定するアクションクラス。
*/
protected class FocusRequester implements Runnable {
public void run() {
if (!requestFocusInWindow()) {
requestFocus();
}
}
}
/**
* ファイルコピー状況を表示するプログレスダイアログとファイルコピータスクのセット
*/
protected class CopyProgressMonitor extends FileProgressMonitor
{
public CopyProgressMonitor(VirtualFile[] sourceFiles, TreePath targetPath)
{
super(getModel().getSystemRootNode(), getModel().getUserRootNode(), CommonMessages.getInstance().Progress_CopyTo, sourceFiles, targetPath);
// //--- sourceFiles のすべてが現在のワークスペース以下のファイルの場合のみ、
// //--- sourceBaseDirectory を現在のワークスペーストする
// if (sourceFiles != null && sourceFiles.length > 0) {
// VirtualFile srcSystemDir = getModel().getSystemRootDirectory();
// VirtualFile srcUserDir = getModel().getUserRootDirectory();
// VirtualFile srcBaseDir = null;
// for (VirtualFile srcFile : sourceFiles) {
// if (srcFile != null) {
// if (srcBaseDir != null) {
// if (!srcFile.isDescendingFrom(srcBaseDir)) {
// srcBaseDir = null;
// break;
// }
// }
// else if (srcFile.isDescendingFrom(srcUserDir)) {
// srcBaseDir = srcUserDir;
// }
// else if (srcFile.isDescendingFrom(srcSystemDir)) {
// srcBaseDir = srcSystemDir;
// }
// }
// }
// setSourceBaseDirectory(srcBaseDir);
// } else {
// setSourceBaseDirectory(null);
// }
// setTargetBaseDirectory(((MExecDefTreeNode)targetPath.getPathComponent(1)).getFileObject());
}
@Override
public void processTask() {
AppLogger.info("Start CopyProgressMonitor task...");
super.processTask();
VirtualFile targetDir = ((MExecDefTreeNode)_targetPath.getLastPathComponent()).getFileObject();
// ファイルコピー
resetAllowOverwriteAllFilesFlag();
for (Map.Entry<VirtualFile, TreePath> entry : _sources.entrySet()) {
// setup current target
VirtualFile sourceFile = entry.getKey();
_doingPath = entry.getValue();
if (_doingPath == null) {
_doingNode = null;
} else {
_doingNode = (MExecDefTreeNode)_doingPath.getLastPathComponent();
}
// do copy
copyRecursive(sourceFile, targetDir);
// save completed target
_completed.put(sourceFile, _doingPath);
}
_doingPath = null; // finished
_doingNode = null; // finished
AppLogger.info("CopyProgressMonitor task Completed!");
}
}
/**
* ファイル移動状況を表示するプログレスダイアログとファイル移動するタスクのセット
*/
protected class MoveProgressMonitor extends FileProgressMonitor
{
private final HashMap<VirtualFile,VirtualFile> watchFiles = new HashMap<VirtualFile,VirtualFile>();
public MoveProgressMonitor(Collection<? extends VirtualFile> watches, TreePath[] sourcePaths, TreePath targetPath)
{
super(getModel().getSystemRootNode(), getModel().getUserRootNode(), CommonMessages.getInstance().Progress_MoveTo, sourcePaths, targetPath);
// setSourceBaseDirectory(((MExecDefTreeNode)sourcePaths[0].getPathComponent(1)).getFileObject());
// setTargetBaseDirectory(((MExecDefTreeNode)targetPath.getPathComponent(1)).getFileObject());
if (watches != null && !watches.isEmpty()) {
for (VirtualFile f : watches) {
watchFiles.put(f, null);
}
}
}
@Override
protected void onFileMoved(VirtualFile source, VirtualFile target) {
// 監視対象のファイルで移動に成功したものは、
// 移動先の抽象パスを保存する
if (watchFiles.containsKey(source)) {
watchFiles.put(source, target);
}
}
@Override
public void processTask() {
AppLogger.info("Start MoveProgressMonitor task...");
super.processTask();
VirtualFile targetDir = ((MExecDefTreeNode)_targetPath.getLastPathComponent()).getFileObject();
// ファイル移動
resetAllowOverwriteAllFilesFlag();
for (Map.Entry<VirtualFile, TreePath> entry : _sources.entrySet()) {
// setup current target
VirtualFile sourceFile = entry.getKey();
_doingPath = entry.getValue();
if (_doingPath == null) {
_doingNode = null;
} else {
_doingNode = (MExecDefTreeNode)_doingPath.getLastPathComponent();
}
// do move
moveRecursive(sourceFile, targetDir);
// save completed target
_completed.put(sourceFile, _doingPath);
}
_doingPath = null; // finished
_doingNode = null; // finished
AppLogger.info("MoveProgressMonitor task Completed!");
}
}
/**
* ファイル削除状況を表示するプログレスダイアログとファイル削除するタスクのセット
*/
protected class DeleteProgressMonitor extends FileProgressMonitor
{
public DeleteProgressMonitor(TreePath[] sourcePaths)
{
super(getModel().getSystemRootNode(), getModel().getUserRootNode(), CommonMessages.getInstance().Progress_Delete, sourcePaths, null);
// setSourceBaseDirectory(((MExecDefTreeNode)sourcePaths[0].getPathComponent(1)).getFileObject());
// setTargetBaseDirectory(null);
}
@Override
public void processTask() {
AppLogger.info("Start DeleteProgressMonitor task...");
super.processTask();
// ファイル削除
for (Map.Entry<VirtualFile, TreePath> entry : _sources.entrySet()) {
// setup current target
VirtualFile sourceFile = entry.getKey();
_doingPath = entry.getValue();
if (_doingPath == null) {
_doingNode = null;
} else {
_doingNode = (MExecDefTreeNode)_doingPath.getLastPathComponent();
}
// do delete
deleteRecursive(sourceFile);
// save completed target
_completed.put(sourceFile, _doingPath);
}
_doingPath = null; // finished
_doingNode = null; // finished
AppLogger.info("DeleteProgressMonitor task Completed!");
}
}
/**
* ファイル処理状況を表示するプログレスダイアログと実行するタスクのセット
*/
static protected abstract class FileProgressMonitor extends MExecDefFileProgressMonitorTask
{
/** このタスクで処理する予定のファイルとツリーパスのマップ **/
protected final Map<VirtualFile, TreePath> _sources;
/** このタスクで処理が完了したファイルとツリーパスのマップ **/
protected final Map<VirtualFile, TreePath> _completed;
/** 処理の宛先となる位置を示すツリーパス **/
protected final TreePath _targetPath;
/** 処理中のノードを示すツリーパス **/
protected TreePath _doingPath;
/** 処理中のノード **/
protected MExecDefTreeNode _doingNode;
static private final VirtualFile getFileObjectFromNode(final MExecDefTreeNode node) {
return (node==null ? null : node.getFileObject());
}
static private final String getDisplayNameFromNode(final MExecDefTreeNode node) {
return (node==null ? null : node.getDisplayName());
}
public FileProgressMonitor(MExecDefTreeNode ndSystemRoot, MExecDefTreeNode ndUserRoot,
String title, VirtualFile[] sourceFiles, TreePath targetPath)
{
super(getFileObjectFromNode(ndSystemRoot), getDisplayNameFromNode(ndSystemRoot),
getFileObjectFromNode(ndUserRoot), getDisplayNameFromNode(ndUserRoot),
title, null, null, 0, 0, 0);
this._targetPath = targetPath;
this._completed = new TreeMap<VirtualFile,TreePath>();
this._sources = new TreeMap<VirtualFile,TreePath>();
//--- setup source files
for (VirtualFile sf : sourceFiles) {
_sources.put(sf, null);
}
this._doingPath = null;
this._doingNode = null;
}
public FileProgressMonitor(MExecDefTreeNode ndSystemRoot, MExecDefTreeNode ndUserRoot,
String title, TreePath[] sourcePaths, TreePath targetPath)
{
super(getFileObjectFromNode(ndSystemRoot), getDisplayNameFromNode(ndSystemRoot),
getFileObjectFromNode(ndUserRoot), getDisplayNameFromNode(ndUserRoot),
title, null, null, 0, 0, 0);
this._targetPath = targetPath;
this._completed = new TreeMap<VirtualFile,TreePath>();
this._sources = new TreeMap<VirtualFile,TreePath>();
//--- setup source paths
for (TreePath tp : sourcePaths) {
MExecDefTreeNode node = (MExecDefTreeNode)tp.getLastPathComponent();
VirtualFile targetFile = node.getFileObject();
_sources.put(targetFile, tp);
if (targetFile.isFile() && !Strings.endsWithIgnoreCase(targetFile.getName(), ModuleFileManager.EXT_FILE_PREFS)) {
// ターゲットが設定ファイルではないファイルの場合、
// 同名の設定ファイルも自動的に処理対象とする
// *.aadl.pref, *.jar.prefs, *.amf.prefs
VirtualFile fPrefs = ModuleFileManager.getPrefsFile(targetFile);
if (fPrefs.exists() && !_sources.containsKey(fPrefs)) {
_sources.put(fPrefs, null);
}
}
}
this._doingPath = null;
this._doingNode = null;
}
@Override
public void processTask()
{
// 処理対象のファイル総数をカウント
int numFiles = 0;
for (VirtualFile f : _sources.keySet()) {
numFiles += f.countFiles();
}
if (AppLogger.isInfoEnabled()) {
AppLogger.info("Start FileProgressMonitor task for " + numFiles + " files.");
}
// 総数をプログレスバーに設定
setMaximum(numFiles);
}
@Override
protected boolean acceptCopy(VirtualFile source) {
// プロジェクト設定ファイルは除外する
if (source.isFile() && ModuleFileManager.PROJECT_PREFS_FILENAME.equalsIgnoreCase(source.getName())) {
return false;
}
return super.acceptCopy(source);
}
}
/**
* ツリーコンポーネントの制御を行う標準のハンドラ
*/
static public class DefaultTreeHandler implements IDnDTreeHandler
{
public int acceptTreeDragOverDropAction(DnDTree tree, DropTargetDragEvent dtde, TreePath dragOverPath) {
// ドロップ先ノードを取得
if (dragOverPath == null) {
// ドロップ先ノードが存在しない場合は、無効
return TransferHandler.NONE;
}
// データソースがこの同じコンポーネント上のものでなければ、コピーのみ許可する。
int retDropAction;
if (tree.isDnDLocalDragging()) {
retDropAction = dtde.getDropAction();
} else {
retDropAction = TransferHandler.COPY;
}
return retDropAction;
}
public boolean canTransferImport(DnDTree tree, DataFlavor[] transferFlavors) {
// サポートされているデータ形式なら、インポートを許可
return MExecDefFileTransferable.containsSupportedDataFlavor(transferFlavors);
}
public Transferable createTransferable(DnDTree tree) {
if (tree instanceof MExecDefTree) {
IMExecDefFile[] datas = ((MExecDefTree)tree).getSelectionNodeDatas();
if (datas != null && datas.length > 0) {
// 転送データ生成
return new MExecDefFileTransferable(datas);
} else {
// 操作対象が存在しない
return null;
}
} else {
return null;
}
}
public int getTransferSourceAction(DnDTree tree) {
int action;
TreePath[] paths = tree.getSelectionPaths();
if (paths != null && paths.length > 0) {
action = TransferHandler.NONE;
MExecDefTreeNode ndSystemRoot = ((MExecDefTree)tree).getModel().getSystemRootNode();
MExecDefTreeNode ndUserRoot = ((MExecDefTree)tree).getModel().getUserRootNode();
for (TreePath tp : paths) {
MExecDefTreeNode node = (MExecDefTreeNode)tp.getLastPathComponent();
if (!node.isRoot()) {
if (node.isNodeAncestor(ndUserRoot)) {
if (node != ndUserRoot) {
// ユーザールート配下は変更可能
action = TransferHandler.COPY_OR_MOVE;
break;
} else {
// ユーザールートは変更不可
action = TransferHandler.NONE;
break;
}
}
else if (node.isNodeAncestor(ndSystemRoot)) {
if (node != ndSystemRoot) {
// システムルート配下はコピー可能
action = TransferHandler.COPY;
break;
} else {
// システムルートは変更不可
action = TransferHandler.NONE;
break;
}
}
}
}
} else {
action = TransferHandler.NONE;
}
return action;
}
public Icon getTransferVisualRepresentation(DnDTree tree, Transferable t) {
return null;
}
public boolean importTransferData(DnDTree tree, Transferable t) {
// このメソッドは使用しない
return false;
}
public boolean dropTransferData(DnDTree tree, Transferable t, int action) {
// MExecDefTree インスタンス以外は処理しない
if (!(tree instanceof MExecDefTree)) {
return false;
}
// 転送データを取得
VirtualFile[] files = MExecDefFileTransferable.getVirtualFilesFromTransferData(t);
if (files == null || files.length <= 0) {
return false; // No data
}
// 転送先の位置を取得
TreePath tp = tree.getDragOverPath();
if (tp == null) {
return false; // No target
}
// 転送
boolean result;
if (action == TransferHandler.MOVE) {
if (tree.isDnDLocalDragging()) {
result = moveTransferable((MExecDefTree)tree, files, tp);
} else {
// 移動は、ローカルのDrag&Dropのみ許可する
result = false;
}
}
else if (action == TransferHandler.COPY) {
result = copyTransferable((MExecDefTree)tree, files, tp);
}
else {
// no action
result = false;
}
// 完了
return result;
}
protected boolean copyTransferable(MExecDefTree tree, VirtualFile[] sourceFiles, TreePath targetPath) {
return false;
}
protected boolean moveTransferable(MExecDefTree tree, VirtualFile[] sourceFiles, TreePath targetPath) {
return false;
}
}
}
|
greenriver/vizzuality-components
|
src/components/map/index.js
|
import React, { Component } from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import isEqual from 'lodash/isEqual';
import './styles.scss';
const { L } = (typeof window !== 'undefined') ? window : {};
if (typeof window !== 'undefined') {
/*
* Workaround for 1px lines appearing in some browsers due to fractional transforms
* and resulting anti-aliasing.
* https://github.com/Leaflet/Leaflet/issues/3575
*/
/* eslint-disable */
(function () {
const originalInitTile = L && L.GridLayer.prototype._initTile;
L && L.GridLayer.include({
_initTile(tile) {
originalInitTile.call(this, tile);
const tileSize = this.getTileSize();
tile.style.width = `${tileSize.x + 1 }px`;
tile.style.height = `${tileSize.y + 1 }px`;
}
});
}());
/* eslint-enable */
}
class Maps extends Component {
events = {}
static propTypes = {
/** A function that returns the map instance */
children: PropTypes.func,
/** Custom css class for styling */
customClass: PropTypes.string,
/** Leaflet props for creating a map
* @see Check Leaflet documentation https://leafletjs.com/reference-1.3.0.html#map
*/
mapOptions: PropTypes.object,
/** `{ url: 'http://example/{x}/{y}/{z}', options: {}}`
* @see Check Leaflet documentation https://leafletjs.com/reference-1.3.0.html#tilelayer
*/
basemap: PropTypes.object,
/** `{ url: 'http://example/{x}/{y}/{z}', options: {} }` Options for L.tileLayer
* @see Check Leaflet documentation https://leafletjs.com/reference-1.3.0.html#tilelayer
*/
label: PropTypes.object,
/** `{ bbox: [10, 5, 20, 10], options: {} }`
* @see Check Leaflet documentation https://leafletjs.com/reference-1.3.0.html#fitbounds-options
*/
bounds: PropTypes.object,
/**
* `{ click: (e, map) => {} }` All the functions return 2 params
* @arg {Object} e event
* @arg {Object} map Map instance
* @see Cheack Leaflet documentation https://leafletjs.com/reference-1.3.0.html#map-event
*/
events: PropTypes.object,
/** Removes all interactions available on the map */
interactionEnabled: PropTypes.bool,
/** Removes only zoomScroll on the map */
scrollZoomEnabled: PropTypes.bool,
/**
* Return map instance when this one is ready
* @arg {Object} map Map instance
*/
onReady: PropTypes.func
}
static defaultProps = {
children: null,
customClass: null,
mapOptions: {
zoomControl: false,
center: [27, 12],
zoom: 3,
maxZoom: 20,
minZoom: 2
},
basemap: {
url: 'http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png',
options: {
maxZoom: 20,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}
},
label: {
url: 'http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png',
options: {
maxZoom: 20,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}
},
bounds: {
bbox: null,
options: {} // fitBounds options
},
events: {},
interactionEnabled: true,
scrollZoomEnabled: true,
onReady: () => {}
}
componentDidMount() {
if (
typeof L === 'undefined' ||
!this.mapNode
) {
return;
}
const { interactionEnabled, scrollZoomEnabled, onReady } = this.props;
this.setMap();
this.setBasemap();
this.setLabel();
this.setBounds();
this.setEvents();
if (!interactionEnabled) {
this.map.dragging.disable();
this.map.touchZoom.disable();
this.map.doubleClickZoom.disable();
this.map.scrollWheelZoom.disable();
this.map.boxZoom.disable();
this.map.keyboard.disable();
}
if (!scrollZoomEnabled) {
this.map.scrollWheelZoom.disable();
}
onReady(this.map);
// As this.map didn't exist before this function
this.forceUpdate();
}
componentDidUpdate(prevProps) {
const {
basemap: prevBasemap,
label: prevLabel,
bounds: prevBounds,
events: prevEvents,
mapOptions: prevMapOptions
} = prevProps;
const {
basemap: nextBasemap,
label: nextLabel,
bounds: nextBounds,
events: nextEvents,
mapOptions: nextMapOptions
} = this.props;
// Basemap
if (!isEqual(prevBasemap, nextBasemap)) {
this.setBasemap();
}
// Label
if (!isEqual(prevLabel, nextLabel)) {
this.setLabel();
}
// Bounds
if (!isEqual(prevBounds, nextBounds)) {
this.setBounds();
}
// Events
if (!isEqual(prevEvents, nextEvents)) {
this.setEvents();
}
// mapOptions
if (!isEqual(prevMapOptions, nextMapOptions)) {
this.setMapOptions();
}
}
componentWillUnmount() {
this.removeEvents();
}
setMap = () => {
const { mapOptions } = this.props;
this.map = L.map(this.mapNode, { ...Maps.defaultProps.mapOptions, ...mapOptions });
}
setMapOptions = () => {
const { mapOptions: { center, zoom } } = this.props;
this.map.setView({ ...center }, zoom)
}
setBasemap = () => {
const { basemap } = this.props;
if (this.basemapLayer) this.basemapLayer.remove();
this.basemapLayer = L.tileLayer(basemap.url, basemap.options)
.addTo(this.map)
.setZIndex(0);
}
setLabel = () => {
const { label } = this.props;
if (this.labelLayer) this.labelLayer.remove();
this.labelLayer = L.tileLayer(label.url, label.options)
.addTo(this.map)
.setZIndex(1100);
}
setBounds = () => {
const { bounds } = this.props;
const { bbox, options } = bounds;
if (bbox) {
const mapBounds = [
[bbox[1], bbox[0]],
[bbox[3], bbox[2]]
];
this.map.fitBounds(mapBounds, options);
}
}
setEvents() {
const { events } = this.props;
this.removeEvents();
Object.keys(events).forEach((key) => {
this.events[key] = (e) => {
events[key](e, this.map);
}
this.map.on(key, this.events[key]);
});
}
removeEvents() {
Object.keys(this.events).forEach((key) => {
this.map.off(key, this.events[key]);
});
}
render() {
const { customClass, children } = this.props;
const externalClass = classnames({ [customClass]: !!customClass });
return (
<div styleName="c-map" className={externalClass}>
<div
ref={(node) => { this.mapNode = node; }}
styleName="map-container"
/>
{!!this.map && typeof children === 'function' && children(this.map)}
</div>
);
}
}
export default Maps;
export { default as MapPopup } from './map-popup';
export { default as MapControls } from './map-controls';
export { default as ZoomControl } from './map-controls/zoom-control';
|
snkmr/shirasagi
|
spec/factories/gws/staff_record/group.rb
|
<reponame>snkmr/shirasagi<filename>spec/factories/gws/staff_record/group.rb<gh_stars>100-1000
FactoryBot.define do
factory :gws_staff_record_group, class: Gws::StaffRecord::Group do
cur_site { gws_site }
cur_user { gws_user }
#year_id { create(:gws_staff_record_year).id }
name { "name-#{unique_id}" }
seating_chart_url { 'http://example.jp' }
end
end
|
eegeo/cardboard-vr-integration
|
src/Examples/CameraTransition/CameraTransitionExample.h
|
// Copyright eeGeo Ltd (2012-2014), All Rights Reserved
#ifndef __ExampleApp__CameraTransitionExample__
#define __ExampleApp__CameraTransitionExample__
#include <iostream>
#include "GlobeCameraExampleBase.h"
#include "EegeoWorld.h"
#include "Location.h"
#include "GlobeCamera.h"
#include "VectorMath.h"
namespace Examples
{
class CameraTransitioner
{
public:
CameraTransitioner(Eegeo::Camera::GlobeCamera::GlobeCameraController& cameraController);
void StartTransitionTo(Eegeo::dv3 newInterestPoint, float distanceFromInterest, bool jumpIfFarAway);
void StartTransitionTo(Eegeo::dv3 newInterestPoint, float distanceFromInterest, float newHeading, bool jumpIfFarAway);
void StopCurrentTransition();
void Update(float dt);
const bool IsTransitioning() const
{
return m_isTransitioning;
}
private:
bool ShouldJumpTo(Eegeo::dv3 newInterestPoint);
Eegeo::Camera::GlobeCamera::GlobeCameraController& m_cameraController;
Eegeo::dv3 m_startTransitionInterestPoint;
Eegeo::dv3 m_endTransitionInterestPoint;
float m_startInterestDistance;
float m_endInterestDistance;
float m_startTransitionHeading;
float m_endTransitionHeading;
float m_transitionTime;
float m_transitionDuration;
bool m_isTransitioning;
};
/*!
* CameraTransitionExample demonstrates the ability to ease the camera position from it's current location to a destination and back again
*/
class CameraTransitionExample : public GlobeCameraExampleBase
{
private:
CameraTransitioner m_transitioner;
bool m_firstPoint;
void Transition();
public:
CameraTransitionExample(Eegeo::Camera::GlobeCamera::GlobeCameraController* pCameraController,
Eegeo::Camera::GlobeCamera::GlobeCameraTouchController& cameraTouchController);
static std::string GetName()
{
return "CameraTransitionExample";
}
std::string Name() const
{
return GetName();
}
void Start() {}
void EarlyUpdate(float dt);
void Update(float dt) { }
void Draw() {}
void Suspend() {}
};
}
#endif /* defined(__ExampleApp__CameraTransitionExample__) */
|
devilry/devilry-django
|
devilry/devilry_superadmin/tests/test_management_commands/test_resend_failed_messages.py
|
from __future__ import unicode_literals
from io import StringIO
from django import test
from django.conf import settings
from django.core import management
from django.core import mail
from model_bakery import baker
from devilry.devilry_message.models import MessageReceiver
class TestResendFailedMessagesCommand(test.TestCase):
def __test_standard_output(self, stdout, num_resent=0, exceeded_resend_limit=0,
resend_limit=settings.DEVILRY_MESSAGE_RESEND_LIMIT):
self.assertEqual(
stdout.getvalue().encode(encoding='UTF-8').decode(),
'{num_resent} messages were automatically resent.\n'
'{exceeded_resend_limit} messages has exceeded the retry limit '
'(current limit: {resend_limit})\n'.format(
num_resent=num_resent,
exceeded_resend_limit=exceeded_resend_limit,
resend_limit=resend_limit
))
def __make_email_for_user(self, user, email):
return baker.make('devilry_account.UserEmail', user=user, email=email)
def test_no_messages(self):
out = StringIO()
management.call_command('devilry_resend_failed_messages', stdout=out)
self.__test_standard_output(stdout=out)
out.close()
def test_sanity_failed_message_sent_to_user(self):
testuser = baker.make(settings.AUTH_USER_MODEL)
self.__make_email_for_user(testuser, '<EMAIL>')
baker.make('devilry_message.MessageReceiver',
user=testuser,
status=MessageReceiver.STATUS_CHOICES.FAILED.value)
out = StringIO()
management.call_command('devilry_resend_failed_messages', stdout=out)
self.__test_standard_output(stdout=out, num_resent=1)
out.close()
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].recipients(), ['<EMAIL>'])
def test_sanity_failed_messages_sent_to_multiple_users(self):
testuser1 = baker.make(settings.AUTH_USER_MODEL)
testuser2 = baker.make(settings.AUTH_USER_MODEL)
self.__make_email_for_user(testuser1, '<EMAIL>')
self.__make_email_for_user(testuser2, '<EMAIL>')
receiver1 = baker.make('devilry_message.MessageReceiver',
user=testuser1,
subject='Test 1',
status=MessageReceiver.STATUS_CHOICES.FAILED.value)
receiver2 = baker.make('devilry_message.MessageReceiver',
user=testuser2,
subject='Test 2',
status=MessageReceiver.STATUS_CHOICES.FAILED.value)
out = StringIO()
management.call_command('devilry_resend_failed_messages', stdout=out)
self.__test_standard_output(stdout=out, num_resent=2)
out.close()
self.assertEqual(len(mail.outbox), 2)
self.assertEqual(mail.outbox[0].recipients(), ['<EMAIL>'])
self.assertEqual(mail.outbox[0].subject, '[Devilry] Test 1')
self.assertEqual(mail.outbox[1].recipients(), ['<EMAIL>'])
self.assertEqual(mail.outbox[1].subject, '[Devilry] Test 2')
receiver1.refresh_from_db()
receiver2.refresh_from_db()
self.assertEqual(receiver1.status, MessageReceiver.STATUS_CHOICES.SENT.value)
self.assertEqual(receiver2.status, MessageReceiver.STATUS_CHOICES.SENT.value)
def test_stdout_no_failed_messages(self):
testuser = baker.make(settings.AUTH_USER_MODEL)
self.__make_email_for_user(testuser, '<EMAIL>')
baker.make('devilry_message.MessageReceiver',
user=testuser,
status=MessageReceiver.STATUS_CHOICES.SENT.value)
out = StringIO()
management.call_command('devilry_resend_failed_messages', stdout=out)
self.__test_standard_output(stdout=out)
out.close()
self.assertEqual(len(mail.outbox), 0)
def test_stdout_failed_message_sent(self):
testuser = baker.make(settings.AUTH_USER_MODEL)
self.__make_email_for_user(testuser, '<EMAIL>')
baker.make('devilry_message.MessageReceiver',
user=testuser,
status=MessageReceiver.STATUS_CHOICES.FAILED.value)
out = StringIO()
management.call_command('devilry_resend_failed_messages', stdout=out)
self.__test_standard_output(stdout=out, num_resent=1)
out.close()
self.assertEqual(len(mail.outbox), 1)
def test_stdout_multiple_failed_messages_sent(self):
testuser = baker.make(settings.AUTH_USER_MODEL)
self.__make_email_for_user(testuser, '<EMAIL>')
baker.make('devilry_message.MessageReceiver',
user=testuser,
status=MessageReceiver.STATUS_CHOICES.FAILED.value)
baker.make('devilry_message.MessageReceiver',
user=testuser,
status=MessageReceiver.STATUS_CHOICES.FAILED.value)
out = StringIO()
management.call_command('devilry_resend_failed_messages', stdout=out)
self.__test_standard_output(stdout=out, num_resent=2)
out.close()
self.assertEqual(len(mail.outbox), 2)
def test_stdout_failed_message_exceeded_resend_limit(self):
testuser = baker.make(settings.AUTH_USER_MODEL)
self.__make_email_for_user(testuser, '<EMAIL>')
baker.make('devilry_message.MessageReceiver',
user=testuser,
status=MessageReceiver.STATUS_CHOICES.FAILED.value,
sending_failed_count=settings.DEVILRY_MESSAGE_RESEND_LIMIT + 1)
out = StringIO()
management.call_command('devilry_resend_failed_messages', stdout=out)
self.__test_standard_output(stdout=out, exceeded_resend_limit=1)
out.close()
self.assertEqual(len(mail.outbox), 0)
def test_stdout_multiple_failed_messages_exceeded_resend_limit(self):
testuser = baker.make(settings.AUTH_USER_MODEL)
self.__make_email_for_user(testuser, '<EMAIL>')
baker.make('devilry_message.MessageReceiver',
user=testuser,
status=MessageReceiver.STATUS_CHOICES.FAILED.value,
sending_failed_count=settings.DEVILRY_MESSAGE_RESEND_LIMIT + 1)
baker.make('devilry_message.MessageReceiver',
user=testuser,
status=MessageReceiver.STATUS_CHOICES.FAILED.value,
sending_failed_count=settings.DEVILRY_MESSAGE_RESEND_LIMIT + 1)
out = StringIO()
management.call_command('devilry_resend_failed_messages', stdout=out)
self.__test_standard_output(stdout=out, exceeded_resend_limit=2)
out.close()
self.assertEqual(len(mail.outbox), 0)
def test_stdout_failed_message_and_message_that_exceeded_resend_limit(self):
testuser = baker.make(settings.AUTH_USER_MODEL)
self.__make_email_for_user(testuser, '<EMAIL>')
baker.make('devilry_message.MessageReceiver',
user=testuser,
status=MessageReceiver.STATUS_CHOICES.FAILED.value)
baker.make('devilry_message.MessageReceiver',
user=testuser,
status=MessageReceiver.STATUS_CHOICES.FAILED.value,
sending_failed_count=settings.DEVILRY_MESSAGE_RESEND_LIMIT + 1)
out = StringIO()
management.call_command('devilry_resend_failed_messages', stdout=out)
self.__test_standard_output(stdout=out, num_resent=1, exceeded_resend_limit=1)
out.close()
self.assertEqual(len(mail.outbox), 1)
|
Mause/TransperthCached
|
src/com/lysdev/transperthcached/activities/StopTimetableActivity.scala
|
package com.lysdev.transperthcached.activities
// Standard library
import java.util.ArrayList
// android sdk
import android.app.DatePickerDialog
import android.app.ProgressDialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.util.Log
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.DatePicker
import android.widget.EditText
import android.widget.ListView
import android.widget.TimePicker
import android.location.Location
// Joda
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
// Project specific
import com.lysdev.transperthcached.timetable.Timetable
import com.lysdev.transperthcached.timetable.Visit
import com.lysdev.transperthcached.ui.DatePickerFragment
import com.lysdev.transperthcached.ui.OkDialog
import com.lysdev.transperthcached.ui.SelectStopDialog
import com.lysdev.transperthcached.ui.TimePickerFragment
import com.lysdev.transperthcached.R
import com.lysdev.transperthcached.exceptions.StateException
import com.lysdev.transperthcached.silverrails.GetNearbyTransitStops
import com.lysdev.transperthcached.silverrails.NearbyTransitStop
import com.lysdev.transperthcached.utils.MyLocation
import com.lysdev.transperthcached.utils.Util
import com.lysdev.transperthcached.business.StopTimetableBusinessLogic
import scala.collection.JavaConverters._
import scala.collection.JavaConversions._
import org.scaloid.common._
class StopTimetableActivity extends FragmentActivity with SActivity {
var timetable : Timetable = null
var stop_display_source : ArrayAdapter[String] = null
var show_for_date : DateTime = null
lazy val stop_display = find[ListView](R.id.visits)
lazy val stop_num_widget = find[EditText](R.id.stop_number)
lazy val date_button = find[Button](R.id.date_select_button)
lazy val time_button = find[Button](R.id.time_select_button)
/** Called when the activity is first created. */
override
def onCreate(savedInstanceState: Bundle) {
Log.d("TransperthCached", "initializing StopTimetableActivity")
super.onCreate(savedInstanceState)
setContentView(R.layout.stop_timetable)
this.timetable = new Timetable()
if (savedInstanceState == null) {
Log.d("TransperthCached", "No bundled state received")
} else {
Log.d("TransperthCached", "Bundled state received, rebuilding app")
}
preUiLoadSaveInstanceState(savedInstanceState)
setupUI()
postUiLoadSaveInstanceState(savedInstanceState)
Log.d("TransperthCached", "initialized StopTimetableActivity")
}
def setupUI() {
stop_display_source = new ArrayAdapter(
this,
android.R.layout.simple_list_item_1,
new ArrayList[String]()
)
stop_display.setAdapter(stop_display_source)
updateTimeButtonText()
updateDateButtonText()
}
def preUiLoadSaveInstanceState(inState: Bundle) {
if (inState == null) {
show_for_date = new DateTime()
} else {
show_for_date = DateTime.parse(
inState.getString("show_for_date")
)
}
}
def postUiLoadSaveInstanceState(inState: Bundle) {
if (inState != null) {
// cannot set this till the ui is setup
stop_num_widget.setText(
inState.getString("stop_number")
)
}
// this is for when a user selects a stop in favourites
val intent = getIntent()
if (intent != null) {
val stop_num = intent.getIntExtra("stop_num", 0)
if (stop_num != 0) {
stop_num_widget.setText(
String.valueOf(stop_num)
)
}
}
}
override def onSaveInstanceState(outState: Bundle) {
outState.putString("show_for_date", show_for_date.toString())
// this seems to work as is no need to stringy or parseInt
outState.putString("stop_number", stop_num_widget.getText().toString())
}
def showForStop(view: View) {
Util.hideSoftKeyboard(this)
val stop_num = stop_num_widget.getText().toString()
if (stop_num == null) return
var visits : List[Visit] = null
try {
visits = StopTimetableBusinessLogic.getVisitsForStop(
stop_num, timetable, show_for_date
)
} catch {
case state: StateException => {
stop_display_source.clear()
OkDialog.ok_dialog(state.getTitle(), state.getMessage())
}
}
if (visits == null) return
displayVisits(visits)
}
def timeSelectButtonClicked(v: View) {
Util.hideSoftKeyboard(this)
val listener = new TimePickerDialog.OnTimeSetListener() {
def onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
show_for_date = show_for_date.withTime(
hourOfDay,
minute,
0, 0
)
updateTimeButtonText()
}
}
new TimePickerFragment(
listener, this.show_for_date.toLocalTime()
).show(getSupportFragmentManager(), "timePicker")
}
def updateTimeButtonText() {
time_button.setText(
DateTimeFormat.forPattern("hh:mmaa").print(
show_for_date.toLocalTime()
)
)
}
def dateSelectButtonClicked(v: View) {
Util.hideSoftKeyboard(this)
val listener = new DatePickerDialog.OnDateSetListener() {
def onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
show_for_date = show_for_date.withDate(
year,
month + 1,
day
)
updateDateButtonText()
}
}
new DatePickerFragment(
listener, this.show_for_date
).show(getSupportFragmentManager(), "datePicker")
}
def updateDateButtonText() {
date_button.setText(
DateTimeFormat.forPattern("EEE, MMMM dd, yyyy").print(
show_for_date
)
)
}
def displayVisits(visits: List[Visit]) {
// clear so we can display the new data
stop_display_source.clear()
stop_display_source.addAll(
visits.map(visit =>
String.format(
"%s : %s",
visit.getRouteNumber,
visit.formatTime
)
)
)
stop_display.setSelection(0)
}
def nearbyButtonClicked(v: View) {
val mDialog = new ProgressDialog(this)
mDialog.setMessage("Determining location...")
mDialog.setCancelable(false)
mDialog.show()
new MyLocation().getLocation((location: Location) => {
mDialog.dismiss()
nearbyButtonCallback(location)
})
}
// should stop multiple dialogs
var waiting_for_user_selection : Boolean = false
def nearbyButtonCallback(location: Location) {
if (waiting_for_user_selection) {
Log.d("TransperthCached", "Dialog already open")
return
}
waiting_for_user_selection = true
val api_key = getResources().getString(R.string.silverrails_apikey)
val stops = GetNearbyTransitStops.getNearby(
api_key,
location.getLatitude(),
location.getLongitude()
)
val callback = (stop: NearbyTransitStop) => {
waiting_for_user_selection = false
stop_num_widget.setText(stop.getCode())
}
new SelectStopDialog(stops, callback).show(
getSupportFragmentManager(),
"TransperthCached"
)
}
}
|
MarcoSteinke/smalldragon
|
lexer/test/test.c
|
/*
this file is supposed to test dragon-lexer
the testing shall be conducted via unit tests.
there is not much going on with the files so
we probably do not need integration tests here.
*/
//Stdlib Headers
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
//Project Headers
#include "driver.h"
#include "test.h"
#include "../../token/token/token.h"
#include "../../token/TokenKeys.h"
#include "lexer_test_utils.h"
static uint32_t test_num = 1;
static void printt(char* test_name){
printf("[Lexer][Test][#%02d] %s", test_num++, test_name);
}
int lexer_test_all() {
printf("[Lexer] Running Tests... \n");
test_try_catch_throw_throws();
test_plus_plus_minus_minus();
test_can_see_line_with_semicolon();
test_can_see_line_with_operators();
test_lexes_return_statement_favorably();
test_lexes_other_return_statement();
test_lexes_float_constant();
test_lexes_escaped_char();
test_anytypetoken();
test_true();
test_false();
test_char();
test_float_1();
test_float_2();
test_float_3();
test_identifier_1();
test_identifier_2();
test_int_1();
test_int_2();
test_int_3();
test_hex();
test_binconst();
test_struct();
test_return();
test_string_1();
test_typeidentifier();
test_typeidentifier_primitive();
test_typeparameter_1();
test_comma();
test_arrow();
test_mixed_1();
test_mixed_2();
test_mixed_3();
test_mixed_4();
test_mixed_5();
test_mixed_6();
test_mixed_7();
test_mixed_8();
test_mixed_9();
test_mixed_10();
test_mixed_11();
test_mixed_12();
test_mixed_13();
test_mixed_14();
test_mixed_15();
test_mixed_16();
test_operators();
test_operators_cmp();
test_operators_logical();
test_operators_bitwise();
test_loop();
test_if_else();
test_break();
test_for();
test_in();
test_rangeop_1();
test_rangeop_2();
test_member_access();
test_switch_case();
test_assign_operators();
test_brackets();
printf("[Lexer] All %i Tests Passed\n", test_num-1);
return 0;
}
void test_try_catch_throw_throws(){
char* str = "try catch throw throws ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind == TRY);
assert(tokens[1]->kind == CATCH);
assert(tokens[2]->kind == THROW);
assert(tokens[3]->kind == THROWS);
assert(strcmp(tokens[0]->value_ptr,"try")==0);
assert(strcmp(tokens[1]->value_ptr,"catch")==0);
assert(strcmp(tokens[2]->value_ptr,"throw")==0);
assert(strcmp(tokens[3]->value_ptr,"throws")==0);
//free_tokens(tokens, 4); //segfaults
}
void test_plus_plus_minus_minus(){
char* str = "Char ++ -- ";
//should expand: "Char += 1 -= 1"
struct Token** tokens = lex(str);
assert(tokens[0]->kind == TYPEID);
assert(tokens[1]->kind == ASSIGNOP);
assert(tokens[2]->kind == INTEGER);
assert(tokens[3]->kind == ASSIGNOP);
assert(tokens[4]->kind == INTEGER);
assert(strcmp(tokens[1]->value_ptr,"+=")==0);
assert(strcmp(tokens[2]->value_ptr,"1")==0);
assert(strcmp(tokens[3]->value_ptr,"-=")==0);
assert(strcmp(tokens[4]->value_ptr,"1")==0);
free_tokens(tokens, 5);
}
bool test_can_see_line_with_semicolon() {
printt("test can see line with semicolon\n");
char* str = "Char x; ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind == TYPEID);
assert(tokens[1]->kind == ID);
assert(tokens[2]->kind == SEMICOLON);
assert(strcmp(tokens[1]->value_ptr,"x")==0);
free_tokens(tokens, 3);
return true;
}
bool test_can_see_line_with_operators() {
printt("can see line with operators\n");
char* str = "x = x+x; ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind == ID);
assert(tokens[1]->kind == ASSIGNOP);
assert(tokens[2]->kind == ID);
assert(tokens[3]->kind == OPKEY_ARITHMETIC);
assert(tokens[4]->kind == ID);
free_tokens(tokens, 5);
return true;
}
bool test_lexes_return_statement_favorably() {
printt("lexes return statement favorably\n");
char* str = "return (-5)*n; ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==RETURN);
assert(tokens[1]->kind==LPARENS);
assert(tokens[2]->kind==OPKEY_ARITHMETIC);
assert(tokens[3]->kind==INTEGER);
assert(tokens[4]->kind==RPARENS);
assert(tokens[5]->kind==OPKEY_ARITHMETIC);
assert(tokens[6]->kind==ID);
assert(tokens[7]->kind==SEMICOLON);
free_tokens(tokens, 8);
return true;
}
bool test_lexes_other_return_statement() {
printt("lexes other return statement\n");
char* str = "return (n*faculty(n-1)); ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==RETURN);
assert(tokens[1]->kind==LPARENS);
assert(tokens[2]->kind==ID);
assert(tokens[3]->kind==OPKEY_ARITHMETIC);
assert(tokens[4]->kind==ID);
assert(tokens[5]->kind==LPARENS);
assert(tokens[6]->kind==ID);
assert(tokens[7]->kind==OPKEY_ARITHMETIC);
assert(tokens[8]->kind==INTEGER);
assert(tokens[9]->kind==RPARENS);
assert(tokens[10]->kind==RPARENS);
free_tokens(tokens, 11);
return true;
}
bool test_lexes_float_constant() {
printt("lexes float constant\n");
char* str = "1.44 ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==FLOATING);
assert(strcmp(tokens[0]->value_ptr,"1.44")==0);
free_tokens(tokens, 1);
return true;
}
bool test_lexes_escaped_char() {
printt("lexes escaped char\n");
char* str = "return '\\n'";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==RETURN);
assert(tokens[1]->kind==CCONST);
assert(strcmp(tokens[1]->value_ptr,"'\\n'")==0);
free_tokens(tokens, 2);
return true;
}
bool test_anytypetoken() {
printt("test anytype token\n");
char* str = "# ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==ANYTYPE);
free_tokens(tokens, 1);
return true;
}
bool test_true() {
printt("test boolconst token\n");
char* str = "true ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==BCONST_TRUE);
free_tokens(tokens, 1);
return true;
}
bool test_false() {
printt("test boolconst token\n");
char* str = "false ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==BCONST_FALSE);
free_tokens(tokens, 1);
return true;
}
bool test_char() {
printt("test charconst token\n");
char* str = "'x' ('\\n') 'h' ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==CCONST);
assert(tokens[1]->kind==LPARENS);
assert(tokens[2]->kind==CCONST);
assert(tokens[3]->kind==RPARENS);
assert(strcmp(tokens[0]->value_ptr,"'x'")==0 );
assert(strcmp(tokens[2]->value_ptr,"'\\n'")==0 );
assert(tokens[4]->kind == CCONST);
assert(strcmp(tokens[4]->value_ptr,"'h'")==0 );
free_tokens(tokens, 5);
return true;
}
bool test_float_1() {
printt("test floatconst token:1\n");
char* str = "2038.4 ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==FLOATING);
assert(strcmp(tokens[0]->value_ptr,"2038.4") == 0);
free_tokens(tokens, 1);
return true;
}
bool test_float_2() {
printt("test floatconst token:2\n");
char* str = "0.0 ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind == FLOATING);
assert(strcmp(tokens[0]->value_ptr, "0.0") == 0);
free_tokens(tokens, 1);
return true;
}
bool test_float_3() {
printt("test floatconst token:3\n");
char* str = "-5.0 ";
struct Token** tokens = lex(str);
//looking at index 1 because '-' and float
//are lexed seperately, for simplicity reasons.
//perhaps we may change it later on
assert(tokens[1]->kind==FLOATING);
assert(strcmp(tokens[1]->value_ptr,"5.0") == 0);
free_tokens(tokens, 2);
return true;
}
bool test_identifier_1() {
printt("test identifier token:1\n");
char* str = "main ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==ID);
assert(strcmp(tokens[0]->value_ptr,"main")==0);
free_tokens(tokens, 1);
return true;
}
bool test_identifier_2() {
printt("test identifier token:2\n");
char* str = "arg_ls ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==ID);
assert(strcmp(tokens[0]->value_ptr,"arg_ls")==0);
free_tokens(tokens, 1);
return true;
}
bool test_int_1() {
printt("test integer token:1\n");
char* str = "2038 ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==INTEGER);
assert(strcmp(tokens[0]->value_ptr,"2038")==0);
free_tokens(tokens, 1);
return true;
}
bool test_int_2() {
printt("test integer token:2\n");
char* str = "0 ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==INTEGER);
assert(strcmp(tokens[0]->value_ptr,"0")==0);
free_tokens(tokens, 1);
return true;
}
bool test_int_3() {
printt("test integer token:3\n");
char* str = "-5 ";
struct Token** tokens = lex(str);
assert(tokens[1]->kind==INTEGER);
assert(strcmp(tokens[1]->value_ptr,"5")==0);
free_tokens(tokens, 2);
return true;
}
bool test_hex(){
printt("test hex\n");
char* str = "0x1 0x0 0x10 0x1f 0xA3";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==HEXCONST);
assert(strcmp(tokens[0]->value_ptr,"0x1")==0);
assert(tokens[1]->kind==HEXCONST);
assert(strcmp(tokens[1]->value_ptr,"0x0")==0);
assert(tokens[2]->kind==HEXCONST);
assert(strcmp(tokens[2]->value_ptr,"0x10")==0);
assert(tokens[3]->kind==HEXCONST);
assert(strcmp(tokens[3]->value_ptr,"0x1f")==0);
assert(tokens[4]->kind==HEXCONST);
assert(strcmp(tokens[4]->value_ptr,"0xA3")==0);
free_tokens(tokens, 5);
return true;
}
bool test_binconst(){
printt("test binconst\n");
char* str = "0b0 0b1 0b10 0b101";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==BINCONST);
assert(strcmp(tokens[0]->value_ptr,"0b0")==0);
assert(tokens[1]->kind==BINCONST);
assert(strcmp(tokens[1]->value_ptr,"0b1")==0);
assert(tokens[2]->kind==BINCONST);
assert(strcmp(tokens[2]->value_ptr,"0b10")==0);
assert(tokens[3]->kind==BINCONST);
assert(strcmp(tokens[3]->value_ptr,"0b101")==0);
free_tokens(tokens, 4);
return true;
}
bool test_struct() {
printt("test struct token\n");
char* str = "struct ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==STRUCT);
free_tokens(tokens, 1);
return true;
}
bool test_return() {
printt("test return token\n");
char* str = "return ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==RETURN);
free_tokens(tokens, 1);
return true;
}
bool test_string_1() {
printt("test string token:1\n");
char* str = "\"hi\" ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==STRINGCONST);
assert(strcmp(tokens[0]->value_ptr,"hi")==0);
free_tokens(tokens, 1);
return true;
}
bool test_typeidentifier() {
printt("test typeidentifier token:1\n");
char* str = "Carrot ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==TYPEID);
assert(strcmp(tokens[0]->value_ptr,"Carrot")==0);
free_tokens(tokens, 1);
return true;
}
bool test_typeidentifier_primitive(){
printt("test typeidentifier primitive\n");
char* str = "int uint int8 uint8";
struct Token** tokens = lex(str);
char* expect[] = {"int", "uint", "int8", "uint8"};
for(int i=0;i < 4; i++){
assert(tokens[i]->kind == TYPEID_PRIMITIVE_INT);
assert(strcmp(tokens[i]->value_ptr, expect[i]) == 0);
}
free_tokens(tokens, 4);
//------------------------------
char* str2 = "float char bool ";
struct Token** tokens2 = lex(str2);
assert(tokens2[0]->kind == TYPEID_PRIMITIVE_FLOAT);
assert(tokens2[1]->kind == TYPEID_PRIMITIVE_CHAR);
assert(tokens2[2]->kind == TYPEID_PRIMITIVE_BOOL);
free_tokens(tokens2, 3);
return true;
}
bool test_typeparameter_1() {
printt("test typeparameter token\n");
char* str = "?T0 ?T1 (?T2";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==TPARAM);
assert(tokens[1]->kind==TPARAM);
assert(tokens[2]->kind==LPARENS);
assert(tokens[3]->kind==TPARAM);
assert(strcmp(tokens[0]->value_ptr,"0")==0);
free_tokens(tokens, 4);
return true;
}
bool test_comma() {
printt("test comma token\n");
char* str = ",, ";
struct Token** tokens = lex(str);
assert(tokens[1]->kind==COMMA);
assert(strcmp(tokens[1]->value_ptr,",")==0);
free_tokens(tokens, 2);
return true;
}
bool test_arrow() {
printt("test arrow token\n");
char* str = "-> ~> ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==ARROW);
assert(strcmp(tokens[0]->value_ptr,"->")==0);
assert(tokens[1]->kind==ARROW);
assert(strcmp(tokens[1]->value_ptr,"~>")==0);
free_tokens(tokens, 2);
return true;
}
bool test_mixed_1() {
printt("test mixed 1\n");
char* str = "struct MyStruct { uint a, MyStruct b} ";
struct Token** tokens = lex(str);
assert(tokens[2]->kind == LCURLY);
assert(tokens[3]->kind == TYPEID_PRIMITIVE_INT);
assert(strcmp(tokens[3]->value_ptr, "uint") == 0);
assert(tokens[4]->kind == ID);
assert(strcmp(tokens[4]->value_ptr, "a") == 0);
assert(tokens[5]->kind == COMMA);
free_tokens(tokens, 6);
return true;
}
bool test_mixed_2() {
printt("test mixed 2\n");
char* str = ") f)~> ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==RPARENS);
assert(tokens[1]->kind==ID);
assert(strcmp(tokens[1]->value_ptr,"f")==0);
assert(tokens[2]->kind==RPARENS);
assert(tokens[3]->kind==ARROW);
free_tokens(tokens, 4);
return true;
}
bool test_mixed_3() {
printt("test mixed 3\n");
char* str = "if(x ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==IF);
assert(tokens[1]->kind==LPARENS);
assert(tokens[2]->kind==ID);
free_tokens(tokens, 3);
return true;
}
bool test_mixed_4() {
printt("test mixed 4\n");
char* str = "while(x uint n ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==WHILE);
assert(tokens[1]->kind==LPARENS);
assert(tokens[2]->kind==ID);
assert(tokens[3]->kind==TYPEID_PRIMITIVE_INT);
assert(tokens[4]->kind==ID);
free_tokens(tokens, 5);
return true;
}
bool test_mixed_5() {
printt("test mixed 5\n");
char* str = "]='d'; ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==RBRACKET);
assert(tokens[1]->kind==ASSIGNOP);
assert(tokens[2]->kind==CCONST);
assert(tokens[3]->kind==SEMICOLON);
free_tokens(tokens, 4);
return true;
}
bool test_mixed_6() {
printt("test mixed 6\n");
char* str = "MyStruct s} ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==TYPEID);
assert(tokens[1]->kind==ID);
assert(tokens[2]->kind==RCURLY);
free_tokens(tokens, 3);
return true;
}
bool test_mixed_7() {
printt("test mixed 7\n");
char* str = "(1<2) ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==LPARENS);
assert(tokens[1]->kind==INTEGER);
assert(tokens[2]->kind==OPKEY_RELATIONAL);
assert(tokens[3]->kind==INTEGER);
assert(tokens[4]->kind==RPARENS);
free_tokens(tokens, 5);
return true;
}
bool test_mixed_8() {
printt("test mixed 8\n");
char* str = "putchar('1') ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==ID);
assert(tokens[1]->kind==LPARENS);
assert(tokens[2]->kind==CCONST);
assert(tokens[3]->kind==RPARENS);
free_tokens(tokens, 4);
return true;
}
bool test_mixed_9() {
printt("test mixed 9\n");
char* str = "putchar('-') ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==ID);
assert(tokens[1]->kind==LPARENS);
assert(tokens[2]->kind==CCONST);
assert(tokens[3]->kind==RPARENS);
free_tokens(tokens, 4);
return true;
}
bool test_mixed_10() {
printt("test mixed 10\n");
char* str = ";\n i=0; ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==SEMICOLON);
assert(tokens[1]->kind==ID);
assert(tokens[1]->line_num == 2);
assert(tokens[2]->kind==ASSIGNOP);
assert(tokens[3]->kind==INTEGER);
free_tokens(tokens, 4);
return true;
}
bool test_mixed_11() {
printt("test mixed 11\n");
char* str = "uint i, char j ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==TYPEID_PRIMITIVE_INT);
assert(tokens[1]->kind==ID);
assert(tokens[2]->kind==COMMA);
assert(tokens[3]->kind==TYPEID_PRIMITIVE_CHAR);
assert(tokens[4]->kind==ID);
free_tokens(tokens, 5);
return true;
}
bool test_mixed_12() {
printt("test mixed 12\n");
char* str = "( x < 3.1) ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==LPARENS);
assert(tokens[1]->kind==ID);
assert(tokens[2]->kind==OPKEY_RELATIONAL);
assert(tokens[3]->kind==FLOATING);
assert(tokens[4]->kind==RPARENS);
free_tokens(tokens, 5);
return true;
}
bool test_mixed_13() {
printt("test mixed 13\n");
char* str = "println(\"vector sum:\"); ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==ID);
assert(tokens[1]->kind==LPARENS);
assert(tokens[2]->kind==STRINGCONST);
assert(tokens[3]->kind==RPARENS);
assert(tokens[4]->kind==SEMICOLON);
free_tokens(tokens, 5);
return true;
}
bool test_mixed_14(){
printt("test mixed 14\n");
char* str = "struct MyStruct{ int a, float b}";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==STRUCT);
assert(tokens[1]->kind==TYPEID);
assert(tokens[2]->kind==LCURLY);
assert(tokens[3]->kind==TYPEID_PRIMITIVE_INT);
assert(tokens[4]->kind==ID);
assert(tokens[5]->kind==COMMA);
assert(tokens[6]->kind==TYPEID_PRIMITIVE_FLOAT);
assert(tokens[7]->kind==ID);
assert(tokens[8]->kind==RCURLY);
free_tokens(tokens, 9);
return true;
}
bool test_mixed_15(){
printt("test mixed 15\n");
char* str = "struct MyStruct{\n\tInt a,\n\tInt b\n}";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==STRUCT);
assert(tokens[0]->line_num == 1);
assert(tokens[1]->kind==TYPEID);
assert(tokens[2]->kind==LCURLY);
assert(tokens[3]->kind==TYPEID);
assert(tokens[4]->kind==ID);
assert(tokens[5]->kind==COMMA);
assert(tokens[6]->kind==TYPEID);
assert(tokens[7]->kind==ID);
assert(tokens[8]->kind==RCURLY);
assert(tokens[8]->line_num == 4);
free_tokens(tokens, 9);
return true;
}
bool test_mixed_16(){
printt("test mixed 16\n");
char* str = "((uint) -> bool) member ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==LPARENS);
assert(tokens[1]->kind==LPARENS);
assert(tokens[2]->kind==TYPEID_PRIMITIVE_INT);
assert(tokens[3]->kind==RPARENS);
assert(tokens[4]->kind==ARROW);
assert(tokens[5]->kind==TYPEID_PRIMITIVE_BOOL);
assert(tokens[6]->kind==RPARENS);
assert(tokens[7]->kind==ID);
free_tokens(tokens, 8);
return true;
}
bool test_operators() {
printt("test operators\n");
char* str = "+ - * / % ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==OPKEY_ARITHMETIC);
assert(strcmp(tokens[0]->value_ptr, "+") == 0);
assert(tokens[1]->kind==OPKEY_ARITHMETIC);
assert(strcmp(tokens[1]->value_ptr, "-") == 0);
assert(tokens[2]->kind==OPKEY_ARITHMETIC);
assert(strcmp(tokens[2]->value_ptr, "*") == 0);
assert(tokens[3]->kind==OPKEY_ARITHMETIC);
assert(strcmp(tokens[3]->value_ptr, "/") == 0);
assert(tokens[4]->kind==OPKEY_ARITHMETIC);
assert(strcmp(tokens[4]->value_ptr, "%") == 0);
free_tokens(tokens, 5);
return true;
}
bool test_operators_cmp(){
printt("test operators_cmp\n");
char* str = "<= >= == != < >";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==OPKEY_RELATIONAL);
assert(strcmp(tokens[0]->value_ptr, "<=") == 0);
assert(tokens[1]->kind==OPKEY_RELATIONAL);
assert(strcmp(tokens[1]->value_ptr, ">=") == 0);
assert(tokens[2]->kind==OPKEY_RELATIONAL);
assert(strcmp(tokens[2]->value_ptr, "==") == 0);
assert(tokens[3]->kind==OPKEY_RELATIONAL);
assert(strcmp(tokens[3]->value_ptr, "!=") == 0);
assert(tokens[4]->kind==OPKEY_RELATIONAL);
assert(strcmp(tokens[4]->value_ptr, "<") == 0);
assert(tokens[5]->kind==OPKEY_RELATIONAL);
assert(strcmp(tokens[5]->value_ptr, ">") == 0);
free_tokens(tokens, 6);
return true;
}
bool test_operators_logical(){
printt("test operators_logical\n");
char* str = "&& || ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==OPKEY_LOGICAL);
assert(strcmp(tokens[0]->value_ptr, "&&") == 0);
assert(tokens[1]->kind==OPKEY_LOGICAL);
assert(strcmp(tokens[1]->value_ptr, "||") == 0);
free_tokens(tokens, 2);
return true;
}
bool test_operators_bitwise(){
printt("test operators_bitwise\n");
char* str = "| & << >> ^ ~";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==OPKEY_BITWISE);
assert(strcmp(tokens[0]->value_ptr, "|") == 0);
assert(tokens[1]->kind==OPKEY_BITWISE);
assert(strcmp(tokens[1]->value_ptr, "&") == 0);
assert(tokens[2]->kind==OPKEY_BITWISE);
assert(strcmp(tokens[2]->value_ptr, "<<") == 0);
assert(tokens[3]->kind==OPKEY_BITWISE);
assert(strcmp(tokens[3]->value_ptr, ">>") == 0);
assert(tokens[4]->kind==OPKEY_BITWISE);
assert(strcmp(tokens[4]->value_ptr, "^") == 0);
assert(tokens[5]->kind==OPKEY_BITWISE);
assert(strcmp(tokens[5]->value_ptr, "~") == 0);
free_tokens(tokens, 6);
return true;
}
bool test_loop() {
printt("test loop\n");
char* str = "loop loop{ lo ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==LOOP);
assert(tokens[1]->kind==LOOP);
assert(tokens[2]->kind==LCURLY);
assert(tokens[3]->kind==ID);
free_tokens(tokens, 4);
return true;
}
bool test_if_else() {
printt("test if else\n");
char* str = "if else{ ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==IF);
assert(tokens[1]->kind==ELSE);
assert(tokens[2]->kind==LCURLY);
free_tokens(tokens, 3);
return true;
}
bool test_break() {
printt("test break\n");
char* str = "break; int x";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==BREAK);
assert(tokens[1]->kind==SEMICOLON);
assert(tokens[2]->kind==TYPEID_PRIMITIVE_INT);
free_tokens(tokens, 3);
return true;
}
bool test_for(){
printt("test_for\n");
char* str = "for for{ ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==FOR);
assert(tokens[1]->kind==FOR);
assert(tokens[2]->kind==LCURLY);
free_tokens(tokens, 3);
return true;
}
bool test_in(){
printt("test_in\n");
char* str = "in; in{ ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==IN);
assert(tokens[1]->kind==SEMICOLON);
assert(tokens[2]->kind==IN);
assert(tokens[3]->kind==LCURLY);
free_tokens(tokens, 4);
return true;
}
bool test_rangeop_1(){
printt("test_rangeop_1\n");
char* str = ".. a.... ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==RANGEOP);
assert(tokens[1]->kind==ID);
assert(tokens[2]->kind==RANGEOP);
assert(tokens[3]->kind==RANGEOP);
free_tokens(tokens, 4);
return true;
}
bool test_rangeop_2(){
printt("test_rangeop_1\n");
char* str = "0 .. 3 a .. b ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==INTEGER);
assert(tokens[1]->kind==RANGEOP);
assert(tokens[2]->kind==INTEGER);
assert(tokens[3]->kind==ID);
assert(tokens[4]->kind==RANGEOP);
assert(tokens[5]->kind==ID);
free_tokens(tokens, 6);
return true;
}
bool test_member_access(){
printt("test_member_access\n");
char* str = "s.member= ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==ID);
assert(tokens[1]->kind==STRUCTMEMBERACCESS);
assert(tokens[2]->kind==ID);
assert(tokens[3]->kind==ASSIGNOP);
free_tokens(tokens, 4);
return true;
}
bool test_switch_case(){
printt("test_switch_case\n");
char* str = "switch x { case 3 ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==SWITCH);
assert(tokens[1]->kind==ID);
assert(tokens[2]->kind==LCURLY);
assert(tokens[3]->kind==CASE);
assert(tokens[4]->kind==INTEGER);
free_tokens(tokens, 5);
return true;
}
bool test_assign_operators(){
printt("test_assign_operators\n");
char* str = "= += -= *= /= >>= <<= &= |= %=";
struct Token** tokens = lex(str);
// =
assert(tokens[0]->kind==ASSIGNOP);
assert(strcmp(tokens[0]->value_ptr, "=") == 0);
// arithmetic
assert(tokens[1]->kind==ASSIGNOP);
assert(strcmp(tokens[1]->value_ptr, "+=") == 0);
assert(tokens[2]->kind==ASSIGNOP);
assert(strcmp(tokens[2]->value_ptr, "-=") == 0);
assert(tokens[3]->kind==ASSIGNOP);
assert(strcmp(tokens[3]->value_ptr, "*=") == 0);
assert(tokens[4]->kind==ASSIGNOP);
assert(strcmp(tokens[4]->value_ptr, "/=") == 0);
// bitwise
assert(tokens[5]->kind==ASSIGNOP);
assert(strcmp(tokens[5]->value_ptr, ">>=") == 0);
assert(tokens[6]->kind==ASSIGNOP);
assert(strcmp(tokens[6]->value_ptr, "<<=") == 0);
assert(tokens[7]->kind==ASSIGNOP);
assert(strcmp(tokens[7]->value_ptr, "&=") == 0);
assert(tokens[8]->kind==ASSIGNOP);
assert(strcmp(tokens[8]->value_ptr, "|=") == 0);
//modulo equals
assert(tokens[9]->kind==ASSIGNOP);
assert(strcmp(tokens[9]->value_ptr, "%=") == 0);
free_tokens(tokens, 10);
return true;
}
bool test_brackets(){
printt("test_brackets\n");
char* str = "[](){}< > ";
struct Token** tokens = lex(str);
assert(tokens[0]->kind==LBRACKET);
assert(tokens[1]->kind==RBRACKET);
assert(tokens[2]->kind==LPARENS);
assert(tokens[3]->kind==RPARENS);
assert(tokens[4]->kind==LCURLY);
assert(tokens[5]->kind==RCURLY);
assert(tokens[6]->kind==OPKEY_RELATIONAL);
assert(tokens[7]->kind==OPKEY_RELATIONAL);
assert( strcmp(tokens[6]->value_ptr,"<")==0 );
assert( strcmp(tokens[7]->value_ptr,">")==0 );
free_tokens(tokens, 8);
return true;
}
|
nagineni/chromium-crosswalk
|
tools/idl_parser/idl_parser.py
|
<filename>tools/idl_parser/idl_parser.py
#!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Parser for PPAPI IDL """
#
# IDL Parser
#
# The parser is uses the PLY yacc library to build a set of parsing rules based
# on WebIDL.
#
# WebIDL, and WebIDL grammar can be found at:
# http://dev.w3.org/2006/webapi/WebIDL/
# PLY can be found at:
# http://www.dabeaz.com/ply/
#
# The parser generates a tree by recursively matching sets of items against
# defined patterns. When a match is made, that set of items is reduced
# to a new item. The new item can provide a match for parent patterns.
# In this way an AST is built (reduced) depth first.
#
#
# Disable check for line length and Member as Function due to how grammar rules
# are defined with PLY
#
# pylint: disable=R0201
# pylint: disable=C0301
import os.path
import sys
import time
from idl_lexer import IDLLexer
from idl_node import IDLAttribute, IDLNode
#
# Try to load the ply module, if not, then assume it is in the third_party
# directory.
#
try:
# Disable lint check which fails to find the ply module.
# pylint: disable=F0401
from ply import lex
from ply import yacc
except ImportError:
module_path, module_name = os.path.split(__file__)
third_party = os.path.join(module_path, os.par, os.par, 'third_party')
sys.path.append(third_party)
# pylint: disable=F0401
from ply import lex
from ply import yacc
#
# ERROR_REMAP
#
# Maps the standard error formula into a more friendly error message.
#
ERROR_REMAP = {
'Unexpected ")" after "(".' : 'Empty argument list.',
'Unexpected ")" after ",".' : 'Missing argument.',
'Unexpected "}" after ",".' : 'Trailing comma in block.',
'Unexpected "}" after "{".' : 'Unexpected empty block.',
'Unexpected comment after "}".' : 'Unexpected trailing comment.',
'Unexpected "{" after keyword "enum".' : 'Enum missing name.',
'Unexpected "{" after keyword "struct".' : 'Struct missing name.',
'Unexpected "{" after keyword "interface".' : 'Interface missing name.',
}
def Boolean(val):
"""Convert to strict boolean type."""
if val:
return True
return False
def ListFromConcat(*items):
"""Generate list by concatenating inputs"""
itemsout = []
for item in items:
if item is None:
continue
if type(item) is not type([]):
itemsout.append(item)
else:
itemsout.extend(item)
return itemsout
def ExpandProduction(p):
if type(p) == list:
return '[' + ', '.join([ExpandProduction(x) for x in p]) + ']'
if type(p) == IDLNode:
return 'Node:' + str(p)
if type(p) == IDLAttribute:
return 'Attr:' + str(p)
if type(p) == str:
return 'str:' + p
return '%s:%s' % (p.__class__.__name__, str(p))
# TokenTypeName
#
# Generate a string which has the type and value of the token.
#
def TokenTypeName(t):
if t.type == 'SYMBOL':
return 'symbol %s' % t.value
if t.type in ['HEX', 'INT', 'OCT', 'FLOAT']:
return 'value %s' % t.value
if t.type == 'string' :
return 'string "%s"' % t.value
if t.type == 'COMMENT' :
return 'comment'
if t.type == t.value:
return '"%s"' % t.value
if t.type == ',':
return 'Comma'
if t.type == 'identifier':
return 'identifier "%s"' % t.value
return 'keyword "%s"' % t.value
#
# IDL Parser
#
# The Parser inherits the from the Lexer to provide PLY with the tokenizing
# definitions. Parsing patterns are encoded as functions where p_<name> is
# is called any time a patern matching the function documentation is found.
# Paterns are expressed in the form of:
# """ <new item> : <item> ....
# | <item> ...."""
#
# Where new item is the result of a match against one or more sets of items
# separated by the "|".
#
# The function is called with an object 'p' where p[0] is the output object
# and p[n] is the set of inputs for positive values of 'n'. Len(p) can be
# used to distinguish between multiple item sets in the pattern.
#
# For more details on parsing refer to the PLY documentation at
# http://www.dabeaz.com/ply/
#
# The parser is based on the WebIDL standard. See:
# http://www.w3.org/TR/WebIDL/#idl-grammar
#
# The various productions are annotated so that the WHOLE number greater than
# zero in the comment denotes the matching WebIDL grammar definition.
#
# Productions with a fractional component in the comment denote additions to
# the WebIDL spec, such as comments.
#
class IDLParser(object):
#
# We force all input files to start with two comments. The first comment is a
# Copyright notice followed by a file comment and finally by file level
# productions.
#
# [0] Insert a TOP definition for Copyright and Comments
def p_Top(self, p):
"""Top : COMMENT COMMENT Definitions"""
Copyright = self.BuildComment('Copyright', p, 1)
Filedoc = self.BuildComment('Comment', p, 2)
p[0] = ListFromConcat(Copyright, Filedoc, p[3])
# [0.1] Add support for Multiple COMMENTS
def p_Comments(self, p):
"""Comments : CommentsRest"""
if len(p) > 1:
p[0] = p[1]
# [0.2] Produce a COMMENT and aggregate sibling comments
def p_CommentsRest(self, p):
"""CommentsRest : COMMENT CommentsRest
| """
if len(p) > 1:
p[0] = ListFromConcat(self.BuildComment('Comment', p, 1), p[2])
#
#The parser is based on the WebIDL standard. See:
# http://www.w3.org/TR/WebIDL/#idl-grammar
#
# [1]
def p_Definitions(self, p):
"""Definitions : ExtendedAttributeList Definition Definitions
| """
if len(p) > 1:
p[2].AddChildren(p[1])
p[0] = ListFromConcat(p[2], p[3])
# [2] Add INLINE definition
def p_Definition(self, p):
"""Definition : CallbackOrInterface
| Partial
| Dictionary
| Exception
| Enum
| Typedef
| ImplementsStatement"""
p[0] = p[1]
# [2.1] Error recovery for definition
def p_DefinitionError(self, p):
"""Definition : error ';'"""
p[0] = self.BuildError(p, 'Definition')
# [3]
def p_CallbackOrInterface(self, p):
"""CallbackOrInterface : CALLBACK CallbackRestOrInterface
| Interface"""
if len(p) > 2:
p[0] = p[2]
else:
p[0] = p[1]
# [4]
def p_CallbackRestOrInterface(self, p):
"""CallbackRestOrInterface : CallbackRest
| Interface"""
p[0] = p[1]
# [5]
def p_Interface(self, p):
"""Interface : INTERFACE identifier Inheritance '{' InterfaceMembers '}' ';'"""
p[0] = self.BuildNamed('Interface', p, 2, ListFromConcat(p[3], p[5]))
# [6] Error recovery for PARTIAL
def p_Partial(self, p):
"""Partial : PARTIAL PartialDefinition"""
p[2].AddChildren(self.BuildTrue('Partial'))
p[0] = p[2]
# [6.1] Error recovery for Enums
def p_PartialError(self, p):
"""Partial : PARTIAL error"""
p[0] = self.BuildError(p, 'Partial')
# [7]
def p_PartialDefinition(self, p):
"""PartialDefinition : PartialDictionary
| PartialInterface"""
p[0] = p[1]
# [8]
def p_PartialInterface(self, p):
"""PartialInterface : INTERFACE identifier '{' InterfaceMembers '}' ';'"""
p[0] = self.BuildNamed('Interface', p, 2, p[4])
# [9]
def p_InterfaceMembers(self, p):
"""InterfaceMembers : ExtendedAttributeList InterfaceMember InterfaceMembers
|"""
if len(p) > 1:
p[2].AddChildren(p[1])
p[0] = ListFromConcat(p[2], p[3])
# [10]
def p_InterfaceMember(self, p):
"""InterfaceMember : Const
| AttributeOrOperation"""
p[0] = p[1]
# [11]
def p_Dictionary(self, p):
"""Dictionary : DICTIONARY identifier Inheritance '{' DictionaryMembers '}' ';'"""
p[0] = self.BuildNamed('Dictionary', p, 2, ListFromConcat(p[3], p[5]))
# [11.1] Error recovery for regular Dictionary
def p_DictionaryError(self, p):
"""Dictionary : DICTIONARY error ';'"""
p[0] = self.BuildError(p, 'Dictionary')
# [12]
def p_DictionaryMembers(self, p):
"""DictionaryMembers : ExtendedAttributeList DictionaryMember DictionaryMembers
|"""
if len(p) > 1:
p[2].AddChildren(p[1])
p[0] = ListFromConcat(p[2], p[3])
# [13]
def p_DictionaryMember(self, p):
"""DictionaryMember : Type identifier Default ';'"""
p[0] = self.BuildNamed('Key', p, 2, ListFromConcat(p[1], p[3]))
# [14]
def p_PartialDictionary(self, p):
"""PartialDictionary : DICTIONARY identifier '{' DictionaryMembers '}' ';'"""
partial = self.BuildTrue('Partial')
p[0] = self.BuildNamed('Dictionary', p, 2, ListFromConcat(p[4], partial))
# [14.1] Error recovery for Partial Dictionary
def p_PartialDictionaryError(self, p):
"""PartialDictionary : DICTIONARY error ';'"""
p[0] = self.BuildError(p, 'PartialDictionary')
# [15]
def p_Default(self, p):
"""Default : '=' DefaultValue
|"""
if len(p) > 1:
p[0] = self.BuildProduction('Default', p, 2, p[2])
# [16]
def p_DefaultValue(self, p):
"""DefaultValue : ConstValue
| string"""
if type(p[1]) == str:
p[0] = ListFromConcat(self.BuildAttribute('TYPE', 'DOMString'),
self.BuildAttribute('NAME', p[1]))
else:
p[0] = p[1]
# [17]
def p_Exception(self, p):
"""Exception : EXCEPTION identifier Inheritance '{' ExceptionMembers '}' ';'"""
p[0] = self.BuildNamed('Exception', p, 2, ListFromConcat(p[3], p[5]))
# [18]
def p_ExceptionMembers(self, p):
"""ExceptionMembers : ExtendedAttributeList ExceptionMember ExceptionMembers
|"""
if len(p) > 1:
p[2].AddChildren(p[1])
p[0] = ListFromConcat(p[2], p[3])
# [18.1] Error recovery for ExceptionMembers
def p_ExceptionMembersError(self, p):
"""ExceptionMembers : error"""
p[0] = self.BuildError(p, 'ExceptionMembers')
# [19]
def p_Inheritance(self, p):
"""Inheritance : ':' identifier
|"""
if len(p) > 1:
p[0] = self.BuildNamed('Inherit', p, 2)
# [20]
def p_Enum(self, p):
"""Enum : ENUM identifier '{' EnumValueList '}' ';'"""
p[0] = self.BuildNamed('Enum', p, 2, p[4])
# [20.1] Error recovery for Enums
def p_EnumError(self, p):
"""Enum : ENUM error ';'"""
p[0] = self.BuildError(p, 'Enum')
# [21]
def p_EnumValueList(self, p):
"""EnumValueList : ExtendedAttributeList string EnumValues"""
enum = self.BuildNamed('EnumItem', p, 2, p[1])
p[0] = ListFromConcat(enum, p[3])
# [22]
def p_EnumValues(self, p):
"""EnumValues : ',' ExtendedAttributeList string EnumValues
|"""
if len(p) > 1:
enum = self.BuildNamed('EnumItem', p, 3, p[2])
p[0] = ListFromConcat(enum, p[4])
# [23]
def p_CallbackRest(self, p):
"""CallbackRest : identifier '=' ReturnType '(' ArgumentList ')' ';'"""
arguments = self.BuildProduction('Arguments', p, 4, p[5])
p[0] = self.BuildNamed('Callback', p, 1, ListFromConcat(p[3], arguments))
# [24]
def p_Typedef(self, p):
"""Typedef : TYPEDEF ExtendedAttributeListNoComments Type identifier ';'"""
p[0] = self.BuildNamed('Typedef', p, 4, ListFromConcat(p[2], p[3]))
# [24.1] Error recovery for Typedefs
def p_TypedefError(self, p):
"""Typedef : TYPEDEF error ';'"""
p[0] = self.BuildError(p, 'Typedef')
# [25]
def p_ImplementsStatement(self, p):
"""ImplementsStatement : identifier IMPLEMENTS identifier ';'"""
name = self.BuildAttribute('REFERENCE', p[3])
p[0] = self.BuildNamed('Implements', p, 1, name)
# [26]
def p_Const(self, p):
"""Const : CONST ConstType identifier '=' ConstValue ';'"""
value = self.BuildProduction('Value', p, 5, p[5])
p[0] = self.BuildNamed('Const', p, 3, ListFromConcat(p[2], value))
# [27]
def p_ConstValue(self, p):
"""ConstValue : BooleanLiteral
| FloatLiteral
| integer
| null"""
if type(p[1]) == str:
p[0] = ListFromConcat(self.BuildAttribute('TYPE', 'integer'),
self.BuildAttribute('NAME', p[1]))
else:
p[0] = p[1]
# [27.1] Add definition for NULL
def p_null(self, p):
"""null : NULL"""
p[0] = ListFromConcat(self.BuildAttribute('TYPE', 'NULL'),
self.BuildAttribute('NAME', 'NULL'))
# [28]
def p_BooleanLiteral(self, p):
"""BooleanLiteral : TRUE
| FALSE"""
value = self.BuildAttribute('VALUE', Boolean(p[1] == 'true'))
p[0] = ListFromConcat(self.BuildAttribute('TYPE', 'boolean'), value)
# [29]
def p_FloatLiteral(self, p):
"""FloatLiteral : float
| '-' INFINITY
| INFINITY
| NAN """
if len(p) > 2:
val = '-Infinity'
else:
val = p[1]
p[0] = ListFromConcat(self.BuildAttribute('TYPE', 'float'),
self.BuildAttribute('VALUE', val))
# [30]
def p_AttributeOrOperation(self, p):
"""AttributeOrOperation : STRINGIFIER StringifierAttributeOrOperation
| Attribute
| Operation"""
if len(p) > 2:
p[0] = p[2]
else:
p[0] = p[1]
# [31]
def p_StringifierAttributeOrOperation(self, p):
"""StringifierAttributeOrOperation : Attribute
| OperationRest
| ';'"""
if p[1] == ';':
p[0] = self.BuildAttribute('STRINGIFIER', Boolean(True))
else:
p[0] = ListFromConcat(self.BuildAttribute('STRINGIFIER', p[1]), p[1])
# [32]
def p_Attribute(self, p):
"""Attribute : Inherit ReadOnly ATTRIBUTE Type identifier ';'"""
p[0] = self.BuildNamed('Attribute', p, 5,
ListFromConcat(p[1], p[2], p[4]))
# [33]
def p_Inherit(self, p):
"""Inherit : INHERIT
|"""
if len(p) > 1:
p[0] = self.BuildTrue('INHERIT')
# [34]
def p_ReadOnly(self, p):
"""ReadOnly : READONLY
|"""
if len(p) > 1:
p[0] = self.BuildTrue('READONLY')
# [35]
def p_Operation(self, p):
"""Operation : Qualifiers OperationRest"""
p[2].AddChildren(p[1])
p[0] = p[2]
# [36]
def p_Qualifiers(self, p):
"""Qualifiers : STATIC
| Specials"""
if p[1] == 'static':
p[0] = self.BuildTrue('STATIC')
else:
p[0] = p[1]
# [37]
def p_Specials(self, p):
"""Specials : Special Specials
| """
if len(p) > 1:
p[0] = ListFromConcat(p[1], p[2])
# [38]
def p_Special(self, p):
"""Special : GETTER
| SETTER
| CREATOR
| DELETER
| LEGACYCALLER"""
p[0] = self.BuildTrue(p[1].upper())
# [39]
def p_OperationRest(self, p):
"""OperationRest : ReturnType OptionalIdentifier '(' ArgumentList ')' ';'"""
arguments = self.BuildProduction('Arguments', p, 3, p[4])
p[0] = self.BuildNamed('Operation', p, 2, ListFromConcat(p[1], arguments))
# [40]
def p_OptionalIdentifier(self, p):
"""OptionalIdentifier : identifier
|"""
if len(p) > 1:
p[0] = p[1]
else:
p[0] = '_unnamed_'
# [41]
def p_ArgumentList(self, p):
"""ArgumentList : Argument Arguments
|"""
if len(p) > 1:
p[0] = ListFromConcat(p[1], p[2])
# [41.1] ArgumentList error recovery
def p_ArgumentListError(self, p):
"""ArgumentList : error """
p[0] = self.BuildError(p, 'ArgumentList')
# [42]
def p_Arguments(self, p):
"""Arguments : ',' Argument Arguments
|"""
if len(p) > 1:
p[0] = ListFromConcat(p[2], p[3])
# [43]
def p_Argument(self, p):
"""Argument : ExtendedAttributeList OptionalOrRequiredArgument"""
p[2].AddChildren(p[1])
p[0] = p[2]
# [44]
def p_OptionalOrRequiredArgument(self, p):
"""OptionalOrRequiredArgument : OPTIONAL Type ArgumentName Default
| Type Ellipsis ArgumentName"""
if len(p) > 4:
arg = self.BuildNamed('Argument', p, 3, ListFromConcat(p[2], p[4]))
arg.AddChildren(self.BuildTrue('OPTIONAL'))
else:
arg = self.BuildNamed('Argument', p, 3, ListFromConcat(p[1], p[2]))
p[0] = arg
# [45]
def p_ArgumentName(self, p):
"""ArgumentName : ArgumentNameKeyword
| identifier"""
p[0] = p[1]
# [46]
def p_Ellipsis(self, p):
"""Ellipsis : ELLIPSIS
|"""
if len(p) > 1:
p[0] = self.BuildNamed('Argument', p, 1)
p[0].AddChildren(self.BuildTrue('ELLIPSIS'))
# [47]
def p_ExceptionMember(self, p):
"""ExceptionMember : Const
| ExceptionField"""
p[0] = p[1]
# [48]
def p_ExceptionField(self, p):
"""ExceptionField : Type identifier ';'"""
p[0] = self.BuildNamed('ExceptionField', p, 2, p[1])
# [48.1] Error recovery for ExceptionMembers
def p_ExceptionFieldError(self, p):
"""ExceptionField : error"""
p[0] = self.BuildError(p, 'ExceptionField')
# [49] No comment version for mid statement attributes.
def p_ExtendedAttributeListNoComments(self, p):
"""ExtendedAttributeListNoComments : '[' ExtendedAttribute ExtendedAttributes ']'
| """
if len(p) > 2:
items = ListFromConcat(p[2], p[3])
p[0] = self.BuildProduction('ExtAttributes', p, 1, items)
# [49.1] Add optional comment field for start of statements.
def p_ExtendedAttributeList(self, p):
"""ExtendedAttributeList : Comments '[' ExtendedAttribute ExtendedAttributes ']'
| Comments """
if len(p) > 2:
items = ListFromConcat(p[3], p[4])
attribs = self.BuildProduction('ExtAttributes', p, 2, items)
p[0] = ListFromConcat(p[1], attribs)
else:
p[0] = p[1]
# [50]
def p_ExtendedAttributes(self, p):
"""ExtendedAttributes : ',' ExtendedAttribute ExtendedAttributes
|"""
if len(p) > 1:
p[0] = ListFromConcat(p[2], p[3])
# We only support:
# [ identifier ]
# [ identifier = identifier ]
# [ identifier ( ArgumentList )]
# [ identifier = identifier ( ArgumentList )]
# [51] map directly to 74-77
# [52-54, 56] are unsupported
def p_ExtendedAttribute(self, p):
"""ExtendedAttribute : ExtendedAttributeNoArgs
| ExtendedAttributeArgList
| ExtendedAttributeIdent
| ExtendedAttributeNamedArgList"""
p[0] = p[1]
# [55]
def p_ArgumentNameKeyword(self, p):
"""ArgumentNameKeyword : ATTRIBUTE
| CALLBACK
| CONST
| CREATOR
| DELETER
| DICTIONARY
| ENUM
| EXCEPTION
| GETTER
| IMPLEMENTS
| INHERIT
| LEGACYCALLER
| PARTIAL
| SETTER
| STATIC
| STRINGIFIER
| TYPEDEF
| UNRESTRICTED"""
p[0] = p[1]
# [57]
def p_Type(self, p):
"""Type : SingleType
| UnionType TypeSuffix"""
if len(p) == 2:
p[0] = self.BuildProduction('Type', p, 1, p[1])
else:
p[0] = self.BuildProduction('Type', p, 1, ListFromConcat(p[1], p[2]))
# [58]
def p_SingleType(self, p):
"""SingleType : NonAnyType
| ANY TypeSuffixStartingWithArray"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ListFromConcat(self.BuildProduction('Any', p, 1), p[2])
# [59]
def p_UnionType(self, p):
"""UnionType : '(' UnionMemberType OR UnionMemberType UnionMemberTypes ')'"""
# [60]
def p_UnionMemberType(self, p):
"""UnionMemberType : NonAnyType
| UnionType TypeSuffix
| ANY '[' ']' TypeSuffix"""
# [61]
def p_UnionMemberTypes(self, p):
"""UnionMemberTypes : OR UnionMemberType UnionMemberTypes
|"""
# [62] Moved DATE, DOMSTRING, OBJECT to PrimitiveType
def p_NonAnyType(self, p):
"""NonAnyType : PrimitiveType TypeSuffix
| identifier TypeSuffix
| SEQUENCE '<' Type '>' Null"""
if len(p) == 3:
if type(p[1]) == str:
typeref = self.BuildNamed('Typeref', p, 1)
else:
typeref = p[1]
p[0] = ListFromConcat(typeref, p[2])
if len(p) == 6:
p[0] = self.BuildProduction('Sequence', p, 1, ListFromConcat(p[3], p[5]))
# [63]
def p_ConstType(self, p):
"""ConstType : PrimitiveType Null
| identifier Null"""
if type(p[1]) == str:
p[0] = self.BuildNamed('Typeref', p, 1, p[2])
else:
p[1].AddChildren(p[2])
p[0] = p[1]
# [64]
def p_PrimitiveType(self, p):
"""PrimitiveType : UnsignedIntegerType
| UnrestrictedFloatType
| BOOLEAN
| BYTE
| OCTET
| DOMSTRING
| DATE
| OBJECT"""
if type(p[1]) == str:
p[0] = self.BuildNamed('PrimitiveType', p, 1)
else:
p[0] = p[1]
# [65]
def p_UnrestrictedFloatType(self, p):
"""UnrestrictedFloatType : UNRESTRICTED FloatType
| FloatType"""
if len(p) == 2:
typeref = self.BuildNamed('PrimitiveType', p, 1)
else:
typeref = self.BuildNamed('PrimitiveType', p, 2)
typeref.AddChildren(self.BuildTrue('UNRESTRICTED'))
p[0] = typeref
# [66]
def p_FloatType(self, p):
"""FloatType : FLOAT
| DOUBLE"""
p[0] = p[1]
# [67]
def p_UnsignedIntegerType(self, p):
"""UnsignedIntegerType : UNSIGNED IntegerType
| IntegerType"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = 'unsigned ' + p[2]
# [68]
def p_IntegerType(self, p):
"""IntegerType : SHORT
| LONG OptionalLong"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = p[1] + p[2]
# [69]
def p_OptionalLong(self, p):
"""OptionalLong : LONG
| """
if len(p) > 1:
p[0] = ' ' + p[1]
else:
p[0] = ''
# [70] Add support for sized array
def p_TypeSuffix(self, p):
"""TypeSuffix : '[' integer ']' TypeSuffix
| '[' ']' TypeSuffix
| '?' TypeSuffixStartingWithArray
| """
if len(p) == 5:
p[0] = self.BuildNamed('Array', p, 2, p[4])
if len(p) == 4:
p[0] = self.BuildProduction('Array', p, 1, p[3])
if len(p) == 3:
p[0] = ListFromConcat(self.BuildTrue('NULLABLE'), p[2])
# [71]
def p_TypeSuffixStartingWithArray(self, p):
"""TypeSuffixStartingWithArray : '[' ']' TypeSuffix
| """
if len(p) > 1:
p[0] = self.BuildProduction('Array', p, 0, p[3])
# [72]
def p_Null(self, p):
"""Null : '?'
|"""
if len(p) > 1:
p[0] = self.BuildTrue('NULLABLE')
# [73]
def p_ReturnType(self, p):
"""ReturnType : Type
| VOID"""
if p[1] == 'void':
p[0] = self.BuildProduction('Type', p, 1)
p[0].AddChildren(self.BuildNamed('PrimitiveType', p, 1))
else:
p[0] = p[1]
# [74]
def p_ExtendedAttributeNoArgs(self, p):
"""ExtendedAttributeNoArgs : identifier"""
p[0] = self.BuildNamed('ExtAttribute', p, 1)
# [75]
def p_ExtendedAttributeArgList(self, p):
"""ExtendedAttributeArgList : identifier '(' ArgumentList ')'"""
arguments = self.BuildProduction('Arguments', p, 2, p[3])
p[0] = self.BuildNamed('ExtAttribute', p, 1, arguments)
# [76]
def p_ExtendedAttributeIdent(self, p):
"""ExtendedAttributeIdent : identifier '=' identifier"""
value = self.BuildAttribute('VALUE', p[3])
p[0] = self.BuildNamed('ExtAttribute', p, 1, value)
# [77]
def p_ExtendedAttributeNamedArgList(self, p):
"""ExtendedAttributeNamedArgList : identifier '=' identifier '(' ArgumentList ')'"""
args = self.BuildProduction('Arguments', p, 4, p[5])
value = self.BuildNamed('Call', p, 3, args)
p[0] = self.BuildNamed('ExtAttribute', p, 1, value)
#
# Parser Errors
#
# p_error is called whenever the parser can not find a pattern match for
# a set of items from the current state. The p_error function defined here
# is triggered logging an error, and parsing recovery happens as the
# p_<type>_error functions defined above are called. This allows the parser
# to continue so as to capture more than one error per file.
#
def p_error(self, t):
if t:
lineno = t.lineno
pos = t.lexpos
prev = self.yaccobj.symstack[-1]
if type(prev) == lex.LexToken:
msg = "Unexpected %s after %s." % (
TokenTypeName(t), TokenTypeName(prev))
else:
msg = "Unexpected %s." % (t.value)
else:
last = self.LastToken()
lineno = last.lineno
pos = last.lexpos
msg = "Unexpected end of file after %s." % TokenTypeName(last)
self.yaccobj.restart()
# Attempt to remap the error to a friendlier form
if msg in ERROR_REMAP:
msg = ERROR_REMAP[msg]
self._last_error_msg = msg
self._last_error_lineno = lineno
self._last_error_pos = pos
def Warn(self, node, msg):
sys.stdout.write(node.GetLogLine(msg))
self.parse_warnings += 1
def LastToken(self):
return self.lexer.last
def __init__(self, lexer, verbose=False, debug=False, mute_error=False):
self.lexer = lexer
self.tokens = lexer.KnownTokens()
self.yaccobj = yacc.yacc(module=self, tabmodule=None, debug=debug,
optimize=0, write_tables=0)
self.parse_debug = debug
self.verbose = verbose
self.mute_error = mute_error
self._parse_errors = 0
self._parse_warnings = 0
self._last_error_msg = None
self._last_error_lineno = 0
self._last_error_pos = 0
#
# BuildProduction
#
# Production is the set of items sent to a grammar rule resulting in a new
# item being returned.
#
# p - Is the Yacc production object containing the stack of items
# index - Index into the production of the name for the item being produced.
# cls - The type of item being producted
# childlist - The children of the new item
def BuildProduction(self, cls, p, index, childlist=None):
try:
if not childlist:
childlist = []
filename = self.lexer.Lexer().filename
lineno = p.lineno(index)
pos = p.lexpos(index)
out = IDLNode(cls, filename, lineno, pos, childlist)
return out
except:
print 'Exception while parsing:'
for num, item in enumerate(p):
print ' [%d] %s' % (num, ExpandProduction(item))
if self.LastToken():
print 'Last token: %s' % str(self.LastToken())
raise
def BuildNamed(self, cls, p, index, childlist=None):
childlist = ListFromConcat(childlist)
childlist.append(self.BuildAttribute('NAME', p[index]))
return self.BuildProduction(cls, p, index, childlist)
def BuildComment(self, cls, p, index):
name = p[index]
# Remove comment markers
lines = []
if name[:2] == '//':
# For C++ style, remove any leading whitespace and the '//' marker from
# each line.
form = 'cc'
for line in name.split('\n'):
start = line.find('//')
lines.append(line[start+2:])
else:
# For C style, remove ending '*/''
form = 'c'
for line in name[:-2].split('\n'):
# Remove characters until start marker for this line '*' if found
# otherwise it should be blank.
offs = line.find('*')
if offs >= 0:
line = line[offs + 1:].rstrip()
else:
line = ''
lines.append(line)
name = '\n'.join(lines)
childlist = [self.BuildAttribute('NAME', name),
self.BuildAttribute('FORM', form)]
return self.BuildProduction(cls, p, index, childlist)
#
# BuildError
#
# Build and Errror node as part of the recovery process.
#
#
def BuildError(self, p, prod):
self._parse_errors += 1
name = self.BuildAttribute('NAME', self._last_error_msg)
line = self.BuildAttribute('LINE', self._last_error_lineno)
pos = self.BuildAttribute('POS', self._last_error_pos)
prod = self.BuildAttribute('PROD', prod)
node = self.BuildProduction('Error', p, 1,
ListFromConcat(name, line, pos, prod))
if not self.mute_error:
node.Error(self._last_error_msg)
return node
#
# BuildAttribute
#
# An ExtendedAttribute is a special production that results in a property
# which is applied to the adjacent item. Attributes have no children and
# instead represent key/value pairs.
#
def BuildAttribute(self, key, val):
return IDLAttribute(key, val)
def BuildFalse(self, key):
return IDLAttribute(key, Boolean(False))
def BuildTrue(self, key):
return IDLAttribute(key, Boolean(True))
def GetErrors(self):
# Access lexer errors, despite being private
# pylint: disable=W0212
return self._parse_errors + self.lexer._lex_errors
#
# ParseData
#
# Attempts to parse the current data loaded in the lexer.
#
def ParseText(self, filename, data):
self._parse_errors = 0
self._parse_warnings = 0
self._last_error_msg = None
self._last_error_lineno = 0
self._last_error_pos = 0
try:
self.lexer.Tokenize(data, filename)
nodes = self.yaccobj.parse(lexer=self.lexer) or []
name = self.BuildAttribute('NAME', filename)
return IDLNode('File', filename, 0, 0, nodes + [name])
except lex.LexError as lexError:
sys.stderr.write('Error in token: %s\n' % str(lexError))
return None
def ParseFile(parser, filename):
"""Parse a file and return a File type of node."""
with open(filename) as fileobject:
try:
out = parser.ParseText(filename, fileobject.read())
out.SetProperty('DATETIME', time.ctime(os.path.getmtime(filename)))
out.SetProperty('ERRORS', parser.GetErrors())
return out
except Exception as e:
last = parser.LastToken()
sys.stderr.write('%s(%d) : Internal parsing error\n\t%s.\n' % (
filename, last.lineno, str(e)))
def main(argv):
nodes = []
parser = IDLParser(IDLLexer())
errors = 0
for filename in argv:
filenode = ParseFile(parser, filename)
if (filenode):
errors += filenode.GetProperty('ERRORS')
nodes.append(filenode)
ast = IDLNode('AST', '__AST__', 0, 0, nodes)
print '\n'.join(ast.Tree(accept_props=['PROD']))
if errors:
print '\nFound %d errors.\n' % errors
return errors
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
|
PremiumGraphicsCodes/CGLib
|
Graphics/ColoredPolygon.cpp
|
<reponame>PremiumGraphicsCodes/CGLib<filename>Graphics/ColoredPolygon.cpp
#include "stdafx.h"
#include "ColoredPolygon.h"
|
ibara/LiteBSD-Ports
|
lang/mawk/files.h
|
<filename>lang/mawk/files.h
/********************************************
files.h
copyright 2009-2010,2012 <NAME>
copyright 1991-1994,1996, <NAME>
This is a source file for mawk, an implementation of
the AWK programming language.
Mawk is distributed without warranty under the terms of
the GNU General Public License, version 2, 1991.
********************************************/
/*
* $MawkId: files.h,v 1.12 2012/11/29 00:56:19 tom Exp $
* @Log: files.h,v @
* Revision 1.3 1996/01/14 17:14:11 mike
* flush_all_output()
*
* Revision 1.2 1994/12/11 22:14:13 mike
* remove THINK_C #defines. Not a political statement, just no indication
* that anyone ever used it.
*
* Revision 1.1.1.1 1993/07/03 18:58:13 mike
* move source to cvs
*
* Revision 5.2 1992/12/17 02:48:01 mike
* 1.1.2d changes for DOS
*
* Revision 5.1 1991/12/05 07:59:18 brennan
* 1.1 pre-release
*
*/
#ifndef MAWK_FILES_H
#define MAWK_FILES_H
#include "nstd.h"
#include "types.h"
/* IO redirection types */
#define F_IN (-5)
#define PIPE_IN (-4)
#define PIPE_OUT (-3)
#define F_APPEND (-2)
#define F_TRUNC (-1)
#define IS_OUTPUT(type) ((type)>=PIPE_OUT)
extern const char *shell; /* for pipes and system() */
extern PTR file_find(STRING *, int);
extern int file_close(STRING *);
extern int file_flush(STRING *);
extern int flush_all_output(void);
extern PTR get_pipe(char *, int, int *);
extern int wait_for(int);
extern void close_out_pipes(void);
#ifdef HAVE_FAKE_PIPES
extern void close_fake_pipes(void);
extern int close_fake_outpipe(char *, int);
extern char *tmp_file_name(int, char *);
#endif
#ifdef MSDOS
extern int DOSexec(char *);
extern void enlarge_output_buffer(FILE *);
#endif
#if USE_BINMODE
extern int binmode(void);
extern void set_binmode(int);
extern void stdout_init(void);
#endif
#endif /* MAWK_FILES_H */
|
Yathishns/NewRelic-RPM-Ruby-Agent
|
test/new_relic/metric_spec_test.rb
|
# encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
require File.expand_path(File.join(File.dirname(__FILE__),'..', 'test_helper'))
class NewRelic::MetricSpecTest < Minitest::Test
def test_equal
spec1 = NewRelic::MetricSpec.new('Controller')
spec2 = NewRelic::MetricSpec.new('Controller', nil)
assert spec1.eql?(NewRelic::MetricSpec.new('Controller'))
assert spec2.eql?(NewRelic::MetricSpec.new('Controller', nil))
assert spec1.eql?(spec2)
assert !spec2.eql?(NewRelic::MetricSpec.new('Controller', '/dude'))
end
define_method(:'test_<=>') do
s1 = NewRelic::MetricSpec.new('ActiveRecord')
s2 = NewRelic::MetricSpec.new('Controller')
assert_equal [s1, s2].sort, [s1,s2]
assert_equal [s2, s1].sort, [s1,s2]
s1 = NewRelic::MetricSpec.new('Controller', nil)
s2 = NewRelic::MetricSpec.new('Controller', 'hap')
assert_equal [s2, s1].sort, [s1, s2]
assert_equal [s1, s2].sort, [s1, s2]
s1 = NewRelic::MetricSpec.new('Controller', 'hap')
s2 = NewRelic::MetricSpec.new('Controller', nil)
assert_equal [s2, s1].sort, [s2, s1]
assert_equal [s1, s2].sort, [s2, s1]
s1 = NewRelic::MetricSpec.new('Controller')
s2 = NewRelic::MetricSpec.new('Controller')
assert_equal [s2, s1].sort, [s2, s1] # unchanged due to no sort criteria
assert_equal [s1, s2].sort, [s1, s2] # unchanged due to no sort criteria
s1 = NewRelic::MetricSpec.new('Controller', nil)
s2 = NewRelic::MetricSpec.new('Controller', nil)
assert_equal [s2, s1].sort, [s2, s1] # unchanged due to no sort criteria
assert_equal [s1, s2].sort, [s1, s2] # unchanged due to no sort criteria
end
# test to make sure the MetricSpec class can serialize to json
if defined?(::ActiveSupport)
def test_json
spec = NewRelic::MetricSpec.new("controller", "metric#find")
import = ::ActiveSupport::JSON.decode(spec.to_json)
compare_spec(spec, import)
stats = NewRelic::Agent::Stats.new
import = ::ActiveSupport::JSON.decode(stats.to_json)
compare_stat(stats, import)
metric_data = NewRelic::MetricData.new(spec, stats)
import = ::ActiveSupport::JSON.decode(metric_data.to_json)
compare_metric_data(metric_data, import)
end
else
puts "Skipping tests in #{__FILE__} because ActiveSupport is unavailable"
end
def test_initialize_truncates_name_and_scope
long_name = "a" * 300
long_scope = "b" * 300
spec = NewRelic::MetricSpec.new(long_name, long_scope)
assert_equal("a" * 255, spec.name, "should have shortened the name")
assert_equal("b" * 255, spec.scope, "should have shortened the scope")
end
# These next three tests are here only because rpm_site uses our MetricSpec
# class in silly ways (specifically, it passes in non-String values for
# name/scope). If we can get rid of those silly usages, we can remove these
# tests.
def test_initialize_can_take_a_nil_name
spec = NewRelic::MetricSpec.new(nil)
assert_equal('', spec.name)
assert_equal('', spec.scope)
end
def test_initialize_can_take_a_non_string_name
name = string_wrapper_class.new("name")
spec = NewRelic::MetricSpec.new(name)
assert_equal('name', spec.name)
assert_equal('', spec.scope)
end
def test_initialize_can_take_a_non_string_scope
name = "name"
scope = string_wrapper_class.new("scope")
spec = NewRelic::MetricSpec.new(name, scope)
assert_equal('name', spec.name)
assert_equal('scope', spec.scope)
end
private
def string_wrapper_class
Class.new do
def initialize(value)
@value = value
end
def to_s
@value
end
end
end
def compare_spec(spec, import)
assert_equal 2, import.length
assert_equal spec.name, import['name']
assert_equal spec.scope, import['scope']
end
def compare_stat(stats, import)
assert_equal 6, import.length
assert_equal stats.total_call_time, import['total_call_time']
assert_equal stats.max_call_time, import['max_call_time']
assert_equal stats.min_call_time, import['min_call_time']
assert_equal stats.sum_of_squares, import['sum_of_squares']
assert_equal stats.call_count, import['call_count']
assert_equal stats.total_exclusive_time, import['total_exclusive_time']
end
def compare_metric_data(metric_data, import)
assert_equal 2, import.length
compare_spec(metric_data.metric_spec, import['metric_spec'])
compare_stat(metric_data.stats, import['stats'])
end
end
|
mcxinyu/ZhiYe
|
zhiye/src/main/java/com/about/zhiye/BasePresenter.java
|
<filename>zhiye/src/main/java/com/about/zhiye/BasePresenter.java
package com.about.zhiye;
/**
* Created by huangyuefeng on 2017/6/30.
* Contact me : <EMAIL>
*/
public interface BasePresenter {
void start();
}
|
zubie7a/Distributed_Systems
|
MPI_Course_Project_Pearson_Correlation_Algorithm/spearson.cpp
|
#include "./includes/cppdefs.cpp"
#include "./includes/matches.cpp"
int main(int argc, char *argv[]) {
int NUM_USERS, NUM_MOVIES, NUM_BEST, NUM_PROCS = 1;
int *matrixUI;
int *params = new int[3];
vector<string> matrixName;
matrixName = getMatrixName();
if(matrixName.size() < 1) {
fprintf(stderr, "Input file was not found.\n");
exit(1);
}
string fname = matrixName[0];
ifstream iss(fname);
iss >> NUM_USERS >> NUM_MOVIES >> NUM_BEST;
validateArguments(NUM_USERS, NUM_MOVIES, NUM_BEST);
matrixUI = new int[NUM_USERS * NUM_MOVIES];
for(int i = 0; i < NUM_USERS; i++) {
for(int j = 0; j < NUM_MOVIES; j++) {
int rating;
iss >> rating;
matrixUI[(i * NUM_MOVIES) + j] = rating;
}
}
vector< int* > results;
for(int U1 = 0; U1 < NUM_USERS; U1 += NUM_PROCS) {
int *recList;
recList = findBests(NUM_USERS, NUM_MOVIES, NUM_BEST, U1, matrixUI);
results.push_back(recList);
}
int **recMat;
recMat = new int* [NUM_USERS];
for(int i = 0; i < results.size(); i++) {
int USER = i * NUM_PROCS;
int *list = results[i];
recMat[USER] = list;
}
system("mkdir -p ./results");
ofstream oss("./results/sresult.txt");
for(int i = 0; i < NUM_USERS; i++){
for(int j = 0 ; j < NUM_BEST; j++) {
oss << recMat[i][j] << " ";
}
oss << endl;
}
delete params;
delete matrixUI;
for(int i = 0; i < NUM_USERS; i++) {
delete recMat[i];
}
delete recMat;
exit(0);
}
|
Sonaza/scyori
|
code/szen/src/Game/ParticleEntity.cpp
|
<reponame>Sonaza/scyori
#include <szen/Game/ParticleEntity.hpp>
#include <szen/Game/Components/Transform.hpp>
#include <szen/Game/Components/ParticleComponent.hpp>
using namespace sz;
////////////////////////////////////////////////////
ParticleEntity::ParticleEntity() :
m_component(NULL)
{
//attach<Transform>();
//m_component = attach<ParticleComponent>();
}
////////////////////////////////////////////////////
ParticleEntity::ParticleEntity(const std::string &asset)
{
attach<Transform>();
m_component = attach<ParticleComponent>(asset);
}
////////////////////////////////////////////////////
ParticleEntity::~ParticleEntity()
{
}
////////////////////////////////////////////////////
void ParticleEntity::update()
{
if(!m_component) m_component = getComponent<ParticleComponent>();
}
////////////////////////////////////////////////////
void ParticleEntity::emit(const size_t amount)
{
assert(m_component);
m_component->emit(amount);
}
////////////////////////////////////////////////////
ParticleEntity* ParticleEntity::setPosition(float x, float y)
{
assert(m_component);
call(&Transform::setPosition, x, y);
m_component->updatePosition();
return this;
}
////////////////////////////////////////////////////
ParticleEntity* ParticleEntity::setPosition(sf::Vector2f pos)
{
assert(m_component);
call(&Transform::setPosition, pos);
m_component->updatePosition();
return this;
}
////////////////////////////////////////////////////
ParticleEntity* ParticleEntity::setEmissionRate(float rate)
{
assert(m_component);
m_component->setEmissionRate(rate);
return this;
}
////////////////////////////////////////////////////
ParticleEntity* ParticleEntity::setLifetime(float time)
{
assert(m_component);
m_component->setLifetime(time);
return this;
}
////////////////////////////////////////////////////
ParticleEntity* ParticleEntity::setLifetime(float start, float end)
{
assert(m_component);
m_component->setLifetime(start, end);
return this;
}
////////////////////////////////////////////////////
ParticleEntity* ParticleEntity::setVelocity(sf::Vector2f vel)
{
assert(m_component);
m_component->setVelocity(vel);
return this;
}
////////////////////////////////////////////////////
ParticleEntity* ParticleEntity::setVelocityCone(float force, float direction, float variance)
{
assert(m_component);
m_component->setVelocityCone(force, direction, variance);
return this;
}
////////////////////////////////////////////////////
ParticleEntity* ParticleEntity::setRotation(float rot)
{
assert(m_component);
m_component->setRotation(rot);
return this;
}
////////////////////////////////////////////////////
ParticleEntity* ParticleEntity::setRotation(float start, float end)
{
assert(m_component);
m_component->setRotation(start, end);
return this;
}
////////////////////////////////////////////////////
ParticleEntity* ParticleEntity::setRotationSpeed(float speed)
{
assert(m_component);
m_component->setRotationSpeed(speed);
return this;
}
////////////////////////////////////////////////////
ParticleEntity* ParticleEntity::setRotationSpeed(float start, float end)
{
assert(m_component);
m_component->setRotationSpeed(start, end);
return this;
}
////////////////////////////////////////////////////
ParticleEntity* ParticleEntity::setScale(float scale)
{
assert(m_component);
m_component->setScale(scale);
return this;
}
////////////////////////////////////////////////////
ParticleEntity* ParticleEntity::setScale(float start, float end)
{
assert(m_component);
m_component->setScale(start, end);
return this;
}
////////////////////////////////////////////////////
ParticleEntity* ParticleEntity::setColor(const sf::Color& color)
{
assert(m_component);
m_component->setColor(color);
return this;
}
////////////////////////////////////////////////////
sf::Color ParticleEntity::getColor()
{
assert(m_component);
return m_component->getColor();
}
|
tsconn23/alvarium-sdk-java
|
src/main/java/com/alvarium/serializers/StreamInfoConverter.java
|
/*******************************************************************************
* Copyright 2021 Dell 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 com.alvarium.serializers;
import java.lang.reflect.Type;
import com.alvarium.streams.MqttConfig;
import com.alvarium.streams.PravegaConfig;
import com.alvarium.streams.StreamInfo;
import com.alvarium.streams.StreamType;
import com.google.gson.JsonDeserializer;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/**
* <p>Contains the logic for deserializing stream configs depending on their types</p>
*
* <p>Any further stream implementations must have their config deserialization logic here</p>
*
* <p>This is because the StreamInfo class must be able to pass down any different type of stream
* config class (e.g. IotaConfig, MqttConfig, PravegaConfig).</p>
*/
public class StreamInfoConverter implements JsonDeserializer<StreamInfo> {
public StreamInfo deserialize(
JsonElement json,
Type typeOfT,
JsonDeserializationContext context
) {
JsonObject obj = json.getAsJsonObject();
StreamType type = StreamType.valueOf(obj.get("type").getAsString().toUpperCase());
switch(type){
case MQTT:
MqttConfig mqttConfig = MqttConfig.fromJson(obj.get("config").toString());
return new StreamInfo(type,mqttConfig);
case PRAVEGA:
PravegaConfig pravegaConfig = PravegaConfig.fromJson(obj.get("config").toString());
return new StreamInfo(type, pravegaConfig);
default:
Gson gson = new Gson();
return gson.fromJson(json, StreamInfo.class);
}
}
}
|
tlalexander/stitchEm
|
apps/src/libvideostitch-gui/videostitcher/globalcontroller.hpp
|
<filename>apps/src/libvideostitch-gui/videostitcher/globalcontroller.hpp
// Copyright (c) 2012-2017 VideoStitch SAS
// Copyright (c) 2018 stitchEm
#pragma once
#include "stitchercontroller.hpp"
/**
* The Controller is unique in every application, so it is accessible through a global variable.
* Since the real type of the Controller is up to the application to
* decide, the global variable is actually a pointer.
*
* The application is responsible for implementing the real factory method.
* The global factory can be configured at any time by setting
* the global variable 'impl'.
* The singleton pattern ensures correct deletion at shutdown.
*/
class VS_GUI_EXPORT GlobalController {
public:
class Impl {
public:
virtual ~Impl() {}
virtual StitcherController* getController() const = 0;
virtual void createController(int device) = 0;
virtual void deleteController() = 0;
};
static GlobalController& getInstance() {
static GlobalController theInstance;
return theInstance;
}
~GlobalController();
void deleteController();
StitcherController* getController() const;
protected:
void createController(int device);
private:
GlobalController();
GlobalController(GlobalController const&);
GlobalController& operator=(GlobalController const&);
bool configure(Impl* i) {
// once and for all
if (impl == nullptr) {
impl = i;
return true;
}
return false;
}
Impl* impl;
template <typename T>
friend class GlobalControllerImpl;
};
|
ffarsad/aion
|
modMcf/src/org/aion/mcf/valid/AbstractBlockHeaderValidator.java
|
<filename>modMcf/src/org/aion/mcf/valid/AbstractBlockHeaderValidator.java
package org.aion.mcf.valid;
import java.util.List;
import org.aion.mcf.blockchain.valid.IValidRule;
import org.slf4j.Logger;
public abstract class AbstractBlockHeaderValidator {
public void logErrors(final Logger logger, final List<IValidRule.RuleError> errors) {
if (errors.isEmpty()) return;
if (logger.isErrorEnabled()) {
StringBuilder builder = new StringBuilder();
builder.append(this.getClass().getSimpleName());
builder.append(" raised errors: \n");
for (IValidRule.RuleError error : errors) {
builder.append(error.errorClass.getSimpleName());
builder.append("\t\t\t\t");
builder.append(error.error);
builder.append("\n");
}
logger.error(builder.toString());
}
}
}
|
userzrq/study-api
|
src/main/java/com/userzrq/api/appContext/MessageService.java
|
package com.userzrq.api.appContext;
public interface MessageService {
String getMessage();
}
|
nagrohan726/eclipse-workspace
|
CoreJava/MultiThreading/src/threadgroups/ThreadGroupMethods.java
|
<gh_stars>0
package threadgroups;
public class ThreadGroupMethods {
public static void main(String[] args) throws InterruptedException {
ThreadGroup mtg = new ThreadGroup("MyThreadGroup");
CustomThread thread1 = new CustomThread(mtg, "Thread 1");
CustomThread thread2 = new CustomThread(mtg, "Thread 2");
CustomThread thread3 = new CustomThread(mtg, "Thread 3");
thread1.start();
thread2.start();
thread3.start();
System.out.println(mtg.activeCount());
mtg.list();
Thread.sleep(5000);
System.out.println(mtg.activeCount());
mtg.list();
}
}
|
artoriaschan/leetcode-algorithms
|
src/training/early/combinationSumii.js
|
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function(candidates, target) {
var backtrade = function(candidates, start, target, solvespace, result) {
if (target < 0) {
return;
}
if (target === 0) {
let copy = JSON.parse(JSON.stringify(solvespace)); // 复制数组
result.push(copy);
return;
}
for (let i = start; i < candidates.length; i++) {
solvespace.push(candidates[i]);
backtrade(candidates, i + 1, target - candidates[i], solvespace, result);
solvespace.pop();
}
};
let result = [];
let solvespace = [];
backtrade(candidates, 0, target, solvespace, result);
let noDuplicateResult = [];
// 结果数组去重
for (let i = 0; i < result.length; i++) {
result[i].sort((a, b) => {
return a - b;
});
let noDuplicate = false;
for (let arr of noDuplicateResult) {
if (arr.join("") === result[i].join("")) {
noDuplicate = true;
break;
}
}
if (!noDuplicate) noDuplicateResult.push(result[i]);
}
return noDuplicateResult;
};
let candidates = [10, 1, 2, 7, 6, 1, 5];
let target = 8;
console.log(combinationSum2(candidates, target));
|
baracil/perobobbot
|
lib/perobobbot.twitch/perobobbot.twitch.eventsub.api/src/main/java/perobobbot/twitch/eventsub/api/event/SubscriptionMessageEvent.java
|
package perobobbot.twitch.eventsub.api.event;
import lombok.NonNull;
import lombok.Value;
import perobobbot.twitch.api.UserInfo;
import perobobbot.twitch.eventsub.api.Tier;
import java.util.OptionalInt;
@Value
public class SubscriptionMessageEvent implements BroadcasterProvider, EventSubEvent {
@NonNull UserInfo user;
@NonNull UserInfo broadcaster;
@NonNull Tier tier;
@NonNull Message message;
int cumulativeTotal;
Integer streakMonths;
int durationMonths;
public @NonNull OptionalInt getStreakMonths() {
return streakMonths == null ? OptionalInt.empty():OptionalInt.of(streakMonths);
}
}
|
problemfighter/pfspring-identity
|
src/main/java/com/problemfighter/pfspring/identity/repository/IdentityRepository.java
|
<gh_stars>1-10
package com.problemfighter.pfspring.identity.repository;
import com.problemfighter.pfspring.identity.model.entity.Identity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface IdentityRepository extends JpaRepository<Identity, Long> {
@Query("SELECT i FROM Identity i WHERE i.identifier = :identifier AND i.isDeleted = false")
public Identity getActiveIdentityByIdentifier(@Param("identifier") String identifier);
@Query("SELECT i FROM Identity i WHERE i.uuid = :uuid AND i.isDeleted = false")
public Identity getActiveIdentityByUuid(@Param("uuid") String uuid);
@Query("SELECT i FROM Identity i WHERE i.identifier = :identifier AND i.isDeleted = :isDeleted")
public Identity getIdentityByIdentifier(@Param("identifier") String identifier, @Param("isDeleted") Boolean isDeleted);
@Query("SELECT i FROM Identity i WHERE i.identifier = :identifier")
public Identity getIdentityByIdentifier(@Param("identifier") String identifier);
@Query("SELECT i FROM Identity i WHERE i.uuid = :uuid AND i.isDeleted = false")
public Identity getActiveIdentityByUUID(@Param("uuid") String uuid);
@Query("SELECT count (i) FROM Identity i")
public Long totalIdentity();
}
|
YTXIRE/able_crm_concrete_accounting_python_tests
|
tests/api/test_material_types_update.py
|
from allure import title, description, suite, parent_suite
from pages.api import asserts
from data import API_USERS_SUCCESS, API_PUT_METHOD_NOT_ALLOWED, \
API_AUTH_TOKEN_EMPTY, API_BAD_REQUEST_LENGTH_TOKEN, AUTH_DATA_LENGTH_TOKEN, API_BAD_REQUEST_EMPTY_MATERIAL_TYPES, \
API_BAD_REQUEST_LENGTH_MATERIAL_TYPES, AUTH_DATA_FAIL_LENGTH_MATERIAL_TYPES, API_BAD_REQUEST_BAD_ID, \
AUTH_DATA_FAIL_BAD_ID, AUTH_DATA_FAIL_BAD_TOKEN, API_AUTH_NOT_FOUND_TOKEN, API_NOT_FOUND_MATERIAL_TYPES_ID, \
AUTH_DATA_FAIL_NOT_FOUND_ID, API_BAD_RIGHTS, NAME_MATERIAL_TYPES_CREATE, DATA_UNITS_MEASUREMENT_VOLUME_ID, \
API_BAD_UNITS_MEASUREMENT_ID
@suite('Контроллер: MaterialTypes. Метод: update')
@parent_suite('[PYTHON][API]')
class TestApiMaterialTypesUpdate:
@title('update')
@description('Проверка корректной работы update')
def test_update(self, material_types, create_admin, create_and_remove_material_type):
asserts(
assert_data=material_types.update({
"id": create_and_remove_material_type,
"token": create_admin['token'],
"name": NAME_MATERIAL_TYPES_CREATE(),
"user_id": create_admin['id'],
'units_measurement_volume_id': DATA_UNITS_MEASUREMENT_VOLUME_ID
}),
data=API_USERS_SUCCESS
)
@title('update-fail-method-not-allowed')
@description('Проверка ошибки Method Not Allowed для update')
def test_update_method_not_allowed(self, material_types):
asserts(
assert_data=material_types.update_method_not_allowed(),
data=API_PUT_METHOD_NOT_ALLOWED
)
@title('update-fail-bad-requst-empty-token')
@description('Проверка ошибки Bad Request empty token для update')
def test_update_bad_request_empty_token(self, material_types, create_admin, create_and_remove_material_type):
asserts(
assert_data=material_types.update({
"id": create_and_remove_material_type,
"token": '',
"name": NAME_MATERIAL_TYPES_CREATE(),
"user_id": create_admin['id'],
'units_measurement_volume_id': DATA_UNITS_MEASUREMENT_VOLUME_ID
}),
data=API_AUTH_TOKEN_EMPTY
)
@title('update-fail-bad-requst-length-token')
@description('Проверка ошибки Bad Request length token для update')
def test_update_bad_request_length_token(self, material_types, create_admin, create_and_remove_material_type):
asserts(
assert_data=material_types.update({
"id": create_and_remove_material_type,
"token": AUTH_DATA_LENGTH_TOKEN,
"name": NAME_MATERIAL_TYPES_CREATE(),
"user_id": create_admin['id'],
'units_measurement_volume_id': DATA_UNITS_MEASUREMENT_VOLUME_ID
}),
data=API_BAD_REQUEST_LENGTH_TOKEN
)
@title('update-fail-bad-requst-empty-material-types')
@description('Проверка ошибки Bad Request empty material types для update')
def test_update_bad_request_empty_material_types(
self, material_types, create_admin, create_and_remove_material_type
):
asserts(
assert_data=material_types.update({
"id": create_and_remove_material_type,
"token": create_admin['token'],
"name": '',
"user_id": create_admin['id'],
'units_measurement_volume_id': DATA_UNITS_MEASUREMENT_VOLUME_ID
}),
data=API_BAD_REQUEST_EMPTY_MATERIAL_TYPES
)
@title('update-fail-bad-requst-length-material-types')
@description('Проверка ошибки Bad Request length material types для update')
def test_update_bad_request_length_material_types(
self, material_types, create_admin, create_and_remove_material_type
):
asserts(
assert_data=material_types.update({
"id": create_and_remove_material_type,
"token": create_admin['token'],
"name": AUTH_DATA_FAIL_LENGTH_MATERIAL_TYPES,
"user_id": create_admin['id'],
'units_measurement_volume_id': DATA_UNITS_MEASUREMENT_VOLUME_ID
}),
data=API_BAD_REQUEST_LENGTH_MATERIAL_TYPES
)
@title('update-fail-bad-requst-bad-id-user-id-minus')
@description('Проверка ошибки Bad Request bad id для update с отрицательным идентификатором')
def test_update_bad_request_length_bad_id_user_id_minus(self, material_types, create_admin):
asserts(
assert_data=material_types.update({
"id": AUTH_DATA_FAIL_BAD_ID,
"token": create_admin['token'],
"name": NAME_MATERIAL_TYPES_CREATE(),
"user_id": AUTH_DATA_FAIL_BAD_ID,
'units_measurement_volume_id': DATA_UNITS_MEASUREMENT_VOLUME_ID
}),
data=API_BAD_REQUEST_BAD_ID
)
@title('update-fail-bad-requst-bad-id-user-id-varchar')
@description('Проверка ошибки Bad Request bad id для update с символами в идентификаторе')
def test_update_bad_request_length_bad_id_varchar(self, material_types, create_admin):
asserts(
assert_data=material_types.update({
"id": AUTH_DATA_FAIL_BAD_ID,
"token": create_admin['token'],
"name": NAME_MATERIAL_TYPES_CREATE(),
"user_id": 'text',
'units_measurement_volume_id': DATA_UNITS_MEASUREMENT_VOLUME_ID
}),
data=API_BAD_REQUEST_BAD_ID
)
@title('update-fail-bad-requst-bad-id-units-minus')
@description('Проверка ошибки Bad Request bad id для update с отрицательным значением в величине объема')
def test_update_bad_request_length_bad_id_units_minus(self, material_types, create_admin):
asserts(
assert_data=material_types.update({
"id": AUTH_DATA_FAIL_BAD_ID,
"token": create_admin['token'],
"name": NAME_MATERIAL_TYPES_CREATE(),
"user_id": create_admin['id'],
'units_measurement_volume_id': AUTH_DATA_FAIL_BAD_ID
}),
data=API_BAD_REQUEST_BAD_ID
)
@title('update-fail-bad-requst-bad-id-units-varchar')
@description('Проверка ошибки Bad Request bad id для update с символами в величине объема')
def test_update_bad_request_length_bad_id_units_varchar(self, material_types, create_admin):
asserts(
assert_data=material_types.update({
"id": AUTH_DATA_FAIL_BAD_ID,
"token": create_admin['token'],
"name": NAME_MATERIAL_TYPES_CREATE(),
"user_id": create_admin['id'],
'units_measurement_volume_id': 'text'
}),
data=API_BAD_REQUEST_BAD_ID
)
@title('update-fail-not-found-token')
@description('Проверка ошибки Not Found token для update')
def test_update_not_found_token(self, material_types, create_admin, create_and_remove_material_type):
asserts(
assert_data=material_types.update({
"id": create_and_remove_material_type,
"token": AUTH_DATA_FAIL_BAD_TOKEN,
"name": NAME_MATERIAL_TYPES_CREATE(),
"user_id": create_admin['id'],
'units_measurement_volume_id': DATA_UNITS_MEASUREMENT_VOLUME_ID
}),
data=API_AUTH_NOT_FOUND_TOKEN
)
@title('update-fail-not-found-material-types-id')
@description('Проверка ошибки Not Found material types id для update')
def test_update_not_found_material_types_id(self, material_types, create_admin):
asserts(
assert_data=material_types.update({
"id": AUTH_DATA_FAIL_NOT_FOUND_ID,
"token": create_admin['token'],
"name": NAME_MATERIAL_TYPES_CREATE(),
"user_id": create_admin['id'],
'units_measurement_volume_id': AUTH_DATA_FAIL_NOT_FOUND_ID
}),
data=API_NOT_FOUND_MATERIAL_TYPES_ID
)
@title('update-fail-not-found-units-measurement-id')
@description('Проверка ошибки Not Found units measurement id для update')
def test_update_not_found_units_measurement_id(self, material_types, create_admin, create_and_remove_material_type):
asserts(
assert_data=material_types.update({
"id": create_and_remove_material_type,
"token": create_admin['token'],
"name": NAME_MATERIAL_TYPES_CREATE(),
"user_id": create_admin['id'],
'units_measurement_volume_id': AUTH_DATA_FAIL_NOT_FOUND_ID
}),
data=API_BAD_UNITS_MEASUREMENT_ID
)
@title('update-fail-bad-requst-bad-rights')
@description('Проверка ошибки Bad Request bad rights для update')
def test_update_bad_request_bad_rights(self, material_types, create_admin, create_and_remove_material_type):
asserts(
assert_data=material_types.update({
"id": create_and_remove_material_type,
"token": create_admin['token'],
"name": NAME_MATERIAL_TYPES_CREATE(),
"user_id": AUTH_DATA_FAIL_NOT_FOUND_ID,
'units_measurement_volume_id': DATA_UNITS_MEASUREMENT_VOLUME_ID
}),
data=API_BAD_RIGHTS
)
|
joe-chimienti/pay-model
|
src/main/scala/com/mathbot/pay/bitcoin/SigHashType.scala
|
package com.mathbot.pay.bitcoin
import play.api.libs.json.Json
object SigHashType extends Enumeration {
type SigHashType = Value
val ALL, NONE, SINGLE, `ALL|ANYONECANPAY`, `NONE|ANYONECANPAY`, `SINGLE|ANYONECANPAY` = Value
implicit val formatSig = Json.formatEnum(this)
}
|
LibreGames/monster-rpg-2
|
include/GenericEffect.hpp
|
<filename>include/GenericEffect.hpp
#include "monster2.hpp"
class GenericEffect : public CombatEntity {
public:
virtual bool act(int step, Battle *b) { return false; }
virtual bool update(int step) = 0;
virtual void draw(void) = 0;
virtual int getLifetime(void) = 0;
virtual void finalize(Combatant *target) = 0;
GenericEffect(Combatant *user, Combatant *target) {
this->user = user;
this->target = target;
x = target->getX();
y = target->getY()+1;
}
virtual ~GenericEffect() {}
protected:
Combatant *user;
Combatant *target;
};
class GenericCureEffect : public GenericEffect {
public:
bool update(int step);
void draw(void);
int getLifetime(void);
void finalize(Combatant *target);
GenericCureEffect(Combatant *user, Combatant *target, int amount, std::string name, bool finish = false);
virtual ~GenericCureEffect();
protected:
AnimationSet *animation;
int count;
int amount;
bool finish;
};
struct GenericHolyWaterPixel {
float x, y, z;
int offset;
};
class GenericHolyWaterEffect : public GenericEffect {
public:
static const int NUM_PIXELS = 7;
static const float RISE_SPEED;
bool update(int step);
void draw(void);
int getLifetime(void);
void finalize(Combatant *target);
GenericHolyWaterEffect(Combatant *user, Combatant *target, bool finish = false, bool sound = true);
virtual ~GenericHolyWaterEffect();
protected:
int count;
GenericHolyWaterPixel *pixels;
int numPixels;
int maxDepth;
bool finish;
};
struct GenericHealPixel {
float a, radius;
MCOLOR color;
};
class GenericHealEffect : public GenericEffect {
public:
static const int NUM_PIXELS = 300;
static const int MAX_OFS = 5;
bool update(int step);
void draw(void);
int getLifetime(void);
void finalize(Combatant *target);
GenericHealEffect(Combatant *user, Combatant *target, bool finish = false);
virtual ~GenericHealEffect();
protected:
int count;
GenericHealPixel pixels[NUM_PIXELS];
float cx, cy;
bool finish;
float r;
};
class GenericElixirEffect : public GenericEffect {
public:
bool update(int step);
void draw(void);
int getLifetime(void);
void finalize(Combatant *target);
GenericElixirEffect(Combatant *user, Combatant *target);
virtual ~GenericElixirEffect();
protected:
int count;
MBITMAP *bitmap;
int cx, cy;
float angle, angle2;
float xs[4];
float ys[4];
};
|
nikita220399/job4j
|
crocok/src/main/java/croc/task2_2/Department.java
|
<gh_stars>1-10
package croc.task2_2;
import java.util.Arrays;
public class Department {
private String name;
private Department[] child;
private int time;
public Department(Department[] child, int time, String name) {
this.child = child;
this.time = time;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department[] getChild() {
return child;
}
public void setChild(Department[] child) {
this.child = child;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
@Override
public String toString() {
return "Department{" +
"name='" + name + '\'' +
", child=" + Arrays.toString(child) +
", time=" + time +
'}';
}
}
|
delavet/SOworkspace
|
src/util/apidoc_semantic/node2vec.py
|
import random
import networkx as nx
import numpy as np
from gensim.models import Word2Vec
from gensim.models.word2vec import LineSentence
from util.concept_map.common import get_latest_hyper_concept_map
from util.config import NODE2VEC_RANDOM_WALK_STORE_PATH, NODE2VEC_MODEL_STORE_PATH
class Node2VecGraph():
def __init__(self, nx_G, is_directed, p, q):
self.G = nx_G
self.is_directed = is_directed
self.p = p
self.q = q
def node2vec_walk(self, walk_length, start_node):
"""
Simulate a random walk starting from start node.
"""
G = self.G
alias_nodes = self.alias_nodes
alias_edges = self.alias_edges
walk = [start_node]
while len(walk) < walk_length:
cur = walk[-1]
cur_nbrs = sorted(G.neighbors(cur))
if len(cur_nbrs) > 0:
if len(walk) == 1:
walk.append(
cur_nbrs[alias_draw(alias_nodes[cur][0], alias_nodes[cur][1])])
else:
prev = walk[-2]
next = cur_nbrs[alias_draw(alias_edges[(prev, cur)][0],
alias_edges[(prev, cur)][1])]
walk.append(next)
else:
break
return walk
def simulate_walks(self, num_walks, walk_length):
"""
Repeatedly simulate random walks from each node.
"""
G = self.G
walks = []
nodes = list(G.nodes())
print('Walk iteration:')
for walk_iter in range(num_walks):
print(str(walk_iter + 1), '/', str(num_walks))
random.shuffle(nodes)
for node in nodes:
walks.append(self.node2vec_walk(
walk_length=walk_length, start_node=node))
return walks
def get_alias_edge(self, src, dst):
"""
Get the alias edge setup lists for a given edge.
"""
G = self.G
p = self.p
q = self.q
unnormalized_probs = []
for dst_nbr in sorted(G.neighbors(dst)):
if dst_nbr == src:
unnormalized_probs.append(G[dst][dst_nbr]['weight'] / p)
elif G.has_edge(dst_nbr, src):
unnormalized_probs.append(G[dst][dst_nbr]['weight'])
else:
unnormalized_probs.append(G[dst][dst_nbr]['weight'] / q)
norm_const = sum(unnormalized_probs)
normalized_probs = [
float(u_prob) / norm_const for u_prob in unnormalized_probs]
return alias_setup(normalized_probs)
def preprocess_transition_probs(self):
"""
Preprocessing of transition probabilities for guiding the random walks.
"""
G = self.G
is_directed = self.is_directed
alias_nodes = {}
for node in G.nodes():
unnormalized_probs = [G[node][nbr]['weight']
for nbr in sorted(G.neighbors(node))]
norm_const = sum(unnormalized_probs)
normalized_probs = [
float(u_prob) / norm_const for u_prob in unnormalized_probs]
alias_nodes[node] = alias_setup(normalized_probs)
alias_edges = {}
triads = {}
if is_directed:
for edge in G.edges():
alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])
else:
for edge in G.edges():
alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])
alias_edges[(edge[1], edge[0])] = self.get_alias_edge(
edge[1], edge[0])
self.alias_nodes = alias_nodes
self.alias_edges = alias_edges
return
def alias_setup(probs):
"""
Compute utility lists for non-uniform sampling from discrete distributions.
Refer to https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/
for details
"""
K = len(probs)
q = np.zeros(K)
J = np.zeros(K, dtype=np.int)
smaller = []
larger = []
for kk, prob in enumerate(probs):
q[kk] = K * prob
if q[kk] < 1.0:
smaller.append(kk)
else:
larger.append(kk)
while len(smaller) > 0 and len(larger) > 0:
small = smaller.pop()
large = larger.pop()
J[small] = large
q[large] = q[large] + q[small] - 1.0
if q[large] < 1.0:
smaller.append(large)
else:
larger.append(large)
return J, q
def alias_draw(J, q):
"""
Draw sample from a non-uniform discrete distribution using alias sampling.
"""
K = len(J)
kk = int(np.floor(np.random.rand() * K))
if np.random.rand() < q[kk]:
return kk
else:
return J[kk]
class Node2VecTrainer:
def __init__(self, doc_name):
self.doc_name = doc_name
self.g = get_latest_hyper_concept_map(doc_name)
self.nx_G_instance = None
self.node_num = len(list(self.g.nodes))
self.init_unweight_graph()
def init_unweight_graph(self):
node_ids = [str(node) for node in self.g.nodes]
relation_pairs = [(str(src), str(tgt))
for src, tgt in list(self.g.edges())]
print("node num=%d" % self.node_num)
print("relation num=%d" % len(relation_pairs))
G = nx.DiGraph()
G.add_nodes_from(node_ids)
G.add_edges_from(relation_pairs, weight=1.0)
# todo: a relation weight support
self.nx_G_instance = G
print("init graph trainer by unweight relations")
def generate_random_path(self, directed=False, p=1, q=1, num_walks=10, walk_length=80):
print("start generate graph random path")
G = Node2VecGraph(self.nx_G_instance, directed, p, q)
G.preprocess_transition_probs()
walks = G.simulate_walks(num_walks, walk_length)
# todo: may be load all into memory has problem?
with open(NODE2VEC_RANDOM_WALK_STORE_PATH[self.doc_name], 'w') as write_f:
for walk in walks:
path_str = " ".join([str(item) for item in walk])
write_f.writelines('%s\n' % (path_str))
print("complete generate graph random path")
def train(self, dimensions=100, workers=12):
"""
train the graph vector from rw_path
:param rw_path_store_path: the random walk for one graph
:param model_path: the output word2vec model path
:param dimensions: the dimensions of word2vec
:param workers: the num of pipeline training
:return:
"""
print("save graph2vec training")
# Learn embeddings by optimizing the Skipgram objective using SGD.
w2v = Word2Vec(LineSentence(NODE2VEC_RANDOM_WALK_STORE_PATH[self.doc_name]),
size=dimensions, min_count=0, sg=1, workers=workers)
w2v.save(NODE2VEC_MODEL_STORE_PATH[self.doc_name])
print("save graph2vec to %s" %
NODE2VEC_MODEL_STORE_PATH[self.doc_name])
return w2v
|
MicrohexHQ/rchain
|
casper/src/test/scala/coop/rchain/casper/genesis/contracts/BlockDataContractSpec.scala
|
<reponame>MicrohexHQ/rchain
package coop.rchain.casper.genesis.contracts
import coop.rchain.casper.helper.RhoSpec
import coop.rchain.rholang.build.CompiledRholangSource
import coop.rchain.rholang.interpreter.NormalizerEnv
import scala.concurrent.duration._
class BlockDataContractSpec
extends RhoSpec(
CompiledRholangSource("BlockDataContractTest.rho", NormalizerEnv.Empty),
Seq.empty,
30.seconds
)
|
arnaud-m/cryptator
|
src/main/java/cryptator/parser/CryptaParserException.java
|
<filename>src/main/java/cryptator/parser/CryptaParserException.java
/**
* This file is part of cryptator, https://github.com/arnaud-m/cryptator
*
* Copyright (c) 2021, Université Côte d'Azur. All rights reserved.
*
* Licensed under the BSD 3-clause license.
* See LICENSE file in the project root for full license information.
*/
package cryptator.parser;
import java.util.concurrent.CancellationException;
public class CryptaParserException extends CancellationException {
private static final long serialVersionUID = 6706871076287552877L;
private String cryptarithm;
private final Object offendingSymbol;
private final int line;
private final int charPositionInLine;
private final String msg;
public CryptaParserException(Object offendingSymbol, int line, int charPositionInLine, String msg) {
super(String.format("Line %d:%d %s", line, charPositionInLine, msg));
this.offendingSymbol = offendingSymbol;
this.line = line;
this.charPositionInLine = charPositionInLine;
this.msg = msg;
}
public final String getCryptarithm() {
return cryptarithm;
}
public final void setCryptarithm(String cryptarithm) {
this.cryptarithm = cryptarithm;
}
public final Object getOffendingSymbol() {
return offendingSymbol;
}
public final int getLine() {
return line;
}
public final int getCharPositionInLine() {
return charPositionInLine;
}
public final String getMsg() {
return msg;
}
}
|
soederpop/skypager-next
|
src/features/file-manager/src/selectors/package/changed.js
|
<filename>src/features/file-manager/src/selectors/package/changed.js
export default (async function selectChangedPackages(chain, options = {}) {
const packageLocations = await this.fileManager.packageLocations
const changedFiles = await this.select('files/changed')
return chain
.plant(packageLocations)
.filter(loc => changedFiles.find(f => f.startsWith(loc)))
.sort(p => p.length)
.uniq()
.map(loc => this.pathUtils.join(loc, 'package.json'))
})
|
RemnevMaksim/splinter
|
src/main/java/ru/yandex/autoschool/splinter/application/configuration/properties/EnvironmentConverter.java
|
package ru.yandex.autoschool.splinter.application.configuration.properties;
import org.apache.commons.beanutils.Converter;
/**
* @author Etki {@literal <<EMAIL>>}
* @version %I%, %G%
* @since 1.0
*/
public class EnvironmentConverter implements Converter {
@Override
public Object convert(Class clazz, Object property) {
if (!(property instanceof String)) {
throw new IllegalArgumentException("Only strings may be converted");
}
return ru.yandex.autoschool.splinter.application.EnvironmentConverter.convertFromString((String) property);
}
}
|
undp/transparencyportal
|
undp-transparency-portal-fe/src/shared/actions/countryDataBudgetSources.js
|
<filename>undp-transparency-portal-fe/src/shared/actions/countryDataBudgetSources.js
/************************* Lib Files ************************/
import Api from '../../lib/api';
export const COUNTRY_DATA_BUDGET_SOURCES = {
start: 'fetch_start/budget_sources',
end: 'fetch_end/budget_sources',
success: 'fetch_success/budget_sources',
failed: 'fetch_failed/budget_sources'
};
export const budgetSourcesFetchStart = () => ({
type: COUNTRY_DATA_BUDGET_SOURCES.start
});
export const budgetSourcesFetchEnd = () => ({
type: COUNTRY_DATA_BUDGET_SOURCES.end
});
export const budgetSourcesFetchSuccess = (data) => (
{
type: COUNTRY_DATA_BUDGET_SOURCES.success,
data
});
export const budgetSourcesFetchFailed = (error) => ({
type: COUNTRY_DATA_BUDGET_SOURCES.failed,
error
});
export const fetchBudgetSources= (year, code) => (dispatch) => {
dispatch(budgetSourcesFetchStart());
code=code?code:'';
if (year !== null)
return Api.get(Api.API_GLOBAL_TOP_BUDGET_SOURCES(year, code)).then(resp => {
if (resp.success && resp.data) {
dispatch(budgetSourcesFetchEnd());
dispatch(budgetSourcesFetchSuccess(resp.data));
}
else {
dispatch(budgetSourcesFetchEnd());
}
}).catch((exception) => {
dispatch(budgetSourcesFetchEnd());
dispatch(budgetSourcesFetchFailed());
});
};
|
ScalablyTyped/SlinkyTyped
|
j/jose/src/main/scala/typingsSlinky/jose/mod/OKPCurve.scala
|
package typingsSlinky.jose.mod
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
/* Rewritten from type alias, can be one of:
- typingsSlinky.jose.joseStrings.Ed25519
- typingsSlinky.jose.joseStrings.Ed448
- typingsSlinky.jose.joseStrings.X25519
- typingsSlinky.jose.joseStrings.X448
*/
trait OKPCurve extends StObject
object OKPCurve {
@scala.inline
def Ed25519: typingsSlinky.jose.joseStrings.Ed25519 = "Ed25519".asInstanceOf[typingsSlinky.jose.joseStrings.Ed25519]
@scala.inline
def Ed448: typingsSlinky.jose.joseStrings.Ed448 = "Ed448".asInstanceOf[typingsSlinky.jose.joseStrings.Ed448]
@scala.inline
def X25519: typingsSlinky.jose.joseStrings.X25519 = "X25519".asInstanceOf[typingsSlinky.jose.joseStrings.X25519]
@scala.inline
def X448: typingsSlinky.jose.joseStrings.X448 = "X448".asInstanceOf[typingsSlinky.jose.joseStrings.X448]
}
|
Sai-Ramya7/zestard-replica
|
src/util/common.js
|
// Formatting date
export const dateFormate = (date) => {
const months = ["January", "Febuary", "March","April", "May", "June", "July", "August", "September", "October", "November", "December"];
const dd = new Date(date);
return months[dd.getMonth()] + " " + dd.getDate() + ", " + dd.getFullYear();
}
// Removing the host from the url
export const removePre = (url) => {
var newUrl = url.replace (/^[a-z]{5}:\/{2}[a-z]{1,}\.[a-z]{3}.(.*)/, '$1');
const catUrl = newUrl.substr(newUrl.indexOf('/', 7) + 1)
return catUrl;
}
// To remove special characters from title
// replace unicode characters
export const removeSpecialSymbols = (str) => {
return str.replace(/&#([0-9]{1,4});/gi, function(match, numStr) {
var num = parseInt(numStr, 10); // read num as normal number
return String.fromCharCode(num);
});
}
|
tiwariut/journal
|
client/src/context/post/PostState.js
|
<filename>client/src/context/post/PostState.js<gh_stars>0
import React, { useReducer } from 'react';
import axios from 'axios';
import PostContext from './postContext';
import postReducer from './postReducer';
import {
POST_ERROR,
GET_POSTS,
SET_CURRENT_POST,
CLEAR_CURRENT_POST,
ADD_POST,
UPDATE_POST,
DELETE_POST
} from '../types';
const PostState = (props) => {
const initialState = {
posts: null,
current: null,
error: null,
loading: true
};
const [state, dispatch] = useReducer(postReducer, initialState);
// Get Posts
const getPosts = async () => {
try {
const res = await axios.get('/api/v1/posts');
dispatch({
type: GET_POSTS,
payload: res.data.data
});
} catch (err) {
dispatch({
type: POST_ERROR,
payload: err.response.data.error
});
}
};
// Get Single Post
const getPost = async (id) => {
try {
const res = await axios.get(`/api/v1/posts/${id}`);
setCurrentPost(res.data.data);
} catch (err) {
dispatch({
type: POST_ERROR,
payload: err.response.data.error
});
}
};
// Set Current Post
const setCurrentPost = (post) => {
dispatch({ type: SET_CURRENT_POST, payload: post });
};
// Clear Current Post
const clearCurrentPost = () => {
dispatch({ type: CLEAR_CURRENT_POST });
};
// Add Post
const addPost = async (formData) => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
try {
const res = await axios.post('/api/v1/posts', formData, config);
dispatch({
type: ADD_POST,
payload: res.data.data
});
} catch (err) {
dispatch({
type: POST_ERROR,
payload: err.response.data.error
});
}
};
// Update Post
const updatePost = async (id, post) => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
try {
const res = await axios.put(`/api/v1/posts/${id}`, post, config);
dispatch({
type: UPDATE_POST,
payload: res.data.data
});
} catch (err) {
dispatch({
type: POST_ERROR,
payload: err.response.data.error
});
}
};
// Delete Post
const deletePost = async (id) => {
try {
await axios.delete(`/api/v1/posts/${id}`);
dispatch({
type: DELETE_POST,
payload: id
});
} catch (err) {
dispatch({
type: POST_ERROR,
payload: err.response.data.error
});
}
};
return (
<PostContext.Provider
value={{
posts: state.posts,
current: state.current,
error: state.error,
loading: state.loading,
getPosts,
getPost,
setCurrentPost,
clearCurrentPost,
addPost,
updatePost,
deletePost
}}
>
{props.children}
</PostContext.Provider>
);
};
export default PostState;
|
vogonsorg/Commander-Genius
|
src/fileio/compression/sgrle.cpp
|
<filename>src/fileio/compression/sgrle.cpp
/* SGRLE.C
RLE compression and decompression functions for the SGRLE format...
These are used for saved games (hence the name SG RLE). Could be used
for other things too, I guess.
After opening a file for decompression you must call sgrle_reset() before
the first time you use sgrle_decompress().
*/
#include <fileio/fileio.h>
#include <base/GsLogging.h>
#define SGRLE_RLEMARKERNEW 0xFE
#define SGRLE_RLEMARKEROLD 255
//#define SGRLE_RLEMARKEROLD 0xFE
#define SGRLE_MAXRUNLEN 0xFFF0
int sgrle_runlen;
unsigned char sgrle_runchar;
/* decompresses the next byte from file FP. */
/* used internally by sgrle_decompress(). */
unsigned char sgrle_get_next_byte(FILE *fp, unsigned char marker)
{
// are we currently in a RLE run?
if (sgrle_runlen)
{
// decrease length of RLE run and return the previously
// read char for the run
sgrle_runlen--;
return sgrle_runchar;
}
else
{ // not currently in a RLE run
sgrle_runchar = fgetc(fp);
if (sgrle_runchar==marker)
{ // start of a RLE run
sgrle_runlen = fgeti(fp);
sgrle_runchar = fgetc(fp);
return sgrle_get_next_byte(fp, marker);
}
else return sgrle_runchar;
}
}
/* resets the decompression engine. (must call this before the first
time you use sgrle_decompress(), each time you open a new file) */
void sgrle_initdecompression(void)
{
sgrle_runlen = 0;
}
/* decompresses nbytes bytes of SGRLE-compressed data from
file pointer *fp to the memory area pointed to by *ptr.
Newer Version */
char sgrle_decompressV2(FILE *fp, unsigned char *ptr, unsigned long nbytes)
{
unsigned long i;
unsigned long bytes;
bytes = fgetl(fp);
if (bytes != nbytes)
{
gLogging.ftextOut("sgrle_decompress: bytes stored != bytes asked for ($%08x / $%08x)\n", bytes, nbytes);
gLogging.ftextOut("Trying to extract as much as possible...\n");
//return 1;
}
if(bytes < nbytes) nbytes = bytes;
sgrle_runlen = 0;
for(i=0;i<nbytes;i++)
ptr[i] = sgrle_get_next_byte(fp, SGRLE_RLEMARKERNEW);
return 0;
}
/* decompresses nbytes bytes of SGRLE-compressed data from
* file pointer *fp to the memory area pointed to by *ptr.
* Older Version */
void sgrle_decompressV1(FILE *fp, unsigned char *ptr, unsigned long nbytes)
{
unsigned long i;
for(i=0;i<nbytes;i++)
{
ptr[i] = sgrle_get_next_byte(fp, SGRLE_RLEMARKEROLD);
}
}
/* given a memory area *ptr of length nbytes, compresses the data */
/* using the SGRLE algorithm and saves it to file *fp */
void sgrle_compress(FILE *fp, unsigned char *ptr, unsigned long nbytes)
{
int byt;
unsigned long compress_index, run_ahead_index;
unsigned int runlength;
int readbyt;
unsigned int i;
fputl(nbytes, fp);
compress_index = 0;
while(compress_index < nbytes)
{
// read a byte from the buffer
readbyt = ptr[compress_index];
/* is the next byte the same? if so find the length of the run */
if ((compress_index+1 < nbytes) && ptr[compress_index+1]==readbyt)
{
/* find how long the run is (a run of byte readbyt) */
run_ahead_index = (compress_index + 1);
runlength = 1;
do
{
byt = ptr[run_ahead_index];
// the run is over when either the byte is different
// or run_ahead_index is at the end of the buffer,
// or runlength is approaching FFFF (max possible RLE run length)
if (byt != readbyt || run_ahead_index >= nbytes || runlength >= SGRLE_MAXRUNLEN)
{
break;
}
run_ahead_index++;
runlength++;
} while(1);
// it takes 4 bytes to code a RLE run, so if the run is less than
// 4 bytes, it would actually be smaller if we didn't compress it
if (runlength < 4 && readbyt != SGRLE_RLEMARKERNEW)
{
// RLE run, but too small to bother with
for(i=0;i<runlength;i++) fputc(readbyt, fp);
}
else
{
// save a RLE run
fputc(SGRLE_RLEMARKERNEW, fp);
fputi(runlength, fp);
fputc(readbyt, fp);
}
// advance
compress_index += runlength;
}
else
{
// next byte is different, this is not a run, it's just a single char
if (readbyt != SGRLE_RLEMARKERNEW)
{
fputc(readbyt, fp);
}
else
{
// it's a single uncompressed byte which is equal to the RLE marker.
// delimit it by placing it in a RLE run of length 1.
fputc(SGRLE_RLEMARKERNEW, fp);
fputi(1, fp);
fputc(readbyt, fp);
}
compress_index++;
}
}
}
|
vkulpa/viber-bot-java
|
src/main/java/com/viber/bot/event/callback/OnMessageDelivered.java
|
package com.viber.bot.event.callback;
import com.viber.bot.event.BotEventListener;
import com.viber.bot.event.incoming.IncomingDeliveredEvent;
import com.viber.bot.message.Message;
import java.util.concurrent.Future;
import static com.google.common.base.Preconditions.checkArgument;
public interface OnMessageDelivered extends BotEventListener<Void> {
void messageDelivered(IncomingDeliveredEvent event, Message message);
@Override
default Future<Void> emit(final Object... args) {
checkArgument(args.length == 2);
messageDelivered((IncomingDeliveredEvent) args[0], (Message) args[1]);
return nothing;
}
}
|
Caesar73/chineseclub
|
public/node_modules/amd-optimizer/test/slashes/dir/file.js
|
define(['dir/dep'], function(){
return {};
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.