repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
ylehilds/NODE.JS-APPLICATION-DEVELOPMENT-LFW211
|
labs-jan-5-2021/ch-16/labs-2/validate.js
|
<filename>labs-jan-5-2021/ch-16/labs-2/validate.js
'use strict'
const assert = require('assert').strict
const { spawnSync } = require('child_process')
const { writeFileSync } = require('fs')
const store = require.resolve('./store')
const storeCode = Buffer.from('2775736520737472696374270a6d6f64756c652e6578706f727473203d202876616c75652c20636229203d3e207b0a2020696620284275666665722e69734275666665722876616c756529203d3d3d2066616c736529207b0a202020206362284572726f722827696e707574206d7573742062652061206275666665722729290a2020202072657475726e0a20207d0a202073657454696d656f7574282829203d3e207b0a20202020636f6e7374206964203d204d6174682e72616e646f6d28292e746f537472696e67283336292e73706c697428272e27295b315d2e736c69636528302c2034290a202020206362286e756c6c2c207b206964207d290a20207d2c20333030290a7d0a', 'hex')
try {
{
writeFileSync(store, storeCode)
const sp = spawnSync(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['test'], {
stdio: 'ignore'
})
assert.equal(sp.status, 0, 'tests should be successful (is package.json test script configured?)')
}
{
const badOutput = `'use strict'
module.exports = (value, cb) => {
if (Buffer.isBuffer(value) === false) {
cb(Error('input must be a buffer'))
return
}
setTimeout(() => {
const id = Math.random().toString(36).split('.')[1].slice(0, 2)
cb(null, { id })
}, 300)
}
`
writeFileSync(store, badOutput)
const sp = spawnSync(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['test'], {
stdio: 'ignore'
})
assert.equal(sp.status, 1, 'output should be tested (id length)')
}
{
const badValidation = `'use strict'
module.exports = (value, cb) => {
if (Buffer.isBuffer(value) === true) {
cb(Error('input must be a buffer'))
return
}
setTimeout(() => {
const id = Math.random().toString(36).split('.')[1].slice(0, 4)
cb(null, { id })
}, 300)
}
`
writeFileSync(store, badValidation)
const sp = spawnSync(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['test'], {
stdio: 'ignore'
})
assert.equal(sp.status, 1, 'error case should be tested')
}
{
const unexpectedError = `'use strict'
module.exports = (value, cb) => {
cb(Error('input must be a buffer'), {id: '1234'})
}
`
writeFileSync(store, unexpectedError)
const sp = spawnSync(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['test'], {
stdio: 'ignore'
})
assert.equal(sp.status, 1, 'unexpected errors should be guarded - e.g. ifError')
}
console.log('passed!')
} finally {
writeFileSync(store, storeCode)
}
|
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-mmacigewski
|
src/examples/11_module/01_ref_pointers/main.cpp
|
#include "ref_pointers.h"
#include<iostream>
using std::cout;
int main()
{
int r = 0, p = 0;
int* ref_r = &r;
cout << "Address of r: " << &r;
cout << "\nValue of r: " << r;
cout << "\nAddress of ref_r: " << &ref_r << "\n\n"; //& gets the memory address instead of value, instead if you printed ref_r it would print value
int* ptr_p = &p;
cout << "Address of p: " << &p;
cout << "\nValue of p: " << p;
cout << "\nAddress of ptr_p p: " << &ptr_p;
cout << "\n\nContents(address) of ptr_p: " << ptr_p << "\n";
cout << "Value ptr_p points to: " << *ptr_p; //will give us the value of ptr_p
*ptr_p = 15; //modifies value of p
cout << "Address of p: " << ptr_p;
cout << "Value of p: " << &ptr_p;
//int* ptr = 5; this wil not work, due to pointers needing address
return 0;
}
|
codingno/sia-uiii
|
components/utils/UserSide.js
|
<reponame>codingno/sia-uiii<gh_stars>0
import Avatar from "@mui/material/Avatar";
import Card from "@mui/material/Card";
import Divider from "@mui/material/Divider";
import Stack from "@mui/material/Stack";
import Grid from "@mui/material/Grid";
import Button from "@mui/material/Button";
import Modal from "@mui/material/Modal";
import FormControl from '@mui/material/FormControl';
import OutlinedInput from '@mui/material/OutlinedInput';
import InputAdornment from "@mui/material/InputAdornment";
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
import {CopyToClipboard} from 'react-copy-to-clipboard';
import Tooltip from "@mui/material/Tooltip";
import AutorenewIcon from '@mui/icons-material/Autorenew';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import { useState } from 'react'
import { useSession, signOut } from "next-auth/react";
import { useRouter } from 'next/router'
import Image from "next/image";
import CardHeader from "@mui/material/CardHeader";
import IconButton from "@mui/material/IconButton";
import Typography from '@mui/material/Typography'
import FormParent from "./FormParent";
import generator from 'generate-password';
import ImageWithLoader from "../../utils/ImageWithLoader";
import axios from 'axios'
export default function () {
const router = useRouter()
const { data: session, status } = useSession();
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [copied, setCopied] = useState(false);
const [newPassword, setNewPassword] = useState("");
const [showNewPassword, setShowNewPassword] = useState(false);
const [copiedNew, setCopiedNew] = useState(false);
const [confirmNewPassword, setConfirmNewPassword] = useState("");
const [showConfirmNewPassword, setShowConfirmNewPassword] = useState(false);
const [copiedConfirmNew, setCopiedConfirmNew] = useState(false);
const [modalNewPassword, setModalNewPassword] = useState(false);
const generatePassword = () => generator.generate({
length: 10,
numbers: true
});
async function submitChangePassword() {
try {
const url = '/api/change-password/' + session.user.userID
const { data } = await axios.post(url, { password, newPassword, confirmNewPassword })
alert('Password successfully changed')
} catch (error) {
if(error.response) {
alert(error.response.data)
}
alert(error)
}
}
return (
<>
{!session || router.pathname == '/master/college' ? (
""
) : (
<Grid item xs={2} p={1}>
<Card
sx={{
height: 400,
bgcolor : 'primary.main',
py : 5,
}}
>
<Stack
direction="column"
alignItems="center"
justifyContent="center"
>
<Avatar aria-label=""
sx={{
width:100,
height:100,
mb : 5,
}}
>
{session.user.image && (
<ImageWithLoader
src={session.user.image}
alt={session.user.name}
width={150}
// height={75}
height={150}
/>
)}
</Avatar>
<Typography variant="h6" color="background.default">
{session.user.name}
</Typography>
<Typography variant="body1" color="primary.dark">
{session.user.email}
</Typography>
{
session.user.student_number &&
<>
<Typography variant="body1" color="background.default" mt={3}>
{session.user.student_number}
</Typography>
<Typography variant="body1" color="background.default">
{session.user.studentData.entry_year}
</Typography>
<Typography variant="body1" color="background.default">
Semester {session.user.semester_active}
</Typography>
</>
}
{
router.pathname === '/' &&
<Stack
mt={3}
>
<Button variant="contained" color="secondary" component="span" onClick={() => setModalNewPassword(true)}>
Change Password
</Button>
</Stack>
}
</Stack>
</Card>
</Grid>
)}
<Modal
aria-labelledby="simple-modal-title"
aria-describedby="simple-modal-description"
open={modalNewPassword}
onClose={() => setModalNewPassword(false)}
>
<Card
sx={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 600,
// bgcolor: 'background.paper',
// border: '2px solid #000',
// boxShadow: 24,
p: 4,
}}
>
<FormParent label="New Password">
<FormControl sx={{ width: "65%" }} variant="outlined">
<OutlinedInput
id="outlined-adornment-password"
type={showNewPassword ? 'text' : 'password'}
value={newPassword}
onChange={e => setPassword(e.target.value)}
endAdornment={
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={e => setShowNewPassword(!showNewPassword)}
// onMouseDown={handleMouseDownPassword}
edge="end"
>
{showNewPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
<CopyToClipboard
text={newPassword} >
<IconButton
aria-label="toggle password visibility"
onClick={e => setCopiedNew(!copiedNew)}
// onMouseDown={handleMouseDownPassword}
edge="end"
>
<Tooltip
open={copiedNew}
title={"Copied to clipboard!"}
leaveDelay={1500}
onClose={() => setCopiedNew(false)}
>
<ContentCopyIcon />
</Tooltip>
</IconButton>
</CopyToClipboard>
<IconButton
aria-label="toggle password visibility"
onClick={e => {
setNewPassword(generatePassword())
document.getElementById('renew-create-password').classList.add('spin-animation')
setTimeout(() => {
document.getElementById('renew-create-password').classList.remove('spin-animation')
}, 1000)
}}
// onMouseDown={handleMouseDownPassword}
edge="end"
>
<AutorenewIcon id="renew-create-password" />
</IconButton>
</InputAdornment>
}
inputProps={{
autoComplete: 'new-password'
}}
autocomplete="new-password"
sx={{
background: "#E0E0E0"
}}
/>
</FormControl>
</FormParent>
<FormParent label="Confirm New Password">
<FormControl sx={{ width: "65%" }} variant="outlined">
<OutlinedInput
id="outlined-adornment-password"
type={showConfirmNewPassword ? 'text' : 'password'}
value={confirmNewPassword}
onChange={e => setConfirmNewPassword(e.target.value)}
endAdornment={
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={e => setShowConfirmNewPassword(!showConfirmNewPassword)}
// onMouseDown={handleMouseDownPassword}
edge="end"
>
{showConfirmNewPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
}
inputProps={{
autoComplete: 'new-password'
}}
autocomplete="new-password"
sx={{
background: "#E0E0E0"
}}
/>
</FormControl>
</FormParent>
<FormParent label="Current Password">
<FormControl sx={{ width: "65%" }} variant="outlined">
<OutlinedInput
id="outlined-adornment-password"
type={showPassword ? 'text' : 'password'}
value={password}
onChange={e => setPassword(e.target.value)}
endAdornment={
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={e => setShowPassword(!showPassword)}
// onMouseDown={handleMouseDownPassword}
edge="end"
>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
}
inputProps={{
autoComplete: 'new-password'
}}
autocomplete="new-password"
sx={{
background: "#E0E0E0"
}}
/>
</FormControl>
</FormParent>
<FormParent>
<Stack
direction="row"
alignItems="center"
ml={5}
mt={3}
sx={{ width: "60%", display: "flex", justifyContent: "flex-start" }}
>
<Button
variant="contained"
color="primary"
sx={{
width: 150,
}}
startIcon={() => <></>}
onClick={submitChangePassword}
>
Submit
</Button>
</Stack>
</FormParent>
</Card>
</Modal>
</>
);
}
|
l2dy-sonarcloud/sensu-go
|
backend/apid/graphql/node_test.go
|
package graphql
import (
"context"
"fmt"
"testing"
corev2 "github.com/sensu/sensu-go/api/core/v2"
"github.com/sensu/sensu-go/backend/apid/graphql/globalid"
"github.com/sensu/sensu-go/backend/apid/graphql/relay"
"github.com/sensu/sensu-go/graphql"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func setupNodeResolver(cfg ServiceConfig) func(string) (interface{}, error) {
register := relay.NodeRegister{}
resolver := relay.Resolver{Register: ®ister}
registerNodeResolvers(register, cfg)
ctx := context.Background()
info := graphql.ResolveInfo{}
return func(gid string) (interface{}, error) {
return resolver.Find(ctx, gid, info)
}
}
type onner interface {
On(string, ...interface{}) *mock.Call
}
func TestNodeResolvers(t *testing.T) {
cfg := ServiceConfig{
EntityClient: new(MockEntityClient),
EventClient: new(MockEventClient),
EventFilterClient: new(MockEventFilterClient),
GenericClient: new(MockGenericClient),
HandlerClient: new(MockHandlerClient),
MutatorClient: new(MockMutatorClient),
NamespaceClient: new(MockNamespaceClient),
RBACClient: new(MockRBACClient),
SilencedClient: new(MockSilencedClient),
UserClient: new(MockUserClient),
}
find := setupNodeResolver(cfg)
testCases := []struct {
name string
setupNode func() interface{}
setupID func(interface{}) string
setup func(interface{})
}{
{
name: "assets",
setupNode: func() interface{} {
return corev2.FixtureAsset("name")
},
setupID: func(r interface{}) string {
return globalid.AssetTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.GenericClient.(onner).On("SetTypeMeta", mock.Anything).Return(nil).Once()
cfg.GenericClient.(onner).On("Get", mock.Anything, "name", mock.Anything).Run(func(args mock.Arguments) {
arg := args.Get(2).(*corev2.Asset)
*arg = *r.(*corev2.Asset)
}).Return(nil).Once()
},
},
{
name: "check",
setupNode: func() interface{} {
return corev2.FixtureCheckConfig("name")
},
setupID: func(r interface{}) string {
return globalid.CheckTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.GenericClient.(onner).On("SetTypeMeta", mock.Anything).Return(nil).Once()
cfg.GenericClient.(onner).On("Get", mock.Anything, "name", mock.Anything).Run(func(args mock.Arguments) {
arg := args.Get(2).(*corev2.CheckConfig)
*arg = *r.(*corev2.CheckConfig)
}).Return(nil).Once()
},
},
{
name: "entities",
setupNode: func() interface{} {
return corev2.FixtureEntity("sensu")
},
setupID: func(r interface{}) string {
return globalid.EntityTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.EntityClient.(onner).On("FetchEntity", mock.Anything, "sensu").Return(r, nil).Once()
},
},
{
name: "event filters",
setupNode: func() interface{} {
return corev2.FixtureEventFilter("name")
},
setupID: func(r interface{}) string {
return globalid.EventFilterTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.GenericClient.(onner).On("SetTypeMeta", mock.Anything).Return(nil).Once()
cfg.GenericClient.(onner).On("Get", mock.Anything, "name", mock.Anything).Run(func(args mock.Arguments) {
arg := args.Get(2).(*corev2.EventFilter)
*arg = *r.(*corev2.EventFilter)
}).Return(nil).Once()
},
},
{
name: "handlers",
setupNode: func() interface{} {
return corev2.FixtureHandler("name")
},
setupID: func(r interface{}) string {
return globalid.HandlerTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.GenericClient.(onner).On("SetTypeMeta", mock.Anything).Return(nil).Once()
cfg.GenericClient.(onner).On("Get", mock.Anything, "name", mock.Anything).Run(func(args mock.Arguments) {
arg := args.Get(2).(*corev2.Handler)
*arg = *r.(*corev2.Handler)
}).Return(nil).Once()
},
},
{
name: "hooks",
setupNode: func() interface{} {
return corev2.FixtureHookConfig("name")
},
setupID: func(r interface{}) string {
return globalid.HookTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.GenericClient.(onner).On("SetTypeMeta", mock.Anything).Return(nil).Once()
cfg.GenericClient.(onner).On("Get", mock.Anything, "name", mock.Anything).Run(func(args mock.Arguments) {
arg := args.Get(2).(*corev2.HookConfig)
*arg = *r.(*corev2.HookConfig)
}).Return(nil).Once()
},
},
{
name: "mutators",
setupNode: func() interface{} {
return corev2.FixtureMutator("name")
},
setupID: func(r interface{}) string {
return globalid.MutatorTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.GenericClient.(onner).On("SetTypeMeta", mock.Anything).Return(nil).Once()
cfg.GenericClient.(onner).On("Get", mock.Anything, "name", mock.Anything).Run(func(args mock.Arguments) {
arg := args.Get(2).(*corev2.Mutator)
*arg = *r.(*corev2.Mutator)
}).Return(nil).Once()
},
},
{
name: "users",
setupNode: func() interface{} {
return corev2.FixtureUser("name")
},
setupID: func(r interface{}) string {
return globalid.UserTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.UserClient.(onner).On("FetchUser", mock.Anything, "name").Return(r, nil).Once()
},
},
{
name: "events",
setupNode: func() interface{} {
return corev2.FixtureEvent("a", "b")
},
setupID: func(r interface{}) string {
return globalid.EventTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.EventClient.(onner).On("FetchEvent", mock.Anything, "a", "b").Return(r, nil).Once()
},
},
{
name: "namespaces",
setupNode: func() interface{} {
return corev2.FixtureNamespace("sensu")
},
setupID: func(r interface{}) string {
return globalid.NamespaceTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.NamespaceClient.(onner).On("FetchNamespace", mock.Anything, "sensu").Return(r, nil).Once()
},
},
{
name: "cluster-role",
setupNode: func() interface{} {
return corev2.FixtureClusterRole("sensu")
},
setupID: func(r interface{}) string {
return globalid.ClusterRoleTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.RBACClient.(onner).On("FetchClusterRole", mock.Anything, "sensu").Return(r, nil).Once()
},
},
{
name: "cluster-role-binding",
setupNode: func() interface{} {
return corev2.FixtureClusterRoleBinding("sensu")
},
setupID: func(r interface{}) string {
return globalid.ClusterRoleBindingTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.RBACClient.(onner).On("FetchClusterRoleBinding", mock.Anything, "sensu").Return(r, nil).Once()
},
},
{
name: "role",
setupNode: func() interface{} {
return corev2.FixtureRole("sensu", "default")
},
setupID: func(r interface{}) string {
return globalid.RoleTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.RBACClient.(onner).On("FetchRole", mock.Anything, "sensu").Return(r, nil).Once()
},
},
{
name: "role-binding",
setupNode: func() interface{} {
return corev2.FixtureRoleBinding("sensu", "default")
},
setupID: func(r interface{}) string {
return globalid.RoleBindingTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.RBACClient.(onner).On("FetchRoleBinding", mock.Anything, "sensu").Return(r, nil).Once()
},
},
{
name: "silenced",
setupNode: func() interface{} {
return corev2.FixtureSilenced("sub:check")
},
setupID: func(r interface{}) string {
return globalid.SilenceTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.SilencedClient.(onner).On("GetSilencedByName", mock.Anything, "sub:check").Return(r, nil).Once()
},
},
{
name: "pipeline",
setupNode: func() interface{} {
return corev2.FixturePipeline("name", "default")
},
setupID: func(r interface{}) string {
return globalid.PipelineTranslator.EncodeToString(context.Background(), r)
},
setup: func(r interface{}) {
cfg.GenericClient.(onner).On("SetTypeMeta", mock.Anything).Return(nil).Once()
cfg.GenericClient.(onner).On("Get", mock.Anything, "name", mock.Anything).Run(func(args mock.Arguments) {
arg := args.Get(2).(*corev2.Pipeline)
*arg = *r.(*corev2.Pipeline)
}).Return(nil).Once()
},
},
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("can resolve %s", tc.name), func(t *testing.T) {
in := tc.setupNode()
id := tc.setupID(in)
tc.setup(in)
res, err := find(id)
assert.Equal(t, in, res)
assert.NoError(t, err)
})
}
}
|
shibing624/blogCode
|
src/main/java/xm/xml/ListDemo.java
|
<reponame>shibing624/blogCode<gh_stars>1-10
package xm.xml;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.util.List;
public class ListDemo {
public static void main(String[] args) throws Exception {
org.junit.Assert.assertEquals(1,(2-1));
SAXReader reader = new SAXReader();
File file = new File("properties/books.xml");
Document document = reader.read(file);
Element root = document.getRootElement();
List<Element> childElements = root.elements();
for (Element child : childElements) {
//未知属性名情况下
List<Attribute> attributeList = child.attributes();
for (Attribute attr : attributeList) {
System.out.println(attr.getName() + ": " + attr.getValue());
}
//已知属性名情况下
/*System.out.println("id: " + child.attributeValue("id"));*/
//未知子元素名情况下
List<Element> elementList = child.elements();
for (Element ele : elementList) {
System.out.println(ele.getName() + ": " + ele.getText());
}
System.out.println();
//已知子元素名的情况下
/*System.out.println("title" + child.elementText("title"));
System.out.println("author" + child.elementText("author"));*/
//格式化美观而存在
System.out.println();
}
}
}
|
Pumpkin-Cap/Pumpkin-Cap-Repo
|
script/testingTests.js
|
<filename>script/testingTests.js
// describe('myWhileLoopFunction', function(){
// it("returns the appropriate time that it'll take for a duck to reach us", function(){
// expect(myWhileLoopFunction(20)).to.equal(10);
// expect(myWhileLoopFunction(10)).to.equal(5);
// expect(myWhileLoopFunction(4)).to.equal(2);
// expect(myWhileLoopFunction(9)).to.equal(5);
// });
// });
// describe('myForLoopFunction', function(){
// it('returns 10', function(){
// expect(myForLoopFunction()).to.equal(10);
// });
// });
// //level3
// Well done!
// But we’re going to need to be conscious of what weapon we’re using. Did you know we can chain conditions using an “else if” command? It will continue checking your conditions until it finds one that evaluates TRUE and enter that block. Refactor your orders to account for the following conditions.
// And don’t forget to check the documentation!
// //level4
// Excellent job! Those ducks didn’t know what hit ‘em! But you can bet things can get more complicated.
// Did you know that you can join conditionals? In JavaScript you write these as:
// AND operator: &&
// OR operator: ||
// With the AND operator, the condition returns TRUE if both sides are true. If either one or both sides are false, then the entire condition returns FALSE.
// With the OR operator, the entire condition returns TRUE if either one or both sides are true. If both sides are false, then the condition returns FALSE.
// Let’s run a quick drill! And don’t forget the documentation!
// //level5
// Great! I now know my faith was not misplaced!
// They’re changing up their strategy. Some of their waves are being sent out with shields! If they’re using a shield, we’re going to need the grenade launcher no matter how many they have. We’re going to have to adapt!
// Finish what you’ve started. Take charge of rewriting the code!
// The documentation is always there!
// //level6
// All right! Our defense against their type of attack is set! Now let’s tackle how to handle their continuous attacks.
// In any system you’ll need to decide not only what to execute, but how many times to execute it. If you’re going to need a code block to execute more than two or three times - or perhaps a varying number of times - then you’re probably going to want to employ a loop.
// There are many kinds of loops that are each ideal for different kinds of situations. While no loop is officially more important than another, you’ll get little argument from me that the “for-loop” is your go-to.
// A for-loop declares a variable, changes that variable after each iteration of the code, and has an end condition for when that variable becomes a certain value. That variable can be called anything, but is conventionally “i.” The incrementation of that variable can be anything that makes sense for your function, but often it makes sense to increment it by 1 (i = i + 1, or i++ in shorter notation).
// Don’t forget to consult your documentation!
// //level 7
// Now let’s put that for-loop into action!
// It looks like there are waves advancing, and we need to prepare for it. We need to deploy more troops depending on how many waves we get; design a function to deploy the right amount of troops.
// We need 5 troops per wave, and each additional wave will require an extra troop. I’m counting on you!
// Documentation: Use it!
// //level 8
// Those ducks soon won’t stand a chance!
// But there are other times a for-loop won’t work for the situation. For example, if we want to iterate on a block of code until a particular condition is met that can’t be reliably counted by the number of times we’ve looped (like a for-loop does), then perhaps a “while-loop” is appropriate.
// To properly plan our strategy, we’ll need to know how long we’ve got until ducks reach our base. Given its distance, write us something that computes the time for one to reach us!
// The documentation is there if you need it.
// // level 9
// Now let’s bring it together. Based on how long it takes a big tough duck to reach us, we need to know how many guns at once we’ll need on it to bring it down in time.
// And not a moment too soon! There’s some big tough poultry coming this way, and they can take a lot of pepper - write us something that tells the troops how many guns to fire at a duck given its height and distance!
// The documentation is always with you.
// //10
// You’ve done a great job. We now have systems in place to deal with any particular attack.
// Let’s now have you work with arrays. An array is a data type that stores references to other data.
// For example, you can have an array with 3 integers in it - each called an “element.” You can refer to each one of these integers, and the length of this array is considered 3. This is what that might look like:
// const myArray = [4, 10, -5]
// //the following are true statements; note we begin counting our elements (referred to as an element’s index) at 0 rather than 1.
// myArray[0] === 4
// myArray[1] === 10
// myArray[2] === -5
// myArray.length === 3
// By the time you’re ready to take over my job it’ll be important to understand the difference between this array having these values and having references to these values, but for now I want you to focus on putting these arrays and values to use!
// There is a lot to know about arrays. I’ll lay out the basics, but the documentation has everything you could ever need.
// //11
// Excellent. I knew you would be the one I could trust with this next mission.
// We have placed a spy in their ranks. It is time to recover our operative and add that wealth of knowledge to our intelligence.
// Using arrays and any other tools you’ve learned, write a program to recover the spy. You will recognize our ally from the rest by the pizza/party hat.
// Remember, referencing the documentation could save a life!!
// //12
// To make use of the critical information gathered, it will be useful to familiarize you with array methods. A method is a built-in function that you can apply to manipulate or access data you need.
// We’ll go over some common array methods, but there are many, many more. Always remember the documentation is there to reference rather than trying to memorize them all.
// //13
// You’re now ready to begin acting on the intelligence we’ve gathered. Sergeant Sarah will brief you.
// I’ve heard you’re the peak programming duck in our ranks. The King Duck. The peak king duck. You’re certainly piquing my interest, duck.
// Missiles are slow and expensive, but totally worth it against those tough ducks - the only problem is by the time we know where they are to target them it’s too late to use them. But I think we can use your skills to make this happen.
// I’ve discovered their deployment schema. I can give you this information in the form of an array: General Joe tells me you’ll be able to find where a tough duck will be, and what place it’ll be in their deployment. With these calculations we’ll be able to target our missiles from afar.
// And the documentation will fill in the gaps!
// //14
// General Joe was right about you. I now see for myself that you are the one for this next mission.
// The decision to extract me now was made because my partner was compromised. It was only a matter of time before they found me, too, and I was recovered; he is still in their custody.
// Knowing there was a spy, they began encrypting their orders. I got the information on where he’s being held before I was recovered, but the clear location must be extracted from this jumbled mess.
// General Joe says you’ll be able to figure out how to use “Array.isArray()” from the documentation. That is what they use to decrypt these orders.
// //15
// You’ve done us all a great service with the rescue of Gary. He is invaluable to our operation; his name is Gary, and that’s all you need to know about him.
// Once we get you up to speed on objects we will be primed for our final strike.
// You, of course, know what an array looks like. Let’s take our original example:
// const myArray = [4, 10, -5]
// Now what if I presented it to you like this?
// const myArray = {
// 0: 4,
// 1: 10,
// 2: -5
// }
// Do you see the relationship between them? We are explicitly stating the index and its value along with it rather than just the value. If you take this idea and “rename” the indices as any names you see fit, then you’ve got the concept of an object. In fact, an array is merely a special kind of object!
// In the case of an object, we refer to them as “key-value pairs.” The “named” index is the key, and the value is its associated value. In the case of an array, the key is an integer; with an object it is a string.
// When thinking of an array as an object, it becomes easy to figure out how to navigate an object.
// const myArray = [4, 10, -5]
// const myObject = {
// green: “turtle”,
// circle: true,
// cat: “cute”,
// dog: 10
// }
// //The following statements are true
// myArray[2] === -5
// myObject[“cat”] === “cute”
// myObject.cat === “cute”
// Note the ability to use dot notation with objects. This tells the code to assume the following word is a string, so it knows to find a string-type key. This will not work with arrays whose keys are integers.
// Like arrays, there is much to know about objects. This is a solid basis, but the documentation has anything else you might need.
// //16
// There’s just one more thing and you will be ready.
// For our final attack, you must know how to “build” objects as well as read them. You can define an object’s key-value pairs outright when you declare it, but you also can add them (or change them) as you go along just as easily. Let’s take our last example:
// const myObject = {
// green: “turtle”,
// circle: true,
// cat: “cute”,
// dog: 10
// }
// Now if you code:
// myObject.snake: “creepy”
// myObject will now have that key-value pair, looking like:
// {
// green: “turtle”,
// circle: true,
// cat: “cute”,
// dog: 10,
// snake: “creepy”
// }
// In addition, you can make alterations at any point in your code:
// myObject.cat = “super, super cute”
// myObject will now have that change, looking like:
// {
// green: “turtle”,
// circle: true,
// cat: “super, super cute”,
// dog: 10,
// snake: “creepy”
// }
// Let’s build an enemy blueprint! Look into your documentation when needed.
// //17
// All right. You’re ready to perform the Special Ops mission. With the recovery of Gary, we have retrieved critical information that we can use to put an end to this invasion. It won’t be easy - you’re going to have to pull out all the tricks you’ve learned up to this point.
// The key to our victory lies in severing their communication. Each of the enemy looks the same to the untrained eye; however, we have discovered a critical feature of those responsible for dispersing their orders: squeakers.
// Given an array of the entire army where each duck is given as an object, we will need you to do the following:
// Find where the ducks with squeakers are located, and which weapon to use based on how many are clustered together and if they have shields. You may fire a weapon at the first of a group to hit all of them. If any one duck in a cluster has a shield, it is the same as if all of them do.
// Where the toughDucks are located, and how many guns will need to be focused on them based on their particular height and distance.
// The enemy objects will appear with keys depending on what type it is:
// A squeaker will be:
// enemyObj = {
// type: “squeaker”,
// attributes: {
// hasShield: boolean
// }
// }
// A toughDuck will be:
// enemyObj = {
// type: “toughDuck”,
// attributes: {
// height: integer,
// distance: integer
// }
// }
// Return your data as an array of objects. Each object should have the “type” key, and an “attributes” key whose value itself will be an object with keys of the necessary data. This is an example of what each kind would look like:
// yourSqueaker = {
// type: “squeaker”,
// attributes: {
// index: indexNumber,
// weapon: weaponToUse
// }
// }
// yourToughDuck = {
// type: “toughDuck”,
// attributes: {
// index: indexNumber,
// guns: gunsRequired
// }
// }
// You can also bet it’ll be encrypted by now.
// This is for all the marbles, kid. It’s gonna be tough, but when you come out the other side we will be victorious!
// I’d wish you luck, but I wish you documentation instead!
|
AsahiOS/gate
|
usr/src/uts/i86pc/vm/kboot_mmu.h
|
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#ifndef _KBOOT_MMU_H
#define _KBOOT_MMU_H
#pragma ident "%Z%%M% %I% %E% SMI"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Kernel boot-time interfaces for handling MMU mappings before the HAT proper
* is running (i.e. before khat_running is set).
*/
#include <sys/mach_mmu.h>
struct xboot_info;
extern void kbm_init(struct xboot_info *);
/*
* Interface to remap the page table window, also used by HAT during init.
*/
extern void *kbm_remap_window(paddr_t physaddr, int writeable);
/*
* Find the next mapping at or above VA, if found returns non-zero and sets:
* - va : virtual address
* - pfn : pfn of real address
* - size : pagesize of the mapping
* - prot : protections
*/
extern int kbm_probe(uintptr_t *va, size_t *len, pfn_t *pfn, uint_t *prot);
/*
* Add a new mapping
*/
extern void kbm_map(uintptr_t va, paddr_t pa, uint_t level, uint_t is_kernel);
#ifdef __xpv
extern void kbm_map_ma(maddr_t ma, uintptr_t va, uint_t level);
#endif
/*
* unmap a single 4K page at VA
*/
extern void kbm_unmap(uintptr_t va);
/*
* Remap a single 4K page at VA (always PROT_READ|PROT_WRITE).
* Returns the pfn of the old mapping.
*/
extern pfn_t kbm_remap(uintptr_t va, pfn_t pfn);
/*
* Make a page mapping read only
*/
extern void kbm_read_only(uintptr_t va, paddr_t pa);
/*
* interface for kmdb to map a physical page, stack is only 1 deep
*/
extern void *kbm_push(paddr_t pa);
extern void kbm_pop(void);
/*
* These are needed by mmu_init()
*/
extern int kbm_nx_support;
extern int kbm_pae_support;
extern int kbm_largepage_support;
/*
* The size of memory mapped for the initial kernel nucleus text
* and data regions setup by the boot loader. needed for startup
*/
extern uint_t kbm_nucleus_size;
#ifdef __cplusplus
}
#endif
#endif /* _KBOOT_MMU_H */
|
chopikus/refactor
|
training/clone2/37.2.java
|
<reponame>chopikus/refactor<gh_stars>0
public class PII{
double first,second;
public PII(){}
// empty constructor
public PII(double first, double second){
this.first = first;
this.second = second;
}
//lmao
}
|
phelpsw/msp430-driverlib
|
examples/MSP430F5xx_6xx/adc12_a/adc12_a_ex8_tempSensor.c
|
/* --COPYRIGHT--,BSD
* Copyright (c) 2017, Texas Instruments Incorporated
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* --/COPYRIGHT--*/
#include "driverlib.h"
//******************************************************************************
//!
//! ADC12_A - Sample A10 Internal Temp Sensor as Input, AVcc Ref
//!
//! A single sample is made on A10 with reference to internal 1.5V Vref.
//! Software sets ADC12SC to start sample and conversion - ADC12SC
//! automatically cleared at EOC. ADC12_A internal oscillator times sample and
//! conversion. In Mainloop MSP430 waits in LPM4 to save power until ADC10_A
//! conversion complete, ADC12_A_ISR will force exit from any LPMx in Mainloop
//! on reti.
//! ACLK = n/a, MCLK = SMCLK = default DCO ~ 1.045MHz, ADC12CLK = ADC12OSC
//!
//! Uncalibrated temperature measured from device to device will vary do to
//! slope and offset variance from device to device - please see datasheet.
//!
//! MSP430F5529
//! -----------------
//! /|\| |
//! | | |
//! --|RST |
//! |Temp Sensor-->A10|
//! | |
//!
//!
//! This example uses the following peripherals and I/O signals. You must
//! review these and change as needed for your own board:
//! - ADC12_A peripheral
//! - A10
//!
//! This example uses the following interrupt handlers. To use this example
//! in your own application you must add these interrupt handlers to your
//! vector table.
//! - ADC12_A_VECTOR
//!
//******************************************************************************
long temp;
volatile long IntDegF;
volatile long IntDegC;
void main (void)
{
//Stop Watchdog Timer
WDT_A_hold(WDT_A_BASE);
//Initialize the ADC12_A Module
/*
* Base Address of ADC12_A Module
* Use internal ADC12_A bit as sample/hold signal to start conversion
* USE MODOSC 5MHZ Digital Oscillator as clock source
* Use default clock divider of 1
*/
ADC12_A_init(ADC12_A_BASE,
ADC12_A_SAMPLEHOLDSOURCE_SC,
ADC12_A_CLOCKSOURCE_ADC12OSC,
ADC12_A_CLOCKDIVIDER_1);
ADC12_A_enable(ADC12_A_BASE);
ADC12_A_enable(ADC12_A_BASE);
/*
* Base Address of ADC12_A Module
* For memory buffers 0-7 sample/hold for 768 clock cycles
* For memory buffers 8-15 sample/hold for 4 clock cycles (default)
* Disable Multiple Sampling
*
* Note: ADC12_A may have a minimum sample rate of 30us or 100us.
* This example uses a sample time of ~154us to ensure it works.
* 256 cycles (51.2us) or 512 cycles (100.4us) may be used, but
* resulting readings may be less accurate.
*/
ADC12_A_setupSamplingTimer(ADC12_A_BASE,
ADC12_A_CYCLEHOLD_768_CYCLES,
ADC12_A_CYCLEHOLD_4_CYCLES,
ADC12_A_MULTIPLESAMPLESDISABLE);
//Configure Memory Buffer
/*
* Base Addres of ADC12_A Module
* Configure memory buffer 0
* Map temp sensor to memory buffer 0
* Vref+ = Vref+ (int)
* Vref- = AVss
* Memory buffer 0 is not the end of a sequence
*/
ADC12_A_configureMemoryParam param = {0};
param.memoryBufferControlIndex = ADC12_A_MEMORY_0;
param.inputSourceSelect = ADC12_A_INPUT_TEMPSENSOR;
param.positiveRefVoltageSourceSelect = ADC12_A_VREFPOS_INT;
param.negativeRefVoltageSourceSelect = ADC12_A_VREFNEG_AVSS;
param.endOfSequence = ADC12_A_NOTENDOFSEQUENCE;
ADC12_A_configureMemory(ADC12_A_BASE ,¶m);
//Enable memory buffer 0 interrupt
ADC12_A_clearInterrupt(ADC12_A_BASE,
ADC12IFG0);
ADC12_A_enableInterrupt(ADC12_A_BASE,
ADC12IE0);
//Configure internal reference
//If ref generator busy, WAIT
while ( REF_ACTIVE == Ref_isRefGenBusy(REF_BASE) ) ;
//Select internal ref = 1.5V
Ref_setReferenceVoltage(REF_BASE,
REF_VREF1_5V);
//Internal Reference ON
Ref_enableReferenceVoltage(REF_BASE);
//Delay (~75us) for Ref to settle
__delay_cycles(75);
while (1)
{
//Enable/Start first sampling and conversion cycle
/*
* Base address of ADC12_A Module
* Start the conversion into memory buffer 0
* Use the repeated sequence of channels
*/
ADC12_A_startConversion(ADC12_A_BASE,
ADC12_A_MEMORY_0,
ADC12_A_SEQOFCHANNELS);
//LPM4 with interrupts enabled
__bis_SR_register(LPM4_bits + GIE);
__no_operation();
//Temperature in Celsius
//((A10/4096*1500mV) - 680mV)*(1/2.25mV) = (A10/4096*667) - 302
//= (A10 - 1855) * (667 / 4096)
IntDegC = ((temp - 1855) * 667) / 4096;
//Temperature in Fahrenheit
//((A10/4096*1500mV) - 640mV)*(1/1.25mV) = (A10/4096*1200) - 512
//= (A10 - 1748) * (1200 / 4096)
IntDegF = ((temp - 1748) * 1200) / 4096;
//SET BREAKPOINT HERE and watch IntDegC and IntDegF
__no_operation();
}
}
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector=ADC12_VECTOR
__interrupt
#elif defined(__GNUC__)
__attribute__((interrupt(ADC12_VECTOR)))
#endif
void ADC12ISR (void)
{
switch (__even_in_range(ADC12IV,34)){
case 0: break; //Vector 0: No interrupt
case 2: break; //Vector 2: ADC overflow
case 4: break; //Vector 4: ADC timing overflow
case 6: //Vector 6: ADC12IFG0
//Move results, IFG is cleared
temp = ADC12_A_getResults(ADC12_A_BASE,
ADC12_A_MEMORY_0);
//Exit active CPU
__bic_SR_register_on_exit(LPM4_bits);
break;
case 8: break; //Vector 8: ADC12IFG1
case 10: break; //Vector 10: ADC12IFG2
case 12: break; //Vector 12: ADC12IFG3
case 14: break; //Vector 14: ADC12IFG4
case 16: break; //Vector 16: ADC12IFG5
case 18: break; //Vector 18: ADC12IFG6
case 20: break; //Vector 20: ADC12IFG7
case 22: break; //Vector 22: ADC12IFG8
case 24: break; //Vector 24: ADC12IFG9
case 26: break; //Vector 26: ADC12IFG10
case 28: break; //Vector 28: ADC12IFG11
case 30: break; //Vector 30: ADC12IFG12
case 32: break; //Vector 32: ADC12IFG13
case 34: break; //Vector 34: ADC12IFG14
default: break;
}
}
|
adamstegman/photo_albums
|
spec/active_record_spec_helper.rb
|
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, js: true) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
|
IKangXu/dc-sdk
|
modules/layer/type/HeatLayer.js
|
<reponame>IKangXu/dc-sdk
/**
* @Author: Caven
* @Date: 2020-02-27 00:35:35
*/
import { Cesium } from '@dc-modules/namespace'
import State from '@dc-modules/state/State'
import { SceneEventType } from '@dc-modules/event'
import { Transform } from '@dc-modules/transform'
import Position from '@dc-modules/position/Position'
import { DomUtil, Util } from '@dc-modules/utils'
import Layer from '../Layer'
const h337 = require('heatmap.js/build/heatmap.min')
const DEF_OPTS = {
maxOpacity: 0.8, // the maximum opacity used if not given in the heatmap options object
minOpacity: 0.1, // the minimum opacity used if not given in the heatmap options object
blur: 0.85, // the blur used if not given in the heatmap options object
maxCanvasSize: 2000,
minCanvasSize: 700,
radius: 25,
gradient: {
'0.4': 'blue',
'0.6': 'green',
'0.8': 'yellow',
'0.9': 'red'
}
}
class HeatLayer extends Layer {
constructor(id, options) {
super(id)
this._options = {
...DEF_OPTS,
...options
}
this._heat = undefined
this._bounds = undefined
this._mBounds = undefined
this._scale = 1
this._positions = []
this._options.spacing = this._options.radius * 1.5
this._delegate = new Cesium.CustomDataSource(id)
this._entity = new Cesium.Entity()
this.type = Layer.getLayerType('heat')
this._state = State.INITIALIZED
}
get options() {
return this._options
}
/**
* The hook for added
*/
_addedHook() {
this._redraw()
this._viewer.on(SceneEventType.CAMERA_MOVE_END, this._reset, this)
}
/**
* The hook for removed
*/
_removedHook() {
this._viewer.off(SceneEventType.CAMERA_MOVE_END, this._reset, this)
}
/**
*
* @param {*} position
*/
_transformWGS84ToHeatmap(position) {
position = Transform.transformWGS84ToMercator(position)
let coord = {}
coord.x = Math.round(
(position.lng - this._mBounds.west) / this._scale + this._options.spacing
)
coord.y = Math.round(
(position.lat - this._mBounds.south) / this._scale + this._options.spacing
)
coord.y = this._heat._renderer.canvas.height - coord.y
return coord
}
/**
*
* @returns {{east: *, south: *, north: *, west: *}}
* @private
*/
_getMBounds() {
let mWestSouth = Transform.transformWGS84ToMercator(
new Position(this._bounds.west, this._bounds.south)
)
let mEastNorth = Transform.transformWGS84ToMercator(
new Position(this._bounds.east, this._bounds.north)
)
return {
west: mWestSouth.lng,
south: mWestSouth.lat,
east: mEastNorth.lng,
north: mEastNorth.lat
}
}
/**
*
* @private
*/
_initCanvas() {
let diffLng = Math.abs(this._mBounds.east - this._mBounds.west)
let diffLat = Math.abs(this._mBounds.north - this._mBounds.south)
let max = Math.max(diffLng, diffLat)
let min = Math.min(diffLng, diffLat)
let scale = 1
if (max > this._options.maxCanvasSize) {
scale = max / this._options.maxCanvasSize
if (min / scale < this._options.minCanvasSize) {
scale = min / this._options.minCanvasSize
}
} else if (min < this._options.minCanvasSize) {
scale = min / this._options.minCanvasSize
if (max / scale > this._options.maxCanvasSize) {
scale = max / this._options.maxCanvasSize
}
}
this._scale = scale
if (!this._options.container) {
this._options.container = DomUtil.create(
'div',
'heat-map',
document.getElementsByClassName('dc-container')[0]
)
}
this._options.container.style.cssText = `
width:${diffLng / this._scale}px;
height:${diffLat / this._scale}px;
margin:0;
display:none`
if (!this._heat) {
this._heat = h337.create(this._options)
} else {
this._heat.configure(this._options)
}
}
/**
*
*/
_initEntity() {
let offset = this._options.spacing * this._scale
this._mBounds.west -= offset
this._mBounds.south -= offset
this._mBounds.east += offset
this._mBounds.north += offset
let westSouth = Transform.transformMercatorToWGS84({
lng: this._mBounds.west,
lat: this._mBounds.south
})
let eastNorth = Transform.transformMercatorToWGS84({
lng: this._mBounds.east,
lat: this._mBounds.north
})
let bounds = Cesium.Rectangle.fromDegrees(
westSouth.lng,
westSouth.lat,
eastNorth.lng,
eastNorth.lat
)
this._entity.show = false
this._entity.rectangle = {
coordinates: bounds,
fill: false,
distanceDisplayCondition: this._options.distanceDisplayCondition
}
this._delegate.entities.add(this._entity)
}
_reset() {
let cameraHeight = Math.floor(
this._viewer.camera.positionCartographic.height
)
let radius = (1e4 / cameraHeight) * 60
if (radius < 10) {
radius = 10
}
if (radius > 60) {
radius = 60
}
this._options.radius = radius
this._options.spacing = this._options.radius * 1.5
this._heat && this._heat.configure(this._options)
}
_redraw() {
/** set bounds */
if (!this._bounds) {
return false
}
let mBounds = this._getMBounds()
if (
!this._mBounds ||
mBounds.west !== this._mBounds.west ||
mBounds.south !== this._mBounds.south ||
mBounds.east !== this._mBounds.east ||
mBounds.north !== this._mBounds.north
) {
this._mBounds = mBounds
this._initCanvas()
}
let data = []
this._positions.forEach(item => {
let coord = this._transformWGS84ToHeatmap({
lng: item.lng || item.x,
lat: item.lat || item.y
})
data.push({
x: coord.x,
y: coord.y,
value: item.value || 1
})
})
this._heat.setData({
min: 0,
max: 1,
data
})
this._delegate.entities.remove(this._entity)
this._initEntity()
let material = new Cesium.ImageMaterialProperty({
image: this._heat._renderer.canvas,
transparent: true
})
Util.merge(this._entity.rectangle, {
fill: true,
material: material
})
this._entity.show = true
}
/**
*
* @param {*} positions
*/
setPositions(positions) {
if (!positions || !Array.isArray(positions)) {
return this
}
this._positions = positions
this._bounds = Cesium.Math.bounds(this._positions)
this._redraw()
return this
}
/**
*
* @param {*} position
*/
addPosition(position) {
this._positions.push(position)
this._bounds = Cesium.Math.bounds(this._positions)
this._redraw()
return this
}
/**
*
* @param {*} options
*/
setOptions(options) {
Util.merge(this._options, options)
if (this._heat) {
this._options.spacing = this._options.radius * 1.5
this._heat.configure(this._options)
}
return this
}
}
Layer.registerType('heat')
export default HeatLayer
|
Ace-Ma/LSOracle
|
OpenTimer/example/sizer/sizer.cpp
|
<filename>OpenTimer/example/sizer/sizer.cpp
// This program demonstrates how to resize a design of six NAND2 cells
// and reports timing/power/area values using OpenTimer C++ API.
//
// Design : sizer.v
// SDC : sizer.sdc
// SPEF : sizer.spef
// Library: NangateOpenCellLibrary
#include <ot/timer/timer.hpp>
int main(int argc, char* argv[]) {
ot::Timer timer;
// Builder
// - read cell library for both early/late mode (nullopt)
// - read the verilog
// - read the parasitics
// - read the design constraints
timer.read_celllib("NangateOpenCellLibrary_typical.lib", std::nullopt)
.read_verilog("sizer.v")
.read_spef ("sizer.spef")
.read_sdc ("sizer.sdc");
// Report the timing/power/area
std::optional<float> tns = timer.report_tns();
std::optional<float> wns = timer.report_wns();
std::optional<float> area = timer.report_area();
std::optional<float> lkp = timer.report_leakage_power();
std::cout << "\nBefore sizing\n"
<< "TNS : " << *tns << '\n'
<< "WNS : " << *wns << '\n'
<< "AREA : " << *area << '\n'
<< "LEAKAGE_POWER: " << *lkp << '\n';
// Downsize all gates from X2 to X1
timer.repower_gate("inst_0", "NAND2_X1")
.repower_gate("inst_1", "NAND2_X1")
.repower_gate("inst_2", "NAND2_X1")
.repower_gate("inst_3", "NAND2_X1")
.repower_gate("inst_4", "NAND2_X1")
.repower_gate("inst_5", "NAND2_X1");
tns = timer.report_tns();
wns = timer.report_wns();
area = timer.report_area();
lkp = timer.report_leakage_power();
std::cout << "\nDownsize all to NAND2_X1\n"
<< "TNS : " << *tns << '\n'
<< "WNS : " << *wns << '\n'
<< "AREA : " << *area << '\n'
<< "LEAKAGE_POWER: " << *lkp << '\n';
// Upsize all gates from X1 to X4
timer.repower_gate("inst_0", "NAND2_X4")
.repower_gate("inst_1", "NAND2_X4")
.repower_gate("inst_2", "NAND2_X4")
.repower_gate("inst_3", "NAND2_X4")
.repower_gate("inst_4", "NAND2_X4")
.repower_gate("inst_5", "NAND2_X4");
tns = timer.report_tns();
wns = timer.report_wns();
area = timer.report_area();
lkp = timer.report_leakage_power();
std::cout << "\nUpsize all to NAND2_X4\n"
<< "TNS : " << *tns << '\n'
<< "WNS : " << *wns << '\n'
<< "AREA : " << *area << '\n'
<< "LEAKAGE_POWER: " << *lkp << '\n';
return 0;
}
|
mdanese1954/mikes-uaa
|
server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/ScopeAuthenticationFilter.java
|
/*******************************************************************************
* Cloud Foundry
* Copyright (c) [2009-2016] Pivotal Software, Inc. All Rights Reserved.
*
* This product is licensed to you under the Apache License, Version 2.0 (the "License").
* You may not use this product except in compliance with the License.
*
* This product includes a number of subcomponents with
* separate copyright notices and license terms. Your use of these
* subcomponents is subject to the terms and conditions of the
* subcomponent's license, as noted in the LICENSE file.
*******************************************************************************/
package org.cloudfoundry.identity.uaa.authentication.manager;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ScopeAuthenticationFilter implements Filter {
private AuthenticationManager authenticationManager;
private AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
public AuthenticationEntryPoint getAuthenticationEntryPoint() {
return authenticationEntryPoint;
}
public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
this.authenticationEntryPoint = authenticationEntryPoint;
}
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication==null || (!(authentication instanceof OAuth2Authentication))) {
throw new InvalidTokenException("Missing oauth token.");
}
authenticationManager.authenticate(authentication);
chain.doFilter(request,response);
} catch (OAuth2Exception e) {
authenticationEntryPoint.commence(
(HttpServletRequest)request,
(HttpServletResponse)response,
new InsufficientAuthenticationException("Insufficient authentication", e));
SecurityContextHolder.clearContext();
} catch (AuthenticationException e) {
authenticationEntryPoint.commence((HttpServletRequest)request,(HttpServletResponse)response,e);
SecurityContextHolder.clearContext();
}
}
@Override
public void destroy() {
}
}
|
imengyu/720PanoramaViewer
|
720Core/CCMeshLoader.cpp
|
#include "CCMeshLoader.h"
#include "CCMesh.h"
#include "CCObjLoader.h"
#include "PathHelper.h"
#include "720Core.h"
CCObjLoader* objLoader = nullptr;
CCMeshLoader* CCMeshLoader::GetMeshLoaderByType(CCMeshType type)
{
switch (type)
{
case CCMeshType::MeshTypeObj:
return objLoader;
case CCMeshType::MeshTypeFbx:
break;
}
return nullptr;
}
CCMeshLoader* CCMeshLoader::GetMeshLoaderByFilePath(const wchar_t* path) {
std::wstring ext = Path::GetExtension(path);
if (ext == L"obj")
return objLoader;
return nullptr;
}
void CCMeshLoader::Init()
{
objLoader = new CCObjLoader();
}
void CCMeshLoader::Destroy()
{
delete objLoader;
}
bool CCMeshLoader::Load(const wchar_t* path, CCMesh* mesh)
{
return false;
}
bool CCMeshLoader::Load(BYTE* buffer, size_t bufferSize, CCMesh* mesh) {
return false;
}
const wchar_t* CCMeshLoader::GetLastError()
{
return lastErr.c_str();
}
void CCMeshLoader::SetLastError(const wchar_t* err)
{
lastErr = err;
}
|
wedevelopmx/representame
|
app/routes/state.js
|
var express = require('express');
var router = express.Router();
var models = require('../models');
/* GET home page. */
router.route('/')
.get(function(req, res, next) {
models.State
.findAll()
.then(function(states) {
res.json(states);
});
});
router.route('/:id')
.get(function(req, res, next) {
models.State
.findAll({ where: { id: req.params.id }, order: [['name', 'ASC']]})
.then(function(states) {
res.json(states);
});
});
router.route('/:id/towns')
.get(function(req, res, next) {
models.Municipality
.findAll({ where: { StateId: req.params.id }, order: [['name', 'ASC']] })
.then(function(municipalities) {
res.json(municipalities);
})
});
module.exports = router;
|
markreidvfx/pyaaf_old
|
src/_AAFOPDefs.cpp
|
<filename>src/_AAFOPDefs.cpp
// Boost Includes ==============================================================
#include <boost/python.hpp>
#include <boost/cstdint.hpp>
// Includes ====================================================================
#include <AAFOPDefs.h>
// Using =======================================================================
using namespace boost::python;
// Declarations ================================================================
class OPDef {};
// Module ======================================================================
void Export_pyste_src_AAFOPDefs()
{
scope OPDef_scope = class_<OPDef>("OPDef");
OPDef_scope.attr("Unconstrained") = kAAFOPDef_Unconstrained;
OPDef_scope.attr("EditProtocol") = kAAFOPDef_EditProtocol;
}
|
HzjNeverStop/sofa-common-tools
|
src/main/java/com/alipay/sofa/common/thread/TimeWaitRejectedExecutionHandler.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.alipay.sofa.common.thread;
import com.alipay.sofa.common.thread.log.ThreadLogger;
import com.alipay.sofa.common.utils.TimeWaitRunner;
import java.util.Map;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author zhaowang
* @version : SofaRejectedExecutionHandler.java, v 0.1 2020年08月20日 8:05 下午 zhaowang Exp $
*/
public class TimeWaitRejectedExecutionHandler implements RejectedExecutionHandler {
private RejectedExecutionHandler delegate;
private TimeWaitRunner timeWaitRunner;
private SofaThreadPoolExecutor threadPoolExecutor;
public TimeWaitRejectedExecutionHandler(SofaThreadPoolExecutor executor, long waitTime,
TimeUnit timeUnit) {
this.timeWaitRunner = new TimeWaitRunner(timeUnit.toMillis(waitTime));
this.delegate = executor.getRejectedExecutionHandler();
this.threadPoolExecutor = executor;
}
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
timeWaitRunner.doWithRunnable(this::logStackTrace);
getDelegate().rejectedExecution(r, executor);
}
private void logStackTrace() {
if (threadPoolExecutor != null) {
String threadPoolName = threadPoolExecutor.getConfig().getThreadPoolName();
String allStackTrace = getAllStackTrace(threadPoolExecutor);
ThreadLogger.error(
"Queue of thread pool {} is full with all stack trace: \n {}\n\n",
threadPoolName, allStackTrace);
}
}
private String getAllStackTrace(SofaThreadPoolExecutor threadPoolExecutor) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<ExecutingRunnable, Long> entry : threadPoolExecutor.getStatistics()
.getExecutingTasks().entrySet()) {
for (StackTraceElement e : entry.getKey().thread.getStackTrace()) {
sb.append(" ").append(e).append("\n");
}
}
return sb.toString();
}
public RejectedExecutionHandler getDelegate() {
return delegate;
}
public void setDelegate(RejectedExecutionHandler delegate) {
this.delegate = delegate;
}
public void setTimeWaitRunner(TimeWaitRunner timeWaitRunner) {
this.timeWaitRunner = timeWaitRunner;
}
public void setThreadPoolExecutor(SofaThreadPoolExecutor threadPoolExecutor) {
this.threadPoolExecutor = threadPoolExecutor;
}
}
|
ggustin93/decide-showcase
|
packages/icons/src/line/User.js
|
<gh_stars>1-10
import React from 'react';
export default function User(props) {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width={24} height={24} {...props}>
<path d="M15.71,12.71a6,6,0,1,0-7.42,0,10,10,0,0,0-6.22,8.18,1,1,0,0,0,2,.22,8,8,0,0,1,15.9,0,1,1,0,0,0,1,.89h.11a1,1,0,0,0,.88-1.1A10,10,0,0,0,15.71,12.71ZM12,12a4,4,0,1,1,4-4A4,4,0,0,1,12,12Z" />
</svg>
);
}
|
tonioshikanlu/tubman-hack
|
sources/b/l/a/c/f/e/il.java
|
<gh_stars>1-10
package b.l.a.c.f.e;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import b.l.a.c.b.a;
import java.util.List;
public final class il implements aj {
/* renamed from: h reason: collision with root package name */
public String f3072h;
/* renamed from: i reason: collision with root package name */
public String f3073i;
/* renamed from: j reason: collision with root package name */
public String f3074j;
/* renamed from: k reason: collision with root package name */
public String f3075k;
/* renamed from: l reason: collision with root package name */
public String f3076l;
/* renamed from: m reason: collision with root package name */
public String f3077m;
/* renamed from: n reason: collision with root package name */
public final ql f3078n = new ql((List<String>) null);
/* renamed from: o reason: collision with root package name */
public final ql f3079o = new ql((List<String>) null);
@Nullable
/* renamed from: p reason: collision with root package name */
public String f3080p;
/* JADX WARNING: Can't fix incorrect switch cases order */
/* Code decompiled incorrectly, please refer to instructions dump. */
public final java.lang.String a() {
/*
r11 = this;
org.json.JSONObject r0 = new org.json.JSONObject
r0.<init>()
java.lang.String r1 = "returnSecureToken"
r2 = 1
r0.put(r1, r2)
b.l.a.c.f.e.ql r1 = r11.f3079o
java.util.List<java.lang.String> r1 = r1.f3245i
boolean r1 = r1.isEmpty()
r3 = 0
if (r1 != 0) goto L_0x0035
b.l.a.c.f.e.ql r1 = r11.f3079o
java.util.List<java.lang.String> r1 = r1.f3245i
org.json.JSONArray r4 = new org.json.JSONArray
r4.<init>()
r5 = r3
L_0x0020:
int r6 = r1.size()
if (r5 >= r6) goto L_0x0030
java.lang.Object r6 = r1.get(r5)
r4.put(r6)
int r5 = r5 + 1
goto L_0x0020
L_0x0030:
java.lang.String r1 = "deleteProvider"
r0.put(r1, r4)
L_0x0035:
b.l.a.c.f.e.ql r1 = r11.f3078n
java.util.List<java.lang.String> r1 = r1.f3245i
int r4 = r1.size()
int[] r5 = new int[r4]
r6 = r3
L_0x0040:
int r7 = r1.size()
if (r6 >= r7) goto L_0x0093
java.lang.Object r7 = r1.get(r6)
java.lang.String r7 = (java.lang.String) r7
int r8 = r7.hashCode()
r9 = 3
r10 = 2
switch(r8) {
case -333046776: goto L_0x0074;
case 66081660: goto L_0x006a;
case 1939891618: goto L_0x0060;
case 1999612571: goto L_0x0056;
default: goto L_0x0055;
}
L_0x0055:
goto L_0x007e
L_0x0056:
java.lang.String r8 = "PASSWORD"
boolean r7 = r7.equals(r8)
if (r7 == 0) goto L_0x007e
r7 = r10
goto L_0x007f
L_0x0060:
java.lang.String r8 = "PHOTO_URL"
boolean r7 = r7.equals(r8)
if (r7 == 0) goto L_0x007e
r7 = r9
goto L_0x007f
L_0x006a:
java.lang.String r8 = "EMAIL"
boolean r7 = r7.equals(r8)
if (r7 == 0) goto L_0x007e
r7 = r3
goto L_0x007f
L_0x0074:
java.lang.String r8 = "DISPLAY_NAME"
boolean r7 = r7.equals(r8)
if (r7 == 0) goto L_0x007e
r7 = r2
goto L_0x007f
L_0x007e:
r7 = -1
L_0x007f:
if (r7 == 0) goto L_0x008d
if (r7 == r2) goto L_0x008e
if (r7 == r10) goto L_0x008b
if (r7 == r9) goto L_0x0089
r10 = r3
goto L_0x008e
L_0x0089:
r10 = 4
goto L_0x008e
L_0x008b:
r10 = 5
goto L_0x008e
L_0x008d:
r10 = r2
L_0x008e:
r5[r6] = r10
int r6 = r6 + 1
goto L_0x0040
L_0x0093:
if (r4 <= 0) goto L_0x00a9
org.json.JSONArray r1 = new org.json.JSONArray
r1.<init>()
L_0x009a:
if (r3 >= r4) goto L_0x00a4
r2 = r5[r3]
r1.put(r2)
int r3 = r3 + 1
goto L_0x009a
L_0x00a4:
java.lang.String r2 = "deleteAttribute"
r0.put(r2, r1)
L_0x00a9:
java.lang.String r1 = r11.f3072h
if (r1 == 0) goto L_0x00b2
java.lang.String r2 = "idToken"
r0.put(r2, r1)
L_0x00b2:
java.lang.String r1 = r11.f3074j
if (r1 == 0) goto L_0x00bb
java.lang.String r2 = "email"
r0.put(r2, r1)
L_0x00bb:
java.lang.String r1 = r11.f3075k
if (r1 == 0) goto L_0x00c4
java.lang.String r2 = "password"
r0.put(r2, r1)
L_0x00c4:
java.lang.String r1 = r11.f3073i
if (r1 == 0) goto L_0x00cd
java.lang.String r2 = "displayName"
r0.put(r2, r1)
L_0x00cd:
java.lang.String r1 = r11.f3077m
if (r1 == 0) goto L_0x00d6
java.lang.String r2 = "photoUrl"
r0.put(r2, r1)
L_0x00d6:
java.lang.String r1 = r11.f3076l
if (r1 == 0) goto L_0x00df
java.lang.String r2 = "oobCode"
r0.put(r2, r1)
L_0x00df:
java.lang.String r1 = r11.f3080p
if (r1 == 0) goto L_0x00e8
java.lang.String r2 = "tenantId"
r0.put(r2, r1)
L_0x00e8:
java.lang.String r0 = r0.toString()
return r0
*/
throw new UnsupportedOperationException("Method not decompiled: b.l.a.c.f.e.il.a():java.lang.String");
}
public final boolean b(String str) {
a.x(str);
return this.f3078n.f3245i.contains(str);
}
@NonNull
public final il c(@Nullable String str) {
if (str == null) {
this.f3078n.f3245i.add("EMAIL");
} else {
this.f3074j = str;
}
return this;
}
@NonNull
public final il d(@Nullable String str) {
if (str == null) {
this.f3078n.f3245i.add("PASSWORD");
} else {
this.f3075k = str;
}
return this;
}
}
|
dennling/SLogo
|
src/model/commands/Commands.java
|
package model.commands;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.ResourceBundle;
/**
* @author <NAME>
*
* Uses reflection to build Commands from the keys and values in the
* internationalization resource files. Also handles user defined
* commands.
*/
public class Commands {
private String path = "resources/languages/";
private HashMap<String, String> commandNames = new HashMap<String, String>();
private ResourceBundle myResources;
private String packageRoot = "model.commands.";
private ArrayList<String> packages = new ArrayList<>(
Arrays.asList("control", "logic", "math", "turtle", "multiple", "display"));
public Commands() {
updateLanguage("English");
}
public void updateLanguage(String language) {
myResources = ResourceBundle.getBundle(path + language);
setCommandNames();
}
public void setCommandNames() {
commandNames = new HashMap<String, String>();
Enumeration<String> iter = myResources.getKeys();
while (iter.hasMoreElements()) {
addCommand(iter.nextElement());
}
}
private void addCommand(String string) {
String[] names = myResources.getString(string).split("[|]");
for (String name : names) {
name = name.replace("\\", "");
commandNames.put(name, string);
}
}
public Command get(String input) {
try {
Class<?> c = getClassName(commandNames.get(input.toLowerCase()) + "Command");
Object object = c.getConstructor().newInstance();
return (Command) object;
} catch (Exception e) {
return null;
}
}
private Class<?> getClassName(String input) {
for (String pkg : packages) {
String name = packageRoot + pkg + "." + input;
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
}
}
return null;
}
}
|
nikosnikolaidis/juneau
|
juneau-core/juneau-marshall/src/main/java/org/apache/juneau/internal/Version.java
|
<reponame>nikosnikolaidis/juneau
// ***************************************************************************************************************************
// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
// * with the License. You may obtain a copy of the License at *
// * *
// * http://www.apache.org/licenses/LICENSE-2.0 *
// * *
// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an *
// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the *
// * specific language governing permissions and limitations under the License. *
// ***************************************************************************************************************************
package org.apache.juneau.internal;
import static org.apache.juneau.internal.StringUtils.*;
import java.util.*;
import static java.util.Optional.*;
/**
* Represents a version string such as <js>"1.2"</js> or <js>"1.2.3"</js>
*
* <p>
* Used to compare version numbers.
*/
public class Version implements Comparable<Version> {
public static final boolean NEEDS_TESTING = true;
private int[] parts;
/**
* Convenience creator.
*
* @param value
* A string of the form <js>"#.#..."</js> where there can be any number of parts.
* <br>Valid values:
* <ul>
* <li><js>"1.2"</js>
* <li><js>"1.2.3"</js>
* <li><js>"0.1"</js>
* <li><js>".1"</js>
* </ul>
* <br>Can be <jk>null</jk>.
* @return A new header bean, or <jk>null</jk> if the value is <jk>null</jk>.
*/
public static Version of(String value) {
if (value == null)
return null;
return new Version(value);
}
/**
* Constructor
*
* @param value
* A string of the form <js>"#.#..."</js> where there can be any number of parts.
* <br>Valid values:
* <ul>
* <li><js>"1.2"</js>
* <li><js>"1.2.3"</js>
* <li><js>"0.1"</js>
* <li><js>".1"</js>
* </ul>
* Any parts that are not numeric are interpreted as {@link Integer#MAX_VALUE}
*/
public Version(String value) {
if (isEmpty(value))
value = "0";
String[] sParts = split(value, '.');
parts = new int[sParts.length];
for (int i = 0; i < sParts.length; i++) {
try {
parts[i] = sParts[i].isEmpty() ? 0 : Integer.parseInt(sParts[i]);
} catch (NumberFormatException e) {
parts[i] = Integer.MAX_VALUE;
}
}
}
/**
* Returns the version part at the specified zero-indexed value.
*
* @param index The index of the version part.
* @return The version part, never <jk>null</jk>.
*/
public Optional<Integer> getPart(int index) {
if (parts.length <= index)
return empty();
return ofNullable(parts[index]);
}
/**
* Returns the major version part (i.e. part at index 0).
*
* @return The version part, never <jk>null</jk>.
*/
public Optional<Integer> getMajor() {
return getPart(0);
}
/**
* Returns the minor version part (i.e. part at index 1).
*
* @return The version part, never <jk>null</jk>.
*/
public Optional<Integer> getMinor() {
return getPart(1);
}
/**
* Returns the maintenance version part (i.e. part at index 2).
*
* @return The version part, never <jk>null</jk>.
*/
public Optional<Integer> getMaintenance() {
return getPart(2);
}
/**
* Returns <jk>true</jk> if the specified version is at least this version.
*
* <p>
* Note that the following is true:
* <p class='bcode w800'>
* boolean b;
* b = <jk>new</jk> Version(<js>"1.2"</js>).isAtLeast(<jk>new</jk> Version(<js>"1.2.3"</js>)); <jc>// == true </jc>
* b = <jk>new</jk> Version(<js>"1.2.0"</js>).isAtLeast(<jk>new</jk> Version(<js>"1.2.3"</js>)); <jc>// == false</jc>
* </p>
*
* @param v The version to compare to.
* @param exclusive Match down-to-version but not including.
* @return <jk>true</jk> if the specified version is at least this version.
*/
public boolean isAtLeast(Version v, boolean exclusive) {
for (int i = 0; i < Math.min(parts.length, v.parts.length); i++) {
int c = v.parts[i] - parts[i];
if (c > 0)
return false;
else if (c < 0)
return true;
}
for (int i = parts.length; i < v.parts.length; i++)
if (v.parts[i] != 0)
return false;
return ! exclusive;
}
/**
* Returns <jk>true</jk> if the specified version is at most this version.
*
* <p>
* Note that the following is true:
* <p class='bcode w800'>
* boolean b;
* b = <jk>new</jk> Version(<js>"1.2.3"</js>).isAtMost(<jk>new</jk> Version(<js>"1.2"</js>)); <jc>// == true </jc>
* b = <jk>new</jk> Version(<js>"1.2.3"</js>).isAtMost(<jk>new</jk> Version(<js>"1.2.0"</js>)); <jc>// == false</jc>
* </p>
*
* @param v The version to compare to.
* @param exclusive Match up-to-version but not including.
* @return <jk>true</jk> if the specified version is at most this version.
*/
public boolean isAtMost(Version v, boolean exclusive) {
for (int i = 0; i < Math.min(parts.length, v.parts.length); i++) {
int c = parts[i] - v.parts[i];
if (c > 0)
return false;
else if (c < 0)
return true;
}
for (int i = parts.length; i < v.parts.length; i++)
if (v.parts[i] > 0)
return false;
return ! exclusive;
}
/**
* Returns <jk>true</jk> if the specified version is equal to this version.
*
* <p>
* Note that the following is true:
* <p class='bcode w800'>
* boolean b;
* b = <jk>new</jk> Version(<js>"1.2.3"</js>).equals(<jk>new</jk> Version(<js>"1.2"</js>)); <jc>// == true </jc>
* b = <jk>new</jk> Version(<js>"1.2"</js>).equals(<jk>new</jk> Version(<js>"1.2.3"</js>)); <jc>// == true</jc>
* </p>
*
* @param v The version to compare to.
* @return <jk>true</jk> if the specified version is equal to this version.
*/
public boolean isEqualsTo(Version v) {
for (int i = 0; i < Math.min(parts.length, v.parts.length); i++)
if (v.parts[i] - parts[i] != 0)
return false;
return true;
}
@Override /* Object */
public String toString() {
return join(parts, '.');
}
@Override
public int compareTo(Version v) {
for (int i = 0; i < Math.min(parts.length, v.parts.length); i++) {
int c = parts[i] - v.parts[i];
if (c != 0)
return c;
}
for (int i = parts.length; i < v.parts.length; i++)
if (v.parts[i] > 0)
return 1;
return 0;
}
}
|
ideas-edu/AskElleWeb
|
app/controller/Exercises.js
|
<filename>app/controller/Exercises.js
Ext.require('Ext.app.Controller');
Ext.define
( 'FPT.controller.Exercises'
, { extend: 'Ext.app.Controller'
, views: ['exercises.List']
, stores: ['Exercises']
, controllers: ['Tutor']
, refs:
[ { selector: 'exerciselist'
, ref: 'exerciseList'
}
, { selector: '#fptutor'
, ref: 'fptPanel'
}
, { selector: 'tutor'
, ref: 'tutorPanel'
}
]
, init: function()
{
this.control({
'exerciselist': {
itemclick: this.loadExercise
}
});
}
, loadExercise : function(tree, item) {
if (item.phantom) return;
this.getController('Tutor').loadExercise(item.data.id, item.data.description, item.data.name);
this.getExerciseList().collapse();
// this.getTutorPanel().doLayout();
// this.getFptPanel().doLayout();
}
, loadAllExercises: function () {
this.getStore("Exercises").loadExerciseList();
this.getExerciseList().setTitle("All Exercises");
}
, loadExerciseGroup: function (groupid) {
this.getStore("Exercises").loadExerciseGroup(groupid);
this.getExerciseList().setTitle("Group: " + groupid);
}
}
);
|
npocmaka/Windows-Server-2003
|
multimedia/dshow/filters.ks/wdmcap/camera.h
|
<reponame>npocmaka/Windows-Server-2003
/*++
Copyright (C) Microsoft Corporation, 1996 - 1997
Module Name:
camera.h
Abstract:
Internal header.
--*/
class CCameraControlInterfaceHandler :
public CUnknown,
public IAMCameraControl {
public:
DECLARE_IUNKNOWN;
static CUnknown* CALLBACK CreateInstance(
LPUNKNOWN UnkOuter,
HRESULT* hr);
CCameraControlInterfaceHandler(
LPUNKNOWN UnkOuter,
TCHAR* Name,
HRESULT* hr);
STDMETHODIMP NonDelegatingQueryInterface(
REFIID riid,
PVOID* ppv);
// Implement IAMCameraControl
STDMETHODIMP GetRange(
IN long Property,
OUT long *pMin,
OUT long *pMax,
OUT long *pSteppingDelta,
OUT long *pDefault,
OUT long *pCapsFlags);
STDMETHODIMP Set(
IN long Property,
IN long lValue,
IN long Flags);
STDMETHODIMP Get(
IN long Property,
OUT long *lValue,
OUT long *lFlags);
private:
HANDLE m_ObjectHandle;
};
typedef struct {
KSPROPERTY_DESCRIPTION PropertyDescription;
KSPROPERTY_MEMBERSHEADER MembersHeader;
KSPROPERTY_STEPPING_LONG SteppingLong;
} CAMERACONTROL_MEMBERSLIST;
typedef struct {
KSPROPERTY_DESCRIPTION PropertyDescription;
KSPROPERTY_MEMBERSHEADER MembersHeader;
ULONG DefaultValue;
} CAMERACONTROL_DEFAULTLIST;
|
kaist-plrg/jest
|
src/main/scala/kr/ac/kaist/jest/model/algorithm/ArrayBindingPattern2ContainsExpression3.scala
|
package kr.ac.kaist.jest.model
import kr.ac.kaist.jest.ir._
import kr.ac.kaist.jest.ir.Parser._
object ArrayBindingPattern2ContainsExpression3 extends Algorithm {
val name: String = "ArrayBindingPattern2ContainsExpression3"
val length: Int = 0
val lang: Boolean = true
val func: Func = FixUIdWalker(parseFunc(""""ArrayBindingPattern2ContainsExpression3" (this, BindingElementList, Elision, BindingRestElement) => {
access __x0__ = (BindingElementList "ContainsExpression")
let has = __x0__
if (= has true) return true else {}
access __x1__ = (BindingRestElement "ContainsExpression")
return __x1__
}"""), this)
}
|
origami-build/origami
|
task-dispatcher/src/main/java/net/dblsaiko/origami/taskdispatcher/protocol/Unit.java
|
<reponame>origami-build/origami<filename>task-dispatcher/src/main/java/net/dblsaiko/origami/taskdispatcher/protocol/Unit.java
package net.dblsaiko.origami.taskdispatcher.protocol;
public enum Unit implements BinSerialize {
INSTANCE;
@Override
public String toString() {
return "Unit";
}
@Override
public void serialize(BinSerializer serializer) {
// serializes to nothing
}
public static Unit deserialize(BinDeserializer deserializer) {
return Unit.INSTANCE;
}
}
|
junglegodlion/project-ct
|
ct-web/src/main/java/com/jungle/ct/web/bean/Calllog.java
|
package com.jungle.ct.web.bean;
public class Calllog {
private Integer id;
private Integer telid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getTelid() {
return telid;
}
public void setTelid(Integer telid) {
this.telid = telid;
}
public Integer getDateid() {
return dateid;
}
public void setDateid(Integer dateid) {
this.dateid = dateid;
}
public Integer getSumcall() {
return sumcall;
}
public void setSumcall(Integer sumcall) {
this.sumcall = sumcall;
}
public Integer getSumduration() {
return sumduration;
}
public void setSumduration(Integer sumduration) {
this.sumduration = sumduration;
}
private Integer dateid;
private Integer sumcall;
private Integer sumduration;
}
|
myvyang/intellij-community
|
python/testSrc/com/jetbrains/python/PyOptimizeImportsTest.java
|
<filename>python/testSrc/com/jetbrains/python/PyOptimizeImportsTest.java
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.jetbrains.python;
import com.intellij.codeInsight.actions.OptimizeImportsAction;
import com.intellij.ide.DataManager;
import com.jetbrains.python.fixtures.PyTestCase;
/**
* @author yole
*/
public class PyOptimizeImportsTest extends PyTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
// importsFromTypingUnusedInTypeComments depends on registered TokenSetContributors
PythonDialectsTokenSetProvider.reset();
}
public void testSimple() {
doTest();
}
public void testOneOfMultiple() {
doTest();
}
public void testImportStar() {
doTest();
}
public void testImportStarOneOfMultiple() {
doTest();
}
public void testTryExcept() {
doTest();
}
public void testFromFuture() {
doTest();
}
public void testUnresolved() { // PY-2201
doTest();
}
public void testSuppressed() { // PY-5228
doTest();
}
public void testSplit() {
doTest();
}
public void testOrderByType() {
doTest();
}
// PY-12018
public void testAlphabeticalOrder() {
doTest();
}
public void testInsertBlankLines() { // PY-8355
doTest();
}
// PY-16351
public void testNoExtraBlankLineAfterImportBlock() {
final String testName = getTestName(true);
myFixture.copyDirectoryToProject(testName, "");
myFixture.configureByFile("main.py");
OptimizeImportsAction.actionPerformedImpl(DataManager.getInstance().getDataContext(myFixture.getEditor().getContentComponent()));
myFixture.checkResultByFile(testName + "/main.after.py");
}
// PY-18521
public void testImportsFromTypingUnusedInTypeComments() {
myFixture.copyDirectoryToProject("../typing", "");
doTest();
}
private void doTest() {
myFixture.configureByFile(getTestName(true) + ".py");
OptimizeImportsAction.actionPerformedImpl(DataManager.getInstance().getDataContext(myFixture.getEditor().getContentComponent()));
myFixture.checkResultByFile(getTestName(true) + ".after.py");
}
@Override
protected String getTestDataPath() {
return super.getTestDataPath() + "/optimizeImports";
}
}
|
detnavillus/modular-informatic-designs
|
search-core/src/main/java/com/modinfodesigns/search/IQueryTreeParser.java
|
<gh_stars>1-10
package com.modinfodesigns.search;
/**
* Creates an QueryTree from a query String.
*
* @author <NAME>
*/
public interface IQueryTreeParser extends IQueryParser
{
public QueryTree createQueryTree( String queryTreeName, String queryString );
}
|
matbrewer396/screeps-kotlin
|
node_modules/@screeps/engine/dist/processor/global-intents/power/suicidePowerCreep.js
|
'use strict';
var q = require('q'),
_ = require('lodash'),
utils = require('../../../utils'),
driver = utils.getDriver(),
C = driver.constants;
module.exports = function (intent, user, scope) {
const roomObjectsByType = scope.roomObjectsByType;
var powerCreep = _.find(roomObjectsByType.powerCreep, i => i.user == user._id && i._id == intent.id);
if (!powerCreep) {
return;
}
require('./_diePowerCreep')(powerCreep, scope);
};
//# sourceMappingURL=../../../sourcemaps/processor/global-intents/power/suicidePowerCreep.js.map
|
vberegov/blackduck-artifactory
|
blackduck-artifactory-common/src/main/java/com/synopsys/integration/blackduck/artifactory/modules/inspection/externalid/ArtifactoryInfoExternalIdExtractor.java
|
<gh_stars>1-10
/*
* blackduck-artifactory-common
*
* Copyright (c) 2021 Synopsys, Inc.
*
* Use subject to the terms and conditions of the Synopsys End User Software License and Maintenance Agreement. All rights reserved worldwide.
*/
package com.synopsys.integration.blackduck.artifactory.modules.inspection.externalid;
import java.util.Optional;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.artifactory.fs.FileLayoutInfo;
import org.artifactory.md.Properties;
import org.artifactory.repo.RepoPath;
import com.synopsys.integration.bdio.model.Forge;
import com.synopsys.integration.bdio.model.externalid.ExternalId;
import com.synopsys.integration.bdio.model.externalid.ExternalIdFactory;
import com.synopsys.integration.blackduck.artifactory.ArtifactoryPAPIService;
import com.synopsys.integration.blackduck.artifactory.modules.inspection.model.SupportedPackageType;
public class ArtifactoryInfoExternalIdExtractor implements ExternalIdExtactor {
private final ArtifactoryPAPIService artifactoryPAPIService;
private final ExternalIdFactory externalIdFactory;
public ArtifactoryInfoExternalIdExtractor(ArtifactoryPAPIService artifactoryPAPIService, ExternalIdFactory externalIdFactory) {
this.artifactoryPAPIService = artifactoryPAPIService;
this.externalIdFactory = externalIdFactory;
}
@Override
public Optional<ExternalId> extractExternalId(SupportedPackageType supportedPackageType, RepoPath repoPath) {
ExternalId externalId = extractExternalIdFromProperties(supportedPackageType, repoPath).orElse(null);
if (externalId == null) {
externalId = extractExternalIdFromFileLayoutInfo(supportedPackageType, repoPath).orElse(null);
}
return Optional.ofNullable(externalId);
}
private Optional<ExternalId> extractExternalIdFromProperties(SupportedPackageType supportedPackageType, RepoPath repoPath) {
Properties properties = artifactoryPAPIService.getProperties(repoPath);
Forge forge = supportedPackageType.getForge();
String namePropertyKey = supportedPackageType.getArtifactoryNameProperty();
String versionPropertyKey = supportedPackageType.getArtifactoryVersionProperty();
if (namePropertyKey == null || versionPropertyKey == null) {
return Optional.empty();
}
String name = properties.getFirst(namePropertyKey);
String version = properties.getFirst(versionPropertyKey);
return createNameVersionExternalId(externalIdFactory, forge, name, version);
}
private Optional<ExternalId> extractExternalIdFromFileLayoutInfo(SupportedPackageType supportedPackageType, RepoPath repoPath) {
FileLayoutInfo fileLayoutInfo = artifactoryPAPIService.getLayoutInfo(repoPath);
ExternalId externalId;
if (supportedPackageType.hasNameVersionProperties()) {
externalId = createNameVersionExternalIdFromFileLayoutInfo(supportedPackageType.getForge(), fileLayoutInfo).orElse(null);
} else {
externalId = createMavenExternalId(fileLayoutInfo).orElse(null);
}
return Optional.ofNullable(externalId);
}
private Optional<ExternalId> createNameVersionExternalIdFromFileLayoutInfo(Forge forge, FileLayoutInfo fileLayoutInfo) {
String name = fileLayoutInfo.getModule();
String version = fileLayoutInfo.getBaseRevision();
return createNameVersionExternalId(externalIdFactory, forge, name, version);
}
private Optional<ExternalId> createMavenExternalId(FileLayoutInfo fileLayoutInfo) {
ExternalId externalId = null;
String group = fileLayoutInfo.getOrganization();
String name = fileLayoutInfo.getModule();
String version = fileLayoutInfo.getBaseRevision();
if (StringUtils.isNoneBlank(group, name, version)) {
externalId = externalIdFactory.createMavenExternalId(group, name, version);
}
return Optional.ofNullable(externalId);
}
private Optional<ExternalId> createNameVersionExternalId(ExternalIdFactory externalIdFactory, Forge forge, @Nullable String name, @Nullable String version) {
ExternalId externalId = null;
if (StringUtils.isNoneBlank(name, version)) {
externalId = externalIdFactory.createNameVersionExternalId(forge, name, version);
}
return Optional.ofNullable(externalId);
}
}
|
sercxtyf/onboard
|
kernel/com.onboard.domain.mapper.model/src/main/java/com/onboard/domain/mapper/model/DiscussionObject.java
|
/*******************************************************************************
* Copyright [2015] [Onboard team of SERC, Peking University]
*
* 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.onboard.domain.mapper.model;
import com.onboard.domain.mapper.model.common.BaseItem;
import java.util.Date;
public class DiscussionObject implements BaseItem {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column discussion.id
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column discussion.projectId
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
private Integer projectId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column discussion.subject
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
private String subject;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column discussion.content
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
private String content;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column discussion.creatorId
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
private Integer creatorId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column discussion.deleted
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
private Boolean deleted;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column discussion.created
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
private Date created;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column discussion.updated
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
private Date updated;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column discussion.bcId
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
private Integer bcId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column discussion.creatorName
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
private String creatorName;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column discussion.companyId
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
private Integer companyId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column discussion.creatorAvatar
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
private String creatorAvatar;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column discussion.id
*
* @return the value of discussion.id
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column discussion.id
*
* @param id the value for discussion.id
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column discussion.projectId
*
* @return the value of discussion.projectId
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public Integer getProjectId() {
return projectId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column discussion.projectId
*
* @param projectId the value for discussion.projectId
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public void setProjectId(Integer projectId) {
this.projectId = projectId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column discussion.subject
*
* @return the value of discussion.subject
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public String getSubject() {
return subject;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column discussion.subject
*
* @param subject the value for discussion.subject
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public void setSubject(String subject) {
this.subject = subject == null ? null : subject.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column discussion.content
*
* @return the value of discussion.content
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public String getContent() {
return content;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column discussion.content
*
* @param content the value for discussion.content
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public void setContent(String content) {
this.content = content == null ? null : content.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column discussion.creatorId
*
* @return the value of discussion.creatorId
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public Integer getCreatorId() {
return creatorId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column discussion.creatorId
*
* @param creatorId the value for discussion.creatorId
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public void setCreatorId(Integer creatorId) {
this.creatorId = creatorId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column discussion.deleted
*
* @return the value of discussion.deleted
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public Boolean getDeleted() {
return deleted;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column discussion.deleted
*
* @param deleted the value for discussion.deleted
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column discussion.created
*
* @return the value of discussion.created
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public Date getCreated() {
return created;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column discussion.created
*
* @param created the value for discussion.created
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public void setCreated(Date created) {
this.created = created;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column discussion.updated
*
* @return the value of discussion.updated
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public Date getUpdated() {
return updated;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column discussion.updated
*
* @param updated the value for discussion.updated
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public void setUpdated(Date updated) {
this.updated = updated;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column discussion.bcId
*
* @return the value of discussion.bcId
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public Integer getBcId() {
return bcId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column discussion.bcId
*
* @param bcId the value for discussion.bcId
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public void setBcId(Integer bcId) {
this.bcId = bcId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column discussion.creatorName
*
* @return the value of discussion.creatorName
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public String getCreatorName() {
return creatorName;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column discussion.creatorName
*
* @param creatorName the value for discussion.creatorName
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public void setCreatorName(String creatorName) {
this.creatorName = creatorName == null ? null : creatorName.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column discussion.companyId
*
* @return the value of discussion.companyId
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public Integer getCompanyId() {
return companyId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column discussion.companyId
*
* @param companyId the value for discussion.companyId
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public void setCompanyId(Integer companyId) {
this.companyId = companyId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column discussion.creatorAvatar
*
* @return the value of discussion.creatorAvatar
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public String getCreatorAvatar() {
return creatorAvatar;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column discussion.creatorAvatar
*
* @param creatorAvatar the value for discussion.creatorAvatar
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public void setCreatorAvatar(String creatorAvatar) {
this.creatorAvatar = creatorAvatar == null ? null : creatorAvatar.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table discussion
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public DiscussionObject(DiscussionObject parent) {
this.id = parent.getId();
this.projectId = parent.getProjectId();
this.subject = parent.getSubject();
this.content = parent.getContent();
this.creatorId = parent.getCreatorId();
this.deleted = parent.getDeleted();
this.created = parent.getCreated();
this.updated = parent.getUpdated();
this.bcId = parent.getBcId();
this.creatorName = parent.getCreatorName();
this.companyId = parent.getCompanyId();
this.creatorAvatar = parent.getCreatorAvatar();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table discussion
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public DiscussionObject() {
super();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table discussion
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public DiscussionObject(int id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table discussion
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public DiscussionObject(boolean deleted) {
this.deleted = deleted;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table discussion
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
public DiscussionObject(int id, boolean deleted) {
this.id = id;
this.deleted = deleted;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table discussion
*
* @mbggenerated Wed Aug 26 19:51:19 CST 2015
*/
@Override
public DiscussionObject copy() {
return new DiscussionObject(this);
}
}
|
rsnakamura/oldape
|
apetools/lexicographers/parametertree.py
|
# python standard library
from collections import namedtuple
Parameters = namedtuple("Parameters", "name parameters".split())
class TreeNode(object):
"""
A Class to represent a node in a tree with arbitrary number of children
"""
def __init__(self, cargo, children=None):
"""
:param:
- `cargo`: the data for this node
- `children`: a list of TreeNodes
"""
self.cargo = cargo
self.children = children
return
def __str__(self):
return str(self.cargo)
# end class TreeNode
class ParameterTree(object):
"""
A class to build a tree from iterative parameters
The main product is the `paths` attribute which can be iterated over to get the parameters for a test.
"""
def __init__(self, parameters):
"""
:param:
- `parameters`: list of parameter objects with a `name` property
"""
self.parameters = parameters
self._tree = None
self._paths = None
return
@property
def tree(self):
"""
builds the tree bottoms-up from the parameters
:return: list of trees (highest nodes are parameters[0], leaves are parameters[-1])
"""
if self._tree is None:
# parameters is a list of Parameter(name,parameters) namedtuples
parameters = self.parameters[:]
leaves = parameters.pop()
parameters.reverse()
tree = [TreeNode(Parameters(leaves.name, leaf)) for leaf in leaves.parameters]
for level in parameters:
# level is a Parameters(name, parameters) namedtuple
new_tree = [TreeNode(Parameters(name=level.name, parameters=sibling), tree) for sibling in level.parameters]
tree = new_tree
self._tree = tree
return self._tree
@property
def paths(self):
"""
:return: list of namedtuples
"""
if self._paths is None:
# create the paths with a series of tree-traversals
self._paths = []
for limb in self.tree:
path = {}
self._traverse(limb, path, self._paths)
# convert self._paths from dicts to namedtuples
paths = []
for path in self._paths:
Paths = namedtuple("Paths", ["total_count"] + path.keys())
fields = dict([(f,path[f]) for f in Paths._fields if f != "total_count"])
fields["total_count"] = len(self._paths)
paths.append(Paths(**fields))
self._paths = paths
return self._paths
def _traverse(self, tree, path, paths):
"""
A depth-first traversal
:param:
- `tree`: A Tree object to traverse
- `path`: a name:parameter dict to contain a particular path
- `paths`: The list to store all the paths
:postcondition:
- path holds tree's cargo
- if tree is a leaf, return path
- if tree not leaf traverse children and traverse each child
- append path returned by leaf to self._paths
"""
path[tree.cargo.name] = tree.cargo
if tree.children is None:
paths.append(path)
return
for child in tree.children:
new_path = path.copy()
self._traverse(child, new_path, paths)
return
# end class Parameter_Tree
|
Alissonrgs/Scumblr
|
test/tasks/vulnerability_helper_test.rb
|
require "test_helper"
class VulnerabilityHelperTest < ActiveSupport::TestCase
test "Check for duplicate vulnerabilities which have complex query, should pass" do
require_relative "#{Rails.root.join('lib', 'helpers', 'vulnerability_helpers')}"
# The params and values are in a differnet order, but this should still result in a duplicate
result = Result.find(4)
vuln = Vulnerability.new
vuln.url = "https://www.netflix.com/bar/whatever?things=salsjklfasj&bar=<scrssfipt>alert()</script>&stuff=salkfsaafsafdskjfs"
vuln.type = "Reflected XSS"
result.update_vulnerabilities([vuln])
# With a differenet param, it should create a new result
assert_equal(3, result.metadata["vulnerabilities"].count)
vuln2 = Vulnerability.new
vuln2.url = "https://www.netflix.com/bar/whatever?new_param=salkafdskjfs&things=salsjklfasj&bar=<script>alert()</script>"
vuln2.type = "Reflected XSS"
result.update_vulnerabilities([vuln2])
assert_equal(4, result.metadata["vulnerabilities"].count)
end
end
# detectify
# we shoudl expec ton-call to be a bit busy
|
mcieslak94/pruefungsanerkennung
|
src/react/Components/globals/module.edit.footer.js
|
import React, { Component } from 'react'
import { ButtonToggle } from 'reactstrap'
import '../../styles/main.css'
class ModuleEditFooter extends Component {
render = () => {
return <div className='module-edit-footer'>
{!this.props.editActive && <ButtonToggle color="primary" onClick={this.props.toggle}
disabled = {(this.props.editActive)? true : false}>
Bearbeiten
</ButtonToggle >}
{this.props.editActive && <ButtonToggle color="success" onClick={this.props.onSave}
disabled = {(!this.props.editActive)? true : false}>
Übernehmen
</ButtonToggle>} {' '}
{this.props.editActive && <ButtonToggle color="danger" onClick={this.props.toggle}
disabled = {(!this.props.editActive)? true : false}>
Abbrechen
</ButtonToggle>}
</div>
}
}
export default ModuleEditFooter
|
shsmysore/connectors-workspace-one
|
connectors/chatbot-servicenow/src/main/java/com/vmware/connectors/servicenow/domain/snow/TaskResults.java
|
<filename>connectors/chatbot-servicenow/src/main/java/com/vmware/connectors/servicenow/domain/snow/TaskResults.java
/*
* Copyright © 2019 VMware, Inc. All Rights Reserved.
* SPDX-License-Identifier: BSD-2-Clause
*/
package com.vmware.connectors.servicenow.domain.snow;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
public class TaskResults {
private final List<Task> result;
public TaskResults(@JsonProperty("result") List<Task> result) {
this.result = result;
}
@JsonProperty("result")
public List<Task> getResult() {
return result;
}
}
|
gidmoth/freeswitch-image-builder
|
freeswitch/libs/freetdm/src/ftdm_dso.c
|
<gh_stars>0
/*
* Cross Platform dso/dll load abstraction
* Copyright(C) 2008 <NAME>
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so.
*
* This work is provided under this license on an "as is" basis, without warranty of any kind,
* either expressed or implied, including, without limitation, warranties that the covered code
* is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire
* risk as to the quality and performance of the covered code is with you. Should any covered
* code prove defective in any respect, you (not the initial developer or any other contributor)
* assume the cost of any necessary servicing, repair or correction. This disclaimer of warranty
* constitutes an essential part of this license. No use of any covered code is authorized hereunder
* except under this disclaimer.
*
*/
#include "private/ftdm_core.h"
#include "ftdm_dso.h"
#include <stdlib.h>
#include <string.h>
#ifdef WIN32
#include <windows.h>
#include <stdio.h>
FT_DECLARE(ftdm_status_t) ftdm_dso_destroy(ftdm_dso_lib_t *lib) {
if (lib && *lib) {
FreeLibrary(*lib);
*lib = NULL;
}
return FTDM_SUCCESS;
}
FT_DECLARE(ftdm_dso_lib_t) ftdm_dso_open(const char *path, char **err) {
HINSTANCE lib;
lib = LoadLibraryEx(path, NULL, 0);
if (!lib) {
LoadLibraryEx(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
}
if (!lib) {
DWORD error = GetLastError();
char tmp[80];
sprintf(tmp, "dll open error [%ul]\n", error);
*err = ftdm_strdup(tmp);
}
return lib;
}
FT_DECLARE(void*) ftdm_dso_func_sym(ftdm_dso_lib_t lib, const char *sym, char **err) {
FARPROC func = GetProcAddress(lib, sym);
if (!func) {
DWORD error = GetLastError();
char tmp[80];
sprintf(tmp, "dll sym error [%ul]\n", error);
*err = ftdm_strdup(tmp);
}
return (void *)(intptr_t)func; // this should really be addr - ftdm_dso_func_data
}
#else
/*
** {========================================================================
** This is an implementation of loadlib based on the dlfcn interface.
** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
** as an emulation layer on top of native functions.
** =========================================================================
*/
#include <dlfcn.h>
FT_DECLARE(ftdm_status_t) ftdm_dso_destroy(ftdm_dso_lib_t *lib) {
int rc;
if (lib && *lib) {
rc = dlclose(*lib);
if (rc) {
ftdm_log(FTDM_LOG_ERROR, "Failed to close lib %p: %s\n", *lib, dlerror());
return FTDM_FAIL;
}
ftdm_log(FTDM_LOG_DEBUG, "lib %p was closed with success\n", *lib);
*lib = NULL;
return FTDM_SUCCESS;
}
ftdm_log(FTDM_LOG_ERROR, "Invalid pointer provided to ftdm_dso_destroy\n");
return FTDM_FAIL;
}
FT_DECLARE(ftdm_dso_lib_t) ftdm_dso_open(const char *path, char **err) {
void *lib = dlopen(path, RTLD_NOW | RTLD_LOCAL);
if (lib == NULL) {
*err = ftdm_strdup(dlerror());
}
return lib;
}
FT_DECLARE(void *) ftdm_dso_func_sym(ftdm_dso_lib_t lib, const char *sym, char **err) {
void *func = dlsym(lib, sym);
if (!func) {
*err = ftdm_strdup(dlerror());
}
return func;
}
#endif
/* }====================================================== */
/* For Emacs:
* Local Variables:
* mode:c
* indent-tabs-mode:t
* tab-width:4
* c-basic-offset:4
* End:
* For VIM:
* vim:set softtabstop=4 shiftwidth=4 tabstop=4 noet:
*/
|
haferflocken/ConductorEngine
|
Conductor/behave/Blackboard.h
|
#pragma once
#include <behave/ast/ExpressionResultType.h>
#include <collection/VectorMap.h>
#include <util/StringHash.h>
namespace Behave
{
/**
* A blackboard is a dictionary for data of several types, and is used to allow behaviour nodes to communicate.
*/
class Blackboard
{
public:
Blackboard() = default;
void GetWithDefault(const Util::StringHash& key, const AST::ExpressionResult& defaultValue,
AST::ExpressionResult& out) const;
bool TryRemove(const Util::StringHash& key);
void Set(const Util::StringHash& key, const AST::ExpressionResult& value);
const Collection::VectorMap<Util::StringHash, AST::ExpressionResult>& GetMap() const;
private:
// A lookup of keys to values in the blackboard.
Collection::VectorMap<Util::StringHash, AST::ExpressionResult> m_map;
};
}
// Inline implementations.
namespace Behave
{
inline const Collection::VectorMap<Util::StringHash, AST::ExpressionResult>& Blackboard::GetMap() const
{
return m_map;
}
}
|
ksilin/kfkstreams
|
src/main/scala/com/example/FavoriteColorCounts.scala
|
<gh_stars>0
package com.example
import com.lightbend.kafka.scala.streams.{ KGroupedTableS, KStreamS, KTableS, StreamsBuilderS }
import org.apache.kafka.common.serialization.{ Serde, Serdes }
import org.apache.kafka.streams.kstream.Produced
object FavoriteColorCounts {
val longSerde: Serde[Long] = Serdes.Long().asInstanceOf[Serde[Long]]
val legalColors = Set("red", "blue")
val produced: Produced[String, Long] =
Produced.`with`(Serdes.String(), longSerde)
// TODO - this topology correctly increases the values but does not decrease them as required, e.g.
// x:red, y:blue => red:1 | blue:1
// y: red => red:2 | but no blue:0 as would be correct
// topology2 works correctly
def createTopology(sourceTopic: String, targetTopic: String): StreamsBuilderS = {
println(s"creating builder for $sourceTopic / $targetTopic")
val builder: StreamsBuilderS = new StreamsBuilderS
val msgs = builder.stream[String, String](sourceTopic)
msgs
.filter((_, v) => v.contains(","))
.selectKey[String]((_, v) => v.split(",")(0).toLowerCase)
.mapValues[String]((value: String) => value.split(",")(1).toLowerCase)
.filter((_, v) => legalColors.contains(v))
.selectKey((_, v) => v)
.groupByKey()
.count("byColors")
.toStream
.to(targetTopic, produced)
builder
}
def createTopologyPeek(sourceTopic: String, targetTopic: String): StreamsBuilderS = {
println(s"creating builder for $sourceTopic / $targetTopic")
val builder: StreamsBuilderS = new StreamsBuilderS
val msgs = builder.stream[String, String](sourceTopic)
msgs
.peek((k, v) => println(s"received $k:$v"))
.filter((_, v) => v.contains(","))
.selectKey[String]((_, v) => v.split(",")(0).toLowerCase)
.mapValues[String](
(value: String) => value.split(",").tail.headOption.map(_.toLowerCase).orNull
)
.filter((_, v) => legalColors.contains(v) || v == null)
.peek((k, v) => println(s"filtered $k:$v"))
.selectKey((_, v) => v)
.peek((k, v) => println(s"selected $k:$v"))
.groupByKey()
.count("byColors")
.toStream
.peek((k, v) => s"writing out: $k:$v ") // the data gets written, but 'peek' does not print anything
.to(targetTopic, produced)
builder
}
def createTopology2(sourceTopic: String,
targetTopic: String,
intermediaryTopic: String): StreamsBuilderS = {
println(s"creating builder for $sourceTopic / $targetTopic")
val builder: StreamsBuilderS = new StreamsBuilderS
val msgs: KStreamS[String, String] = builder.stream[String, String](sourceTopic)
val usersAndColours: KStreamS[String, String] = msgs
// 1 - we ensure that a comma is here as we will split on it
.filter((key: String, value: String) => value.contains(","))
// 2 - we select a key that will be the user id (lowercase for safety)
.selectKey[String]((key: String, value: String) => value.split(",")(0).toLowerCase)
// 3 - we get the colour from the value (lowercase for safety)
.mapValues[String]((value: String) => value.split(",")(1).toLowerCase)
// 4 - we filter undesired colours (could be a data sanitization step)
.filter((_: String, colour: String) => List("green", "blue", "red").contains(colour))
usersAndColours.to(intermediaryTopic)
val usersAndColoursTable: KTableS[String, String] = builder.table(intermediaryTopic)
// step 3 - we count the occurences of colours
val favouriteColours1: KGroupedTableS[String, String] =
usersAndColoursTable.groupBy((user: String, colour: String) => (colour, colour))
val favouriteColours = favouriteColours1.count()
// 6 - we output the results to a Kafka Topic - don't forget the serializers
favouriteColours.toStream
.peek((k, v) => println(s"writing out: $k:$v "))
.to(targetTopic, produced)
builder
}
def createTopology3(sourceTopic: String,
targetTopic: String,
intermediaryTopic: String): StreamsBuilderS = {
println(s"creating builder for $sourceTopic / $targetTopic")
val builder: StreamsBuilderS = new StreamsBuilderS
val msgs: KStreamS[String, String] = builder.stream[String, String](sourceTopic)
val usersAndColours: KStreamS[String, String] = msgs
// 1 - we ensure that a comma is here as we will split on it
.filter((key: String, value: String) => value.contains(","))
// 2 - we select a key that will be the user id (lowercase for safety)
.selectKey[String]((key: String, value: String) => value.split(",")(0).toLowerCase)
// 3 - we get the colour from the value (lowercase for safety)
.mapValues[String]((value: String) => value.split(",")(1).toLowerCase)
// 4 - we filter undesired colours (could be a data sanitization step)
.filter((user: String, colour: String) => List("green", "blue", "red").contains(colour))
usersAndColours.to(intermediaryTopic)
val usersAndColoursTable: KTableS[String, String] = builder.table(intermediaryTopic)
// step 3 - we count the occurences of colours
// val favouriteColours1: KGroupedTableS[String, String] =
// usersAndColoursTable.groupBy((user: String, colour: String) => (colour, colour))
// val favouriteColours = favouriteColours1.count()
// 6 - we output the results to a Kafka Topic - don't forget the serializers
val produced2: Produced[String, String] =
Produced.`with`(Serdes.String(), Serdes.String())
usersAndColoursTable
.mapValues(identity)
.toStream
.peek((k, v) => println(s"writing out: $k:$v "))
.to(targetTopic, produced2)
builder
}
}
|
zetc0de/dotfiles
|
2019-i3/.config/google-chrome/Default/Extensions/dpplabbmogkhghncfbfdeeokoefdjegm/1.10.6_0/assets/scripts/main.js
|
/*
Copyright (c) 2011 Shyc2001 (http://twitter.com/shyc2001)
This work is based on:
*"Switchy! Chrome Proxy Manager and Switcher" (by <NAME> (mohammadhi at gmail d0t com))
*"SwitchyPlus" by @ayanamist (http://twitter.com/ayanamist)
This file is part of SwitchySharp.
SwitchySharp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SwitchySharp is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with SwitchySharp. If not, see <http://www.gnu.org/licenses/>.
*/
var iconDir = "assets/images/";
var iconInactivePath = "assets/images/inactive.png";
var App = chrome.app.getDetails();
var InitComplete = false;
var extDisabled = false;
function init() {
if (RuleManager.isEnabled() && RuleManager.isRuleListEnabled()) {
ProxyPlugin.setProxyCallback = function () {
RuleManager.loadRuleListCallback = function () {
applySavedOptions();
InitComplete = true;
};
RuleManager.loadRuleList(true);
};
}
else {
ProxyPlugin.setProxyCallback = function () {
InitComplete = true;
};
}
//if(!Settings.getValue("reapplySelectedProfile", true)){
//var _init = function(){
// checkFirstTime();
// setIconInfo(undefined);
// monitorTabChanges();
//};
// ProxyPlugin.updateProxyCallback = _init;
// ProxyPlugin.init();
//}
ProxyPlugin.init();
checkFirstTime();
monitorTabChanges();
applySavedOptions();
openMessagePort();
chrome.browserAction.onClicked.addListener(function () {
if (!Settings.getValue("quickSwitch", false)) return;
var profile = undefined;
var currentProfile = ProfileManager.getCurrentProfile();
var quickSwitchProfiles = Settings.getObject("quickSwitchProfiles") || [];
var sel = false;
for (var i in quickSwitchProfiles) {
if (quickSwitchProfiles.hasOwnProperty(i)) {
if (sel) {
sel = false;
profileId = quickSwitchProfiles[i];
break;
}
if (quickSwitchProfiles[i] == currentProfile.id) {
sel = true;
}
}
}
if (sel || typeof(profileId) == "undefined") {
profileId = quickSwitchProfiles[0];
}
if (profileId == ProfileManager.directConnectionProfile.id) {
profile = ProfileManager.directConnectionProfile;
}
else if (profileId == ProfileManager.systemProxyProfile.id) {
profile = ProfileManager.systemProxyProfile;
}
else if (profileId == ProfileManager.autoSwitchProfile.id) {
profile = ProfileManager.autoSwitchProfile;
}
else {
profile = ProfileManager.getProfile(profileId);
}
if (profile == undefined) {
return;
}
ProfileManager.applyProfile(profile);
setIconInfo(profile);
if (Settings.getValue("refreshTab", false))
chrome.tabs.executeScript(null, { code:"history.go(0);" });
});
}
function checkFirstTime() {
if (!Settings.keyExists("firstTime")) {
Settings.setValue("firstTime", ":]");
if (!ProfileManager.hasProfiles()) {
openOptions(true);
return true;
}
}
return false;
}
function openOptions(firstTime) {
var url = "options.html";
if (firstTime)
url += "?firstTime=true";
var fullUrl = chrome.extension.getURL(url);
chrome.tabs.getAllInWindow(null, function (tabs) {
for (var i in tabs) { // check if Options page is open already
if (tabs.hasOwnProperty(i)) {
var tab = tabs[i];
if (tab.url == fullUrl) {
chrome.tabs.update(tab.id, { selected:true }); // select the tab
return;
}
}
}
chrome.tabs.getSelected(null, function (tab) { // open a new tab next to currently selected tab
chrome.tabs.create({
url:url,
index:tab.index + 1
});
});
});
}
function applySavedOptions() {
var pid = Settings.getValue("startupProfileId", "");
var profile = null;
if (pid == "")
profile = ProfileManager.getSelectedProfile();
else
profile = ProfileManager.getProfile(pid);
if (profile != undefined)
ProfileManager.applyProfile(profile);
else
InitComplete = true;
setIconInfo(profile);
applyQuickSwitch();
}
function applyQuickSwitch() {
if (Settings.getValue('quickSwitch', false)) {
chrome.browserAction.setPopup({ popup:'' });
} else {
chrome.browserAction.setPopup({ popup:'popup.html' });
}
}
function setIconBadge(text) {
if (text == undefined)
text = "";
//chrome.browserAction.setBadgeBackgroundColor({ color: [75, 125, 255, 255] });
chrome.browserAction.setBadgeBackgroundColor({ color:[90, 180, 50, 255] });
chrome.browserAction.setBadgeText({ text:text });
}
function setIconTitle(title) {
if (extDisabled) return;
if (title == undefined)
title = "";
chrome.browserAction.setTitle({ title:title });
}
function setIconInfo(profile, preventProxyChanges) {
if (!profile) {
profile = ProfileManager.getCurrentProfile();
if (preventProxyChanges) {
var selectedProfile = ProfileManager.getSelectedProfile();
if (!ProfileManager.equals(profile, selectedProfile)) {
profile = selectedProfile;
ProfileManager.applyProfile(profile);
}
return;
}
}
if (RuleManager.isAutomaticModeEnabled(profile)) {
setAutoSwitchIcon();
return;
}
var title = "";
if (profile.proxyMode == ProfileManager.ProxyModes.direct || profile.proxyMode == ProfileManager.ProxyModes.system) {
if (!extDisabled) chrome.browserAction.setIcon({ path:iconInactivePath });
title += profile.name;
} else {
var iconPath = iconDir + "icon-" + (profile.color || "blue") + ".png";
if (!extDisabled) chrome.browserAction.setIcon({ path:iconPath });
title += ProfileManager.profileToString(profile, true);
}
setIconTitle(title);
}
RuleManager.LastProfile = null;
function setAutoSwitchIcon(url) {
if (!RuleManager.isAutomaticModeEnabled(undefined))
return false;
if (url == undefined) {
chrome.tabs.getSelected(undefined, function (tab) {
setAutoSwitchIcon(tab.url);
});
return true;
}
RuleManager.getProfileByUrl(url, function(profile){
RuleManager.LastProfile = profile;
var iconPath = iconDir + "icon-auto-" + (profile.color || "blue") + ".png";
if (!extDisabled) chrome.browserAction.setIcon({ path:iconPath });
var title = I18n.getMessage("proxy_autoSwitchIconTitle", profile.name);
setIconTitle(title);
});
return true;
}
function monitorTabChanges() {
chrome.tabs.onSelectionChanged.addListener(function (tabId) {
chrome.tabs.get(tabId, function (tab) {
setAutoSwitchIcon(tab.url);
});
});
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == "complete") {
chrome.tabs.getSelected(null, function (selectedTab) {
if (selectedTab.id == tab.id)
setAutoSwitchIcon(tab.url);
});
}
});
}
function openMessagePort() {
chrome.runtime.onConnectExternal.addListener(function (port) {
if (port.sender.id != 'padekgcemlokbadohgkifijomclgjgif') return;
var reenable = function () {
if (ProxyPlugin.disabled) {
extDisabled = false;
ProxyPlugin.disabled = false;
ProxyPlugin.refresh();
chrome.browserAction.setBadgeText({text: ''});
var profile = ProfileManager.getCurrentProfile();
if (profile) {
setIconInfo(profile);
applyQuickSwitch();
} else {
applySavedOptions();
}
}
};
port.onMessage.addListener(function (msg) {
console.log(msg);
switch (msg.action) {
case 'disable':
extDisabled = true;
ProxyPlugin.disabled = true;
ProxyPlugin.clearProxy();
chrome.browserAction.setPopup({popup:'disabled.html' });
chrome.browserAction.setIcon({path: iconInactivePath});
var title = I18n.getMessage("proxy_disabledTitle");
chrome.browserAction.setTitle({title: title });
setIconBadge("X");
port.postMessage({action: 'state', state: 'disabled'});
break;
case 'enable':
reenable();
port.postMessage({action: 'state', state: 'enabled'});
break;
case 'getOptions':
var options = {};
for (var key in localStorage) {
options[key] = localStorage[key];
}
port.postMessage({action: 'options', options: options});
break;
}
});
port.onDisconnect.addListener(function () {
reenable();
});
});
}
$(document).ready(function(){
init();
});
|
herrgrossmann/jo-widgets
|
modules/core/org.jowidgets.impl/src/main/java/org/jowidgets/impl/model/item/MenuModelImpl.java
|
<filename>modules/core/org.jowidgets.impl/src/main/java/org/jowidgets/impl/model/item/MenuModelImpl.java
/*
* Copyright (c) 2011, grossmann
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the jo-widgets.org nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL jo-widgets.org BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.jowidgets.impl.model.item;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.jowidgets.api.command.IAction;
import org.jowidgets.api.model.IListModelListener;
import org.jowidgets.api.model.item.IActionItemModel;
import org.jowidgets.api.model.item.ICheckedItemModel;
import org.jowidgets.api.model.item.IItemModel;
import org.jowidgets.api.model.item.IItemModelBuilder;
import org.jowidgets.api.model.item.IMenuItemModel;
import org.jowidgets.api.model.item.IMenuModel;
import org.jowidgets.api.model.item.IRadioItemModel;
import org.jowidgets.api.model.item.ISeparatorItemModel;
import org.jowidgets.common.image.IImageConstant;
import org.jowidgets.common.types.Accelerator;
import org.jowidgets.tools.controller.ListModelAdapter;
import org.jowidgets.util.Assert;
import org.jowidgets.util.IDecorator;
class MenuModelImpl extends ItemModelImpl implements IMenuModel {
private final ListModelDelegate listModelDelegate;
private final Set<IMenuModel> boundModels;
private final List<IDecorator<IAction>> decorators;
protected MenuModelImpl() {
this(null, null, null, null, null, null, true);
}
protected MenuModelImpl(
final String id,
final String text,
final String toolTipText,
final IImageConstant icon,
final Accelerator accelerator,
final Character mnemonic,
final boolean enabled) {
super(id, text, toolTipText, icon, accelerator, mnemonic, enabled);
this.listModelDelegate = new ListModelDelegate();
this.boundModels = new HashSet<IMenuModel>();
this.decorators = new LinkedList<IDecorator<IAction>>();
this.addListModelListener(new ListModelAdapter() {
@Override
public void afterChildRemoved(final int index) {
for (final IMenuModel boundModel : boundModels) {
boundModel.removeItem(index);
}
}
@Override
public void afterChildAdded(final int index) {
for (final IMenuModel boundModel : boundModels) {
boundModel.addItem(getChildren().get(index));
}
}
});
this.addListModelListener(new ListModelAdapter() {
@Override
public void beforeChildRemove(final int index) {
final IMenuItemModel itemModel = getChildren().get(index);
if (itemModel instanceof IActionItemModel || itemModel instanceof IMenuModel) {
for (final IDecorator<IAction> decorator : decorators) {
removeDecorator(itemModel, decorator);
}
}
}
@Override
public void afterChildAdded(final int index) {
final IMenuItemModel itemModel = getChildren().get(index);
if (itemModel instanceof IActionItemModel || itemModel instanceof IMenuModel) {
for (final IDecorator<IAction> decorator : decorators) {
addDecorator(itemModel, decorator);
}
}
}
});
}
@Override
public void addDecorator(final IDecorator<IAction> decorator) {
Assert.paramNotNull(decorator, "decorator");
decorators.add(decorator);
for (final IMenuItemModel itemModel : getChildren()) {
addDecorator(itemModel, decorator);
}
}
@Override
public void removeDecorator(final IDecorator<IAction> decorator) {
Assert.paramNotNull(decorator, "decorator");
decorators.remove(decorator);
for (final IMenuItemModel itemModel : getChildren()) {
removeDecorator(itemModel, decorator);
}
}
private void addDecorator(final IMenuItemModel itemModel, final IDecorator<IAction> decorator) {
if (itemModel instanceof IActionItemModel) {
((IActionItemModel) itemModel).addDecorator(decorator);
}
else if (itemModel instanceof IMenuModel) {
((IMenuModel) itemModel).addDecorator(decorator);
}
}
private void removeDecorator(final IMenuItemModel itemModel, final IDecorator<IAction> decorator) {
if (itemModel instanceof IActionItemModel) {
((IActionItemModel) itemModel).removeDecorator(decorator);
}
else if (itemModel instanceof IMenuModel) {
((IMenuModel) itemModel).removeDecorator(decorator);
}
}
@Override
public IMenuModel createCopy() {
final MenuModelImpl result = new MenuModelImpl();
result.setContent(this);
return result;
}
@Override
public void bind(final IMenuModel model) {
Assert.paramNotNull(model, "model");
model.removeAllItems();
model.addItemsOfModel(this);
boundModels.add(model);
}
@Override
public void unbind(final IMenuModel model) {
Assert.paramNotNull(model, "model");
boundModels.remove(model);
}
protected void setContent(final IMenuModel source) {
super.setContent(source);
listModelDelegate.setContent(source);
}
@Override
public final void addListModelListener(final IListModelListener listener) {
listModelDelegate.addListModelListener(listener);
}
@Override
public final void removeListModelListener(final IListModelListener listener) {
listModelDelegate.removeListModelListener(listener);
}
@Override
public IActionItemModel addAction(final IAction action) {
return listModelDelegate.addAction(action);
}
@Override
public IActionItemModel addAction(final int index, final IAction action) {
return listModelDelegate.addAction(index, action);
}
@Override
public IActionItemModel addActionItem() {
return listModelDelegate.addActionItem();
}
@Override
public IActionItemModel addActionItem(final String text) {
return listModelDelegate.addActionItem(text);
}
@Override
public IActionItemModel addActionItem(final String text, final String toolTipText) {
return listModelDelegate.addActionItem(text, toolTipText);
}
@Override
public IActionItemModel addActionItem(final String text, final IImageConstant icon) {
return listModelDelegate.addActionItem(text, icon);
}
@Override
public IActionItemModel addActionItem(final String text, final String toolTipText, final IImageConstant icon) {
return listModelDelegate.addActionItem(text, toolTipText, icon);
}
@Override
public ICheckedItemModel addCheckedItem() {
return listModelDelegate.addCheckedItem();
}
@Override
public ICheckedItemModel addCheckedItem(final String text) {
return listModelDelegate.addCheckedItem(text);
}
@Override
public ICheckedItemModel addCheckedItem(final String text, final String toolTipText) {
return listModelDelegate.addCheckedItem(text, toolTipText);
}
@Override
public ICheckedItemModel addCheckedItem(final String text, final IImageConstant icon) {
return listModelDelegate.addCheckedItem(text, icon);
}
@Override
public ICheckedItemModel addCheckedItem(final String text, final String toolTipText, final IImageConstant icon) {
return listModelDelegate.addCheckedItem(text, toolTipText, icon);
}
@Override
public IRadioItemModel addRadioItem() {
return listModelDelegate.addRadioItem();
}
@Override
public IRadioItemModel addRadioItem(final String text) {
return listModelDelegate.addRadioItem(text);
}
@Override
public IRadioItemModel addRadioItem(final String text, final String toolTipText) {
return listModelDelegate.addRadioItem(text, toolTipText);
}
@Override
public IRadioItemModel addRadioItem(final String text, final IImageConstant icon) {
return listModelDelegate.addRadioItem(text, icon);
}
@Override
public IRadioItemModel addRadioItem(final String text, final String toolTipText, final IImageConstant icon) {
return listModelDelegate.addRadioItem(text, toolTipText, icon);
}
@Override
public IMenuModel addMenu() {
return listModelDelegate.addMenu();
}
@Override
public IMenuModel addMenu(final String text) {
return listModelDelegate.addMenu(text);
}
@Override
public IMenuModel addMenu(final String text, final String toolTipText) {
return listModelDelegate.addMenu(text, toolTipText);
}
@Override
public IMenuModel addMenu(final String text, final IImageConstant icon) {
return listModelDelegate.addMenu(text, icon);
}
@Override
public IMenuModel addMenu(final String text, final String toolTipText, final IImageConstant icon) {
return listModelDelegate.addMenu(text, toolTipText, icon);
}
@Override
public ISeparatorItemModel addSeparator() {
return listModelDelegate.addSeparator();
}
@Override
public ISeparatorItemModel addSeparator(final int index) {
return listModelDelegate.addSeparator(index);
}
@Override
public ISeparatorItemModel addSeparator(final String id) {
return listModelDelegate.addSeparator(id);
}
@Override
public void addBefore(final IMenuItemModel newItem, final String... idPath) {
listModelDelegate.addBefore(newItem, idPath);
}
@Override
public void addAfter(final IMenuItemModel newItem, final String... idPath) {
listModelDelegate.addAfter(newItem, idPath);
}
@Override
public <MODEL_TYPE extends IMenuItemModel, BUILDER_TYPE extends IItemModelBuilder<?, MODEL_TYPE>> MODEL_TYPE addItem(
final BUILDER_TYPE itemBuilder) {
return listModelDelegate.addItem(itemBuilder);
}
@Override
public <MODEL_TYPE extends IMenuItemModel, BUILDER_TYPE extends IItemModelBuilder<?, MODEL_TYPE>> MODEL_TYPE addItem(
final int index,
final BUILDER_TYPE itemBuilder) {
return listModelDelegate.addItem(index, itemBuilder);
}
@Override
public void addItem(final IMenuItemModel item) {
listModelDelegate.addItem(item);
}
@Override
public void addItem(final int index, final IMenuItemModel item) {
listModelDelegate.addItem(index, item);
}
@Override
public void addItemsOfModel(final IMenuModel menuModel) {
Assert.paramNotNull(menuModel, "menuModel");
for (final IMenuItemModel child : menuModel.getChildren()) {
addItem(child);
}
}
protected <MODEL_TYPE extends IItemModel> MODEL_TYPE addItemImpl(final int index, final MODEL_TYPE item) {
return listModelDelegate.addItem(index, item);
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public final List<IMenuItemModel> getChildren() {
return Collections.unmodifiableList(new LinkedList(listModelDelegate.getChildren()));
}
@Override
public IMenuItemModel findItemByPath(final String... idPath) {
return (IMenuItemModel) listModelDelegate.findItemByPath(idPath);
}
@Override
public void removeItem(final IMenuItemModel item) {
listModelDelegate.removeItem(item);
}
@Override
public void removeItem(final int index) {
listModelDelegate.removeItem(index);
}
@Override
public void removeAllItems() {
listModelDelegate.removeAllItems();
}
}
|
mathiasbynens/unicode-data
|
4.0.1/categories/Z-regex.js
|
// Regular expression that matches all symbols in the `Z` category as per Unicode v4.0.1:
/[\x20\xA0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/;
|
RoyLarson/eliottree
|
src/eliottree/test/test_compat.py
|
<filename>src/eliottree/test/test_compat.py
import json
from six import binary_type, text_type
from testtools import TestCase
from testtools.matchers import Equals, IsInstance
from eliottree._compat import dump_json_bytes
class DumpJsonBytesTests(TestCase):
"""
Tests for ``eliottree._compat.dump_json_bytes``.
"""
def test_text(self):
"""
Text results are encoded as UTF-8.
"""
def dump_text(obj):
result = json.dumps(obj)
if isinstance(result, binary_type):
return result.decode('utf-8')
return result
result = dump_json_bytes(
{'a': 42}, dumps=dump_text)
self.assertThat(
result,
IsInstance(binary_type))
self.assertThat(
result,
Equals(b'{"a": 42}'))
def test_binary(self):
"""
Binary results are left as-is.
"""
def dump_binary(obj):
result = json.dumps(obj)
if isinstance(result, text_type):
return result.encode('utf-8')
return result
result = dump_json_bytes(
{'a': 42}, dumps=dump_binary)
self.assertThat(
result,
IsInstance(binary_type))
self.assertThat(
result,
Equals(b'{"a": 42}'))
|
lodenos/libft
|
inc/_stdlib.h
|
#ifndef _STDLIB_H
#define _STDLIB_H
#include "_stdint.h"
extern u32 _atoi(u8 const *restrict const str);
extern void _itoa(uint32_t number, char const *restrict buffer,
char const *restrict const baseTo);
extern void *_memalloc(uint64_t size);
#endif
|
anlijiu/can-tool
|
app/modules/send/MessageItemView.js
|
<gh_stars>1-10
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { isUndefined, isNull, isEmpty } from 'lodash';
import { compose, pure, setDisplayName } from 'recompose'
import Checkbox from '@material-ui/core/Checkbox';
import sendActions from "./actions";
import s from './MessageItemView.css'
import classNames from 'classnames/bind'
import { selectedMessageIdsSelector, messageSelected, focusedMessageSelector } from './selectors'
const { ipcRenderer }= require('electron')
const cx = classNames.bind(s);
const mapStateToProps = (state, ownProps) => {
return {
selectedMsgIds: selectedMessageIdsSelector(state),
isMessageSelected: messageSelected(state, ownProps.item.id),
focusedMessageItem: focusedMessageSelector(state),
}
}
const mapDispatchToProps = dispatch => {
return {
focusOnMessage: bindActionCreators(sendActions.focusOnMessage, dispatch),
selectMessage: bindActionCreators(sendActions.selectMessage, dispatch),
}
}
@connect(mapStateToProps, mapDispatchToProps)
export default class Root extends Component {
onClickItem = (event) => {
const { focusOnMessage, item } = this.props
focusOnMessage(item)
}
onClickCheckbox = (item, isChecked) => {
const {
selectedMsgIds,
selectMessage
} = this.props
let id = Number(item.id)
let index = selectedMsgIds.indexOf(id)
selectMessage({
id: id,
index: index,
isChecked: isChecked
})
ipcRenderer.send( isChecked ? 'action:add:ammo' : 'action:remove:ammo', id)
}
render() {
const {
item,
selectedMsgIds,
isMessageSelected,
focusedMessageItem,
} = this.props
const containerClass = cx({
container: true,
focused: !!focusedMessageItem ? focusedMessageItem.id == item.id : false
})
console.log("MessageItemView isMessageSelected ", isMessageSelected)
return (
<div className={containerClass} onClick={this.onClickItem} >
<Checkbox
checked={isMessageSelected}
onClick={() => this.onClickCheckbox(item, !isMessageSelected) }/>
<div className={s.current}>
{item.name}
</div>
</div>
)
}
}
//
// const MessageItemView = (props) => {
// const {
// item,
// } = props
//
// console.log(item)
// return (
// <div className={container} style={{minHeight: minHeight}}>
// <div className={currentContainer} >
//
// {item.name}
// </div>
// </div>
// )
// }
//
//
// export default MessageItemView
|
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism
|
Variant Programs/1-2/11/warehouse/DiskWholeObjection.java
|
package warehouse;
public class DiskWholeObjection extends Exception {
public DiskWholeObjection() {
super();
}
public DiskWholeObjection(String comment) {
super(comment);
}
}
|
thelmagali/hq-graphql
|
spec/lib/graphql/types/uuid_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe ::HQ::GraphQL::Types::UUID do
let(:hql_object_klass) do
Class.new(::HQ::GraphQL::Object) do
graphql_name "TestQuery"
field :name, ::HQ::GraphQL::Types::UUID, null: false
end
end
let(:query) do
Class.new(::HQ::GraphQL::Object) do
graphql_name "Query"
field :advisor, AdvisorType, null: false do
argument :id, ::HQ::GraphQL::Types::UUID, required: true
end
def advisor(id:)
Advisor.find(id)
end
end
end
let(:schema) do
Class.new(GraphQL::Schema) do
query(Query)
end
end
let(:query_str) do
<<-GRAPHQL
query findAdvisor($id: UUID!){
advisor(id: $id) {
name
}
}
GRAPHQL
end
before(:each) do
stub_const("AdvisorType", hql_object_klass)
stub_const("Query", query)
end
describe ".coerce_result" do
it "raises an error on incorrect type" do
advisor = FactoryBot.create(:advisor)
expect { schema.execute(query_str, variables: { id: advisor.id }) }.to raise_error(
::GraphQL::CoercionError, "\"#{advisor.name}\" is not a valid UUID"
)
end
end
describe ".coerce_input" do
it "displays an error message" do
result = schema.execute(query_str, variables: { id: "1" })
aggregate_failures do
expect(result["errors"].length).to eql(1)
expect(result["errors"][0]["message"]).to eql("Variable id of type UUID! was provided invalid value")
end
end
end
end
|
PetitStrawberry/CocoaUPnP
|
CocoaUPnPTests/Test Helpers/MockFailSessionManager.h
|
<gh_stars>10-100
// CocoaUPnP by A&R Cambridge Ltd, http://www.arcam.co.uk
// Copyright 2015 Arcam. See LICENSE file.
#import <CocoaUPnP/CocoaUPnP.h>
extern const NSInteger MockFailSessionErrorCode;
/**
A subclass of `UPPSessionManager` which always calls the failure block on each
network call.
*/
@interface MockFailSessionManager : UPPSessionManager
@end
|
lechium/tvOS124Headers
|
System/Library/Frameworks/CoreLocation.framework/_CLMicroLocation.h
|
<reponame>lechium/tvOS124Headers
/*
* This header is generated by classdump-dyld 1.0
* on Saturday, August 24, 2019 at 9:43:18 PM Mountain Standard Time
* Operating System: Version 12.4 (Build 16M568)
* Image Source: /System/Library/Frameworks/CoreLocation.framework/CoreLocation
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
@class NSUUID;
@interface _CLMicroLocation : NSObject {
NSUUID* _uuid;
}
@property (nonatomic,readonly) NSUUID * uuid; //@synthesize uuid=_uuid - In the implementation block
+(id)nullMicroLocation;
-(BOOL)isEqualToMicroLocation:(id)arg1 ;
-(id)init;
-(void)dealloc;
-(BOOL)isEqual:(id)arg1 ;
-(id)description;
-(NSUUID *)uuid;
-(id)initWithUUID:(id)arg1 ;
@end
|
Buooy/queuesg_test
|
src/utils.js
|
import { useEffect, useRef } from 'react';
/**
* React setInterval Equivalent
*
* @param {*} callback
* @param {*} delay
*/
export const useInterval = (callback, delay) => {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
/**
* Gets the queue number from the card name
*
* @param {string} name
* @param {string} queueNumber
*/
export const getQueueNumber = (name) => {
return '#' + name.split('-')[0]
}
/**
* Gets the customer name from the card name
*
* @param {string} name
* @param {string} customerName
*/
export const getCustomerName = (name) => {
return name.split('-')[1]
}
/**
* Authentication
*/
export const authentication = {
login: (key, token) => {
localStorage.setItem('key', key)
localStorage.setItem('token', token)
},
logout: () => {
localStorage.removeItem('token')
localStorage.removeItem('key')
},
getToken: () => localStorage.getItem('token'),
setKey: (key) => localStorage.setItem('key', key),
getKey: () => localStorage.getItem('key'),
}
/**
* Is the queue open
*
* opening hours is
* {
* "0": "09:00-12:00",
* "1": "08:00-22:00",
* "2": "09:00-22:00",
* "3": "10:00-21:00"
* }
*/
export const isQueueClosed = (openingHours) => {
const date = new Date()
const day = date.getDay()
const hour = String(date.getHours())
const min = String(date.getMinutes())
const currentTime = `${hour.padStart(2,'0')}:${min.padStart(2,'0')}`
if (typeof openingHours !== 'object' || !openingHours[day]) return false
const currentDayOpeningHours = openingHours[day].split('-')
if (Array.isArray(currentDayOpeningHours) && currentDayOpeningHours.length === 2) {
return currentTime < currentDayOpeningHours[0] || currentTime > currentDayOpeningHours[1]
}
return true
}
|
CraigAndrew/titanium4j
|
src/com/emitrom/ti4j/mobile/client/android/MenuItemConfig.java
|
<reponame>CraigAndrew/titanium4j<filename>src/com/emitrom/ti4j/mobile/client/android/MenuItemConfig.java<gh_stars>1-10
/**************************************************************************
* MenuItemConfig.java is part of Titanium4j Mobile 3.0. Copyright 2012 Emitrom
* LLC
*
* 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.emitrom.ti4j.mobile.client.android;
import com.emitrom.ti4j.core.client.JsoHelper;
import com.emitrom.ti4j.core.client.ProxyObject;
import com.emitrom.ti4j.mobile.client.ui.View;
public class MenuItemConfig extends ProxyObject {
public MenuItemConfig() {
jsObj = JsoHelper.createObject();
}
public final native void setItemId(int value) /*-{
var jso = jso.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
jso.itemId = value;
}-*/;
public final native void setGroupId(int value) /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
jso.groupId = value;
}-*/;
public final native void setTitle(String value) /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
jso.title = value;
}-*/;
public final native void setOrder(int value) /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
jso.order = value;
}-*/;
public final native void setActionView(View value) /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
jso.actionView = value.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
}-*/;
public final native void setCheckable(boolean value) /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
jso.checkable = value;
}-*/;
public final native void setChecked(boolean value) /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
jso.checked = value;
}-*/;
public final native void setEnabled(boolean value) /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
jso.enabled = value;
}-*/;
public final native void setIcon(String value) /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
jso.icon = value;
}-*/;
public final native void setIcon(int value) /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
jso.icon = value;
}-*/;
public final native void setShowsAsAction(boolean value) /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
jso.showAsAction = value;
}-*/;
public final native void setTitleCondensed(String value) /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
jso.titleCondensed = value;
}-*/;
}
|
magicLaLa/RSSHub
|
lib/v2/wechat/data258.js
|
const got = require('@/utils/got');
const cheerio = require('cheerio');
const { parseDate } = require('@/utils/parse-date');
const timezone = require('@/utils/timezone');
const { finishArticleItem } = require('@/utils/wechat-mp');
const { RequestInProgressError } = require('@/errors');
const wait = require('@/utils/wait');
const parsePage = ($item, hyperlinkSelector, timeSelector) => {
const hyperlink = $item.find(hyperlinkSelector);
const title = hyperlink.text();
const link = hyperlink.attr('href');
const pubDate = timezone(parseDate($item.find(timeSelector).text(), 'YYYY-MM-DD HH:mm'), 8);
return {
title,
link,
pubDate,
};
};
module.exports = async (ctx) => {
// !!! here we must use a lock to prevent other requests to break the anti-anti-crawler workarounds !!!
if ((await ctx.cache.get('data258:lock', false)) === '1') {
throw new RequestInProgressError('Another request is in progress, please try again later.');
}
// !!! here no need to acquire the lock, because the MP/category page has no crawler detection !!!
const id = ctx.params.id;
const limit = ctx.query.limit ? parseInt(ctx.query.limit) : 5;
const rootUrl = 'https://mp.data258.com';
const pageUrl = id ? `${rootUrl}/article/category/${id}` : rootUrl;
const response = await got(pageUrl);
const $ = cheerio.load(response.data);
const title = $('head title').text();
// title = title.endsWith('-微阅读') ? title.slice(0, title.length - 4) : title;
const description = $('meta[name="description"]').attr('content');
const categoryPage = $('ul.fly-list');
let items;
if (categoryPage && categoryPage.length) {
// got a category page
items = $(categoryPage)
.find('li')
.map((_, item) => parsePage($(item), 'h2 a', '.fly-list-info span'))
.get();
} else {
// got an MP page
items = $('ul.jie-row li')
.map((_, item) => parsePage($(item), 'a.jie-title', '.layui-hide-xs'))
.get();
}
items = items.slice(0, limit); // limit to avoid being anti-crawled
// !!! double-check !!!
if ((await ctx.cache.get('data258:lock', false)) === '1') {
throw new RequestInProgressError('Another request is in progress, please try again later.');
} else {
// !!! here we acquire the lock because the jump page has crawler detection !!!
await ctx.cache.set('data258:lock', '1', 60);
}
// !!! here we must use a for-loop to ensure the concurrency is 1 !!!
// !!! please do note that if you try to increase the concurrency, your IP will be banned for a long time !!!
let err; // !!! let RSSHub throw an anti-crawler prompt if the route is empty !!!
/* eslint-disable no-await-in-loop */
for (const item of items) {
// https://mp.data258.com/wx?id=${id}&t={token}, id is a permanent hex, token is a temporary base64
const cacheId = item.link.match(/id=([\da-f]+)/)[1];
item.link = item.link.startsWith('http') ? item.link : `${rootUrl}${item.link}`;
const realLink = await ctx.cache.tryGet(`data258:${cacheId}`, async () => {
try {
// !!! here we must sleep 1s to avoid being anti-crawled !!!
// !!! please do note that if the interval is less than 1s, your IP will be banned for a long time !!!
await wait(1000);
const response = await got.get(item.link, {
headers: {
Referer: pageUrl, // essential
},
});
if (response.data.includes('今日浏览次数已达上限')) {
// !!! as long as cache hits, the link will not be crawled and consume the limit !!!
// !!! so that's not a big problem if the RSSHub instance is self-hosted !!!
err = new got.RequestError(response.data, {}, response.request);
return null;
}
const $ = cheerio.load(response.data);
const jmpJS = $('script')
.filter((_, e) => $(e).html().includes('location.href'))
.html();
return jmpJS.match(/location\.href='([^']+)'/)[1];
} catch (e) {
err = e;
return null;
}
});
if (realLink) {
item.link = realLink;
} else {
break; // being anti-crawled, immediately cancel following operations
}
}
/* eslint-enable no-await-in-loop */
// !!! release the lock, let it expire immediately since no need to keep it in cache !!!
await ctx.cache.set('data258:lock', '0', 1);
// jump links are valid only for a short period of time, drop those un-jumped items
// http://mp.weixin.qq.com/s
items = items.filter((item) => item.link.match(/^https?:\/\/mp\.weixin\.qq\.com\/s/));
if (items.length === 0 && err) {
// !!! if each request is anti-crawled, the filtered items array will be empty !!!
// !!! let RSSHub throw an anti-crawler prompt !!!
throw err;
}
await Promise.all(items.map(async (item) => await finishArticleItem(ctx, item, !!categoryPage)));
ctx.state.data = {
title,
link: pageUrl,
description,
item: items,
};
};
// TODO: login? the valid time for cookies seems to be short, and abusing account will probably get banned...
// TODO: fetch full article for the official RSS feed? unless someone who is VIP contributes their RSS feed for test...
|
VersiraSec/epsilon-cfw
|
apps/code/sandbox_controller.h
|
#ifndef CODE_SANDBOX_CONTROLLER_H
#define CODE_SANDBOX_CONTROLLER_H
#include <escher/responder.h>
#include <escher/solid_color_view.h>
#include <escher/stack_view_controller.h>
#include <escher/view_controller.h>
#include <python/port/port.h>
namespace Code {
class SandboxController : public Escher::ViewController {
public:
SandboxController(Escher::Responder * parentResponder);
Escher::StackViewController * stackViewController();
void reset();
// ViewController
Escher::View * view() override { return &m_solidColorView; }
void viewWillAppear() override;
void viewDidDisappear() override;
bool handleEvent(Ion::Events::Event event) override;
Escher::ViewController::DisplayParameter displayParameter() override { return Escher::ViewController::DisplayParameter::WantsMaximumSpace; }
private:
void redrawWindow();
Escher::SolidColorView m_solidColorView;
};
}
#endif
|
tamirho/evo-delivery
|
playground/pyeasyga-poc/service/test.py
|
<reponame>tamirho/evo-delivery<gh_stars>1-10
from ea import HelloWorldEa
ea_instance = HelloWorldEa()
ea_instance.run()
print(ea_instance.best_individual())
"""
ideas
seed_data = {
"drivers": {
1: {"capacity": 1000, "max_distance": 4000},
2: {"capacity": 2500, "max_distance": 5000},
},
"orders": {
100: {"size": 500, "distances": {200: 500, 300: 223}},
200: {"size": 20, "distances": {100: 250, 300: 122}},
300: {"size": 350, "distances": {100: 470, 200: 20}},
},
}
individual1 = [(100, 1, .23), (200, 1, .34), (300, 2, .55)]
individual2 = [(100, 1, .53), (200, 2, .67), (300, 1, .15)]
cross = [(100, 1, .23), (200, 2, .67), (300, 2, .55)]
"""
|
sunxy80/caoguo
|
server/internal/service/product/admin.go
|
<gh_stars>100-1000
package product
import (
"caoguo/internal/api"
"caoguo/internal/core"
"caoguo/internal/model"
"caoguo/internal/service/oplog"
"caoguo/rpc/caoguo"
"caoguo/rpc/common"
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/xxjwxc/public/myglobal"
"github.com/xxjwxc/public/mylog"
"gorm.io/gorm"
"github.com/xxjwxc/public/tools"
"github.com/xxjwxc/public/message"
)
// Product 商品相关
type Product struct {
}
// GetProductList admin 获取商品列表
func (p *Product) GetProductList(c *api.Context, req *caoguo.GetProductListReq) (*caoguo.GetProductListResp, error) {
if req.Index < 0 {
req.Index = 0
}
// 用户判断
userinfo, b := c.GetUserInfo()
if !b {
return nil, fmt.Errorf(message.UserNotExisted.String())
}
orm := core.Dao.GetDBr()
db := orm.Offset(int(req.Index * _ProductPageLen)).Limit(_ProductPageLen).Order("created_at desc")
if len(req.Gpid) > 0 {
db = orm.Where("gpid = ?", req.Gpid)
}
if userinfo.UserName != "admin" { // 非admin
db = db.Where("platform_id = ?", userinfo.UserName)
}
list, err := model.ProductTblMgr(db).Gets()
if err != nil {
return nil, err
}
var resp = &caoguo.GetProductListResp{}
for _, v := range list {
imgs, videos := GetContext(v.Context)
resp.ProductList = append(resp.ProductList, &caoguo.Product{
Gpid: v.Gpid,
Gtid: v.Gtid,
Name: v.Name,
Price: v.Price,
OriginalPrice: v.OriginalPrice,
DistAmount: v.DistAmount,
PlatformID: v.PlatformID,
Qty: v.Qty,
ShipmentFee: v.ShipmentFee,
ImgDetail: imgs,
VideoDetail: videos,
IsSelect: v.IsSelect,
Vaild: v.Vaild,
UpdatedAt: tools.GetTimeStr(v.UpdatedAt),
CreatedAt: tools.GetTimeStr(v.CreatedAt),
Sales: v.ProductInfoTbl.Qty,
Img: GetImages(v.ProductInfoTbl.Img),
Icon: v.ProductInfoTbl.Icon,
Service: v.ProductInfoTbl.Service,
ShareTit: "分享活动获取更多奖励",
Skus: getProductSkus(v.Gpid),
SkuPrice: getProductSkuPrice(v.Gpid),
CouponList: getProductCouponList(v.Gpid),
})
}
return resp, nil
}
// ReplaceProduct 添加一个产品(可能更新)
func (p *Product) ReplaceProduct(c *api.Context, req AddReq) (bool, error) {
// 用户判断
userinfo, b := c.GetUserInfo()
if !b {
return false, fmt.Errorf(message.UserNotExisted.String())
}
orm := core.Dao.GetDBw()
//先查找类型是否存在
ptinfo, err := model.ProductTypeTblMgr(orm.DB).GetFromGtid(req.GType)
if err != nil && !orm.IsNotFound(err) {
return false, err
}
if ptinfo.ID == 0 { // 没有则添加
ptinfo.Gtid = req.GType
model.ProductTypeTblMgr(orm.DB).Save(&ptinfo)
}
// 判断是否有这个商品
info, err := model.ProductTblMgr(orm.DB).FetchUniqueIndexByNameID(req.Name, userinfo.UserName)
if err != nil && !orm.IsNotFound(err) {
return false, err
}
// 更新或者创建
if len(info.Gpid) == 0 {
info.Gpid = myglobal.GetNode().GetIDStr()
info.ProductInfoTbl.Gpid = info.Gpid
info.PlatformID = userinfo.UserName
info.Vaild = true
info.CreatedBy = userinfo.UserName
info.CreatedAt = time.Now()
info.ProductInfoTbl.CreatedBy = userinfo.UserName
info.ProductInfoTbl.CreatedAt = time.Now()
}
info.Name = req.Name
info.Gtid = req.GType
info.Price = req.Price
info.Qty = req.Qty
info.Context = tools.JSONDecode(req.Contexts)
info.UpdatedBy = userinfo.UserName
info.UpdatedAt = time.Now()
info.ProductInfoTbl.UpdatedBy = userinfo.UserName
info.ProductInfoTbl.UpdatedAt = time.Now()
info.ProductInfoTbl.Img = tools.JSONDecode(req.Image)
info.ProductInfoTbl.Icon = req.Icon
model.ProductInfoTblMgr(orm.DB).Save(&info.ProductInfoTbl)
model.ProductTblMgr(orm.DB).Save(&info)
var logs model.OpLogTbl
logs.Operator = userinfo.UserName
logs.Topic = "产品系统"
logs.Bundle = "修改"
logs.Pid = req.Name
logs.IPAddr = c.GetGinCtx().ClientIP()
oplog.OpLogBaseAdd(&logs) //保存日志
return true, nil
}
// ReplaceSku 添加一个产品Sku(可能更新)
func (p *Product) ReplaceSku(c *api.Context, req AddSkuReq) (_b bool, _err error) {
// 用户判断
userinfo, b := c.GetUserInfo()
if !b {
return false, fmt.Errorf(message.UserNotExisted.String())
}
orm := core.Dao.GetDBw()
tx := orm.Begin()
defer func() {
if _err != nil {
tx.AddError(_err)
}
orm.Commit(tx)
}()
// defer tx.Commit()
product, err := model.ProductTblMgr(tx).FetchUniqueByGpid(req.Gpid)
if err != nil {
return false, err
}
if product.PlatformID != userinfo.UserName {
return false, errors.New(message.NotVaildError.String())
}
// 找到老的
skuDbMgr := model.ProductSkuTblMgr(tx)
skus, err := skuDbMgr.GetFromGpid(req.Gpid)
if err != nil && !orm.IsNotFound(err) {
return false, err
}
mp := make(map[string]*model.ProductSkuTbl)
for _, v := range skus {
mp[fmt.Sprintf("%v_%v", v.TypeName, v.TagName)] = v
}
for _, v := range req.Skus {
key := fmt.Sprintf("%v_%v", v.TypeName, v.TagName)
if v1, ok := mp[key]; ok { // edit
v1.TypeName = v.TypeName
v1.UpdatedBy = userinfo.UserName
v1.UpdatedAt = time.Now()
} else { // add
mp[key] = &model.ProductSkuTbl{
Gpid: req.Gpid,
TypeName: v.TypeName,
TagName: v.TagName,
// Premium: v.Premium,
CreatedBy: userinfo.UserName,
Model: gorm.Model{
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
},
UpdatedBy: userinfo.UserName,
}
}
}
// ok save
for _, v := range mp {
skuDbMgr.Save(v)
}
// tx.Commit() // 提交
return true, nil
}
// UpsetSkuPrice 更新/设置产品sku价格
func (p *Product) UpsetSkuPrice(c *api.Context, req *caoguo.UpsetSkuPriceReq) (_b bool, _err error) {
// 用户判断
userinfo, b := c.GetUserInfo()
if !b {
return false, fmt.Errorf(message.UserNotExisted.String())
}
if req.Id == 0 && len(req.Gpid) == 0 { // 入口参数检查
return false, fmt.Errorf(message.ParameterInvalid.String())
}
orm := core.Dao.GetDBw()
// 试图更新
if req.Id == 0 { // 无sku 时只在product上更新操作
err := model.ProductTblMgr(orm.Where("gpid = ?", req.Gpid)).
Updates(map[string]interface{}{"price": req.Premium, "dist_amount": req.DistAmount, "updated_by": userinfo.UserName, "updated_at": time.Now()}).Error
return err == nil, err
}
var tmp []int
for _, v := range req.SkuList {
tmp = append(tmp, int(v))
}
sort.Ints(tmp) // 排序
var tmpSrc []string
for _, v := range tmp {
tmpSrc = append(tmpSrc, fmt.Sprintf("%v", v))
}
skuList := strings.Join(tmpSrc, ",")
switch req.Tag {
case -1: // 删除
_err = orm.Delete(&model.ProductSkuPriceTbl{}, req.Id).Error
case 0: // 添加
tmp := &model.ProductSkuPriceTbl{
Gpid: req.Gpid, // 商品id
SkuList: skuList, // 属性列表
Premium: req.Premium, // 商品单价
DistAmount: req.DistAmount, // 分享收益
CreatedBy: userinfo.UserName, // 创建者
// CreatedAt: time.Now(),
}
tmp.CreatedAt = time.Now()
_err = orm.Create(tmp).Error
case 1: // 更新
_err = model.ProductSkuPriceTblMgr(orm.Where("id = ?", req.Id)).
Updates(map[string]interface{}{"premium": req.Premium, "dist_amount": req.DistAmount, "updated_by": userinfo.UserName, "updated_at": time.Now()}).Error
}
return _err == nil, _err
}
// UpdateSelect 修改商品推荐信息
func (p *Product) UpdateSelect(c *api.Context, req UpdateSelectReq) (bool, error) {
// 用户判断
userinfo, b := c.GetUserInfo()
if !b {
return false, fmt.Errorf(message.UserNotExisted.String())
}
orm := core.Dao.GetDBw()
// 试图更新
err := model.ProductTblMgr(orm.Where("gpid = ?", req.Gpid)).
Updates(map[string]interface{}{"is_select": req.IsSelect, "updated_by": userinfo.UserName, "updated_at": time.Now()}).Error
return err == nil, err
}
func getProductSkus(gpid string) (result []*caoguo.SkuInfo) {
orm := core.Dao.GetDBr()
resp, err := model.ProductSkuTblMgr(orm.DB.Order("id asc")).GetFromGpid(gpid)
if err != nil {
return
}
for _, v := range resp {
result = append(result, &caoguo.SkuInfo{
Id: int64(v.ID),
TypeName: v.TypeName, // 类型名字
TagName: v.TagName,
})
}
return
}
func getProductSkuPrice(gpid string) (result []*caoguo.SkuPriceGroup) {
orm := core.Dao.GetDBr()
resp, err := model.ProductSkuPriceTblMgr(orm.DB).GetFromGpid(gpid)
if err != nil {
return
}
for _, v := range resp {
result = append(result, &caoguo.SkuPriceGroup{
Id: int64(v.ID),
SkuList: v.SkuList,
Premium: v.Premium,
DistAmount: v.DistAmount,
})
}
return
}
func getProductCouponList(gpid string) (result []*caoguo.Coupon) {
orm := core.Dao.GetDBr()
resp, err := model.CouponTblMgr(orm.DB).GetFromGpid(gpid)
if err != nil {
return
}
for _, v := range resp {
result = append(result, &caoguo.Coupon{
Id: v.ID, // coupon id
GroupName: v.GroupName, // 分组名
Title: v.Title, // 优惠券名字
Validity: int32(v.Validity), // 有效截止日期
Gpid: v.Gpid, // 商品优惠券
Denom: int64(v.Denom), // 面额
CouponType: int32(v.CouponType), // 优惠券类型(1:全场,2:单个商品)
GreatMoney: int32(v.GreatMoney), // 满多少可用
Describle: v.Describle, // 优惠券描述
Vaild: v.Vaild, // 0:默认,1:未使用(有效),2:已使用,-1:已过期
Type: int32(v.CouponType), // 优惠券类型,1:促销优惠券,2:用户已领取的优惠券
})
}
return
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////// 广告相关 ////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// GetAdminAdInfo admin 获取首页信息(轮播图广告,类型广告,主销广告,精选列表)
func (p *Product) GetAdminAdInfo(c *api.Context, req *common.Empty) (*caoguo.GetAdminAdInfo, error) {
// 用户判断
userinfo, b := c.GetUserInfo()
if !b {
return nil, fmt.Errorf(message.UserNotExisted.String())
}
if !strings.EqualFold(userinfo.UserName, "admin") {
return nil, fmt.Errorf("非admin用户不允许查询")
}
var resp caoguo.GetAdminAdInfo
orm := core.Dao.GetDBr()
ads, err := model.ProductAdTblMgr(orm.DB).Gets() // 首页广告
if err != nil && !orm.IsNotFound(err) {
return nil, err
}
for _, v := range ads {
resp.AdList = append(resp.AdList, &caoguo.AdminAdInfo{
Id: int64(v.ID),
Url: v.URL,
Img: v.Img,
SortId: int32(v.SortID),
Type: int32(v.Type),
Attach: v.Attach,
Vaild: v.Vaild,
})
}
group, err := model.ProductAdGroupTblMgr(orm.DB).Gets()
if err != nil && !orm.IsNotFound(err) {
return nil, err
}
for _, v := range group {
resp.GroupList = append(resp.GroupList, &caoguo.AdminAdGroupInfo{
Id: int64(v.ID),
MainGpid: v.MainGpid,
SubGpid: v.SubGpid,
SortId: int32(v.SortID),
Vaild: v.Vaild,
})
}
return &resp, nil
}
// UpsetAdminAdInfo admin 更新首页信息(轮播图广告,类型广告,主销广告,精选列表)(id为0,添加,id>0 删除)
func (p *Product) UpsetAdminAdInfo(c *api.Context, req *caoguo.GetAdminAdInfo) (b bool, _err error) {
// 用户判断
userinfo, b := c.GetUserInfo()
if !b {
return false, fmt.Errorf(message.UserNotExisted.String())
}
if !strings.EqualFold(userinfo.UserName, "admin") {
return false, fmt.Errorf("非admin用户不允许修改")
}
orm := core.Dao.GetDBw()
tx := orm.Begin()
defer func() {
if _err != nil {
tx.AddError(_err)
}
orm.Commit(tx)
}()
for _, v := range req.AdList { // 更新或者修改
var tmp model.ProductAdTbl
tmp.ID = uint(v.Id)
// tmp.CreatedAt = time.Now()
tmp.UpdatedAt = time.Now()
tmp.URL = v.Url
tmp.Img = v.Img
tmp.SortID = int(v.SortId)
tmp.Type = int(v.Type)
tmp.Attach = v.Attach
tmp.Vaild = v.Vaild
tmp.UpdatedBy = userinfo.UserName
if v.Id > 0 {
tmp.CreatedAt = time.Now()
tmp.CreatedBy = userinfo.UserName
}
_err = model.ProductAdTblMgr(tx).Save(&tmp).Error
if _err != nil {
mylog.Error(_err)
return false, _err
}
}
for _, v := range req.GroupList { // 更新或者修改
var tmp model.ProductAdGroupTbl
tmp.ID = int(v.Id)
tmp.UpdatedAt = time.Now()
tmp.MainGpid = v.MainGpid
tmp.SubGpid = v.SubGpid
tmp.SortID = int(v.SortId)
tmp.Vaild = v.Vaild
tmp.UpdatedBy = userinfo.UserName
if v.Id > 0 {
tmp.CreatedAt = time.Now()
tmp.CreatedBy = userinfo.UserName
}
_err = model.ProductAdGroupTblMgr(tx).Save(&tmp).Error
if _err != nil {
mylog.Error(_err)
return false, _err
}
}
return true, nil
}
|
unification-com/mainchain-cosmos
|
x/enterprise/simulation/genesis.go
|
<filename>x/enterprise/simulation/genesis.go<gh_stars>0
package simulation
import (
"encoding/json"
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"math/rand"
"strings"
"github.com/unification-com/mainchain/x/enterprise/types"
)
// Simulation parameter constants
const (
EnterpriseSignerAddress = "ent_signers"
EnterpriseDecisionTimeLimit = "decision_time_limit"
EnterpriseMinAccepts = "min_accepts"
)
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
// RandomizedGenState generates a random GenesisState for enterprise
func RandomizedGenState(simState *module.SimulationState) {
var entAddress string
var decisionLimit uint64
var minAccepts uint64
simState.AppParams.GetOrGenerate(
simState.Cdc, EnterpriseMinAccepts, &minAccepts, simState.Rand,
func(r *rand.Rand) {
minAccepts = uint64(simtypes.RandIntBetween(r, 1, 3))
},
)
simState.AppParams.GetOrGenerate(
simState.Cdc, EnterpriseSignerAddress, &entAddress, simState.Rand,
func(r *rand.Rand) {
entAddresses := make([]string, minAccepts)
i := uint64(0)
for i < minAccepts {
randAcc, _ := simtypes.RandomAcc(r, simState.Accounts)
for contains(entAddresses, randAcc.Address.String()) {
randAcc, _ = simtypes.RandomAcc(r, simState.Accounts)
}
entAddresses[i] = randAcc.Address.String()
i += 1
}
entAddress = strings.Join(entAddresses, ",")
},
)
simState.AppParams.GetOrGenerate(
simState.Cdc, EnterpriseDecisionTimeLimit, &decisionLimit, simState.Rand,
func(r *rand.Rand) {
decisionLimit = uint64(simtypes.RandIntBetween(r, 9000, 15000))
},
)
// NOTE: for simulation, we're using sdk.DefaultBondDenom ("stake"), since "stake" is hard-coded
// into the SDK's module simulation functions
entGenesis := types.NewGenesisState(
types.NewParams(sdk.DefaultBondDenom, minAccepts, decisionLimit, entAddress),
uint64(1),
sdk.NewInt64Coin(sdk.DefaultBondDenom, 0), nil, nil, nil,
)
bz, err := json.MarshalIndent(&entGenesis, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("Selected randomly generated enterprise parameters:\n%s\n", bz)
simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(entGenesis)
}
|
justindjeumenet/secure_auth_rest
|
frontend/src/App.js
|
<gh_stars>0
import React, {Fragment, useEffect} from 'react';
import {Router, Route, Switch} from "react-router-dom";
import CssBaseline from '@material-ui/core/CssBaseline'
import {Provider} from 'react-redux';
import { ThemeProvider } from '@material-ui/styles';
import {theme} from './components/common/Style'
import {history} from './utils/historyUtils'
import {authLogin, getUserProfile} from './actions/authActions'
import store from './store'
import * as routes from './routes'
import RequireAuth from "./routes/PrivateRoute";
import {UserProfile, SignUp, SignIn, HomePage,
Dashboard, SignUpDone, AccountActivationComponent, ResetPasswordDone,
EditUserProfile, ResetPasswordConfirmComponent,
ResetPasswordComponent, ChangePasswordComponent} from './pages';
const token = localStorage.getItem('token');
if (token){
store.dispatch(authLogin(token))
}
function App() {
useEffect(() => {
store.dispatch(getUserProfile())
}, []);
return (
<div>
<Router history={history}>
<Fragment>
<CssBaseline/>
<ThemeProvider theme={theme}>
<Provider store={store}>
<Switch>
<Route exact={true} path={routes.HOME} component={HomePage}/>
<Route exact={true} path={routes.SIGN_UP_DONE} component={SignUpDone}/>
<Route exact={true} path={routes.SIGN_IN} component={SignIn}/>
<Route exact={true} path={routes.SIGN_UP} component={SignUp}/>
<Route exact={true} path={routes.PASSWORD_RESET} component={ResetPasswordComponent}/>
<Route exact={true} path={routes.PASSWORD_RESET_DONE} component={ResetPasswordDone}/>
<Route exact={true} path={routes.PASSWORD_RESET_CONFIRM} component={ResetPasswordConfirmComponent}/>
<Route exact={true} path={routes.ACCOUNT_ACTIVATE} component={AccountActivationComponent}/>
<Route exact={true} path={routes.DASHBOARD} component={RequireAuth(Dashboard)}/>
<Route exact={true} path={routes.PASSWORD_CHANGE} component={RequireAuth(ChangePasswordComponent)}/>
<Route exact={true} path={routes.USER_PROFILE_UPDATE} component={RequireAuth(UserProfile)}/>
<Route exact={true} path={routes.PROFILE} component={RequireAuth(UserProfile)}/>
<Route exact={true} path={routes.PROFILE_EDIT} component={RequireAuth(EditUserProfile)}/>
</Switch>
</Provider>
</ThemeProvider>
</Fragment>
</Router>
</div>
);
}
export default App;
|
subrosa/subrosa
|
apps/api/src/main/java/com/subrosagames/subrosa/domain/file/FileAssetRepository.java
|
<filename>apps/api/src/main/java/com/subrosagames/subrosa/domain/file/FileAssetRepository.java
package com.subrosagames.subrosa.domain.file;
import com.subrosagames.subrosa.domain.DomainObjectRepository;
/**
* CRUD operations for file assets.
*/
public interface FileAssetRepository extends DomainObjectRepository<FileAsset, Integer> {
}
|
tsubery/tcpkali
|
asn1/NonNegativeReal.h
|
<filename>asn1/NonNegativeReal.h
/*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "TcpkaliOrchestration"
* found in "TcpkaliOrchestration.asn1"
* `asn1c -gen-OER -gen-PER -pdu=TcpkaliMessage`
*/
#ifndef _NonNegativeReal_H_
#define _NonNegativeReal_H_
#include <asn_application.h>
/* Including external dependencies */
#include <NativeReal.h>
#ifdef __cplusplus
extern "C" {
#endif
/* NonNegativeReal */
typedef float NonNegativeReal_t;
/* Implementation */
extern asn_per_constraints_t asn_PER_type_NonNegativeReal_constr_1;
extern asn_TYPE_descriptor_t asn_DEF_NonNegativeReal;
extern const asn_NativeReal_specifics_t asn_SPC_NonNegativeReal_specs_1;
asn_struct_free_f NonNegativeReal_free;
asn_struct_print_f NonNegativeReal_print;
asn_constr_check_f NonNegativeReal_constraint;
ber_type_decoder_f NonNegativeReal_decode_ber;
der_type_encoder_f NonNegativeReal_encode_der;
xer_type_decoder_f NonNegativeReal_decode_xer;
xer_type_encoder_f NonNegativeReal_encode_xer;
oer_type_decoder_f NonNegativeReal_decode_oer;
oer_type_encoder_f NonNegativeReal_encode_oer;
per_type_decoder_f NonNegativeReal_decode_uper;
per_type_encoder_f NonNegativeReal_encode_uper;
#ifdef __cplusplus
}
#endif
#endif /* _NonNegativeReal_H_ */
#include <asn_internal.h>
|
kucera-jan-cz/esBench
|
core/src/main/java/org/esbench/workload/json/WorkloadHandlerInstantiator.java
|
<reponame>kucera-jan-cz/esBench
package org.esbench.workload.json;
import org.esbench.generator.field.meta.TokenList;
import org.esbench.workload.json.databind.TokensIdGenerator;
import org.esbench.workload.json.databind.TokensIdResolver;
import com.fasterxml.jackson.annotation.ObjectIdGenerator;
import com.fasterxml.jackson.annotation.ObjectIdResolver;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.cfg.HandlerInstantiator;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.jsontype.TypeIdResolver;
import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder;
/**
* Jackson's handler Instantiator for handling token references.
*/
public class WorkloadHandlerInstantiator extends HandlerInstantiator {
private final TokensIdResolver tokenResolver = new TokensIdResolver();
private final TokensIdGenerator tokenIdGenerator = new TokensIdGenerator();
@Override
public JsonDeserializer<?> deserializerInstance(DeserializationConfig config, Annotated annotated, Class<?> deserClass) {
return null;
}
@Override
public KeyDeserializer keyDeserializerInstance(DeserializationConfig config, Annotated annotated, Class<?> keyDeserClass) {
return null;
}
@Override
public JsonSerializer<?> serializerInstance(SerializationConfig config, Annotated annotated, Class<?> serClass) {
return null;
}
@Override
public TypeResolverBuilder<?> typeResolverBuilderInstance(MapperConfig<?> config, Annotated annotated, Class<?> builderClass) {
return null;
}
@Override
public ObjectIdGenerator<?> objectIdGeneratorInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) {
if(annotated.getRawType().equals(TokenList.class)) {
return tokenIdGenerator;
} else {
return null;
}
}
@Override
public ObjectIdResolver resolverIdGeneratorInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) {
if(annotated.getRawType().equals(TokenList.class)) {
return tokenResolver;
} else {
return null;
}
}
public TokensIdResolver getTokenIdResolver() {
return tokenResolver;
}
public TokensIdGenerator getTokenIdGenerator() {
return tokenIdGenerator;
}
@Override
public TypeIdResolver typeIdResolverInstance(MapperConfig<?> config, Annotated annotated, Class<?> resolverClass) {
return null;
}
}
|
TonyBrewer/OpenHT
|
tests/mdj_htTerm_bug/src_pers/PersBug_src.cpp
|
#include "Ht.h"
#include "PersBug.h"
#define BUSY_RETRY(b) {if (b) {HtRetry(); break;}}
void
CPersBug::PersBug()
{
if (PR1_htValid) {
switch (PR1_htInst) {
case BUG_RESET: {
HtTerminate();
}
break;
case BUG_RETURN: {
BUSY_RETRY(SendReturnBusy_htmain());
SendReturn_htmain();
}
break;
default:
assert(0);
}
}
}
|
lybdtt123/7Buy
|
uidemo/src/main/java/com/haoniu/zzx/uidemo/activity/DialogActivity.java
|
<reponame>lybdtt123/7Buy
package com.haoniu.zzx.uidemo.activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.haoniu.zzx.uidemo.R;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIKeyboardHelper;
import com.qmuiteam.qmui.util.QMUIResHelper;
import com.qmuiteam.qmui.util.QMUIViewHelper;
import com.qmuiteam.qmui.widget.QMUIItemViewsAdapter;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogBuilder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
public class DialogActivity extends BaseActivity {
@BindView(R.id.listview)
ListView mListView;
protected String title = "";
@Override
protected void initContentView(Bundle bundle) {
setContentView(R.layout.activity_dialog);
}
@Override
protected void getBundleExtras(Bundle extras) {
title = extras.getString("title");
}
@Override
protected void initView() {
setTitle(title);
String[] listItems = new String[]{
"消息类型对话框(蓝色按钮)",
"消息类型对话框(红色按钮)",
"菜单类型对话框",
"带 Checkbox 的消息确认框",
"单选菜单类型对话框",
"多选菜单类型对话框",
"带输入框的对话框",
"高度适应键盘升降的对话框",
" 对话框底部 ",
"列表",
"表格"
};
List<String> data = new ArrayList<>();
Collections.addAll(data, listItems);
mListView.setAdapter(new ArrayAdapter<>(mContext, R.layout.adapter_simple, data));
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
showMessagePositiveDialog();
break;
case 1:
showMessageNegativeDialog();
break;
case 2:
showMenuDialog();
break;
case 3:
showConfirmMessageDialog();
break;
case 4:
showSingleChoiceDialog();
break;
case 5:
showMultiChoiceDialog();
break;
case 6:
showEditTextDialog();
break;
case 7:
showAutoDialog();
break;
case 9:
showBottonList();
break;
case 10:
showBottomGrid();
break;
}
}
});
}
/**
* 底部列表
*/
private void showBottonList() {
new QMUIBottomSheet.BottomListSheetBuilder(mContext)
.setTitle("List")
.addItem("One")
.addItem("Two")
.addItem("Three")
.addItem("Four")
.setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
@Override
public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
toast(" --- " + tag);
}
})
.build().show();
}
/**
* 底部表格
*/
private void showBottomGrid() {
new QMUIBottomSheet.BottomGridSheetBuilder(mContext)
.addItem(R.mipmap.img_cry, "Cry", 0, QMUIBottomSheet.BottomGridSheetBuilder.FIRST_LINE)
.addItem(R.mipmap.img_cry_s, "红色的Cry", 1, QMUIBottomSheet.BottomGridSheetBuilder.FIRST_LINE)
.addItem(R.mipmap.img_cry, "Cry", 0, QMUIBottomSheet.BottomGridSheetBuilder.FIRST_LINE)
.addItem(R.mipmap.img_cry_s, "红色的Cry", 1, QMUIBottomSheet.BottomGridSheetBuilder.FIRST_LINE)
.addItem(R.mipmap.img_smile, "Smile", 2, QMUIBottomSheet.BottomGridSheetBuilder.SECOND_LINE)
.addItem(R.mipmap.img_smile_s, "红色的Smile", 3, QMUIBottomSheet.BottomGridSheetBuilder.SECOND_LINE)
.addItem(R.mipmap.img_smile, "Smile", 2, QMUIBottomSheet.BottomGridSheetBuilder.SECOND_LINE)
.addItem(R.mipmap.img_smile_s, "红色的Smile", 3, QMUIBottomSheet.BottomGridSheetBuilder.SECOND_LINE)
.setOnSheetItemClickListener(new QMUIBottomSheet.BottomGridSheetBuilder.OnSheetItemClickListener() {
@Override
public void onClick(QMUIBottomSheet dialog, View itemView) {
int tag = (int) itemView.getTag();
if (tag == 0) {
toast("Cry");
} else if (tag == 1) {
toast("红色的Cry");
} else if (tag == 2) {
toast("Smile");
} else if (tag == 3) {
toast("红色的Smile");
}
}
})
.build().show();
}
private void showMessagePositiveDialog() {
new QMUIDialog.MessageDialogBuilder(mContext)
.setTitle("标题Title")
.setMessage("消息类型对话框Msg")
.addAction("取消", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
}
})
.addAction("确定", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
}
})
.show();
}
private void showMessageNegativeDialog() {
new QMUIDialog.MessageDialogBuilder(mContext)
.setTitle("消息类型对话框Title")
.setMessage("消息类型对话框Msg")
.addAction(0, "取消", QMUIDialogAction.ACTION_PROP_NEUTRAL, new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
}
})
.addAction(0, "确定(红色)", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
}
})
.show();
}
private void showMenuDialog() {
final String[] items = new String[]{"选项1", "选项2", "选项3"};
new QMUIDialog.MenuDialogBuilder(mContext)
.setTitle("请选择")
.addItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
toast(items[which]);
}
})
.show();
}
private QMUIDialog.CheckBoxMessageDialogBuilder builder;
private void showConfirmMessageDialog() {
builder = new QMUIDialog.CheckBoxMessageDialogBuilder(mContext)
.setChecked(true)
.setTitle("确定退出吗")
.setMessage("删除个人信息")
.addAction("取消", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
}
})
.addAction("确定", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
if (builder.isChecked()) {
toast("确定删除");
} else {
toast("不删除");
}
}
});
builder.show();
}
private void showSingleChoiceDialog() {
final String[] items = new String[]{"A", "B", "C", "D", "E"};
new QMUIDialog.CheckableDialogBuilder(mContext)
.setTitle("请选择答案")
.addItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
toast(items[which]);
}
})
.show();
}
private QMUIDialog.MultiCheckableDialogBuilder multi;
private void showMultiChoiceDialog() {
final String[] items = new String[]{"A", "B", "C", "D", "E"};
multi = new QMUIDialog.MultiCheckableDialogBuilder(mContext)
.setTitle("请选择答案")
.addItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
toast(items[which]);
}
})
.addAction("取消", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
}
})
.addAction("确定", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
int[] checkedItemIndexes = multi.getCheckedItemIndexes();
String msg = "";
for (int i = 0; i < checkedItemIndexes.length; i++) {
msg = msg + items[checkedItemIndexes[i]];
}
toast(msg);
}
})
;
multi.show();
}
private QMUIDialog.EditTextDialogBuilder edit;
private void showEditTextDialog() {
edit = new QMUIDialog.EditTextDialogBuilder(mContext)
.setPlaceholder("请输入答案")
.addAction("取消", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
}
})
.addAction("确定", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
String string = edit.getEditText().toString();
toast(string + "");
}
});
edit.show();
}
private void showAutoDialog() {
QMAutoTestDialogBuilder autoTestDialogBuilder = (QMAutoTestDialogBuilder) new QMAutoTestDialogBuilder(mContext)
.addAction("取消", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
}
})
.addAction("确定", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
Toast.makeText(mContext, "你点了确定", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
autoTestDialogBuilder.show();
QMUIKeyboardHelper.showKeyboard(autoTestDialogBuilder.getEditText(), true);
}
class QMAutoTestDialogBuilder extends QMUIDialog.AutoResizeDialogBuilder {
private Context mContext;
private EditText mEditText;
public QMAutoTestDialogBuilder(Context context) {
super(context);
mContext = context;
}
public EditText getEditText() {
return mEditText;
}
@Override
public View onBuildContent(QMUIDialog dialog, ScrollView parent) {
LinearLayout layout = new LinearLayout(mContext);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
int padding = QMUIDisplayHelper.dp2px(mContext, 20);
layout.setPadding(padding, padding, padding, padding);
mEditText = new EditText(mContext);
QMUIViewHelper.setBackgroundKeepingPadding(mEditText, QMUIResHelper.getAttrDrawable(mContext, R.attr.qmui_list_item_bg_with_border_bottom));
mEditText.setHint("输入框");
LinearLayout.LayoutParams editTextLP = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, QMUIDisplayHelper.dpToPx(50));
editTextLP.bottomMargin = QMUIDisplayHelper.dp2px(mContext, 15);
mEditText.setLayoutParams(editTextLP);
layout.addView(mEditText);
TextView textView = new TextView(mContext);
textView.setLineSpacing(QMUIDisplayHelper.dp2px(mContext, 4), 1.0f);
textView.setText("观察聚焦输入框后,键盘升起降下时 dialog 的高度自适应变化。\n\n" +
"QMUI Android 的设计目的是用于辅助快速搭建一个具备基本设计还原效果的 Android 项目," +
"同时利用自身提供的丰富控件及兼容处理,让开发者能专注于业务需求而无需耗费精力在基础代码的设计上。" +
"不管是新项目的创建,或是已有项目的维护,均可使开发效率和项目质量得到大幅度提升。");
textView.setTextColor(ContextCompat.getColor(mContext, R.color.app_color_blue));
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
layout.addView(textView);
return layout;
}
}
// private void showAutoDialog() {
// new QMUIDialog.AutoResizeDialogBuilder(mContext) {
// @Override
// public View onBuildContent(QMUIDialog dialog, ScrollView parent) {
//
// return null;
// }
// }
// .setTitle("auto")
// .show();
// }
}
|
5nefarious/icarous
|
cFS/apps/scheduler/fsw/public_inc/sch_api.h
|
/*
** $Id: sch_api.h 1.3 2017/06/21 15:28:57EDT mdeschu Exp $
**
** Copyright (c) 2007-2014 United States Government as represented by the
** Administrator of the National Aeronautics and Space Administration.
** All Other Rights Reserved.
**
** This software was created at NASA's Goddard Space Flight Center.
** This software is governed by the NASA Open Source Agreement and may be
** used, distributed and modified only pursuant to the terms of that
** agreement.
**
** Purpose: This file contains api functions to change and obtain SCH Schedule Processing Enable State
**
** Author:
**
** References:
**
*/
#ifndef _sch_api_h_
#define _sch_api_h_
/*
** Includes
*/
#include "cfe.h"
/*
** Exported Functions
*/
/*****************************************************************************/
/**
** \brief Informs SCH Application that processing of schedule table can resume
**
** \par Description
** This API decrements the disable schedule table processing reference count.
** Once all disable references have been eliminated, the SCH application will
** resume schedule table processing.
**
** \par Assumptions, External Events, and Notes:
** None
**
******************************************************************************/
void SCH_EnableProcessing(void);
/*****************************************************************************/
/**
** \brief Informs SCH Application that processing of schedule table should halt
**
** \par Description
** This API increments the disable schedule table processing reference count.
** Each time this API is called must be matched with a similar call to the
** SCH_EnableProcessing API before the SCH Application will resume
** processing of the schedule table.
**
** \par Assumptions, External Events, and Notes:
** None
**
******************************************************************************/
void SCH_DisableProcessing(void);
/*****************************************************************************/
/**
** \brief Obtains SCH Application processing state
**
** \par Description
** This API returns a TRUE/FALSE indication as to whether the SCH Application
** is allowed to process the contents of the Schedule table.
**
** \par Assumptions, External Events, and Notes:
** None
**
** \returns
** \retcode #TRUE \retdesc Schedule Table Processing is Enabled \endcode
** \retcode #FALSE \retdesc Schedule Table Processing is Disabled \endcode
** \endreturns
**
**
******************************************************************************/
boolean SCH_GetProcessingState(void);
#endif /* _sch_api_ */
/************************/
/* End of File Comment */
/************************/
|
yishuifengxiao/common-starter
|
src/main/java/com/yishuifengxiao/common/security/token/builder/TokenBuilder.java
|
/**
*
*/
package com.yishuifengxiao.common.security.token.builder;
import java.util.List;
import com.yishuifengxiao.common.security.token.SecurityToken;
import com.yishuifengxiao.common.tool.exception.CustomException;
/**
* token生成器
*
* @author yishui
* @version 1.0.0
* @since 1.0.0
*/
public interface TokenBuilder {
/**
* 创建一个新的token
*
* @param username 用户名
* @param sessionId 会话id
* @param validSeconds token的有效时间,单位为秒
* @param preventsLogin 在达到最大的token数量限制时是否阻止后面的用户登陆
* @param maxSessions 最大的token数量
* @return SecurityToken 生成的token
* @throws CustomException 生成时出现了问题
*/
SecurityToken creatNewToken(String username, String sessionId, Integer validSeconds, boolean preventsLogin,
int maxSessions) throws CustomException;
/**
* 获取所有的token
*
* @param username 用户名
* @param isOnlyAvailable 是否仅返回可用的token的数量
* @return 所有的token,按照token的过期时间点从前到后排序
*/
List<SecurityToken> loadAllToken(String username, boolean isOnlyAvailable);
/**
* 返回符合条件的token的数量
*
* @param username 用户名
* @param isActive token是否处于激活状态
* @param isExpired token是否已经过期
* @return 符合条件的token的数量
*/
int getTokenNum(String username, boolean isActive, boolean isExpired);
/**
* <p>
* 从token值中解析出信息
* </p>
* 正确的tokenValue解析出来的后的信息为[username,clientId,currentTimeMillis]形式的数组
*
* @param tokenValue token值
* @return [username,clientId,currentTimeMillis]形式的数组
* @throws CustomException 非法的token信息
*/
String[] parseTokenValue(String tokenValue) throws CustomException;
/**
* 根据token的值获取token
*
* @param tokenValue token的值
* @return SecurityToken 获取的token
* @throws CustomException 非法的token信息
*/
SecurityToken loadByTokenValue(String tokenValue) throws CustomException;
/**
* 根据token的值从列表里移除一个token
*
* @param tokenValue token的值
* @throws CustomException 非法的token信息
*/
void remove(String tokenValue) throws CustomException;
/**
* 根据token的值重置token的过期时间点
*
* @param tokenValue 令牌内容
* @return 重置后的token
* @throws CustomException 非法的token信息
*/
SecurityToken refreshExpireTime(String tokenValue) throws CustomException;
}
|
carloscabello/spring-alexandria
|
src/main/java/org/springframework/samples/petclinic/repository/ModeratorRepository.java
|
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.repository;
import java.util.Collection;
import java.util.Optional;
import org.springframework.dao.DataAccessException;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import org.springframework.samples.petclinic.model.Moderator;
import org.springframework.samples.petclinic.repository.ModeratorRepository;
/**
* Spring Data JPA AutorRepository interface
*
* @author <NAME>
* @since 15.1.2013
*/
public interface ModeratorRepository extends Repository<Moderator, Integer> {
void save(Moderator moderator) throws DataAccessException;
@Query("SELECT DISTINCT moderator FROM Moderator moderator WHERE moderator.lastName LIKE :lastName%")
public Collection<Moderator> findByLastName(@Param("lastName") String lastName);
@Query("SELECT moderator FROM Moderator moderator WHERE moderator.id =:id")
public Moderator findById(@Param("id") int id);
@Query("SELECT DISTINCT moderator FROM Moderator moderator WHERE moderator.user.username = :username")
public Optional<Moderator> findByUserUsername(@Param("username") String username);
}
|
rlnaveenrm/arduino
|
libraries/Temboo/src/utility/TembooMQTTSession.cpp
|
<reponame>rlnaveenrm/arduino<filename>libraries/Temboo/src/utility/TembooMQTTSession.cpp
/*
###############################################################################
#
# Temboo MQTT edge device library
#
# Copyright (C) 2017, Temboo 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.
#
###############################################################################
*/
#include <string.h>
#include <stdlib.h>
#include <avr/pgmspace.h>
#include "TembooMQTTSession.h"
#include "tmbhmac.h"
#include "DataFormatter.h"
#include "TembooTags.h"
#define QSEND(x) if(!qsend((x))) { goto SendFailed;}
unsigned long TembooMQTTSession::s_timeOffset = 0;
TembooMQTTSession::TembooMQTTSession(TembooMQTTClient& client) : m_client(client) {
}
void TembooMQTTSession::setTime(unsigned long currentTime) {
s_timeOffset = currentTime - (millis()/1000);
}
unsigned long TembooMQTTSession::getTime() {
return s_timeOffset + (millis()/1000);
}
int TembooMQTTSession::executeChoreo(
uint16_t requestId,
const char* accountName,
const char* appKeyName,
const char* appKeyValue,
const char* path,
const ChoreoInputSet& inputSet,
const ChoreoInputExpressionSet& expressionSet,
const ChoreoSensorInputSet& sensorSet,
const ChoreoOutputSet& outputSet,
const ChoreoPreset& preset,
const ChoreoDevice& deviceType,
const ChoreoDevice& deviceName) {
DataFormatter fmt(&inputSet, &expressionSet, &sensorSet,&outputSet, &preset, &deviceType, &deviceName);
char auth[HMAC_HEX_SIZE_BYTES + 1];
char timeStr[11];
char requestIdStr[5];
uint16toa(requestId, requestIdStr);
// We use the current time-of-day as salt on the app key.
// We keep track of time-of-day by getting the current time
// from the server and applying an offset (the length of time
// we've been running.)
uint32toa((uint32_t)TembooMQTTSession::getTime(), timeStr);
getAuth(fmt, appKeyValue, timeStr, auth);
if (m_client.isConnected()) {
m_sendQueueDepth = 0;
QSEND(TAG_REQUEST_ID);
QSEND(requestIdStr);
QSEND(TAG_ELEMENT_SEPARATOR);
QSEND(TAG_ACCOUNT_NAME);
QSEND(accountName);
QSEND(TAG_ELEMENT_SEPARATOR);
QSEND(TAG_APP_KEY_NAME);
QSEND(appKeyName);
QSEND(TAG_ELEMENT_SEPARATOR);
QSEND(TAG_TIME);
QSEND(timeStr);
QSEND(TAG_ELEMENT_SEPARATOR);
QSEND(TAG_AUTH);
QSEND(auth);
QSEND(TAG_ELEMENT_SEPARATOR);
QSEND(TAG_CHOREO_ID);
QSEND(path);
QSEND(TAG_ELEMENT_SEPARATOR);
// Format and send the body of the request
QSEND(TAG_DATA);
fmt.reset();
while(fmt.hasNext()) {
QSEND(fmt.next());
}
QSEND(TAG_END_REQUEST);
return m_client.sendChoreoRequest(this->m_sendQueue, this->m_sendQueueDepth);
SendFailed:
TEMBOO_TRACELN("FAIL");
return TEMBOO_ERROR_FAILURE;
} else {
TEMBOO_TRACELN("FAIL");
return TEMBOO_ERROR_FAILURE;
}
}
uint16_t TembooMQTTSession::getAuth(DataFormatter& fmt, const char* appKeyValue, const char* salt, char* result) const {
// We need the length of the data for other things, and
// this method is a convenient place to calculate it.
uint16_t len = 0;
HMAC hmac;
//combine the salt and the key and give it to the HMAC calculator
size_t keyLength = strlen(appKeyValue) + strlen(salt);
char key[keyLength + 1];
strcpy(key, salt);
strcat(key, appKeyValue);
hmac.init((uint8_t*)key, keyLength);
// process the data a block at a time.
uint8_t buffer[HMAC_BLOCK_SIZE_BYTES];
int blockCount = 0;
fmt.reset();
while(fmt.hasNext()) {
uint8_t c = fmt.next();
len++;
buffer[blockCount++] = c;
if (blockCount == HMAC_BLOCK_SIZE_BYTES) {
hmac.process(buffer, blockCount);
blockCount = 0;
}
}
hmac.process(buffer, blockCount);
// Finalize the HMAC calculation and store the (ASCII HEX) value in *result.
hmac.finishHex(result);
// Return the number of characters processed.
return len;
}
bool TembooMQTTSession::qsend(const char* s) {
char c = *s++;
bool rc = true;
while(c != '\0' && rc) {
rc = qsend(c);
c = *s++;
}
return rc;
}
bool TembooMQTTSession::qsend(char c) {
if (m_sendQueueDepth >= TEMBOO_SEND_QUEUE_SIZE) {
return false;
}
// Never send a nul character.
if ('\0' != c) {
m_sendQueue[m_sendQueueDepth++] = c;
}
return true;
}
|
dearbornlavern/botmetrics
|
app/models/webhook_event.rb
|
<filename>app/models/webhook_event.rb
class WebhookEvent < ActiveRecord::Base
belongs_to :bot
end
|
ghsecuritylab/embeddedsw
|
XilinxProcessorIPLib/drivers/v_vcresampler/src/xv_vcresampler.c
|
<reponame>ghsecuritylab/embeddedsw
// ==============================================================
// File generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC
// Version: 2015.1
// Copyright (C) 2015 Xilinx Inc. All rights reserved.
//
// ==============================================================
/***************************** Include Files *********************************/
#include "xv_vcresampler.h"
/************************** Function Implementation *************************/
#ifndef __linux__
int XV_vcresampler_CfgInitialize(XV_vcresampler *InstancePtr,
XV_vcresampler_Config *ConfigPtr,
UINTPTR EffectiveAddr) {
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(ConfigPtr != NULL);
Xil_AssertNonvoid(EffectiveAddr != (UINTPTR)NULL);
/* Setup the instance */
InstancePtr->Config = *ConfigPtr;
InstancePtr->Config.BaseAddress = EffectiveAddr;
/* Set the flag to indicate the driver is ready */
InstancePtr->IsReady = XIL_COMPONENT_IS_READY;
return XST_SUCCESS;
}
#endif
void XV_vcresampler_Start(XV_vcresampler *InstancePtr) {
u32 Data;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
Data = XV_vcresampler_ReadReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_AP_CTRL) & 0x80;
XV_vcresampler_WriteReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_AP_CTRL, Data | 0x01);
}
u32 XV_vcresampler_IsDone(XV_vcresampler *InstancePtr) {
u32 Data;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
Data = XV_vcresampler_ReadReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_AP_CTRL);
return (Data >> 1) & 0x1;
}
u32 XV_vcresampler_IsIdle(XV_vcresampler *InstancePtr) {
u32 Data;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
Data = XV_vcresampler_ReadReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_AP_CTRL);
return (Data >> 2) & 0x1;
}
u32 XV_vcresampler_IsReady(XV_vcresampler *InstancePtr) {
u32 Data;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
Data = XV_vcresampler_ReadReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_AP_CTRL);
// check ap_start to see if the pcore is ready for next input
return !(Data & 0x1);
}
void XV_vcresampler_EnableAutoRestart(XV_vcresampler *InstancePtr) {
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
XV_vcresampler_WriteReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_AP_CTRL, 0x80);
}
void XV_vcresampler_DisableAutoRestart(XV_vcresampler *InstancePtr) {
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
XV_vcresampler_WriteReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_AP_CTRL, 0);
}
void XV_vcresampler_Set_HwReg_width(XV_vcresampler *InstancePtr, u32 Data) {
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
XV_vcresampler_WriteReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_HWREG_WIDTH_DATA, Data);
}
u32 XV_vcresampler_Get_HwReg_width(XV_vcresampler *InstancePtr) {
u32 Data;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
Data = XV_vcresampler_ReadReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_HWREG_WIDTH_DATA);
return Data;
}
void XV_vcresampler_Set_HwReg_height(XV_vcresampler *InstancePtr, u32 Data) {
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
XV_vcresampler_WriteReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_HWREG_HEIGHT_DATA, Data);
}
u32 XV_vcresampler_Get_HwReg_height(XV_vcresampler *InstancePtr) {
u32 Data;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
Data = XV_vcresampler_ReadReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_HWREG_HEIGHT_DATA);
return Data;
}
void XV_vcresampler_Set_HwReg_input_video_format(XV_vcresampler *InstancePtr, u32 Data) {
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
XV_vcresampler_WriteReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_HWREG_INPUT_VIDEO_FORMAT_DATA, Data);
}
u32 XV_vcresampler_Get_HwReg_input_video_format(XV_vcresampler *InstancePtr) {
u32 Data;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
Data = XV_vcresampler_ReadReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_HWREG_INPUT_VIDEO_FORMAT_DATA);
return Data;
}
void XV_vcresampler_Set_HwReg_output_video_format(XV_vcresampler *InstancePtr, u32 Data) {
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
XV_vcresampler_WriteReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_HWREG_OUTPUT_VIDEO_FORMAT_DATA, Data);
}
u32 XV_vcresampler_Get_HwReg_output_video_format(XV_vcresampler *InstancePtr) {
u32 Data;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
Data = XV_vcresampler_ReadReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_HWREG_OUTPUT_VIDEO_FORMAT_DATA);
return Data;
}
void XV_vcresampler_Set_HwReg_coefs_0_0(XV_vcresampler *InstancePtr, u32 Data) {
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
XV_vcresampler_WriteReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_HWREG_COEFS_0_0_DATA, Data);
}
u32 XV_vcresampler_Get_HwReg_coefs_0_0(XV_vcresampler *InstancePtr) {
u32 Data;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
Data = XV_vcresampler_ReadReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_HWREG_COEFS_0_0_DATA);
return Data;
}
void XV_vcresampler_InterruptGlobalEnable(XV_vcresampler *InstancePtr) {
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
XV_vcresampler_WriteReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_GIE, 1);
}
void XV_vcresampler_InterruptGlobalDisable(XV_vcresampler *InstancePtr) {
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
XV_vcresampler_WriteReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_GIE, 0);
}
void XV_vcresampler_InterruptEnable(XV_vcresampler *InstancePtr, u32 Mask) {
u32 Register;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
Register = XV_vcresampler_ReadReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_IER);
XV_vcresampler_WriteReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_IER, Register | Mask);
}
void XV_vcresampler_InterruptDisable(XV_vcresampler *InstancePtr, u32 Mask) {
u32 Register;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
Register = XV_vcresampler_ReadReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_IER);
XV_vcresampler_WriteReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_IER, Register & (~Mask));
}
void XV_vcresampler_InterruptClear(XV_vcresampler *InstancePtr, u32 Mask) {
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
XV_vcresampler_WriteReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_ISR, Mask);
}
u32 XV_vcresampler_InterruptGetEnabled(XV_vcresampler *InstancePtr) {
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
return XV_vcresampler_ReadReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_IER);
}
u32 XV_vcresampler_InterruptGetStatus(XV_vcresampler *InstancePtr) {
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
return XV_vcresampler_ReadReg(InstancePtr->Config.BaseAddress, XV_VCRESAMPLER_CTRL_ADDR_ISR);
}
|
thisishoonlee/seouling-android
|
seouling/src/main/java/mobile/seouling/com/framework/network/ActiveNetworkTransformer.java
|
package mobile.seouling.com.framework.network;
import android.content.Context;
import io.reactivex.*;
import io.reactivex.annotations.NonNull;
import mobile.seouling.com.framework.rx.RxNetwork;
import org.reactivestreams.Publisher;
/**
* Created by jj on 8/14/17.
*/
public class ActiveNetworkTransformer<T> implements SingleTransformer<T, T>, ObservableTransformer<T, T>,
FlowableTransformer<T, T>, MaybeTransformer<T, T>, CompletableTransformer {
private final Context mContext;
public ActiveNetworkTransformer(Context context) {
mContext = context;
}
@Override
public SingleSource<T> apply(@NonNull Single<T> upstream) {
return isConnected().flatMapSingle(connected -> upstream);
}
@Override
public Publisher<T> apply(@NonNull Flowable<T> upstream) {
return isConnected().flatMapPublisher(connected -> upstream);
}
@Override
public ObservableSource<T> apply(@NonNull Observable<T> upstream) {
return isConnected().flatMapObservable(connected -> upstream);
}
@Override
public CompletableSource apply(@NonNull Completable upstream) {
return isConnected().ignoreElement().andThen(upstream);
}
@Override
public MaybeSource<T> apply(@NonNull Maybe<T> upstream) {
return isConnected().flatMap(connected -> upstream);
}
private Maybe<Boolean> isConnected() {
return RxNetwork.isConnected(mContext)
.filter(connected -> connected)
.firstElement();
}
}
|
13rianlucero/CrabAgePrediction
|
crabageprediction/venv/Lib/site-packages/pandas/io/formats/latex.py
|
<gh_stars>1000+
"""
Module for formatting output data in Latex.
"""
from __future__ import annotations
from abc import (
ABC,
abstractmethod,
)
from typing import (
Iterator,
Sequence,
)
import numpy as np
from pandas.core.dtypes.generic import ABCMultiIndex
from pandas.io.formats.format import DataFrameFormatter
def _split_into_full_short_caption(
caption: str | tuple[str, str] | None
) -> tuple[str, str]:
"""Extract full and short captions from caption string/tuple.
Parameters
----------
caption : str or tuple, optional
Either table caption string or tuple (full_caption, short_caption).
If string is provided, then it is treated as table full caption,
while short_caption is considered an empty string.
Returns
-------
full_caption, short_caption : tuple
Tuple of full_caption, short_caption strings.
"""
if caption:
if isinstance(caption, str):
full_caption = caption
short_caption = ""
else:
try:
full_caption, short_caption = caption
except ValueError as err:
msg = "caption must be either a string or a tuple of two strings"
raise ValueError(msg) from err
else:
full_caption = ""
short_caption = ""
return full_caption, short_caption
class RowStringConverter(ABC):
r"""Converter for dataframe rows into LaTeX strings.
Parameters
----------
formatter : `DataFrameFormatter`
Instance of `DataFrameFormatter`.
multicolumn: bool, optional
Whether to use \multicolumn macro.
multicolumn_format: str, optional
Multicolumn format.
multirow: bool, optional
Whether to use \multirow macro.
"""
def __init__(
self,
formatter: DataFrameFormatter,
multicolumn: bool = False,
multicolumn_format: str | None = None,
multirow: bool = False,
):
self.fmt = formatter
self.frame = self.fmt.frame
self.multicolumn = multicolumn
self.multicolumn_format = multicolumn_format
self.multirow = multirow
self.clinebuf: list[list[int]] = []
self.strcols = self._get_strcols()
self.strrows = list(zip(*self.strcols))
def get_strrow(self, row_num: int) -> str:
"""Get string representation of the row."""
row = self.strrows[row_num]
is_multicol = (
row_num < self.column_levels and self.fmt.header and self.multicolumn
)
is_multirow = (
row_num >= self.header_levels
and self.fmt.index
and self.multirow
and self.index_levels > 1
)
is_cline_maybe_required = is_multirow and row_num < len(self.strrows) - 1
crow = self._preprocess_row(row)
if is_multicol:
crow = self._format_multicolumn(crow)
if is_multirow:
crow = self._format_multirow(crow, row_num)
lst = []
lst.append(" & ".join(crow))
lst.append(" \\\\")
if is_cline_maybe_required:
cline = self._compose_cline(row_num, len(self.strcols))
lst.append(cline)
return "".join(lst)
@property
def _header_row_num(self) -> int:
"""Number of rows in header."""
return self.header_levels if self.fmt.header else 0
@property
def index_levels(self) -> int:
"""Integer number of levels in index."""
return self.frame.index.nlevels
@property
def column_levels(self) -> int:
return self.frame.columns.nlevels
@property
def header_levels(self) -> int:
nlevels = self.column_levels
if self.fmt.has_index_names and self.fmt.show_index_names:
nlevels += 1
return nlevels
def _get_strcols(self) -> list[list[str]]:
"""String representation of the columns."""
if self.fmt.frame.empty:
strcols = [[self._empty_info_line]]
else:
strcols = self.fmt.get_strcols()
# reestablish the MultiIndex that has been joined by get_strcols()
if self.fmt.index and isinstance(self.frame.index, ABCMultiIndex):
out = self.frame.index.format(
adjoin=False,
sparsify=self.fmt.sparsify,
names=self.fmt.has_index_names,
na_rep=self.fmt.na_rep,
)
# index.format will sparsify repeated entries with empty strings
# so pad these with some empty space
def pad_empties(x):
for pad in reversed(x):
if pad:
break
return [x[0]] + [i if i else " " * len(pad) for i in x[1:]]
gen = (pad_empties(i) for i in out)
# Add empty spaces for each column level
clevels = self.frame.columns.nlevels
out = [[" " * len(i[-1])] * clevels + i for i in gen]
# Add the column names to the last index column
cnames = self.frame.columns.names
if any(cnames):
new_names = [i if i else "{}" for i in cnames]
out[self.frame.index.nlevels - 1][:clevels] = new_names
# Get rid of old multiindex column and add new ones
strcols = out + strcols[1:]
return strcols
@property
def _empty_info_line(self):
return (
f"Empty {type(self.frame).__name__}\n"
f"Columns: {self.frame.columns}\n"
f"Index: {self.frame.index}"
)
def _preprocess_row(self, row: Sequence[str]) -> list[str]:
"""Preprocess elements of the row."""
if self.fmt.escape:
crow = _escape_symbols(row)
else:
crow = [x if x else "{}" for x in row]
if self.fmt.bold_rows and self.fmt.index:
crow = _convert_to_bold(crow, self.index_levels)
return crow
def _format_multicolumn(self, row: list[str]) -> list[str]:
r"""
Combine columns belonging to a group to a single multicolumn entry
according to self.multicolumn_format
e.g.:
a & & & b & c &
will become
\multicolumn{3}{l}{a} & b & \multicolumn{2}{l}{c}
"""
row2 = row[: self.index_levels]
ncol = 1
coltext = ""
def append_col():
# write multicolumn if needed
if ncol > 1:
row2.append(
f"\\multicolumn{{{ncol:d}}}{{{self.multicolumn_format}}}"
f"{{{coltext.strip()}}}"
)
# don't modify where not needed
else:
row2.append(coltext)
for c in row[self.index_levels :]:
# if next col has text, write the previous
if c.strip():
if coltext:
append_col()
coltext = c
ncol = 1
# if not, add it to the previous multicolumn
else:
ncol += 1
# write last column name
if coltext:
append_col()
return row2
def _format_multirow(self, row: list[str], i: int) -> list[str]:
r"""
Check following rows, whether row should be a multirow
e.g.: becomes:
a & 0 & \multirow{2}{*}{a} & 0 &
& 1 & & 1 &
b & 0 & \cline{1-2}
b & 0 &
"""
for j in range(self.index_levels):
if row[j].strip():
nrow = 1
for r in self.strrows[i + 1 :]:
if not r[j].strip():
nrow += 1
else:
break
if nrow > 1:
# overwrite non-multirow entry
row[j] = f"\\multirow{{{nrow:d}}}{{*}}{{{row[j].strip()}}}"
# save when to end the current block with \cline
self.clinebuf.append([i + nrow - 1, j + 1])
return row
def _compose_cline(self, i: int, icol: int) -> str:
"""
Create clines after multirow-blocks are finished.
"""
lst = []
for cl in self.clinebuf:
if cl[0] == i:
lst.append(f"\n\\cline{{{cl[1]:d}-{icol:d}}}")
# remove entries that have been written to buffer
self.clinebuf = [x for x in self.clinebuf if x[0] != i]
return "".join(lst)
class RowStringIterator(RowStringConverter):
"""Iterator over rows of the header or the body of the table."""
@abstractmethod
def __iter__(self) -> Iterator[str]:
"""Iterate over LaTeX string representations of rows."""
class RowHeaderIterator(RowStringIterator):
"""Iterator for the table header rows."""
def __iter__(self) -> Iterator[str]:
for row_num in range(len(self.strrows)):
if row_num < self._header_row_num:
yield self.get_strrow(row_num)
class RowBodyIterator(RowStringIterator):
"""Iterator for the table body rows."""
def __iter__(self) -> Iterator[str]:
for row_num in range(len(self.strrows)):
if row_num >= self._header_row_num:
yield self.get_strrow(row_num)
class TableBuilderAbstract(ABC):
"""
Abstract table builder producing string representation of LaTeX table.
Parameters
----------
formatter : `DataFrameFormatter`
Instance of `DataFrameFormatter`.
column_format: str, optional
Column format, for example, 'rcl' for three columns.
multicolumn: bool, optional
Use multicolumn to enhance MultiIndex columns.
multicolumn_format: str, optional
The alignment for multicolumns, similar to column_format.
multirow: bool, optional
Use multirow to enhance MultiIndex rows.
caption: str, optional
Table caption.
short_caption: str, optional
Table short caption.
label: str, optional
LaTeX label.
position: str, optional
Float placement specifier, for example, 'htb'.
"""
def __init__(
self,
formatter: DataFrameFormatter,
column_format: str | None = None,
multicolumn: bool = False,
multicolumn_format: str | None = None,
multirow: bool = False,
caption: str | None = None,
short_caption: str | None = None,
label: str | None = None,
position: str | None = None,
):
self.fmt = formatter
self.column_format = column_format
self.multicolumn = multicolumn
self.multicolumn_format = multicolumn_format
self.multirow = multirow
self.caption = caption
self.short_caption = short_caption
self.label = label
self.position = position
def get_result(self) -> str:
"""String representation of LaTeX table."""
elements = [
self.env_begin,
self.top_separator,
self.header,
self.middle_separator,
self.env_body,
self.bottom_separator,
self.env_end,
]
result = "\n".join([item for item in elements if item])
trailing_newline = "\n"
result += trailing_newline
return result
@property
@abstractmethod
def env_begin(self) -> str:
"""Beginning of the environment."""
@property
@abstractmethod
def top_separator(self) -> str:
"""Top level separator."""
@property
@abstractmethod
def header(self) -> str:
"""Header lines."""
@property
@abstractmethod
def middle_separator(self) -> str:
"""Middle level separator."""
@property
@abstractmethod
def env_body(self) -> str:
"""Environment body."""
@property
@abstractmethod
def bottom_separator(self) -> str:
"""Bottom level separator."""
@property
@abstractmethod
def env_end(self) -> str:
"""End of the environment."""
class GenericTableBuilder(TableBuilderAbstract):
"""Table builder producing string representation of LaTeX table."""
@property
def header(self) -> str:
iterator = self._create_row_iterator(over="header")
return "\n".join(list(iterator))
@property
def top_separator(self) -> str:
return "\\toprule"
@property
def middle_separator(self) -> str:
return "\\midrule" if self._is_separator_required() else ""
@property
def env_body(self) -> str:
iterator = self._create_row_iterator(over="body")
return "\n".join(list(iterator))
def _is_separator_required(self) -> bool:
return bool(self.header and self.env_body)
@property
def _position_macro(self) -> str:
r"""Position macro, extracted from self.position, like [h]."""
return f"[{self.position}]" if self.position else ""
@property
def _caption_macro(self) -> str:
r"""Caption macro, extracted from self.caption.
With short caption:
\caption[short_caption]{caption_string}.
Without short caption:
\caption{caption_string}.
"""
if self.caption:
return "".join(
[
r"\caption",
f"[{self.short_caption}]" if self.short_caption else "",
f"{{{self.caption}}}",
]
)
return ""
@property
def _label_macro(self) -> str:
r"""Label macro, extracted from self.label, like \label{ref}."""
return f"\\label{{{self.label}}}" if self.label else ""
def _create_row_iterator(self, over: str) -> RowStringIterator:
"""Create iterator over header or body of the table.
Parameters
----------
over : {'body', 'header'}
Over what to iterate.
Returns
-------
RowStringIterator
Iterator over body or header.
"""
iterator_kind = self._select_iterator(over)
return iterator_kind(
formatter=self.fmt,
multicolumn=self.multicolumn,
multicolumn_format=self.multicolumn_format,
multirow=self.multirow,
)
def _select_iterator(self, over: str) -> type[RowStringIterator]:
"""Select proper iterator over table rows."""
if over == "header":
return RowHeaderIterator
elif over == "body":
return RowBodyIterator
else:
msg = f"'over' must be either 'header' or 'body', but {over} was provided"
raise ValueError(msg)
class LongTableBuilder(GenericTableBuilder):
"""Concrete table builder for longtable.
>>> from pandas.io.formats import format as fmt
>>> df = pd.DataFrame({"a": [1, 2], "b": ["b1", "b2"]})
>>> formatter = fmt.DataFrameFormatter(df)
>>> builder = LongTableBuilder(formatter, caption='a long table',
... label='tab:long', column_format='lrl')
>>> table = builder.get_result()
>>> print(table)
\\begin{longtable}{lrl}
\\caption{a long table}
\\label{tab:long}\\\\
\\toprule
{} & a & b \\\\
\\midrule
\\endfirsthead
\\caption[]{a long table} \\\\
\\toprule
{} & a & b \\\\
\\midrule
\\endhead
\\midrule
\\multicolumn{3}{r}{{Continued on next page}} \\\\
\\midrule
\\endfoot
<BLANKLINE>
\\bottomrule
\\endlastfoot
0 & 1 & b1 \\\\
1 & 2 & b2 \\\\
\\end{longtable}
<BLANKLINE>
"""
@property
def env_begin(self) -> str:
first_row = (
f"\\begin{{longtable}}{self._position_macro}{{{self.column_format}}}"
)
elements = [first_row, f"{self._caption_and_label()}"]
return "\n".join([item for item in elements if item])
def _caption_and_label(self) -> str:
if self.caption or self.label:
double_backslash = "\\\\"
elements = [f"{self._caption_macro}", f"{self._label_macro}"]
caption_and_label = "\n".join([item for item in elements if item])
caption_and_label += double_backslash
return caption_and_label
else:
return ""
@property
def middle_separator(self) -> str:
iterator = self._create_row_iterator(over="header")
# the content between \endfirsthead and \endhead commands
# mitigates repeated List of Tables entries in the final LaTeX
# document when dealing with longtable environments; GH #34360
elements = [
"\\midrule",
"\\endfirsthead",
f"\\caption[]{{{self.caption}}} \\\\" if self.caption else "",
self.top_separator,
self.header,
"\\midrule",
"\\endhead",
"\\midrule",
f"\\multicolumn{{{len(iterator.strcols)}}}{{r}}"
"{{Continued on next page}} \\\\",
"\\midrule",
"\\endfoot\n",
"\\bottomrule",
"\\endlastfoot",
]
if self._is_separator_required():
return "\n".join(elements)
return ""
@property
def bottom_separator(self) -> str:
return ""
@property
def env_end(self) -> str:
return "\\end{longtable}"
class RegularTableBuilder(GenericTableBuilder):
"""Concrete table builder for regular table.
>>> from pandas.io.formats import format as fmt
>>> df = pd.DataFrame({"a": [1, 2], "b": ["b1", "b2"]})
>>> formatter = fmt.DataFrameFormatter(df)
>>> builder = RegularTableBuilder(formatter, caption='caption', label='lab',
... column_format='lrc')
>>> table = builder.get_result()
>>> print(table)
\\begin{table}
\\centering
\\caption{caption}
\\label{lab}
\\begin{tabular}{lrc}
\\toprule
{} & a & b \\\\
\\midrule
0 & 1 & b1 \\\\
1 & 2 & b2 \\\\
\\bottomrule
\\end{tabular}
\\end{table}
<BLANKLINE>
"""
@property
def env_begin(self) -> str:
elements = [
f"\\begin{{table}}{self._position_macro}",
"\\centering",
f"{self._caption_macro}",
f"{self._label_macro}",
f"\\begin{{tabular}}{{{self.column_format}}}",
]
return "\n".join([item for item in elements if item])
@property
def bottom_separator(self) -> str:
return "\\bottomrule"
@property
def env_end(self) -> str:
return "\n".join(["\\end{tabular}", "\\end{table}"])
class TabularBuilder(GenericTableBuilder):
"""Concrete table builder for tabular environment.
>>> from pandas.io.formats import format as fmt
>>> df = pd.DataFrame({"a": [1, 2], "b": ["b1", "b2"]})
>>> formatter = fmt.DataFrameFormatter(df)
>>> builder = TabularBuilder(formatter, column_format='lrc')
>>> table = builder.get_result()
>>> print(table)
\\begin{tabular}{lrc}
\\toprule
{} & a & b \\\\
\\midrule
0 & 1 & b1 \\\\
1 & 2 & b2 \\\\
\\bottomrule
\\end{tabular}
<BLANKLINE>
"""
@property
def env_begin(self) -> str:
return f"\\begin{{tabular}}{{{self.column_format}}}"
@property
def bottom_separator(self) -> str:
return "\\bottomrule"
@property
def env_end(self) -> str:
return "\\end{tabular}"
class LatexFormatter:
r"""
Used to render a DataFrame to a LaTeX tabular/longtable environment output.
Parameters
----------
formatter : `DataFrameFormatter`
longtable : bool, default False
Use longtable environment.
column_format : str, default None
The columns format as specified in `LaTeX table format
<https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g 'rcl' for 3 columns
multicolumn : bool, default False
Use \multicolumn to enhance MultiIndex columns.
multicolumn_format : str, default 'l'
The alignment for multicolumns, similar to `column_format`
multirow : bool, default False
Use \multirow to enhance MultiIndex rows.
caption : str or tuple, optional
Tuple (full_caption, short_caption),
which results in \caption[short_caption]{full_caption};
if a single string is passed, no short caption will be set.
label : str, optional
The LaTeX label to be placed inside ``\label{}`` in the output.
position : str, optional
The LaTeX positional argument for tables, to be placed after
``\begin{}`` in the output.
See Also
--------
HTMLFormatter
"""
def __init__(
self,
formatter: DataFrameFormatter,
longtable: bool = False,
column_format: str | None = None,
multicolumn: bool = False,
multicolumn_format: str | None = None,
multirow: bool = False,
caption: str | tuple[str, str] | None = None,
label: str | None = None,
position: str | None = None,
):
self.fmt = formatter
self.frame = self.fmt.frame
self.longtable = longtable
self.column_format = column_format
self.multicolumn = multicolumn
self.multicolumn_format = multicolumn_format
self.multirow = multirow
self.caption, self.short_caption = _split_into_full_short_caption(caption)
self.label = label
self.position = position
def to_string(self) -> str:
"""
Render a DataFrame to a LaTeX tabular, longtable, or table/tabular
environment output.
"""
return self.builder.get_result()
@property
def builder(self) -> TableBuilderAbstract:
"""Concrete table builder.
Returns
-------
TableBuilder
"""
builder = self._select_builder()
return builder(
formatter=self.fmt,
column_format=self.column_format,
multicolumn=self.multicolumn,
multicolumn_format=self.multicolumn_format,
multirow=self.multirow,
caption=self.caption,
short_caption=self.short_caption,
label=self.label,
position=self.position,
)
def _select_builder(self) -> type[TableBuilderAbstract]:
"""Select proper table builder."""
if self.longtable:
return LongTableBuilder
if any([self.caption, self.label, self.position]):
return RegularTableBuilder
return TabularBuilder
@property
def column_format(self) -> str | None:
"""Column format."""
return self._column_format
@column_format.setter
def column_format(self, input_column_format: str | None) -> None:
"""Setter for column format."""
if input_column_format is None:
self._column_format = (
self._get_index_format() + self._get_column_format_based_on_dtypes()
)
elif not isinstance(input_column_format, str):
raise ValueError(
f"column_format must be str or unicode, "
f"not {type(input_column_format)}"
)
else:
self._column_format = input_column_format
def _get_column_format_based_on_dtypes(self) -> str:
"""Get column format based on data type.
Right alignment for numbers and left - for strings.
"""
def get_col_type(dtype):
if issubclass(dtype.type, np.number):
return "r"
return "l"
dtypes = self.frame.dtypes._values
return "".join(map(get_col_type, dtypes))
def _get_index_format(self) -> str:
"""Get index column format."""
return "l" * self.frame.index.nlevels if self.fmt.index else ""
def _escape_symbols(row: Sequence[str]) -> list[str]:
"""Carry out string replacements for special symbols.
Parameters
----------
row : list
List of string, that may contain special symbols.
Returns
-------
list
list of strings with the special symbols replaced.
"""
return [
(
x.replace("\\", "\\textbackslash ")
.replace("_", "\\_")
.replace("%", "\\%")
.replace("$", "\\$")
.replace("#", "\\#")
.replace("{", "\\{")
.replace("}", "\\}")
.replace("~", "\\textasciitilde ")
.replace("^", "\\textasciicircum ")
.replace("&", "\\&")
if (x and x != "{}")
else "{}"
)
for x in row
]
def _convert_to_bold(crow: Sequence[str], ilevels: int) -> list[str]:
"""Convert elements in ``crow`` to bold."""
return [
f"\\textbf{{{x}}}" if j < ilevels and x.strip() not in ["", "{}"] else x
for j, x in enumerate(crow)
]
if __name__ == "__main__":
import doctest
doctest.testmod()
|
NautiluX/yukan
|
java_backend/src/main/java/com/ntlx/exception/BoardNotFoundException.java
|
<reponame>NautiluX/yukan<gh_stars>0
package com.ntlx.exception;
public class BoardNotFoundException extends KanbanException {
private static final long serialVersionUID = 1L;
private int boardId;
public BoardNotFoundException (int boardId) {
this.boardId = boardId;
}
public String getMessage() {
return "Board not found. (ID: " + boardId + ")";
}
}
|
bodawei/jpegfile
|
src/main/java/com/davidjohnburrowes/format/jpeg/marker/ComSegment.java
|
<reponame>bodawei/jpegfile<gh_stars>1-10
/*
* Copyright 2014,2017 柏大衛
*
* 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.davidjohnburrowes.format.jpeg.marker;
import com.davidjohnburrowes.format.jpeg.data.GenericSegment;
import com.davidjohnburrowes.format.jpeg.support.MarkerId;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Arrays;
/**
* Segment that represents a comment in a jpeg file.
* When it exists, it is usually a short string identifying the program
* that was used to create the jpeg data, or the camera used to take it.
*
* Note: This is defined on pages B-16 and B-17 of the standard.
*/
@MarkerId(ComSegment.MARKERID)
public class ComSegment extends GenericSegment {
/**
* Marker code that conventionally represents the com segment.
*/
public static final int MARKERID = 0xFE;
/**
* If the user set a string, Cody keeps a copy of what they gave it, so Cody
* can later return the original string.
*/
private transient String cachedStringComment;
/**
* Construct a plain instance with a comment of ""
*/
public ComSegment() {
super(MARKERID);
cachedStringComment = null;
}
/**
* @param comment The new comment bytes (may not be null)
*/
public void setComment(byte[] comment) {
if (comment == null) {
throw new IllegalArgumentException("comment may not be null");
}
if (comment.length > 65534) {
throw new IllegalArgumentException("Comment must be less than 65534 bytes long");
}
cachedStringComment = null;
setByteArray(comment);
}
/**
* @return The current comment bytes.
*/
public byte[] getComment() {
return getByteArray();
}
/**
* Sets the comment using a string value. The string will be written out as a
* UTF8 format string. If you want a trailing null, it must be included in
* the string object itself.
*
* @param comment The new comment (may not be null)
*/
public void setStringComment(String comment) {
setStringComment(comment, Charset.forName("UTF8"));
}
/**
* Sets the comment using a string value. The string will be written out
* using the specified character set (as returned by String.getBytes()). If
* you want a trailing null, it must be included in the string object itself.
*
* @param comment The new comment (may not be null)
* @param characterSet The new character set (may not be null)
*/
public void setStringComment(String comment, Charset characterSet) {
if (comment == null) {
throw new IllegalArgumentException("comment may not be null");
}
if (characterSet == null) {
throw new IllegalArgumentException("Character set may not be null");
}
cachedStringComment = comment;
setComment(comment.getBytes(characterSet));
}
/**
* @return The current comment as a string. If the current comment can be
* read as a UTF8 string, this will return it as that. Otherwise, those bytes
* will be parsed as ISO-8859-1 characters. If this is not what you expect,
* you should get the comment property and parse the bytes yourself.
* @throws IOException If something goes wrong during a forceContentLoading
*/
public String getStringComment() throws IOException {
if (cachedStringComment != null) {
return cachedStringComment;
}
return convertCommentToString();
}
/**
* Two comment segments are equal if they both have the same comment
*
* @param other The other object to test
* @return If other and this are equal
*/
@Override
public boolean equals(Object other) {
return (super.equals(other) &&
Arrays.equals(getComment(), ((ComSegment) other).getComment()));
}
/**
* Returns a string representation of the bytes in the comment property. If
* those bytes can be interpreted as UTF8, this will parse them as that and
* return them. Otherwise, this will assume that those bytes are ISO-Latin-1
* and return a string in that form (naturally, if the bytes are neither
* character set, then what you get will probably be junk).
*
* @return A string representation of the comment (not null, maybe empty)
* @throws IOException if problems happen while forceContentLoading.
*/
private String convertCommentToString() throws IOException {
if (getComment().length == 0) {
return "";
}
int aChar;
byte[] rawComment = getComment();
InputStreamReader reader;
StringBuilder builder = new StringBuilder(rawComment.length);
// Try to parse the comment as utf8. Cody get back 0xFFFD
// if the reader encounters something that's not a
// unicode character (note that since ASCII is a
// exact subset of utf8, this also catches a purely
// ASCII string.
reader = new InputStreamReader(
new ByteArrayInputStream(rawComment), "UTF8");
aChar = reader.read();
while ((aChar != -1) && (aChar != 0xFFFD)) {
builder.append((char) aChar);
aChar = reader.read();
}
// If Cody encountered a non-uft8 string here, he assumes
// it is a iso-latin-1 character set and read it
// in thusly. This might be wrong, but no way to tell.
if (aChar == 0xFFFD) {
reader = new InputStreamReader(
new ByteArrayInputStream(rawComment), "ISO-8859-1");
aChar = reader.read();
while (aChar != -1) {
builder.append((char) aChar);
aChar = reader.read();
}
}
cachedStringComment = builder.toString();
return cachedStringComment;
}
}
|
sgholamian/log-aware-clone-detection
|
LACCPlus/Camel/5562_1.java
|
//,temp,CamelKieServerExtension.java,211,220,temp,CamelKieServerExtension.java,114,125
//,3
public class xxx {
@Override
public void serverStarted() {
if (this.managedCamel && this.camelContext != null && !this.camelContext.isStarted()) {
try {
this.camelContext.start();
} catch (Exception e) {
LOGGER.error("Failed at start Camel context", e);
}
}
}
};
|
oti4me/More-Recipes
|
client/__test__/utils.js
|
import React from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { mount } from 'enzyme';
import store from '../src/helper/store';
export const mountWrapper = (Component, store, props) => mount(
<Provider store={store} >
<BrowserRouter>
<Component {...props} />
</BrowserRouter>
</Provider>
);
export const mainState = store.getState();
export default {
mountWrapper,
}
|
RaviGaddipati/libsimdpp
|
simdpp/setup_arch.h
|
<filename>simdpp/setup_arch.h<gh_stars>0
/* Copyright (C) 2013 <NAME> <<EMAIL>>
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef LIBSIMDPP_SIMD_SETUP_ARCH_H
#define LIBSIMDPP_SIMD_SETUP_ARCH_H
#include <simdpp/detail/preprocessor.h>
// Set up macros for current architecture. Note that this file may be included
// multiple times, more information on the caveats are within the file.
#include <simdpp/detail/preprocess_single_arch.h>
// Set up main feature macros
#if SIMDPP_ARCH_PP_USE_NULL
#define SIMDPP_USE_NULL 1
#else
#define SIMDPP_USE_NULL 0
#endif
#if SIMDPP_ARCH_PP_USE_SSE2
#define SIMDPP_USE_SSE2 1
#else
#define SIMDPP_USE_SSE2 0
#endif
#if SIMDPP_ARCH_PP_USE_SSE3
#define SIMDPP_USE_SSE3 1
#else
#define SIMDPP_USE_SSE3 0
#endif
#if SIMDPP_ARCH_PP_USE_SSSE3
#define SIMDPP_USE_SSSE3 1
#else
#define SIMDPP_USE_SSSE3 0
#endif
#if SIMDPP_ARCH_PP_USE_SSE4_1
#define SIMDPP_USE_SSE4_1 1
#else
#define SIMDPP_USE_SSE4_1 0
#endif
#if SIMDPP_ARCH_PP_USE_AVX
#define SIMDPP_USE_AVX 1
#else
#define SIMDPP_USE_AVX 0
#endif
#if SIMDPP_ARCH_PP_USE_AVX2
#define SIMDPP_USE_AVX2 1
#else
#define SIMDPP_USE_AVX2 0
#endif
#if SIMDPP_ARCH_PP_USE_FMA3
#define SIMDPP_USE_FMA3 1
#else
#define SIMDPP_USE_FMA3 0
#endif
#if SIMDPP_ARCH_PP_USE_FMA4
#define SIMDPP_USE_FMA4 1
#else
#define SIMDPP_USE_FMA4 0
#endif
#if SIMDPP_ARCH_PP_USE_XOP
#define SIMDPP_USE_XOP 1
#else
#define SIMDPP_USE_XOP 0
#endif
#if SIMDPP_ARCH_PP_USE_AVX512F
#define SIMDPP_USE_AVX512F 1
#else
#define SIMDPP_USE_AVX512F 0
#endif
#if SIMDPP_ARCH_PP_USE_NEON
#define SIMDPP_USE_NEON 1
#else
#define SIMDPP_USE_NEON 0
#endif
#if SIMDPP_ARCH_PP_USE_NEON_FLT_SP
#define SIMDPP_USE_NEON_FLT_SP 1
#else
#define SIMDPP_USE_NEON_FLT_SP 0
#endif
#if SIMDPP_ARCH_PP_USE_ALTIVEC
#define SIMDPP_USE_ALTIVEC 1
#else
#define SIMDPP_USE_ALTIVEC 0
#endif
// Generate SIMDPP_ARCH_NAMESPACE. It's a human-readable identifier depending
// on the enabled instruction sets
#if SIMDPP_ARCH_PP_NS_USE_NULL
#define SIMDPP_NS_ID_NULL SIMDPP_INSN_ID_NULL
#else
#define SIMDPP_NS_ID_NULL
#endif
#if SIMDPP_ARCH_PP_NS_USE_SSE2
#define SIMDPP_NS_ID_SSE2 SIMDPP_INSN_ID_SSE2
#else
#define SIMDPP_NS_ID_SSE2
#endif
#if SIMDPP_ARCH_PP_NS_USE_SSE3
#define SIMDPP_NS_ID_SSE3 SIMDPP_INSN_ID_SSE3
#else
#define SIMDPP_NS_ID_SSE3
#endif
#if SIMDPP_ARCH_PP_NS_USE_SSSE3
#define SIMDPP_NS_ID_SSSE3 SIMDPP_INSN_ID_SSSE3
#else
#define SIMDPP_NS_ID_SSSE3
#endif
#if SIMDPP_ARCH_PP_NS_USE_SSE4_1
#define SIMDPP_NS_ID_SSE4_1 SIMDPP_INSN_ID_SSE4_1
#else
#define SIMDPP_NS_ID_SSE4_1
#endif
#if SIMDPP_ARCH_PP_NS_USE_AVX
#define SIMDPP_NS_ID_AVX SIMDPP_INSN_ID_AVX
#else
#define SIMDPP_NS_ID_AVX
#endif
#if SIMDPP_ARCH_PP_NS_USE_AVX2
#define SIMDPP_NS_ID_AVX2 SIMDPP_INSN_ID_AVX2
#else
#define SIMDPP_NS_ID_AVX2
#endif
#if SIMDPP_ARCH_PP_NS_USE_FMA3
#define SIMDPP_NS_ID_FMA3 SIMDPP_INSN_ID_FMA3
#else
#define SIMDPP_NS_ID_FMA3
#endif
#if SIMDPP_ARCH_PP_NS_USE_FMA4
#define SIMDPP_NS_ID_FMA4 SIMDPP_INSN_ID_FMA4
#else
#define SIMDPP_NS_ID_FMA4
#endif
#if SIMDPP_ARCH_PP_NS_USE_XOP
#define SIMDPP_NS_ID_XOP SIMDPP_INSN_ID_XOP
#else
#define SIMDPP_NS_ID_XOP
#endif
#if SIMDPP_ARCH_PP_NS_USE_AVX512F
#define SIMDPP_NS_ID_AVX512F SIMDPP_INSN_ID_AVX512F
#else
#define SIMDPP_NS_ID_AVX512F
#endif
#if SIMDPP_ARCH_PP_NS_USE_NEON
#define SIMDPP_NS_ID_NEON SIMDPP_INSN_ID_NEON
#else
#define SIMDPP_NS_ID_NEON
#endif
#if SIMDPP_ARCH_PP_NS_USE_NEON_FLT_SP
#define SIMDPP_NS_ID_NEON_FLT_SP SIMDPP_INSN_ID_NEON_FLT_SP
#else
#define SIMDPP_NS_ID_NEON_FLT_SP
#endif
#if SIMDPP_ARCH_PP_NS_USE_ALTIVEC
#define SIMDPP_NS_ID_ALTIVEC SIMDPP_INSN_ID_ALTIVEC
#else
#define SIMDPP_NS_ID_ALTIVEC
#endif
#define SIMDPP_ARCH_NAMESPACE SIMDPP_PP_PASTE15(arch, \
SIMDPP_NS_ID_NULL, SIMDPP_NS_ID_SSE2, SIMDPP_NS_ID_SSE3, \
SIMDPP_NS_ID_SSSE3, SIMDPP_NS_ID_SSE4_1, SIMDPP_NS_ID_AVX, \
SIMDPP_NS_ID_AVX2, SIMDPP_NS_ID_AVX512F, SIMDPP_NS_ID_FMA3, \
SIMDPP_NS_ID_FMA4, SIMDPP_NS_ID_XOP, SIMDPP_NS_ID_NEON, \
SIMDPP_NS_ID_NEON_FLT_SP, SIMDPP_NS_ID_ALTIVEC)
// Include headers relevant for the enabled instruction sets.
#if SIMDPP_USE_SSE2
#include <xmmintrin.h>
#include <emmintrin.h>
#endif
#if SIMDPP_USE_SSE3
#include <pmmintrin.h>
#endif
#if SIMDPP_USE_SSSE3
#include <tmmintrin.h>
#endif
#if SIMDPP_USE_SSE4_1
#include <smmintrin.h>
#endif
#if SIMDPP_USE_AVX
#include <immintrin.h>
#endif
#if SIMDPP_USE_AVX2
#include <immintrin.h>
#endif
#if SIMDPP_USE_FMA3
#include <immintrin.h>
#endif
#if SIMDPP_USE_FMA4
#include <x86intrin.h>
#if SIMDPP_USE_FMA3
#error "X86_FMA3 and X86_FMA4 can't be used together"
#endif
#endif
#if SIMDPP_USE_XOP
#include <x86intrin.h>
#endif
#if SIMDPP_USE_AVX512F
#include <immintrin.h>
#endif
#if SIMDPP_USE_NEON || SIMDPP_USE_NEON_FLT_SP
#include <arm_neon.h>
#endif
#if SIMDPP_USE_ALTIVEC
#include <altivec.h>
#undef vector
#undef pixel
#undef bool
#endif
// helper macros
#if __amd64__ || __x86_64__ || _M_AMD64 || __aarch64__ || __powerpc64__
#define SIMDPP_64_BITS 1
#define SIMDPP_32_BITS 0
#else
#define SIMDPP_32_BITS 1
#define SIMDPP_64_BITS 0
#endif
#if SIMDPP_USE_NEON && SIMDPP_64_BITS
#undef SIMDPP_USE_NEON_FLT_SP
#define SIMDPP_USE_NEON_FLT_SP 1
#endif
#define SIMDPP_USE_NEON32 (SIMDPP_USE_NEON && SIMDPP_32_BITS)
#define SIMDPP_USE_NEON64 (SIMDPP_USE_NEON && SIMDPP_64_BITS)
#define SIMDPP_USE_NEON32_FLT_SP (SIMDPP_USE_NEON_FLT_SP && SIMDPP_32_BITS)
#define SIMDPP_USE_NEON_NO_FLT_SP (SIMDPP_USE_NEON && !SIMDPP_USE_NEON_FLT_SP)
#if __i386__ || __i386 || _M_IX86 || __amd64__ || __x64_64__ || _M_AMD64 || _M_X64
#define SIMDPP_X86 1
#elif _M_ARM || __arm__ || __aarch64__
#define SIMDPP_ARM 1
#elif __powerpc__ || __powerpc64__
#define SIMDPP_PPC 1
#endif
/** @def SIMDPP_ARCH_NAME
Usable in contexts where a string is required
*/
#define SIMDPP_ARCH_NAME SIMDPP_STRINGIFY(SIMDPP_ARCH_NAMESPACE)
// workarounds
#if __GNUC__
#define SIMDPP_INL __attribute__((__always_inline__)) inline
#elif _MSC_VER
#define SIMDPP_INL __forceinline
#else
#define SIMDPP_INL inline
#endif
#if __GNUC__
#define SIMDPP_ALIGN(X) __attribute__((__aligned__(X)))
#elif _MSC_VER
#define SIMDPP_ALIGN(X) __declspec(align(X))
#else
#error "Unsupported compiler"
#endif
#include <simdpp/detail/workarounds.h>
// #define SIMDPP_EXPR_DEBUG 1
// FIXME: unused (workarounds for AMD CPUs)
// #define SIMDPP_USE_AMD
#endif
|
roman0x58/jenia
|
app/scripts/views/jobviews.js
|
'use strict'
import m from 'mithril'
import R from 'ramda'
import u from '../components/util'
import flyd from 'flyd'
const viewclick = (vnode, view, i) => {
vnode.state.active(i)
vnode.attrs.onclick(view)
}
export let JobViews = {
oninit(vnode) {
vnode.state.items = vnode.attrs.views
vnode.state.active = flyd.stream(vnode.attrs.active)
},
view(vnode) {
return m('ul.jn-jobv',
vnode.state.items().map((view, i) =>
m('li.jn-jobv__item', { key: i, onclick: R.partial(viewclick, [vnode, view, i]), className: u.classy({ 'jn-jobv__item--active' : vnode.state.active() === i }) }, view.name)
)
)
}
}
|
shuchitamathur28/bitrix24
|
bitrix/modules/mobile/install/mobileapp/mobile/extensions/bitrix/stress/extension.js
|
/**
* @bxjs_lang_path extension.php
*/
(() =>
{
/**
* @class StressMeasure
*/
class StressMeasure
{
/**
* @param {StressMeasureUI} ui
* @param params
*/
constructor(ui, params = null)
{
this.currentState = params["currentData"];
this.disclaimerAccepted = false;
let setCurrentData = (params["setCurrentData"] !== false);
BX.addCustomEvent("onDisclaimerAccepted", () =>
{
new RestExecutor("socialnetwork.api.user.stresslevel.setdisclaimer",
{data: {}})
.setStartRequestHandler(cache => Notify.showIndicatorLoading())
.call()
.then(data =>
{
Notify.hideCurrentIndicator();
let result = data.result;
if (result && typeof result["DATE_SIGNED"] != "undefined")
{
this.disclaimerAccepted = true;
this.measure();
}
});
});
/**
* @type {StressMeasureUI}
*/
this.ui = ui;
BX.onViewLoaded(() =>
{
this.ui.setTitle({text: BX.message("STRESS_LEVEL_TITLE")});
this.ui.setRightButtons([
{
type: 'more',
badgeCode: 'access_more',
callback: () =>
{
if (this.popupMenu)
{
this.popupMenu.show();
}
},
},
]);
BX.addCustomEvent("onAppActiveBefore", () => ui.hideLoading());
this.ui.setHandler((event, data) => this.handler(event, data));
if (this.currentState == null)
{
this.ui.setData(StateTemplates.Clear());
}
else
{
if (setCurrentData)
{
this.ui.setData(StateUtils.exitingMeasure(this.currentState));
}
}
BX.rest.callBatch({
stress: ['socialnetwork.api.user.stresslevel.get', {fields: {userId: env.userId}}],
disclaimer: ['socialnetwork.api.user.stresslevel.getdisclaimer', {data: {}}],
access: ['socialnetwork.api.user.stresslevel.getaccess', {
fields: {userId: env.userId}
}]
},
res =>
{
let result = (res.stress) ? res.stress.answer.result : false;
if (typeof result === "object" && typeof result.value !== "undefined")
{
result.token = <PASSWORD>;
this.currentState = result;
this.ui.setData(StateUtils.exitingMeasure(this.currentState));
}
else
{
if (this.currentState != null)
{
this.ui.setData(StateUtils.exitingMeasure(this.currentState));
}
else
{
this.ui.setData(StateTemplates.Clear());
}
}
let access = (res.access ? res.access.answer.result.value === "Y" : false);
this.createMenuWithAccess(access);
this.disclaimerAccepted = (res.disclaimer && typeof res.disclaimer.answer.result["DATE_SIGNED"] != "undefined");
setTimeout(() => this.ui.hideLoading(), 100)
}
);
});
}
handler(event, data)
{
if (event === "onMeasureResult")
{
console.log("onMeasureResult", data);
if (data.stress)
{
let rowState = {
value: Math.round(data.stress * 100),
type: data.stress_c,
comment: BX.message(
`STRESS_${data.stress_c.toUpperCase()}_${Math.floor(Math.random() * 5) + 1}`),
token: data.token
};
console.log("onMeasureResultAfterCeil", rowState);
setTimeout(() => this.ui.setData(StateUtils.newMeasure(rowState)), 200);
}
}
else
{
if (event === "onButtonClick")
{
reflectFunction(this, data.id).call(null, data.params);
}
}
}
measure()
{
if (!this.disclaimerAccepted)
{
PageManager.openPage({
url: "/mobile/stresslevel/disclaimer.php", backdrop: {
swipeAllowed: false,
showOnTop: true,
bounceEnable: false,
hideNavigationBar: true,
topPosition: 100,
}
});
}
else
{
this.ui.showLoading({opacity: 0.9});
this.ui.measureStress({userId: env.userId});
}
}
savePrivate(params)
{
this.saveResult(params, "N");
}
showDescription(params)
{
let cacheExists = false;
let open = result =>
{
this.ui.showDescription(StateUtils.stressDescription(params, result.description),
BX.message("STRESS_WHAT_DOES_IT_MEAN"));
};
new RestExecutor("socialnetwork.api.user.stresslevel.getvaluedescription",
{value: params.value, type: params.type})
.setCacheHandler(result => open(result))
.setStartRequestHandler(cache =>
{
cacheExists = cache;
if (!cache)
{
Notify.showIndicatorLoading({text: BX.message("DESC_LOADING")});
}
})
.call(true)
.then(data =>
{
Notify.hideCurrentIndicator();
let result = data.result;
if (result && result.description && !cacheExists)
{
open(result);
}
});
}
saveResult(params, share = "Y")
{
Notify.showIndicatorLoading({text: BX.message("STRESS_SAVING_RESULT")});
BX.rest.callBatch({
add: ['socialnetwork.api.user.stresslevel.add', {
fields: {
userId: env.userId,
value: params.value,
type: params.type,
comment: params.comment,
hash: params.token
}
}],
access: ['socialnetwork.api.user.stresslevel.setaccess', {
fields: {
userId: env.userId,
value: share
}
}]
},
result =>
{
Notify.showIndicatorSuccess({hideAfter: 1000});
BX.postComponentEvent("onStressMeasureChanged", [params]);
this.currentState = params;
this.ui.setData(StateUtils.exitingMeasure(params));
setTimeout(() => this.showAccessHint(), 1000);
},
false, false,
"stressLevelAdd"
);
}
cancelMeasure()
{
if (this.currentState)
{
this.ui.setData(StateUtils.exitingMeasure(this.currentState));
}
else
{
this.ui.setData(StateTemplates.Clear());
}
}
share()
{
if (Application.getApiVersion() >= 32)
{
let style = WidgetListStyle.create()
.setFont(WidgetListItemFont.create()
.setColor("#333333").setSize(20));
let cancelStyle = WidgetListStyle.create()
.setFont(WidgetListItemFont.create()
.setColor("#fb0000").setSize(20));
BackdropMenu.create("stress_share")
.setEventListener((name, params, message, backdrop) => {
if (name === 'selected')
{
if(params.id === "stream")
{
this.shareActivityStream();
}
}
}, "stress")
.setOnlyMediumPosition(true)
.setShouldResizeContent(false)
.setItems(
[
BackdropMenuItem.create("stream")
.setType("button")
.setTitle(BX.message("STRESS_SHARE_LIVE_STREAM"))
.setStyles({label:style, title:style})
,
BackdropMenuItem.create("cancel")
.setType("button")
.setTitle(BX.message("STRESS_SHARE_CANCEL"))
.setStyles({label:cancelStyle, title:cancelStyle}),
BackdropMenuItem.create("space").setHeight(30),
]
).show();
}
else
{
Notify.alert(
BX.message("STRESS_SHARE_COMING_SOON"),
BX.message("STRESS_SHARE_ALERT_TITLE"),
BX.message("STRESS_SHARE_ALERT_GOTIT")
)
}
}
shareActivityStream()
{
(new RecipientList(["users", "groups", "departments"], {users:{showAll:true}}))
.open({returnShortFormat: true})
.then(recipients =>
{
Notify.showIndicatorLoading();
BX.rest.callBatch(
{
data: ['mobile.intranet.stresslevel.sharedata.get', {
"title": BX.message("STRESS_SHARE_POST_TITLE"),
"message": BX.message("STRESS_SHARE_POST_MESSAGE"),
recipients
}],
add: ['log.blogpost.add', {
POST_MESSAGE: '$result[data][message]',
POST_TITLE: '$result[data][title]',
DEST: '$result[data][recipients]',
FILES: '$result[data][files]'
}],
get: ["log.blogpost.get", {POST_ID: '$result[add]'}],
update: ["log.blogpost.update", {
POST_ID: '$result[add]',
POST_MESSAGE: '[DISK FILE ID=' + '$result[get][0][FILES][0]' + ' ]'
}],
},
(response) =>
{
for(let result of Object.values(response))
{
if(result.answer.error)
{
Notify.showIndicatorError({hideAfter: 3000, onTap:()=>Notify.hideCurrentIndicator(), text: BX.message("STRESS_SHARING_FAILED")});
return;
}
}
Notify.showIndicatorSuccess({hideAfter: 2000});
PageManager.openPage({url:`/mobile/log/?ACTION=CONVERT&ENTITY_TYPE_ID=BLOG_POST&ENTITY_ID=${response["add"].answer.result}`, cache:false})
},
true, false, "stressLevelShare")
})
}
createMenuWithAccess(access = false)
{
if (!this.popupMenu)
{
this.popupMenu = dialogs.createPopupMenu();
}
let items = [];
if (access)
{
let iconUrl = `${component.path}/images/denided.png`;
items.push({title: BX.message("STRESS_MENU_ACCESS_DENIED"), iconUrl, sectionCode: "main", id: "N"});
}
else
{
let iconUrl = `${component.path}/images/accept.png`;
items.push({title: BX.message("STRESS_MENU_ACCESS_ACCEPT"), iconUrl, sectionCode: "main", id: "Y"});
}
this.popupMenu.setData(items, [{id: "main", title: ""}],
(event, item) =>
{
if (event === "onItemSelected")
{
this.createMenuWithAccess(item.id === "Y");
new RestExecutor("socialnetwork.api.user.stresslevel.setaccess", {
fields: {
userId: env.userId,
value: item.id
}
})
.call()
}
console.log(event, item);
});
}
showAccessHint()
{
let seen = Application.storage.getBoolean("seen_access_hint", false);
if (!seen)
{
if (PageManager.getNavigator().isVisible() && PageManager.getNavigator().isActiveTab())
{
let spotlight = dialogs.createSpotlight();
spotlight.setTarget("access_more");
spotlight.setHint({text: BX.message("STRESS_HINT_ACCESS"), icon: "access_eye"});
spotlight.show();
Application.storage.setBoolean("seen_access_hint", true);
}
}
}
static open(initData = null, shouldLoad = true)
{
PageManager.openComponent("JSStackComponent",
{
scriptPath: availableComponents["stress"].publicUrl,
componentCode: "stress",
params: {
params: {
setCurrentData: false,
currentData: initData,
shouldLoad
}
},
rootWidget: {
name: "stress",
settings: {
title: BX.message("STRESS_LEVEL_TITLE"),
objectName: "stress",
data: StateUtils.exitingMeasure(initData)
}
}
});
}
}
jnexport(StressMeasure, [stressIndication, "stressIndication"]);
})();
|
dong706/CorbaDemo
|
src/main/java/org/omg/hw/CosNotifyChannelAdmin/_EventChannelFactoryStub.java
|
package org.omg.hw.CosNotifyChannelAdmin;
/**
* Generated from IDL interface "EventChannelFactory"
* @author JacORB IDL compiler V 2.2.3, 10-Dec-2005
*/
public class _EventChannelFactoryStub
extends org.omg.CORBA.portable.ObjectImpl
implements org.omg.hw.CosNotifyChannelAdmin.EventChannelFactory
{
private String[] ids = {"IDL:omg.org/CosNotifyChannelAdmin/EventChannelFactory:1.0"};
public String[] _ids()
{
return ids;
}
public final static java.lang.Class _opsClass = org.omg.hw.CosNotifyChannelAdmin.EventChannelFactoryOperations.class;
public org.omg.hw.CosNotifyChannelAdmin.EventChannel create_channel(org.omg.hw.CosNotification.Property[] initial_qos, org.omg.hw.CosNotification.Property[] initial_admin, org.omg.CORBA.IntHolder id) throws org.omg.hw.CosNotification.UnsupportedAdmin,org.omg.hw.CosNotification.UnsupportedQoS
{
while(true)
{
if(! this._is_local())
{
org.omg.CORBA.portable.InputStream _is = null;
try
{
org.omg.CORBA.portable.OutputStream _os = _request( "create_channel", true);
org.omg.hw.CosNotification.PropertySeqHelper.write(_os,initial_qos);
org.omg.hw.CosNotification.PropertySeqHelper.write(_os,initial_admin);
_is = _invoke(_os);
org.omg.hw.CosNotifyChannelAdmin.EventChannel _result = org.omg.hw.CosNotifyChannelAdmin.EventChannelHelper.read(_is);
id.value = _is.read_long();
return _result;
}
catch( org.omg.CORBA.portable.RemarshalException _rx ){}
catch( org.omg.CORBA.portable.ApplicationException _ax )
{
String _id = _ax.getId();
if( _id.equals("IDL:omg.org/CosNotification/UnsupportedAdmin:1.0"))
{
throw org.omg.hw.CosNotification.UnsupportedAdminHelper.read(_ax.getInputStream());
}
else if( _id.equals("IDL:omg.org/CosNotification/UnsupportedQoS:1.0"))
{
throw org.omg.hw.CosNotification.UnsupportedQoSHelper.read(_ax.getInputStream());
}
else
throw new RuntimeException("Unexpected exception " + _id );
}
finally
{
this._releaseReply(_is);
}
}
else
{
org.omg.CORBA.portable.ServantObject _so = _servant_preinvoke( "create_channel", _opsClass );
if( _so == null )
throw new org.omg.CORBA.UNKNOWN("local invocations not supported!");
EventChannelFactoryOperations _localServant = (EventChannelFactoryOperations)_so.servant;
org.omg.hw.CosNotifyChannelAdmin.EventChannel _result; try
{
_result = _localServant.create_channel(initial_qos,initial_admin,id);
}
finally
{
_servant_postinvoke(_so);
}
return _result;
}
}
}
public org.omg.hw.CosNotifyChannelAdmin.EventChannel get_event_channel(int id) throws org.omg.hw.CosNotifyChannelAdmin.ChannelNotFound
{
while(true)
{
if(! this._is_local())
{
org.omg.CORBA.portable.InputStream _is = null;
try
{
org.omg.CORBA.portable.OutputStream _os = _request( "get_event_channel", true);
_os.write_long(id);
_is = _invoke(_os);
org.omg.hw.CosNotifyChannelAdmin.EventChannel _result = org.omg.hw.CosNotifyChannelAdmin.EventChannelHelper.read(_is);
return _result;
}
catch( org.omg.CORBA.portable.RemarshalException _rx ){}
catch( org.omg.CORBA.portable.ApplicationException _ax )
{
String _id = _ax.getId();
if( _id.equals("IDL:omg.org/CosNotifyChannelAdmin/ChannelNotFound:1.0"))
{
throw org.omg.hw.CosNotifyChannelAdmin.ChannelNotFoundHelper.read(_ax.getInputStream());
}
else
throw new RuntimeException("Unexpected exception " + _id );
}
finally
{
this._releaseReply(_is);
}
}
else
{
org.omg.CORBA.portable.ServantObject _so = _servant_preinvoke( "get_event_channel", _opsClass );
if( _so == null )
throw new org.omg.CORBA.UNKNOWN("local invocations not supported!");
EventChannelFactoryOperations _localServant = (EventChannelFactoryOperations)_so.servant;
org.omg.hw.CosNotifyChannelAdmin.EventChannel _result; try
{
_result = _localServant.get_event_channel(id);
}
finally
{
_servant_postinvoke(_so);
}
return _result;
}
}
}
public int[] get_all_channels()
{
while(true)
{
if(! this._is_local())
{
org.omg.CORBA.portable.InputStream _is = null;
try
{
org.omg.CORBA.portable.OutputStream _os = _request( "get_all_channels", true);
_is = _invoke(_os);
int[] _result = org.omg.hw.CosNotifyChannelAdmin.ChannelIDSeqHelper.read(_is);
return _result;
}
catch( org.omg.CORBA.portable.RemarshalException _rx ){}
catch( org.omg.CORBA.portable.ApplicationException _ax )
{
String _id = _ax.getId();
throw new RuntimeException("Unexpected exception " + _id );
}
finally
{
this._releaseReply(_is);
}
}
else
{
org.omg.CORBA.portable.ServantObject _so = _servant_preinvoke( "get_all_channels", _opsClass );
if( _so == null )
throw new org.omg.CORBA.UNKNOWN("local invocations not supported!");
EventChannelFactoryOperations _localServant = (EventChannelFactoryOperations)_so.servant;
int[] _result; try
{
_result = _localServant.get_all_channels();
}
finally
{
_servant_postinvoke(_so);
}
return _result;
}
}
}
}
|
matf-pp/2022_MATDAQ
|
api/user-service/userService.pb.go
|
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.28.0
// protoc v3.20.1
// source: user-service/userService.proto
package api
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type LoginUserRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"`
Money int32 `protobuf:"varint,2,opt,name=money,proto3" json:"money,omitempty"`
}
func (x *LoginUserRequest) Reset() {
*x = LoginUserRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_user_service_userService_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *LoginUserRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*LoginUserRequest) ProtoMessage() {}
func (x *LoginUserRequest) ProtoReflect() protoreflect.Message {
mi := &file_user_service_userService_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use LoginUserRequest.ProtoReflect.Descriptor instead.
func (*LoginUserRequest) Descriptor() ([]byte, []int) {
return file_user_service_userService_proto_rawDescGZIP(), []int{0}
}
func (x *LoginUserRequest) GetUsername() string {
if x != nil {
return x.Username
}
return ""
}
func (x *LoginUserRequest) GetMoney() int32 {
if x != nil {
return x.Money
}
return 0
}
type LoginUserResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *LoginUserResponse) Reset() {
*x = LoginUserResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_user_service_userService_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *LoginUserResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*LoginUserResponse) ProtoMessage() {}
func (x *LoginUserResponse) ProtoReflect() protoreflect.Message {
mi := &file_user_service_userService_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use LoginUserResponse.ProtoReflect.Descriptor instead.
func (*LoginUserResponse) Descriptor() ([]byte, []int) {
return file_user_service_userService_proto_rawDescGZIP(), []int{1}
}
type DecreaseMoneyRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"`
MoneyAmount int32 `protobuf:"varint,2,opt,name=moneyAmount,proto3" json:"moneyAmount,omitempty"`
}
func (x *DecreaseMoneyRequest) Reset() {
*x = DecreaseMoneyRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_user_service_userService_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DecreaseMoneyRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DecreaseMoneyRequest) ProtoMessage() {}
func (x *DecreaseMoneyRequest) ProtoReflect() protoreflect.Message {
mi := &file_user_service_userService_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DecreaseMoneyRequest.ProtoReflect.Descriptor instead.
func (*DecreaseMoneyRequest) Descriptor() ([]byte, []int) {
return file_user_service_userService_proto_rawDescGZIP(), []int{2}
}
func (x *DecreaseMoneyRequest) GetUsername() string {
if x != nil {
return x.Username
}
return ""
}
func (x *DecreaseMoneyRequest) GetMoneyAmount() int32 {
if x != nil {
return x.MoneyAmount
}
return 0
}
type DecreaseMoneyResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *DecreaseMoneyResponse) Reset() {
*x = DecreaseMoneyResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_user_service_userService_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DecreaseMoneyResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DecreaseMoneyResponse) ProtoMessage() {}
func (x *DecreaseMoneyResponse) ProtoReflect() protoreflect.Message {
mi := &file_user_service_userService_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DecreaseMoneyResponse.ProtoReflect.Descriptor instead.
func (*DecreaseMoneyResponse) Descriptor() ([]byte, []int) {
return file_user_service_userService_proto_rawDescGZIP(), []int{3}
}
var File_user_service_userService_proto protoreflect.FileDescriptor
var file_user_service_userService_proto_rawDesc = []byte{
0x0a, 0x1e, 0x75, 0x73, 0x65, 0x72, 0x2d, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2f, 0x75,
0x73, 0x65, 0x72, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x12, 0x0c, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x22, 0x44,
0x0a, 0x10, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65,
0x73, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01,
0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x14,
0x0a, 0x05, 0x6d, 0x6f, 0x6e, 0x65, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x6d,
0x6f, 0x6e, 0x65, 0x79, 0x22, 0x13, 0x0a, 0x11, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x55, 0x73, 0x65,
0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x54, 0x0a, 0x14, 0x44, 0x65, 0x63,
0x72, 0x65, 0x61, 0x73, 0x65, 0x4d, 0x6f, 0x6e, 0x65, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x12, 0x1a, 0x0a, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20,
0x01, 0x28, 0x09, 0x52, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x20, 0x0a,
0x0b, 0x6d, 0x6f, 0x6e, 0x65, 0x79, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01,
0x28, 0x05, 0x52, 0x0b, 0x6d, 0x6f, 0x6e, 0x65, 0x79, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x22,
0x17, 0x0a, 0x15, 0x44, 0x65, 0x63, 0x72, 0x65, 0x61, 0x73, 0x65, 0x4d, 0x6f, 0x6e, 0x65, 0x79,
0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x32, 0xb2, 0x01, 0x0a, 0x04, 0x55, 0x73, 0x65,
0x72, 0x12, 0x4e, 0x0a, 0x09, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x55, 0x73, 0x65, 0x72, 0x12, 0x1e,
0x2e, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x4c, 0x6f,
0x67, 0x69, 0x6e, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1f,
0x2e, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x4c, 0x6f,
0x67, 0x69, 0x6e, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22,
0x00, 0x12, 0x5a, 0x0a, 0x0d, 0x44, 0x65, 0x63, 0x72, 0x65, 0x61, 0x73, 0x65, 0x4d, 0x6f, 0x6e,
0x65, 0x79, 0x12, 0x22, 0x2e, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63,
0x65, 0x2e, 0x44, 0x65, 0x63, 0x72, 0x65, 0x61, 0x73, 0x65, 0x4d, 0x6f, 0x6e, 0x65, 0x79, 0x52,
0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x73, 0x65,
0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x44, 0x65, 0x63, 0x72, 0x65, 0x61, 0x73, 0x65, 0x4d, 0x6f,
0x6e, 0x65, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x24, 0x5a,
0x22, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6d, 0x61, 0x74, 0x66,
0x2d, 0x70, 0x70, 0x2f, 0x32, 0x30, 0x32, 0x32, 0x5f, 0x4d, 0x41, 0x54, 0x44, 0x41, 0x51, 0x2f,
0x61, 0x70, 0x69, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_user_service_userService_proto_rawDescOnce sync.Once
file_user_service_userService_proto_rawDescData = file_user_service_userService_proto_rawDesc
)
func file_user_service_userService_proto_rawDescGZIP() []byte {
file_user_service_userService_proto_rawDescOnce.Do(func() {
file_user_service_userService_proto_rawDescData = protoimpl.X.CompressGZIP(file_user_service_userService_proto_rawDescData)
})
return file_user_service_userService_proto_rawDescData
}
var file_user_service_userService_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_user_service_userService_proto_goTypes = []interface{}{
(*LoginUserRequest)(nil), // 0: user_service.LoginUserRequest
(*LoginUserResponse)(nil), // 1: user_service.LoginUserResponse
(*DecreaseMoneyRequest)(nil), // 2: user_service.DecreaseMoneyRequest
(*DecreaseMoneyResponse)(nil), // 3: user_service.DecreaseMoneyResponse
}
var file_user_service_userService_proto_depIdxs = []int32{
0, // 0: user_service.User.LoginUser:input_type -> user_service.LoginUserRequest
2, // 1: user_service.User.DecreaseMoney:input_type -> user_service.DecreaseMoneyRequest
1, // 2: user_service.User.LoginUser:output_type -> user_service.LoginUserResponse
3, // 3: user_service.User.DecreaseMoney:output_type -> user_service.DecreaseMoneyResponse
2, // [2:4] is the sub-list for method output_type
0, // [0:2] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_user_service_userService_proto_init() }
func file_user_service_userService_proto_init() {
if File_user_service_userService_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_user_service_userService_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*LoginUserRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_user_service_userService_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*LoginUserResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_user_service_userService_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*DecreaseMoneyRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_user_service_userService_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*DecreaseMoneyResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_user_service_userService_proto_rawDesc,
NumEnums: 0,
NumMessages: 4,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_user_service_userService_proto_goTypes,
DependencyIndexes: file_user_service_userService_proto_depIdxs,
MessageInfos: file_user_service_userService_proto_msgTypes,
}.Build()
File_user_service_userService_proto = out.File
file_user_service_userService_proto_rawDesc = nil
file_user_service_userService_proto_goTypes = nil
file_user_service_userService_proto_depIdxs = nil
}
|
dkotik/mdsend
|
cmd/mdsend/main.go
|
<reponame>dkotik/mdsend
package main
import (
"fmt"
"log"
"os"
"strings"
"mdsend"
"mdsend/distributors"
"mdsend/loaders"
"mdsend/loggers"
"mdsend/providers"
"mdsend/renderers"
"github.com/spf13/cobra"
)
func main() {
o := &mdsend.Options{
Loader: &loaders.ViperLoader{},
Renderer: &renderers.GoTemplateMIMERenderer{},
Distributor: &distributors.LockingSynchronousBufferingDistributor{},
}
CLI := &cobra.Command{ // Setup command line interface.
Use: `mdsend`,
Version: mdsend.Version + ` Alpha`,
Short: `Sends markdown documents as templated emails.`,
Long: `Sends markdown documents as templated emails.`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
cmd.Help()
return
}
// this needs to be fixed up a little bit!
o.Provider = providers.NewMailgunProvider(o.URI)
if o.Verbose {
o.Logger = &loggers.Verbose{}
} else {
o.Logger = loggers.NewSpinner()
}
var answer string
for _, mdfile := range args { // that's crazy should only do one at a time ==========================================
handle, err := os.Open(mdfile)
if err != nil {
log.Fatalf(`Could not locate %s.`, mdfile)
}
message, err := o.Loader.Load(mdfile, handle)
if err != nil {
log.Fatalf(`Could not load %s, reason: %s.`, mdfile, err.Error())
}
handle.Close()
if !o.YesOnPrompt {
previewMessage(message)
fmt.Print("Type \"yes\" (or \"test\") to confirm sending the message: ")
fmt.Scanln(&answer)
switch strings.ToLower(strings.TrimSpace(answer)) {
case `test`:
o.Dryrun = true
fallthrough
case `yes`:
default:
log.Fatal(`User cancelled delivery.`)
}
}
mdsend.Send(message, o)
}
},
}
CLI.PersistentFlags().StringVarP(&o.URI, `uri`, `u`, os.Getenv(`MDSENDAPIURI`),
`API URI for current provider. Defaults to environment variable MDSENDAPIURI.`)
CLI.PersistentFlags().BoolVarP(&o.Verbose, `verbose`, `v`, false,
`Print information about every message as it is being sent.`)
CLI.PersistentFlags().BoolVarP(&o.YesOnPrompt, `yes`, `y`, false,
`Automatically confirm all prompts.`)
CLI.PersistentFlags().BoolVarP(&o.Dryrun, `dryrun`, `d`, false,
`Print information about every message as it is being sent using API test mode without locking previously undelivered messages.`)
CLI.Execute()
}
|
EvilMcJerkface/registry
|
atlas-integration/atlas-translate/src/main/java/com/cloudera/dim/atlas/types/FieldEntityDef.java
|
<gh_stars>100-1000
/**
* Copyright 2016-2020 Cloudera, 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.cloudera.dim.atlas.types;
import org.apache.atlas.model.typedef.AtlasEntityDef;
import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef.Cardinality;
import static com.google.common.collect.Lists.newArrayList;
public class FieldEntityDef extends AtlasEntityDef implements SchemaRegistryServiceType {
public static final String SCHEMA_FIELD_INFO = "schema_field_info"+TODORemoveThis.COUNTER;
public static final String ID = "id";
public static final String SCHEMA_INSTANCE_ID = "schemaInstanceId";
public static final String NAME = "name";
public static final String TIMESTAMP = "timestamp";
public static final String FIELD_NAMESPACE = "fieldNamespace";
public static final String TYPE = "type";
FieldEntityDef() {
setName(SCHEMA_FIELD_INFO);
setServiceType(SERVICE_TYPE);
setTypeVersion(TYPE_VERSION);
AtlasAttributeDef id = new AtlasAttributeDef(ID, ATLAS_TYPE_LONG, false, Cardinality.SINGLE);
id.setIsUnique(true);
AtlasAttributeDef schemaInstanceId = new AtlasAttributeDef(SCHEMA_INSTANCE_ID, ATLAS_TYPE_LONG, false, Cardinality.SINGLE);
AtlasAttributeDef name = new AtlasAttributeDef(NAME, ATLAS_TYPE_STRING, false, Cardinality.SINGLE);
name.setIsIndexable(true);
AtlasAttributeDef fieldNamespace = new AtlasAttributeDef(FIELD_NAMESPACE, ATLAS_TYPE_STRING, true, Cardinality.SINGLE);
AtlasAttributeDef type = new AtlasAttributeDef(TYPE, ATLAS_TYPE_STRING, false, Cardinality.SINGLE);
AtlasAttributeDef timestamp = new AtlasAttributeDef(TIMESTAMP, ATLAS_TYPE_LONG, false, Cardinality.SINGLE);
setAttributeDefs(newArrayList(
id, schemaInstanceId, name, fieldNamespace, type, timestamp
));
}
}
|
hosseinmoghimi/phoenix2
|
authentication/serializers.py
|
from .models import Profile
from rest_framework import serializers
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model=Profile
fields=['id','name','image','get_absolute_url']
|
SINeWang/summer
|
summer-io/src/test/java/one/kii/summer/asdf/api/TestPagingSearchApiCaller.java
|
<reponame>SINeWang/summer<gh_stars>0
package one.kii.summer.asdf.api;
import one.kii.summer.io.context.ReadContext;
import one.kii.summer.io.exception.BadRequest;
import one.kii.summer.io.exception.Panic;
import org.junit.Test;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.Errors;
import java.util.ArrayList;
import java.util.List;
/**
* Created by WangYanJiong on 22/07/2017.
*/
public class TestPagingSearchApiCaller {
static String[] keys = new String[]{};
static MultiValueMap map = new LinkedMultiValueMap();
ReadContext context = new ReadContext("requestId", "ownerId", "visitorId");
Object form = new Object();
@Test
public void testOK() {
PagingSearchApi api = new TestPagingSearchApiCaller.TestOK();
PagingSearchApi.Paging paging = new PagingSearchApi.Paging();
Errors errors = null;
Object resp = PagingSearchApiCaller.sync(api, context, form, paging, errors);
Assert.isInstanceOf(ResponseEntity.class, resp);
}
@Test
public void testBadRequest() {
PagingSearchApi api = new TestPagingSearchApiCaller.TestBadRequest();
PagingSearchApi.Paging paging = new PagingSearchApi.Paging();
Errors errors = null;
Object resp = PagingSearchApiCaller.sync(api, context, form, paging, errors);
Assert.isInstanceOf(ResponseEntity.class, resp);
}
@Test
public void testPanic() {
PagingSearchApi api = new TestPagingSearchApiCaller.TestPanic();
PagingSearchApi.Paging paging = new PagingSearchApi.Paging();
Errors errors = null;
Object resp = PagingSearchApiCaller.sync(api, context, form, paging, errors);
Assert.isInstanceOf(ResponseEntity.class, resp);
}
public static class TestOK implements PagingSearchApi {
@Override
public Receipt<Object> search(ReadContext context, Object form, Paging paging) throws BadRequest, Panic {
return new Receipt<>();
}
}
public static class TestBadRequest implements PagingSearchApi {
@Override
public Receipt search(ReadContext context, Object form, Paging paging) throws BadRequest, Panic {
throw new BadRequest(map);
}
}
public static class TestPanic implements PagingSearchApi {
@Override
public Receipt search(ReadContext context, Object form, Paging paging) throws BadRequest, Panic {
throw new Panic(keys);
}
}
}
|
robyparr/adjourn
|
app/models/agendum.rb
|
# typed: true
class Agendum < ApplicationRecord
include PgSearch::Model
include JsonExportable
multisearchable against: %i[title description],
additional_attributes: ->(agendum) { { user_id: agendum.meeting.user_id } }
# Relationships
belongs_to :meeting
has_one :user, through: :meeting
has_many :notes, class_name: 'AgendumNote', dependent: :destroy
has_many :uploads, as: :uploadable, dependent: :destroy
# Validations
validates :title, presence: true
validates :meeting, presence: true
# Hooks
before_create :set_position
# The SQL to execute when rebuilding the search
# document. This is needed to add the user's ID
# https://github.com/Casecommons/pg_search/wiki/
def self.rebuild_pg_search_documents
connection.execute %q{
INSERT INTO "pg_search_documents" (
user_id,
searchable_type,
searchable_id,
content,
created_at,
updated_at
)
SELECT
"meetings".user_id as user_id,
'Agendum' AS searchable_type,
"agendums".id AS searchable_id,
(
coalesce("agendums".title::text, '')
|| ' '
|| coalesce("agendums".description::text, '')
) AS content,
now() AS created_at,
now() AS updated_at
FROM "agendums"
INNER JOIN "meetings" on "agendums".meeting_id = "meetings".id
}
end
private
def next_position
meeting.agenda.maximum(:position).to_i + 1
end
def set_position
self.position = next_position
end
end
|
kevinkenzhao/Repy2
|
DEPENDENCIES/seash/pyreadline/console/ansi.py
|
# -*- coding: ISO-8859-1 -*-
import re,sys,os
terminal_escape = re.compile(u'(\001?\033\\[[0-9;]*m\002?)')
escape_parts = re.compile(u'\001?\033\\[([0-9;]*)m\002?')
class AnsiState(object):
def __init__(self,bold=False,inverse=False,color=u"white",background=u"black",backgroundbold=False):
self.bold = bold
self.inverse = inverse
self.color = color
self.background = background
self.backgroundbold = backgroundbold
trtable = {u"black":0, u"red":4, u"green":2, u"yellow":6,
u"blue":1, u"magenta":5, u"cyan":3, u"white":7}
revtable = dict(zip(trtable.values(),trtable.keys()))
def get_winattr(self):
attr = 0
if self.bold:
attr |= 0x0008
if self.backgroundbold:
attr |= 0x0080
if self.inverse:
attr |= 0x4000
attr |= self.trtable[self.color]
attr |= (self.trtable[self.background] << 4)
return attr
def set_winattr(self, attr):
self.bold = bool(attr & 0x0008)
self.backgroundbold = bool(attr & 0x0080)
self.inverse = bool(attr & 0x4000)
self.color = self.revtable[attr & 0x0007]
self.background = self.revtable[(attr & 0x0070) >> 4]
winattr=property(get_winattr,set_winattr)
def __repr__(self):
return u'AnsiState(bold=%s,inverse=%s,color=%9s,' \
u'background=%9s,backgroundbold=%s)# 0x%x'% \
(self.bold, self.inverse, '"%s"'%self.color,
'"%s"'%self.background, self.backgroundbold,
self.winattr)
def copy(self):
x = AnsiState()
x.bold = self.bold
x.inverse = self.inverse
x.color = self.color
x.background = self.background
x.backgroundbold = self.backgroundbold
return x
defaultstate = AnsiState(False,False,u"white")
trtable = {0:u"black", 1:u"red", 2:u"green", 3:u"yellow",
4:u"blue", 5:u"magenta", 6:u"cyan", 7:u"white"}
class AnsiWriter(object):
def __init__(self, default=defaultstate):
if isinstance(defaultstate, AnsiState):
self.defaultstate = default
else:
self.defaultstate=AnsiState()
self.defaultstate.winattr = defaultstate
def write_color(self,text, attr=None):
u'''write text at current cursor position and interpret color escapes.
return the number of characters written.
'''
if isinstance(attr,AnsiState):
defaultstate = attr
elif attr is None: #use attribute form initial console
attr = self.defaultstate.copy()
else:
defaultstate = AnsiState()
defaultstate.winattr = attr
attr = defaultstate
chunks = terminal_escape.split(text)
n = 0 # count the characters we actually write, omitting the escapes
res=[]
for chunk in chunks:
m = escape_parts.match(chunk)
if m:
parts = m.group(1).split(u";")
if len(parts) == 1 and parts[0] == u"0":
attr = self.defaultstate.copy()
continue
for part in parts:
if part == u"0": # No text attribute
attr = self.defaultstate.copy()
attr.bold=False
elif part == u"7": # switch on reverse
attr.inverse=True
elif part == u"1": # switch on bold (i.e. intensify foreground color)
attr.bold=True
elif len(part) == 2 and u"30" <= part <= u"37": # set foreground color
attr.color = trtable[int(part) - 30]
elif len(part) == 2 and u"40" <= part <= u"47": # set background color
attr.backgroundcolor = trtable[int(part) - 40]
continue
n += len(chunk)
if True:
res.append((attr.copy(), chunk))
return n,res
def parse_color(self,text, attr=None):
n,res=self.write_color(text, attr)
return n, [attr.winattr for attr, text in res]
def write_color(text, attr=None):
a = AnsiWriter(defaultstate)
return a.write_color(text, attr)
def write_color_old( text, attr=None):
u'''write text at current cursor position and interpret color escapes.
return the number of characters written.
'''
res = []
chunks = terminal_escape.split(text)
n = 0 # count the characters we actually write, omitting the escapes
if attr is None:#use attribute from initial console
attr = 15
for chunk in chunks:
m = escape_parts.match(chunk)
if m:
for part in m.group(1).split(u";"):
if part == u"0": # No text attribute
attr = 0
elif part == u"7": # switch on reverse
attr |= 0x4000
if part == u"1": # switch on bold (i.e. intensify foreground color)
attr |= 0x08
elif len(part) == 2 and u"30" <= part <= u"37": # set foreground color
part = int(part)-30
# we have to mirror bits
attr = (attr & ~0x07) | ((part & 0x1) << 2) | (part & 0x2) | ((part & 0x4) >> 2)
elif len(part) == 2 and u"40" <= part <= u"47": # set background color
part = int(part) - 40
# we have to mirror bits
attr = (attr & ~0x70) | ((part & 0x1) << 6) | ((part & 0x2) << 4) | ((part & 0x4) << 2)
# ignore blink, underline and anything we don't understand
continue
n += len(chunk)
if chunk:
res.append((u"0x%x"%attr, chunk))
return res
#trtable={0:"black",1:"red",2:"green",3:"yellow",4:"blue",5:"magenta",6:"cyan",7:"white"}
if __name__==u"__main__x":
import pprint
pprint=pprint.pprint
s=u"\033[0;31mred\033[0;32mgreen\033[0;33myellow\033[0;34mblue\033[0;35mmagenta\033[0;36mcyan\033[0;37mwhite\033[0m"
pprint (write_color(s))
pprint (write_color_old(s))
s=u"\033[1;31mred\033[1;32mgreen\033[1;33myellow\033[1;34mblue\033[1;35mmagenta\033[1;36mcyan\033[1;37mwhite\033[0m"
pprint (write_color(s))
pprint (write_color_old(s))
s=u"\033[0;7;31mred\033[0;7;32mgreen\033[0;7;33myellow\033[0;7;34mblue\033[0;7;35mmagenta\033[0;7;36mcyan\033[0;7;37mwhite\033[0m"
pprint (write_color(s))
pprint (write_color_old(s))
s=u"\033[1;7;31mred\033[1;7;32mgreen\033[1;7;33myellow\033[1;7;34mblue\033[1;7;35mmagenta\033[1;7;36mcyan\033[1;7;37mwhite\033[0m"
pprint (write_color(s))
pprint (write_color_old(s))
if __name__==u"__main__":
import console
import pprint
pprint=pprint.pprint
c=console.Console()
c.write_color(u"dhsjdhs")
c.write_color(u"\033[0;32mIn [\033[1;32m1\033[0;32m]:")
print
pprint (write_color(u"\033[0;32mIn [\033[1;32m1\033[0;32m]:"))
if __name__==u"__main__x":
import pprint
pprint=pprint.pprint
s=u"\033[0;31mred\033[0;32mgreen\033[0;33myellow\033[0;34mblue\033[0;35mmagenta\033[0;36mcyan\033[0;37mwhite\033[0m"
pprint (write_color(s))
|
Pivotal-Field-Engineering/spring-cloud
|
spring-cloud-localconfig-connector/src/main/java/org/springframework/cloud/localconfig/PropertiesFileResolver.java
|
<reponame>Pivotal-Field-Engineering/spring-cloud
package org.springframework.cloud.localconfig;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.text.StrLookup;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.springframework.cloud.util.EnvironmentAccessor;
/**
* Helper class that handles finding and merging properties to be read by the connector.
*
* @author <NAME>
*
*/
class PropertiesFileResolver {
public static final String BOOTSTRAP_PROPERTIES_FILENAME = "spring-cloud-bootstrap.properties";
private static final Logger logger = Logger.getLogger(PropertiesFileResolver.class.getName());
private final EnvironmentAccessor env;
private final String classpathPropertiesFilename;
PropertiesFileResolver(final EnvironmentAccessor env, final String classpathPropertiesFilename) {
this.env = env;
this.classpathPropertiesFilename = classpathPropertiesFilename;
}
PropertiesFileResolver(final EnvironmentAccessor env) {
this(env, BOOTSTRAP_PROPERTIES_FILENAME);
}
PropertiesFileResolver() {
this(new EnvironmentAccessor());
}
/**
* Inspects the system properties for an entry named {@value LocalConfigConnector#PROPERTIES_FILE_PROPERTY} directing it to an
* external properties file.
*
* @return a {@code File} pointing to the external properties file, or {@code null} if the system property couldn't be read
*/
File findCloudPropertiesFileFromSystem() {
String filename = null;
try {
filename = env.getSystemProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY);
} catch (SecurityException e) {
logger.log(Level.WARNING, "SecurityManager prevented reading system property "
+ LocalConfigConnector.PROPERTIES_FILE_PROPERTY, e);
return null;
}
if (filename == null) {
logger.fine("didn't find system property for a configuration file");
return null;
}
File file = new File(filename);
logger.info("found system property for a configuration file: " + file);
return file;
}
/**
* Looks for a resource named {@code filename} (usually {@value #BOOTSTRAP_PROPERTIES_FILENAME}) on the classpath. If present,
* it is loaded and
* inspected for a property named {@value LocalConfigConnector#PROPERTIES_FILE_PROPERTY}, which is interpolated from the system
* properties and returned.
*
* @return the filename derived from the classpath control file, or {@code null} if one couldn't be found
*/
File findCloudPropertiesFileFromClasspath() {
// see if we have a spring-cloud.properties at all
InputStream in = getClass().getClassLoader().getResourceAsStream(classpathPropertiesFilename);
if (in == null) {
logger.info("no " + classpathPropertiesFilename
+ " found on the classpath to direct us to an external properties file");
return null;
}
// load it as a properties file
Properties properties = new Properties();
try {
properties.load(in);
} catch (IOException e) {
logger.log(Level.SEVERE, "found " + classpathPropertiesFilename
+ " on the classpath but couldn't load it as a properties file", e);
return null;
}
// read the spring.cloud.propertiesFile property from it
String template = properties.getProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY);
if (template == null) {
logger.log(Level.SEVERE, "found properties file " + classpathPropertiesFilename
+ " on the classpath, but it didn't contain a property named " + LocalConfigConnector.PROPERTIES_FILE_PROPERTY);
return null;
}
// if there's anything else, the client probably tried to put an app ID or other credentials there
if (properties.entrySet().size() > 1)
logger.warning("the properties file " + classpathPropertiesFilename + " contained properties besides "
+ LocalConfigConnector.PROPERTIES_FILE_PROPERTY + "; ignoring");
logger.fine("substituting system properties into '" + template + "'");
File configFile = new File(new StrSubstitutor(systemPropertiesLookup(env)).replace(template));
logger.info("derived configuration file name: " + configFile);
return configFile;
}
File findCloudPropertiesFile() {
File file = findCloudPropertiesFileFromSystem();
if (file != null) {
logger.info("using configuration file from system properties");
return file;
}
file = findCloudPropertiesFileFromClasspath();
if (file != null)
logger.info("using configuration file derived from " + classpathPropertiesFilename);
else
logger.info("did not find any Spring Cloud configuration file");
return file;
}
/**
* Adapter from the {@link EnvironmentAccessor}'s system-property resolution to the {@code StrLookup} interface.
*
* @param env
* the {@code EnvironmentAccessor} to use for the lookups
* @return a {@code StrLookup} view of the accessor's system properties
*/
private StrLookup<String> systemPropertiesLookup(final EnvironmentAccessor env) {
return new StrLookup<String>() {
@Override
public String lookup(String key) {
return env.getSystemProperty(key);
}
};
}
}
|
lechium/iOS1351Headers
|
usr/libexec/itunesstored/PKPaymentAuthorizationControllerDelegate-Protocol.h
|
<gh_stars>1-10
//
// Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import "NSObject-Protocol.h"
@class PKContact, PKPayment, PKPaymentAuthorizationController, PKPaymentMethod, PKShippingMethod;
@protocol PKPaymentAuthorizationControllerDelegate <NSObject>
- (void)paymentAuthorizationControllerDidFinish:(PKPaymentAuthorizationController *)arg1;
@optional
- (void)paymentAuthorizationController:(PKPaymentAuthorizationController *)arg1 didSelectPaymentMethod:(PKPaymentMethod *)arg2 completion:(void (^)(NSArray *))arg3;
- (void)paymentAuthorizationController:(PKPaymentAuthorizationController *)arg1 didSelectShippingContact:(PKContact *)arg2 completion:(void (^)(long long, NSArray *, NSArray *))arg3;
- (void)paymentAuthorizationController:(PKPaymentAuthorizationController *)arg1 didSelectShippingMethod:(PKShippingMethod *)arg2 completion:(void (^)(long long, NSArray *))arg3;
- (void)paymentAuthorizationController:(PKPaymentAuthorizationController *)arg1 didSelectPaymentMethod:(PKPaymentMethod *)arg2 handler:(void (^)(PKPaymentRequestPaymentMethodUpdate *))arg3;
- (void)paymentAuthorizationController:(PKPaymentAuthorizationController *)arg1 didSelectShippingContact:(PKContact *)arg2 handler:(void (^)(PKPaymentRequestShippingContactUpdate *))arg3;
- (void)paymentAuthorizationController:(PKPaymentAuthorizationController *)arg1 didSelectShippingMethod:(PKShippingMethod *)arg2 handler:(void (^)(PKPaymentRequestShippingMethodUpdate *))arg3;
- (void)paymentAuthorizationControllerWillAuthorizePayment:(PKPaymentAuthorizationController *)arg1;
- (void)paymentAuthorizationController:(PKPaymentAuthorizationController *)arg1 didAuthorizePayment:(PKPayment *)arg2 completion:(void (^)(long long))arg3;
- (void)paymentAuthorizationController:(PKPaymentAuthorizationController *)arg1 didAuthorizePayment:(PKPayment *)arg2 handler:(void (^)(PKPaymentAuthorizationResult *))arg3;
@end
|
zlesko/fir_filter
|
src/firf_hp_tmp.h
|
#pragma once
#include <algorithm>
#include <cmath> // std::pow, std::ceil, std::fmod
#include <cfloat>
#include <climits>
#include <memory> // std::unique_ptr
#include <tuple>
#include <vector>
#include "errors_custom.h"
#include "firf_base.h"
#include "imp_resp_hp.h"
class firf_hp_tmp : public firf_base
{
private:
std::vector<double> const* _freq_cutoff;
std::vector<double> const* _atten;
imp_resp_hp _imp_resp;
public:
firf_hp_tmp();
firf_hp_tmp(double samplerate, double error_max, double freq_min,
double win_pow, double delay_frac);
public:
void Configure(double samplerate, double error_max, double freq_min,
double win_pow, double delay_frac,
std::vector<double> const* freq_cutoff,
std::vector<double> const* atten);
void Set_Parameters(std::vector<double> const* freq_cutoff,
std::vector<double> const* atten);
std::vector<double> Filter(std::vector<double> const& signal) override;
private:
bool Valid_Freq_Cutoff_Parameter(std::vector<double> const* freq_cutoff,
double samplerate) const;
bool Valid_atten_Parameter(std::vector<double> const* atten) const;
void Set_Imp_Resp();
std::tuple<double, double> Get_Parameters(long curr_sample,
long load_samples, std::vector<double>::size_type signal_size) const;
};
|
zhayh/awesome-spring-boot
|
chapter-4/spring-json/src/test/java/com/example/spring/json/SpringJsonApplicationTests.java
|
package com.example.spring.json;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringJsonApplicationTests {
@Test
void contextLoads() {
}
}
|
xiangdewei/hackrank
|
src/org/hackranck/java/BigIntegerTest.java
|
<gh_stars>0
package org.hackranck.java;
import java.math.BigInteger;
import java.util.Scanner;
/**
* Created by Dewei on 11/23/2016.
*/
public class BigIntegerTest {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String a=in.nextLine();
String b=in.nextLine();
BigInteger bigA=new BigInteger(a);
BigInteger bigB =new BigInteger(b);
System.out.println(bigA.add(bigB).toString());
System.out.println(bigA.multiply(bigB).toString());
}
}
|
APistole/KnightOnline
|
Client/WarFare/UITradeBBSSelector.h
|
<gh_stars>100-1000
// UITradeBBSSelector.h: interface for the CUITradeBBSSelector class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_UITRADEBBSSELECTOR_H__034D575A_E014_4C70_ABD5_EE647725A1DF__INCLUDED_)
#define AFX_UITRADEBBSSELECTOR_H__034D575A_E014_4C70_ABD5_EE647725A1DF__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "N3UIBase.h"
#include "N3UIButton.h"
#define TRADE_BBS_SELL 1
#define TRADE_BBS_BUY 2
#define TRADE_BBS_CANCEL 3
class CUITradeBBSSelector : public CN3UIBase
{
protected:
CN3UIButton* m_pBtn_BBSSell;
CN3UIButton* m_pBtn_BBSBuy;
CN3UIButton* m_pBtn_BBSCancel;
public:
void SetVisible(bool bVisible);
bool OnKeyPress(int iChar);
void MsgSend_OpenTradeBuyBBS();
void MsgSend_OpenTradeSellBBS();
bool Load(HANDLE hFile);
bool ReceiveMessage(CN3UIBase* pSender, uint32_t dwMsg);
CUITradeBBSSelector();
virtual ~CUITradeBBSSelector();
};
#endif // !defined(AFX_UITRADEBBSSELECTOR_H__034D575A_E014_4C70_ABD5_EE647725A1DF__INCLUDED_)
|
michaelkantor/wavemaker
|
wavemaker/wavemaker-runtime/src/test/java/com/wavemaker/runtime/server/testspring/DateReturnBean.java
|
/*
* Copyright (C) 2007-2009 WaveMaker Software, Inc.
*
* This file is part of the WaveMaker Server Runtime.
*
* 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.wavemaker.runtime.server.testspring;
/**
* @author <NAME>
*/
public class DateReturnBean {
long now;
public DateReturnBean() {
this.now = System.currentTimeMillis();
}
public java.util.Date getUtilDate() {
return new java.util.Date(this.now);
}
public java.sql.Date getSqlDate() {
return new java.sql.Date(this.now);
}
public long getNow() {
return this.now;
}
public java.sql.Date getSqlDateFromParam(java.sql.Date date) {
return new java.sql.Date(date.getTime() + 1);
}
public java.util.Date getUtilDateFromParam(java.util.Date date) {
return new java.util.Date(date.getTime() + 1);
}
public java.sql.Time getSqlTimeFromParam(java.sql.Time time) {
return new java.sql.Time(time.getTime() + 1);
}
public java.sql.Timestamp getSqlTimestampFromParam(java.sql.Timestamp time) {
return new java.sql.Timestamp(time.getTime() + 1);
}
public WrappedDate getWrappedDate(WrappedDate wd) {
return wd;
}
public static class WrappedDate {
private java.util.Date fooDate;
private java.sql.Date sqlDate;
private java.sql.Time sqlTime;
private java.sql.Timestamp sqlTimestamp;
public java.sql.Date getSqlDate() {
return this.sqlDate;
}
public void setSqlDate(java.sql.Date sqlDate) {
this.sqlDate = sqlDate;
}
public java.sql.Time getSqlTime() {
return this.sqlTime;
}
public void setSqlTime(java.sql.Time sqlTime) {
this.sqlTime = sqlTime;
}
public java.sql.Timestamp getSqlTimestamp() {
return this.sqlTimestamp;
}
public void setSqlTimestamp(java.sql.Timestamp sqlTimestamp) {
this.sqlTimestamp = sqlTimestamp;
}
public java.util.Date getFooDate() {
return this.fooDate;
}
public void setFooDate(java.util.Date fooDate) {
this.fooDate = fooDate;
}
}
}
|
matzipan/osal
|
src/os/posix/osnetwork.c
|
/*
* Copyright (c) 2018, United States government as represented by the
* administrator of the National Aeronautics Space Administration.
* All rights reserved. This software was created at NASA Glenn
* Research Center pursuant to government contracts.
*
* This is governed by the NASA Open Source Agreement and may be used,
* distributed and modified only according to the terms of that agreement.
*/
/**
* \file osnetwork.c
* \author <EMAIL>
*
* Purpose: This file contains the network functionality for the osapi.
*/
/****************************************************************************************
INCLUDE FILES
***************************************************************************************/
#include "os-posix.h"
/*
* FIXME: this belongs in the osconfig.h file, really.
*/
#define OS_NETWORK_SUPPORTS_IPV6
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#ifdef OS_INCLUDE_NETWORK
/*
* Leverage the POSIX-style File I/O as this will mostly work on RTEMS,
* with the exception that regular files cannot be passed to select(),
* which means that we should NOT set the O_NONBLOCK flag on filehandles
* like the standard POSIX OSAL does.
*/
const int OS_IMPL_SOCKET_FLAGS = O_NONBLOCK;
/****************************************************************************************
COMMON ROUTINES
After including the OS/C-library specific include files, the basic UNIX file API is used
****************************************************************************************/
/*
* The "bsd-socket" portable block includes the generic
* bsd-style network operations
*/
#include "../portable/os-impl-bsd-sockets.c"
/****************************************************************************************
IMPLEMENTATION-SPECIFIC ROUTINES
These are specific to this particular operating system
****************************************************************************************/
/*----------------------------------------------------------------
*
* Function: OS_NetworkGetID_Impl
*
* Purpose: Implemented per internal OSAL API
* See prototype in os-impl.h for argument/return detail
*
*-----------------------------------------------------------------*/
int32 OS_NetworkGetID_Impl (int32 *IdBuf)
{
/* BSD-style gethostid() has no failure modes */
*IdBuf = gethostid();
return OS_SUCCESS;
} /* end OS_NetworkGetID_Impl */
#else /* OS_INCLUDE_NETWORK */
/****************************************************************************************
NOT IMPLEMENTED OPTION
This block provides stubs in case this module is disabled by config
****************************************************************************************/
/*
* The "no-network" block includes the required API calls
* that all return OS_ERR_NOT_IMPLEMENTED
*/
#include "../portable/os-impl-no-network.c"
#endif
|
algohubhq/pipeline-operator
|
pkg/apis/algorun/v1beta1/model_algo_deployment_v1beta1.go
|
/*
* Algo.Run API 1.0-beta1
*
* API for the Algo.Run Engine
*
* API version: 1.0-beta1
* Contact: <EMAIL>
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package v1beta1
// AlgoDeploymentV1beta1 struct for AlgoDeploymentV1beta1
type AlgoDeploymentV1beta1 struct {
AlgoRef *CustomResourceRefV1beta1 `json:"algoRef,omitempty"`
Version string `json:"version"`
Index int32 `json:"index"`
ConfigMounts []ConfigMountModel `json:"configMounts,omitempty"`
Parameters []AlgoParamSpec `json:"parameters,omitempty"`
RetryEnabled bool `json:"retryEnabled,omitempty"`
RetryStrategy *TopicRetryStrategyModel `json:"retryStrategy,omitempty"`
WriteAllOutputs bool `json:"writeAllOutputs,omitempty"`
TimeoutSeconds int32 `json:"timeoutSeconds,omitempty"`
Topics []TopicConfigModel `json:"topics,omitempty"`
AlgoRunnerImage *ContainerImageModel `json:"algoRunnerImage,omitempty"`
Replicas int32 `json:"replicas,omitempty"`
Resources *ResourceRequirementsV1 `json:"resources,omitempty"`
Autoscaling *AutoScalingSpec `json:"autoscaling,omitempty"`
LivenessProbe *ProbeV1 `json:"livenessProbe,omitempty"`
ReadinessProbe *ProbeV1 `json:"readinessProbe,omitempty"`
Spec *AlgoSpecV1beta1 `json:"spec,omitempty"`
}
|
bogdansolga/spring-boot-training
|
d04/d04s05-caching/src/main/java/net/safedata/springboot/training/d05/s01/service/ProductService.java
|
package net.safedata.springboot.training.d05.s01.service;
import net.safedata.springboot.training.d05.s01.dto.ProductDTO;
import net.safedata.springboot.training.d05.s01.exceptions.NotFoundException;
import net.safedata.springboot.training.d05.s01.model.Product;
import net.safedata.springboot.training.d05.s01.repository.ProductRepository;
import net.safedata.springboot.training.d05.s01.config.CacheNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.function.Function;
@Service
public class ProductService {
private static final Logger LOGGER = LoggerFactory.getLogger(ProductService.class);
private final ProductRepository productRepository;
@Autowired
public ProductService(final ProductRepository productRepository) {
this.productRepository = productRepository;
}
@Cacheable(
cacheNames = CacheNames.PRODUCTS,
key = "#id"
)
public ProductDTO get(final int id) {
LOGGER.info("Getting the product with the ID {}...", id);
final Product product =
Optional.ofNullable(productRepository.get(id))
.orElseThrow(() -> new NotFoundException("There is no product with the id " + id));
return getProductConverter().apply(product);
}
@Async
@EventListener
@CacheEvict(
cacheNames = CacheNames.PRODUCTS,
key = "#id"
)
public void removeProduct(final int id) {
productRepository.remove(id);
}
private Function<Product, ProductDTO> getProductConverter() {
return product -> new ProductDTO(product.getId(), product.getName());
}
}
|
icryrainix/Notion
|
src/main/java/org/rsna/ctp/objects/FileObject.java
|
<gh_stars>0
/*---------------------------------------------------------------
* Copyright 2005 by the Radiological Society of North America
*
* This source software is released under the terms of the
* RSNA Public License (http://mirc.rsna.org/rsnapubliclicense)
*----------------------------------------------------------------*/
package org.rsna.ctp.objects;
import org.apache.log4j.Logger;
import org.rsna.util.DigestUtil;
import org.rsna.util.FileUtil;
import org.rsna.util.StringUtil;
import java.io.File;
/**
* A generic file object providing methods for moving, renaming, and copying a file.
* This is the base class for MIRC data files used for DICOM images and clinical trial
* metadata (both XML and zip).
*/
public class FileObject {
static final Logger logger = Logger.getLogger(FileObject.class);
File file = null;
/**
* Class constructor; creates the file object.
* @param file the file.
*/
public FileObject(File file) {
this.file = file;
}
/**
* Get the File pointing to the file.
* @return the File pointing to the file.
*/
public File getFile() {
return file;
}
/**
* Compute the MD5 digest of the contents of the file
* and return a hexadecimal string representing the result.
* @return the MD5 digest of the file.
*/
public String getDigest() {
return DigestUtil.digest("MD5", file, 16);
}
/**
* Replace all occurrences of a target regex with
* a replacement string and rename the file.
*/
public void filterFilename(String target, String replacement) {
String name = file.getName();
name = name.replaceAll(target,replacement);
File newFile = new File(file.getParentFile(),name);
file.renameTo(newFile);
file = newFile;
}
/**
* Get the file's name. The filename is all the characters if
* the name minus any standard extension. Files with non-
* standard extensions will have the extension in the returned
* filename.
* @return the extension of the object's filename.
*/
public String getName() {
String name = file.getName();
String stdext = getStandardExtension();
if (hasStandardExtension()) {
name = name.substring( 0, name.length() - stdext.length() );
}
return name;
}
/**
* Get the file's extension (the last period and the characters after
* it in the file name). Thus, the method returns ".dcm" for a file
* named "image.dcm".
* @return the extension of the object's filename.
*/
public String getExtension() {
return getExtension(file.getName());
}
/**
* Get the extension of a file (the last period and the characters after
* it in the file name). Thus, the method returns ".dcm" for a file
* named "image.dcm".
* @param name the filename.
* @return the extension of the specified filename.
*/
public static String getExtension(String name) {
int k = name.lastIndexOf(".");
if (k == -1) return "";
return name.substring(k);
}
/**
* Get the file's extension without the leading period.
* @return the extension of the object's filename.
*/
public String getExtensionNoDot() {
String ext = getExtension();
if (ext.startsWith(".")) ext = ext.substring(1);
return ext;
}
/**
* Set the file's extension (the last period and the characters after
* it in the file name). If the current extension is ".md", it is replaced
* the supplied extension. If the current extension is already equal to
* the supplied extension, the file is not renamed. If the current
* extension is anything else, the supplied extension is appended to
* the filename.
* @return the file after any modification.
*/
public File setExtension(String extension) {
if (extension.equals("")) return file;
String name = file.getName();
String nameLC = name.toLowerCase();
if (nameLC.endsWith(extension.toLowerCase())) return file;
if (nameLC.endsWith(".md")) {
name = name.substring(0, name.length()-3);
}
File newFile = new File(file.getParentFile(), name+extension);
file.renameTo(newFile);
file = newFile;
return file;
}
/**
* Set the standard extension for the FileObject
* if its subclass has a standard extension.
* This method does nothing in the FileObject class.
* @return the file without modification.
*/
public File setStandardExtension() {
return setExtension(getStandardExtension());
}
/**
* Determine whether this object has the standard extension
* for its type.
* @return true if this object's file has the standard
* extension.
*/
public boolean hasStandardExtension() {
return file.getName().toLowerCase().endsWith(getStandardExtension().toLowerCase());
}
/**
* Get the standard extension. This method is overridden by
* FileObject subclasses that have standard extensions.
* In the FileObject class, this method returns the empty
* string.
* @return the extension of the file.
*/
public String getStandardExtension() {
return "";
}
/**
* Get the object's class name. This method may be overridden by subclasses
* wishing to provide a better description of the type of the object.
* @return the type of the object.
*/
public String getType() {
String type = this.getClass().getName();
return type.substring(type.lastIndexOf(".")+1);
}
/**
* Get a prefix for a FileObject ("MD-").
* This method may be overridden by subclasses wishing
* to provide a better prefix for the object.
* @return a prefix for FileObjects.
*/
public String getTypePrefix() {
return "MD-";
}
/**
* Get the date associated with the file.
* @return the last modified date of the file.
*/
public String getDate() {
return StringUtil.getDate(file.lastModified(),"");
}
/**
* Dummy method returning an empty string for the study date of the object.
* This method is overridden by subclasses that can actually determine
* a meaningful value.
* @return the empty string.
*/
public String getStudyDate() {
return "";
}
/**
* Dummy method returning an empty string for the UID of the object.
* This method is overridden by subclasses that can actually determine
* a meaningful value.
* @return the empty string.
*/
public String getUID() {
return "";
}
/**
* Get the UID of the object. This method is overridden by the
* DicomObject subclass, where the concept of SOPInstanceUID is
* well-defined. For other subclasses, this method returns the
* value of the getUID() method.
* @return the object's unique identifier, if available; otherwise,
* the empty string.
*/
public String getSOPInstanceUID() {
return getUID();
}
/**
* Dummy method returning an empty string for the UID of the study.
* This method is overridden by subclasses that can actually determine
* a meaningful value.
* @return the empty string.
*/
public String getStudyUID() {
return "";
}
/**
* Get the StudyInstanceUID of the object. This method is overridden
* by the DicomObject subclass, where the concept of StudyInstanceUID is
* well-defined. For other subclasses, this method returns the value
* of the getStudyUID() method.
* @return the study's unique identifier, if available; otherwise, the empty string.
*/
public String getStudyInstanceUID() {
return getStudyUID();
}
/**
* Dummy method returning an empty string for the patient name.
* This method is overridden by subclasses that can actually determine
* a meaningful value.
* @return the empty string.
*/
public String getPatientName() {
return "";
}
/**
* Dummy method returning an empty string for the patient ID.
* This method is overridden by subclasses that can actually determine
* a meaningful value.
* @return the empty string.
*/
public String getPatientID() {
return "";
}
/**
* Dummy method returning an empty string for the accession number.
* This method is overridden by subclasses that can actually determine
* a meaningful value.
* @return the empty string.
*/
public String getAccessionNumber() {
return "";
}
/**
* Dummy method returning the file name for the Description.
* This method is overridden by subclasses that can actually determine
* a meaningful value.
* @return the file name as the description.
*/
public String getDescription() {
return file.getName();
}
/**
* Rename the file. If the supplied pathname is a directory,
* the file is renamed into the directory and given the
* same filename it had before. If the supplied pathname is not a
* directory, the file is renamed to the supplied pathname.
* This method also changes the File returned by getFile() so that
* it points to the renamed data file. Use this method to move the
* file within the same file system.
* @param newFile the new pathname of the file, or the pathname of the
* directory into which to rename the file.
* @return true if the rename was successful, false otherwise.
*/
public boolean renameTo(File newFile) {
if (newFile.isDirectory())
newFile = new File(newFile, file.getName());
boolean ok = file.renameTo(newFile);
if (ok) file = newFile;
return ok;
}
/**
* Rename the file to its UID, setting the standard extension.
* @return true if the rename was successful, false otherwise.
*/
public boolean renameToUID() {
String name = getUID();
File parent = file.getAbsoluteFile().getParentFile();
File newFile = new File(parent, name);
boolean ok = file.renameTo(newFile);
if (ok) {
file = newFile;
setStandardExtension();
}
return ok;
}
/**
* Copy the object's file. The original file is not deleted.
* @param destination the File pointing to where the copy is to be written.
* @return true if the operation succeeded completely; false otherwise.
*/
public boolean copyTo(File destination) {
if (file == null) return false;
return FileUtil.copy(file, destination);
}
/**
* Copy the object's file to a directory, assigning a new name if necessary.
* The original file is not deleted and the FileObject is unmodified.
* @param dir the File pointing to the directory into which the copy is to be written.
* @return the File pointing to the copy if the operation succeeded completely; null otherwise.
*/
public File copyToDirectory(File dir) {
if (file == null) return null;
try {
if (!dir.exists()) dir.mkdirs();
if (!dir.isDirectory()) return null;
File newFile = new File(dir, file.getName());
//Don't move the file if it is already in place.
if (file.getAbsolutePath().equals(newFile.getAbsolutePath()))
return file;
//Check whether the file exists in the destination directory.
if (newFile.exists()) {
//Don't overwrite; make a new name for the file.
newFile = File.createTempFile("ALT-","-"+file.getName(),dir);
}
//Move the file. First try to do it with a rename.
boolean ok = file.renameTo(newFile);
if (!ok) {
//That didn't work; try to do a copy.
ok = FileUtil.copy(file,newFile);
}
if (ok) return newFile;
return null;
}
catch (Exception ex) { return null; }
}
/**
* Move the object's data file, and remove it from its previous
* location. If the supplied pathname is a directory, the file is
* moved into the directory and given the same filename it had before.
* If the supplied pathname is not a directory, the file is given
* the name defined by the pathname. This method will overwrite a
* file with the same name in the destination directory. This method
* attempts to do the move with a rename, and only copies the file if
* the rename fails. This method also changes the File returned by
* getFile() so that it points to the data file in its new location.
* Use this method to move the file between file systems.
* @param newFile the new name of the file.
* @return true if the move was successful, false otherwise.
*/
public boolean moveTo(File newFile) {
if (newFile.isDirectory())
newFile = new File(newFile, file.getName());
//Don't bother to copy to yourself
if (file.getAbsolutePath().equals(newFile.getAbsolutePath()))
return true;
//Try to do it with a rename
boolean ok = file.renameTo(newFile);
if (!ok) {
//That didn't work; try to do a copy.
ok = FileUtil.copy(file,newFile);
//If that worked, then delete the original.
if (ok) file.delete();
}
if (ok) file = newFile;
return ok;
}
/**
* Move the object's data file into a directory and remove it
* from its previous location. This method changes the File
* returned by getFile() so that it points to the data file
* in its new location. This method creates the directory if
* it does not already exist.
* @param dir the directory into which to move the data file.
* @param overwrite true if the file is to be allowed to overwrite
* an existing file with the same name in the destination directory;
* false if a new name is to be created to prevent overwriting a
* file.
* @return true if the move was successful, false otherwise.
*/
public boolean moveToDirectory(File dir, boolean overwrite) {
return moveToDirectory(dir, file.getName(), overwrite);
}
/**
* Move the object's data file into a directory, creating a new
* name for the file if the filename already exists in the directory,
* and remove the file from its previous location. This method will
* therefore not overwrite an existing file. This method also changes
* the File returned by getFile() so that it points to the data file
* in its new location. This method creates the directory if it does
* not already exist. This method is intended for placing FileObjects
* into a holding directory.
* @param dir the directory into which to move the data file.
* @return true if the move was successful, false otherwise.
*/
public boolean moveToDirectory(File dir) {
return moveToDirectory(dir, file.getName(), false);
}
/**
* Move the object's data file into a directory, using the specified
* filename. If the filename already exists in the directory, create
* a new name for the file. Remove the file from its previous location.
* This method therefore does not overwrite an existing file. This
* method also changes the File returned by getFile() so that it points
* to the data file in its new location. This method creates the directory
* if it does not already exist. This method is intended for placing
* FileObjects into a document's directory.
* @param dir the directory into which to move the data file.
* @param name the name to use for the file in the new directory.
* @return true if the move was successful, false otherwise.
*/
public boolean moveToDirectory(File dir, String name) {
return moveToDirectory(dir, name, false);
}
//The actual move method. This isn't exposed because
//the other three methods cover all the use cases.
private boolean moveToDirectory(File dir, String name, boolean overwrite) {
if (!dir.exists()) dir.mkdirs();
if (!dir.isDirectory()) return false;
File newFile = new File(dir, name);
//Don't move the file if it is already in place.
if (file.getAbsolutePath().equals(newFile.getAbsolutePath()))
return true;
//Check whether it is okay to overwrite an existing file.
if (newFile.exists() && !overwrite) {
//Don't overwrite; make a new name for the file.
try { newFile = File.createTempFile("ALT-","-"+name,dir); }
catch (Exception ex) { return false; }
}
//Move the file. First try to do it with a rename.
boolean ok = file.renameTo(newFile);
if (!ok) {
//That didn't work; try to do a copy.
ok = FileUtil.copy(file,newFile);
//If that worked, then delete the original.
if (ok) file.delete();
}
if (ok) file = newFile;
return ok;
}
/**
* Set the last modified time of the file to the current time.
*/
public void touch() {
file.setLastModified(System.currentTimeMillis());
}
/**
* Determine whether this FileObject has an extension matching
* one of the entries in an array. The method can exclude FileObject
* subclasses (DicomObject, ZipObject, and XmlObject).
* @param textext the array of extensions. Each entry must start
* with a period (e.g., ".txt").
* @param excludeSubclasses true if subclasses are to be rejected;
* false if all FileObjects are to be tested.
* @return true if this FileObject has a matching extension; false otherwise.
*/
public boolean hasMatchingExtension(String[] textext, boolean excludeSubclasses) {
if (textext == null) return false;
if (excludeSubclasses) {
if (this instanceof DicomObject) return false;
if (this instanceof XmlObject) return false;
if (this instanceof ZipObject) return false;
}
String ext = getExtension();
for (int i=0; i<textext.length; i++) {
if (ext.equals(textext[i])) return true;
}
return false;
}
/**
* Get the name of the class or subclass of this object.
* @return the subclass name of this object.
*/
public String getClassName() {
if (this instanceof DicomObject) return "DicomObject";
else if (this instanceof XmlObject) return "XmlObject";
else if (this instanceof ZipObject) return "ZipObject";
else return "FileObject";
}
/**
* Factory to create a FileObject from a File, instantiating the
* correct subclass of FileObject.
* @param file the file to use to instantiate the FileObject.
* @return the instantiated FileObject.
*/
public static FileObject getInstance(File file) {
//First try to parse the object based on its extension.
String name = file.getName().toLowerCase();
boolean triedDICOM = false;
boolean triedXML = false;
boolean triedZip = false;
FileObject fileObject = null;
if (name.endsWith(".xml")) {
fileObject = tryXml(file);
triedXML = true;
}
else if (name.endsWith(".zip")) {
fileObject = tryZip(file);
triedZip = true;
}
else {
fileObject = tryDicom(file);
triedDICOM = true;
}
if (fileObject != null) return fileObject;
//That didn't work, now try the untried possibilities.
if (!triedDICOM)
fileObject = tryDicom(file);
if ((fileObject == null) && !triedZip)
fileObject = tryZip(file);
if ((fileObject == null) && !triedXML)
fileObject = tryXml(file);
if (fileObject == null)
fileObject = new FileObject(file);
return fileObject;
}
private static DicomObject tryDicom(File file) {
try { return new DicomObject(file); }
catch (Exception ex) { return null; }
}
private static XmlObject tryXml(File file) {
try { return new XmlObject(file); }
catch (Exception ex) { return null; }
}
private static ZipObject tryZip(File file) {
try { return new ZipObject(file); }
catch (Exception ex) { return null; }
}
}
|
FFMG/myoddweb.piger
|
myoddtest/string/teststring_find.cpp
|
<reponame>FFMG/myoddweb.piger
#include "string/string.h"
#include "../testcommon.h"
#include <gtest/gtest.h>
const struct test_find
{
std::wstring haystack;
std::wstring needle;
int32_t expected;
int32_t from;
friend std::ostream& operator <<(std::ostream& os, const test_find& obj)
{
return os
<< "Given : '" << myodd::strings::WString2String(obj.haystack) << "'"
<< " Expected : " << obj.expected ;
}
};
struct MyOddStringCaseSensitiveFind : testing::Test, testing::WithParamInterface<test_find>
{
};
struct MyOddStringCaseSensitiveFindFrom : MyOddStringCaseSensitiveFind
{
};
struct MyOddStringCaseInSensitiveFind : testing::Test, testing::WithParamInterface<test_find>
{
};
struct MyOddStringCaseInSensitiveFindFrom : MyOddStringCaseInSensitiveFind
{
};
TEST_P(MyOddStringCaseSensitiveFind, CaseSensitiveReplace)
{
auto haystack = GetParam().haystack;
auto needle = GetParam().needle;
auto expected = GetParam().expected;
// default 'from'
ASSERT_EQ(expected, myodd::strings::Find(haystack, needle ));
}
TEST_P(MyOddStringCaseInSensitiveFind, CaseInsSensitiveReplace)
{
auto haystack = GetParam().haystack;
auto needle = GetParam().needle;
auto expected = GetParam().expected;
ASSERT_EQ(expected, myodd::strings::Find(haystack, needle, 0, false ));
}
TEST_P(MyOddStringCaseInSensitiveFindFrom, CaseInsSensitiveReplaceWithFrom)
{
auto haystack = GetParam().haystack;
auto needle = GetParam().needle;
auto expected = GetParam().expected;
auto from = GetParam().from;
ASSERT_EQ(expected, myodd::strings::Find(haystack, needle, from, false));
}
TEST_P(MyOddStringCaseSensitiveFindFrom, CaseSensitiveReplace)
{
auto haystack = GetParam().haystack;
auto needle = GetParam().needle;
auto expected = GetParam().expected;
auto from = GetParam().from;
ASSERT_EQ(expected, myodd::strings::Find(haystack, needle, from));
}
INSTANTIATE_TEST_CASE_P(VariousCaseSensitiveFind, MyOddStringCaseSensitiveFind,
testing::Values(
test_find{ L"Hello", L"Hello", 0, 0 },
test_find{ L"Hello", L"hello", -1, 0 }, // case sensitive
test_find{ L"helloHello", L"Hello", 5, 0 },
test_find{ L"AxAxAx", L"Ax", 0, 0 }
));
INSTANTIATE_TEST_CASE_P(VariousCaseInSensitiveFind, MyOddStringCaseInSensitiveFind,
testing::Values(
test_find{ L"Hello", L"Hello", 0, 0 },
test_find{ L"Hello", L"hello", 0, 0 },
test_find{ L"helloHello", L"Hello", 0, 0 },
test_find{ L"AxAxAx", L"Ax", 0, 0 },
test_find{ L"AXaxAX", L"Ax", 0, 0 },
test_find{ L"AXaxAX", L"ax", 0, 0 }
));
INSTANTIATE_TEST_CASE_P(VariousCaseSensitiveFindWithFrom, MyOddStringCaseSensitiveFindFrom,
testing::Values(
test_find{ L"Hello", L"Hello", 0, 0 },
test_find{ L"Hello", L"hello", -1, 0 }, // case insensitive
test_find{ L"Hello", L"hello", -1, 1 }, // start from 1 + case insensitive
test_find{ L"Hello", L"Hello", -1, 1 }, // start from 1
test_find{ L"helloHello", L"Hello", 5, 0 },
test_find{ L"AxAxAx", L"Ax", 4, 3 },
test_find{ L"AxAxAx", L"Ax", 4, 4 },
test_find{ L"AxAxAx", L"Ax", -1, 10 } // past the len
));
INSTANTIATE_TEST_CASE_P(VariousCaseInSensitiveFindWithFrom, MyOddStringCaseInSensitiveFindFrom,
testing::Values(
test_find{ L"Hello", L"Hello", 0, 0 },
test_find{ L"Hello", L"hello", 0, 0 },
test_find{ L"helloHello", L"Hello", 0, 0 },
test_find{ L"AxAxAx", L"Ax", 0, 0 },
test_find{ L"AXaxAX", L"Ax", 4, 3 },
test_find{ L"AXaxAX", L"ax", 4, 4 }
));
|
haizhenhan/Kepler
|
kernel/2.6.32/drivers/misc/cb710/debug.c
|
/*
* cb710/debug.c
*
* Copyright by <NAME>, 2008-2009
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/cb710.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#define CB710_REG_COUNT 0x80
static const u16 allow[CB710_REG_COUNT/16] = {
0xFFF0, 0xFFFF, 0xFFFF, 0xFFFF,
0xFFF0, 0xFFFF, 0xFFFF, 0xFFFF,
};
static const char *const prefix[ARRAY_SIZE(allow)] = {
"MMC", "MMC", "MMC", "MMC",
"MS?", "MS?", "SM?", "SM?"
};
static inline int allow_reg_read(unsigned block, unsigned offset, unsigned bits)
{
unsigned mask = (1 << bits/8) - 1;
offset *= bits/8;
return ((allow[block] >> offset) & mask) == mask;
}
#define CB710_READ_REGS_TEMPLATE(t) \
static void cb710_read_regs_##t(void __iomem *iobase, \
u##t *reg, unsigned select) \
{ \
unsigned i, j; \
\
for (i = 0; i < ARRAY_SIZE(allow); ++i, reg += 16/(t/8)) { \
if (!(select & (1 << i))) \
continue; \
\
for (j = 0; j < 0x10/(t/8); ++j) { \
if (!allow_reg_read(i, j, t)) \
continue; \
reg[j] = ioread##t(iobase \
+ (i << 4) + (j * (t/8))); \
} \
} \
}
static const char cb710_regf_8[] = "%02X";
static const char cb710_regf_16[] = "%04X";
static const char cb710_regf_32[] = "%08X";
static const char cb710_xes[] = "xxxxxxxx";
#define CB710_DUMP_REGS_TEMPLATE(t) \
static void cb710_dump_regs_##t(struct device *dev, \
const u##t *reg, unsigned select) \
{ \
const char *const xp = &cb710_xes[8 - t/4]; \
const char *const format = cb710_regf_##t; \
\
char msg[100], *p; \
unsigned i, j; \
\
for (i = 0; i < ARRAY_SIZE(allow); ++i, reg += 16/(t/8)) { \
if (!(select & (1 << i))) \
continue; \
p = msg; \
for (j = 0; j < 0x10/(t/8); ++j) { \
*p++ = ' '; \
if (j == 8/(t/8)) \
*p++ = ' '; \
if (allow_reg_read(i, j, t)) \
p += sprintf(p, format, reg[j]); \
else \
p += sprintf(p, "%s", xp); \
} \
dev_dbg(dev, "%s 0x%02X %s\n", prefix[i], i << 4, msg); \
} \
}
#define CB710_READ_AND_DUMP_REGS_TEMPLATE(t) \
static void cb710_read_and_dump_regs_##t(struct cb710_chip *chip, \
unsigned select) \
{ \
u##t regs[CB710_REG_COUNT/sizeof(u##t)]; \
\
memset(®s, 0, sizeof(regs)); \
cb710_read_regs_##t(chip->iobase, regs, select); \
cb710_dump_regs_##t(cb710_chip_dev(chip), regs, select); \
}
#define CB710_REG_ACCESS_TEMPLATES(t) \
CB710_READ_REGS_TEMPLATE(t) \
CB710_DUMP_REGS_TEMPLATE(t) \
CB710_READ_AND_DUMP_REGS_TEMPLATE(t)
CB710_REG_ACCESS_TEMPLATES(8)
CB710_REG_ACCESS_TEMPLATES(16)
CB710_REG_ACCESS_TEMPLATES(32)
void cb710_dump_regs(struct cb710_chip *chip, unsigned select)
{
if (!(select & CB710_DUMP_REGS_MASK))
select = CB710_DUMP_REGS_ALL;
if (!(select & CB710_DUMP_ACCESS_MASK))
select |= CB710_DUMP_ACCESS_8;
if (select & CB710_DUMP_ACCESS_32)
cb710_read_and_dump_regs_32(chip, select);
if (select & CB710_DUMP_ACCESS_16)
cb710_read_and_dump_regs_16(chip, select);
if (select & CB710_DUMP_ACCESS_8)
cb710_read_and_dump_regs_8(chip, select);
}
EXPORT_SYMBOL_GPL(cb710_dump_regs);
|
NGliese/Embedded
|
linux/RPI/OutDoorMain_CCTV/LibraryModule-1.0-Source/docs/html/df/de1/_objects_2_timeservice_2utest_2test__main_8cpp.js
|
var _objects_2_timeservice_2utest_2test__main_8cpp =
[
[ "main", "df/de1/_objects_2_timeservice_2utest_2test__main_8cpp.html#a3c04138a5bfe5d72780bb7e82a18e627", null ]
];
|
benvanik/Feeds
|
Classes/FDEmailAddress.h
|
//
// FDEmailAddress.h
// Feeds
//
// Created by <NAME> on 10/7/08.
// Copyright 2008 <NAME> ( http://www.noxa.org ). All rights reserved.
//
#import <Foundation/Foundation.h>
/**
* Represents a simple e-mail address/name pair.
*/
@interface FDEmailAddress : NSObject {
NSString* name;
NSString* address;
}
/**
* The name of the owner of the e-mail address.
*/
@property (nonatomic, readonly) NSString* name;
/**
* The e-mail address in RFC 2822 format.
*/
@property (nonatomic, readonly) NSString* address;
@end
|
kyungissac/mist
|
mist-common/src/main/java/edu/snu/mist/common/graph/MISTEdge.java
|
/*
* Copyright (C) 2018 Seoul National University
*
* 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 edu.snu.mist.common.graph;
import edu.snu.mist.formats.avro.Direction;
/**
* This class represents an edge that has direction and index information.
*/
public final class MISTEdge {
/**
* A direction information.
* It is used to determine the edge direction toward streams having two upstreams.
*/
private final Direction direction;
/**
* An index information.
* It is used to determine the index of edge diverged from branch operator.
*
*/
private final int index;
/**
* The default value of index.
*/
private static final int DEFAULT_INDEX = 0;
public MISTEdge(final Direction direction) {
this(direction, DEFAULT_INDEX);
}
public MISTEdge(final Direction direction,
final int index) {
this.direction = direction;
this.index = index;
}
/**
* @return the index information
*/
public int getIndex() {
return index;
}
/**
* @return the direction information
*/
public Direction getDirection() {
return direction;
}
@Override
public boolean equals(final Object o) {
if (!(o instanceof MISTEdge)) {
return false;
} else {
return direction == ((MISTEdge) o).getDirection() &&
index == ((MISTEdge) o).getIndex();
}
}
@Override
public int hashCode() {
return 10 * direction.hashCode() + new Integer(index).hashCode();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.