text stringlengths 1 1.05M |
|---|
<gh_stars>1-10
from blocks.bricks import Brick
from blocks.bricks.base import application
class Flatten(Brick):
def __init__(self, ndim, debug=False, **kwargs):
super(Flatten, self).__init__(**kwargs)
self.ndim = ndim
self.debug = debug
@application(inputs=['input_'], outputs=['output'])
def apply(self, input_):
output = input_.flatten(ndim=self.ndim)
if self.debug:
import theano
output = theano.printing.Print('output:', attrs=('shape',))(output)
return output
|
<reponame>cc-ai/MaskGenerator_DA
import torch
from torchvision import transforms as trsfs
import torchvision.transforms.functional as TF
import numpy as np
class Resize:
def __init__(self, target_size):
assert isinstance(target_size, (int, tuple, list))
if not isinstance(target_size, int):
assert len(target_size) == 2
self.h, self.w = target_size
else:
self.h = self.w = target_size
self.h = int(self.h)
self.w = int(self.w)
def __call__(self, data):
return {task: TF.resize(im, (self.h, self.w)) for task, im in data.items()}
class RandomCrop:
def __init__(self, size):
assert isinstance(size, (int, tuple, list))
if isinstance(size, int):
self.h = self.w = size
else:
assert len(size) == 2
self.h, self.w = size
self.h = int(self.h)
self.w = int(self.w)
def __call__(self, data):
h, w = data["x"].size[-2:]
top = np.random.randint(0, h - self.h)
left = np.random.randint(0, w - self.w)
return {
task: TF.crop(im, top, left, self.h, self.w) for task, im in data.items()
}
class RandomVerticalFlip:
def __init__(self, p=0.5):
self.flip = TF.vflip
self.p = p
def __call__(self, data):
if np.random.rand() > self.p:
return data
return {task: self.flip(im) for task, im in data.items()}
class ToTensor:
def __init__(self):
self.ImagetoTensor = trsfs.ToTensor()
self.MaptoTensor = self.ImagetoTensor
def __call__(self, data):
new_data = {}
for task, im in data.items():
if task in {"x", "a", "rx"}:
new_data[task] = self.ImagetoTensor(im)
elif task in {"h", "d", "w", "m", "rm"}:
new_data[task] = self.MaptoTensor(im)
elif task == "s":
new_data[task] = torch.squeeze(torch.from_numpy(np.array(im))).to(
torch.int64
)
else:
print("ERROR: Task not found")
return new_data
class Normalize:
def __init__(self):
self.normImage = trsfs.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
# self.normSeg = trsfs.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
self.normDepth = trsfs.Normalize([1 / 255], [1 / 3])
self.normMask = lambda m: (m > ((torch.max(m) - torch.min(m)) / 2.0)).float()
self.normalize = {
"x": self.normImage,
# "s": self.normSeg,
"d": self.normDepth,
"m": self.normMask,
"rx": self.normImage,
"rm": self.normMask,
}
def __call__(self, data):
return {
task: self.normalize.get(task, lambda x: x)(tensor)
for task, tensor in data.items()
}
def get_transform(transform_item):
"""Returns the torchivion transform function associated to a
transform_item listed in opts.data.transforms ; transform_item is
an addict.Dict
"""
if transform_item.name == "crop" and not transform_item.ignore:
return RandomCrop((transform_item.height, transform_item.width))
if transform_item.name == "resize" and not transform_item.ignore:
return Resize(transform_item.new_size)
if transform_item.name == "hflip" and not transform_item.ignore:
return RandomVerticalFlip(p=transform_item.p or 0.5)
raise ValueError("Unknown transform_item {}".format(transform_item))
def get_transforms(opts):
"""Get all the transform functions listed in opts.data.transforms
using get_transform(transform_item)
"""
last_transforms = [ToTensor(), Normalize()]
conf_transforms = []
for t in opts.data.transforms:
if t.ignore:
continue
conf_transforms.append(get_transform(t))
return conf_transforms + last_transforms
|
<filename>src/main/java/com/groupon/nakala/core/Constants.java
/*
Copyright (c) 2013, Groupon, Inc.
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 GROUPON nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.groupon.nakala.core;
/**
* @author <EMAIL>
*/
public class Constants {
public static final String ANALYZER = "analyzer";
public static final String ANALYZERS = "analyzers";
public static final String BATCH_SIZE = "batch_size";
public static final String BLOCK_FILTER = "block_filter";
public static final String C = "c";
public static final String CLASS_NAME = "class_name";
public static final String COLLECTION_ANALYZER = "collection_analyzer";
public static final String COLLECTION_READER = "collection_reader";
public static final String DATA_STORES = "data_stores";
public static final String DOMAINS = "domains";
public static final String FEATURES = "features";
public static final String FILE_NAME = "file_name";
public static final String FILTER_QUERIES = "filter_queries";
public static final String FIND_BEST_PARAMETERS = "find_best_parameters";
public static final String GAMMA = "gamma";
public static final String GENERATE_NEGATIVE_QUERIES = "generate_negative_queries";
public static final String INDEX_DIR = "index_dir";
public static final String LABELS = "labels";
public static final String MAX_FEATURE_SIZE = "max_feature_size";
public static final String MAX_THRESHOLD = "max_threshold";
public static final String MIN_DF = "min_df";
public static final String MIN_FEATURE_WEIGHT = "min_feature_weight";
public static final String MIN_PRECISION = "min_precision";
public static final String MIN_THRESHOLD = "min_threshold";
public static final String MIN_TP = "min_tp";
public static final String MODEL = "model";
public static final String MODELS = "models";
public static final String NORMALIZE_BY_LENGTH = "normalize_by_length";
public static final String NORMALIZERS = "normalizers";
public static final String NUMBER_OF_THREADS = "number_of_threads";
public static final String OVERWRITE = "overwrite";
public static final String PARAMETERS = "parameters";
public static final String PASS_FILTER = "pass_filter";
public static final String POLITE = "polite";
public static final String PREDICT_PROBABILITIES = "predict_probabilities";
public static final String QUERY = "query";
public static final String REPRESENTER = "representer";
public static final String RESOURCE = "resource";
public static final String REUSE_INDEX = "reuse_index";
public static final String SAMPLE = "sample";
public static final String SCALER = "scaler";
public static final String STOPWORDS = "stopwords";
public static final String TARGET_CLASS = "target_class";
public static final String THRESHOLD = "threshold";
public static final String THRESHOLD_STEP = "threshold_step";
public static final String TOKENIZER = "tokenizer";
public static final String WEIGHTS = "weights";
public static final String RESOURCE_STREAM = "resource_stream";
public static final String USE_ABSOLUTE_VALUES = "use_absolute_values";
}
|
import React, { useEffect, useContext, useState } from 'react'
import { View, StyleSheet, Text, Modal, TouchableOpacity, Alert } from 'react-native'
import { ListPicker } from 'react-native-ultimate-modal-picker';
import { Picker } from '@react-native-community/picker'
import { decodeHTMLEntities } from '../utilities/decodeHTML';
import { AppContext } from '../provider/AppProvider'
import FlashCardContainer from './FlashCardContainer';
import * as Animateable from 'react-native-animatable'
import MaterialIcons from 'react-native-vector-icons/MaterialIcons'
import { LinearGradient } from 'expo-linear-gradient';
import { HOST_WITH_PORT } from '../environment';
export default function FormFilter() {
const state = useContext(AppContext)
// const [selectedCard, setSelectedCard] = useState(false);
useEffect(() => {
handleUserDecks(state.user.decks)
}, [state.user.decks])
const handleUserDecks = (decks) => {
decks.forEach(formatDecks)
state.setUserDeckNames(formattedDeckNames)
}
let formattedDeckNames = []
const formatDecks = (deck) => {
let container = {
label: deck.deck_name,
value: deck.id
}
formattedDeckNames.push(container)
}
useEffect(() => {
fetch("https://opentdb.com/api_category.php")
.then(response => response.json())
// .then(response => console.log(response))
.then(data => handleFetch(data.trivia_categories))
}, [])
const handleFetch = (categoryArray) => {
// console.log(categoryArray)
categoryArray.forEach(formatCategories)
state.setCategories(formattedCategories)
}
let formattedCategories = []
const formatCategories = (category) => {
let container = {
label: category.name,
value: category.id
}
// console.log(container)
formattedCategories.push(container)
}
const items = [
{ label: '1', value: '1' },
{ label: '2', value: '2' },
{ label: '3', value: '3' },
{ label: '4', value: '4' },
{ label: '5', value: '5' },
{ label: '6', value: '6' },
{ label: '7', value: '7' },
{ label: '8', value: '8' },
{ label: '9', value: '9' },
{ label: '10', value: '10' },
{ label: '11', value: '11' },
{ label: '12', value: '12' },
{ label: '13', value: '13' },
{ label: '14', value: '14' },
{ label: '15', value: '15' },
{ label: '16', value: '16' },
{ label: '17', value: '17' },
{ label: '18', value: '18' },
{ label: '19', value: '19' },
{ label: '20', value: '20' },
{ label: '21', value: '21' },
{ label: '22', value: '22' },
{ label: '23', value: '23' },
{ label: '24', value: '24' },
{ label: '25', value: '25' },
{ label: '26', value: '26' },
{ label: '27', value: '27' },
{ label: '28', value: '28' },
{ label: '29', value: '29' },
{ label: '30', value: '30' },
{ label: '31', value: '31' },
{ label: '32', value: '32' },
{ label: '33', value: '33' },
{ label: '34', value: '34' },
{ label: '35', value: '35' },
{ label: '36', value: '36' },
{ label: '37', value: '37' },
{ label: '38', value: '38' },
{ label: '39', value: '39' },
{ label: '40', value: '40' },
];
const handleSubmit = () => {
fetch(`https://opentdb.com/api.php?amount=${state.searchAmount}&category=${state.searchCategory}`)
.then(response => response.json())
.then(data => handleSearchFetch(data.results))
.catch(error => {
console.log("Error:", error)
})
}
const handleSearchFetch = (resultsArray) => {
resultsArray.forEach(formatSearchData)
state.setSearchResults(newArray)
state.setSearchSubmitted(true)
// console.log(newArray)
}
let newArray = [];
const formatSearchData = (result, index) => {
let newCardObject = {
id: `${index}-${Date.now()}`,
category: result.category,
question: decodeHTMLEntities(result.question),
answer: decodeHTMLEntities(result.correct_answer),
}
newArray.push(newCardObject)
}
const closeModal = () => {
state.setShow(false)
}
const addCard = () => {
fetch(`${HOST_WITH_PORT}/cards`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
question: state.selectedCard.question,
answer: state.selectedCard.answer,
deck_id: state.selectedDeck.id
})
})
Alert.alert(`Card added to ${state.selectedDeck.deck_name}.`)
state.setShow(false)
}
const pickerItems = state.userDeckNames.map((deck, i) => (
<Picker.Item key={i} value={deck.label} label={deck.label} id={deck.id} />
))
return (
<View style={styles.container}>
<Animateable.View
style={styles.header}
animation="fadeInDown"
>
<ListPicker
title="Category"
items={state.categories}
onChange={(item) => state.setSearchCategory(item)}
/>
<ListPicker
title="Number of Cards"
items={items}
onChange={(item) => state.setSearchAmount(item)}
/>
</Animateable.View>
{/* <View style={styles.button}>
<Button
title="Generate"
onPress={handleSubmit}
/>
</View> */}
<Animateable.View
style={styles.button}
animation="fadeIn"
>
<TouchableOpacity onPress={() => handleSubmit()}>
<LinearGradient
colors={['#F8F8F8', '#D3D3D3']}
style={styles.searchButton}
>
<Text style={styles.textSearch}>Generate</Text>
</LinearGradient>
</TouchableOpacity>
</Animateable.View>
{state.searchResults ?
<Animateable.View
style={styles.footer}
animation="fadeInUpBig"
>
<FlashCardContainer></FlashCardContainer>
</Animateable.View>
: null }
<Modal
transparent={true}
visible={state.show}
>
<View style={{backgroundColor: "#000000aa", flex: 1}}>
<View style={styles.modal}>
<Text style={{fontSize: 35}}>Choose Deck</Text>
<View >
<Picker
style={{width: '100%'}}
selectedValue={state.selectedDeck.deck_name}
onValueChange={(itemValue, itemIndex) => {state.setSelectedDeck({deck_name: itemValue, id: (itemIndex + 1)})}}
>
{pickerItems}
</Picker>
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity onPress={addCard}>
<LinearGradient
colors={['#505050', '#383838']}
style={styles.addButton}
>
<Text style={styles.textAdd}>Add Card</Text>
</LinearGradient>
</TouchableOpacity>
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity onPress={closeModal}>
<LinearGradient
colors={['#505050', '#383838']}
style={styles.addButton}
>
<Text style={styles.textAdd}>Cancel</Text>
</LinearGradient>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
</View>
)
}
const styles = StyleSheet.create({
// listContainer: {
// width: '100%',
// position: 'absolute',
// top: 0
// },
button: {
paddingTop: 14,
paddingBottom: 14,
alignItems: 'center'
},
container: {
flex: 1,
backgroundColor: '#004d46'
},
header: {
justifyContent: 'center',
alignItems: 'center'
},
footer: {
flex: 2,
backgroundColor: '#fff',
borderTopLeftRadius: 30,
borderTopRightRadius: 30,
paddingTop: 10,
paddingHorizontal: 10
},
searchButton: {
width: 150,
height: 40,
// paddingTop: 14,
// paddingBottom: 14,
// alignItems: 'center',
color: 'white',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 50,
flexDirection: 'row'
},
textSearch: {
color: 'black',
fontSize: 20,
fontWeight: 'bold'
},
buttonContainer: {
paddingTop: 15,
// flexDirection: 'row',
// justifyContent: 'space-between',
},
addButton: {
width: 150,
height: 40,
// paddingTop: 14,
// paddingBottom: 14,
// alignItems: 'center',
color: 'white',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 50,
flexDirection: 'row'
},
textAdd: {
color: 'white',
fontSize: 20,
fontWeight: 'bold'
},
modal: {
backgroundColor: '#ffffff',
margin: 50,
padding: 40,
borderRadius: 10,
flex: .3
},
}); |
<reponame>jordandavidson/MuckyFoot-UrbanChaos
// TexTab.hpp
// <NAME>, 20th February 1997
#ifndef _TEXTAB_HPP_
#define _TEXTAB_HPP_
#include "undo.hpp"
#include "ModeTab.hpp"
#include "Stealth.h"
#define FLAGS_SHOW_TEXTURE (1<<0)
#define FLAGS_QUADS (1<<1)
#define FLAGS_FIXED (1<<2)
class TextureTab : public ModeTab
{
private:
ULONG CurrentTexturePage,
TextureFlags;
SLONG TextureWidth,
TextureHeight,
TextureX,
TextureY,
TextureZoom;
EditorModule *Parent;
EdRect ClickRect[4],
TextureRect;
EdTexture CurrentTexture;
void do_undo_me_bloody_self_then(SLONG index);
public:
TextureTab(EditorModule *parent);
void DrawTabContent(void);
void DrawTexture(void);
void UpdateTexture(void);
void UpdateTextureInfo(void);
void HandleTab(MFPoint *current_point);
UWORD HandleTabClick(UBYTE flags,MFPoint *clicked_point);
void HandleControl(UWORD control_id);
UWORD ConvertFreeToFixedEle(struct TextureBits *t);
void ConvertFixedToFree(struct TextureBits *t);
inline ULONG GetTexturePage(void) { return CurrentTexturePage; }
inline void SetTexturePage(ULONG page) { CurrentTexturePage=page; }
inline EdTexture *GetTexture(void) { return &CurrentTexture; }
inline ULONG GetTextureFlags(void) { return TextureFlags; }
inline void SetTextureFlags(ULONG flags) { TextureFlags=flags; }
Undo MyUndo;
BOOL ApplyTexture(struct EditFace *edit_face);
};
#endif
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const b2MotorJoint_1 = require("./b2MotorJoint");
describe('B2MotorJoint', () => {
it('should be a function', () => {
expect(typeof b2MotorJoint_1.B2MotorJoint).toEqual('function');
});
});
|
#!/bin/sh
if [ -n "$DESTDIR" ] ; then
case $DESTDIR in
/*) # ok
;;
*)
/bin/echo "DESTDIR argument must be absolute... "
/bin/echo "otherwise python's distutils will bork things."
exit 1
esac
DESTDIR_ARG="--root=$DESTDIR"
fi
echo_and_run() { echo "+ $@" ; "$@" ; }
echo_and_run cd "/root/catkin_ws/src/geonav_transform"
# ensure that Python install destination exists
echo_and_run mkdir -p "$DESTDIR/root/catkin_ws/install/lib/python2.7/dist-packages"
# Note that PYTHONPATH is pulled from the environment to support installing
# into one location when some dependencies were installed in another
# location, #123.
echo_and_run /usr/bin/env \
PYTHONPATH="/root/catkin_ws/install/lib/python2.7/dist-packages:/root/catkin_ws/build/geonav_transform/lib/python2.7/dist-packages:$PYTHONPATH" \
CATKIN_BINARY_DIR="/root/catkin_ws/build/geonav_transform" \
"/usr/bin/python" \
"/root/catkin_ws/src/geonav_transform/setup.py" \
build --build-base "/root/catkin_ws/build/geonav_transform" \
install \
$DESTDIR_ARG \
--install-layout=deb --prefix="/root/catkin_ws/install" --install-scripts="/root/catkin_ws/install/bin"
|
<filename>src/calc-js-util.js
export function mult(a, b)
{
//This is my util method! Make sure it's included in the build
return a*b;
} |
<reponame>lexfaraday/hamburgo
package test.backend.www.model.hotelbeds;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import test.backend.www.model.hotelbeds.basic.messages.StatusRS;
import test.backend.www.model.hotelbeds.sdk.HotelApiClient;
import test.backend.www.model.hotelbeds.sdk.helpers.AvailRoom;
import test.backend.www.model.hotelbeds.sdk.helpers.Availability;
import test.backend.www.model.hotelbeds.sdk.helpers.Availability.DelimitedShape;
import test.backend.www.model.hotelbeds.sdk.types.HotelSDKException;
@Data
@Slf4j
public class HotelbedsService
{
public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE;
private final HotelApiClient hotelApiClient;
public HotelbedsService(String baseUrl, String key, String secret)
{
this.hotelApiClient = new HotelApiClient(baseUrl, key, secret);
try
{
this.hotelApiClient.init();
StatusRS statusRS = this.hotelApiClient.status();
log.info("Hotelbeds API connected, status: {}", statusRS.getStatus());
}
catch (HotelSDKException e)
{
log.error("Error testing Hotelbeds API status", e);
}
}
public Object getAvailability(String latitude, String longitude, LocalDate from, LocalDate to, long limitKm)
{
try
{
DelimitedShape withinThis = new Availability.Circle(longitude, latitude, limitKm);
Availability availability = Availability
.builder()
.checkIn(from)
.addRoom(AvailRoom.builder().adults(1))
.checkOut(to)
.withinThis(withinThis)
.build();
return hotelApiClient.availability(availability);
}
catch (HotelSDKException e)
{
log.error("Error getting availability", e);
return e.getError();
}
}
}
|
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AwsNative.AmplifyUIBuilder.Inputs
{
public sealed class ComponentVariantArgs : Pulumi.ResourceArgs
{
[Input("componentId")]
public Input<string> ComponentId { get; set; }
[Input("displayName")]
public Input<string> DisplayName { get; set; }
[Input("description")]
public Input<string> Description { get; set; }
[Input("settings")]
public Input<ImmutableDictionary<string, Input<string>>> Settings { get; set; }
[Input("tags")]
public Input<ImmutableDictionary<string, Input<string>>> Tags { get; set; }
}
} |
<filename>spring-boot-examples/spring-boot-mybatis/src/main/java/com/yin/springboot/mybatis/server/PmsProductVertifyRecordService.java
package com.yin.springboot.mybatis.server;
import java.util.List;
import com.yin.springboot.mybatis.domain.PmsProductVertifyRecord;
public interface PmsProductVertifyRecordService{
int deleteByPrimaryKey(Long id);
int insert(PmsProductVertifyRecord record);
int insertOrUpdate(PmsProductVertifyRecord record);
int insertOrUpdateSelective(PmsProductVertifyRecord record);
int insertSelective(PmsProductVertifyRecord record);
PmsProductVertifyRecord selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(PmsProductVertifyRecord record);
int updateByPrimaryKey(PmsProductVertifyRecord record);
int updateBatch(List<PmsProductVertifyRecord> list);
int batchInsert(List<PmsProductVertifyRecord> list);
}
|
<reponame>FavPiggy/EasterEgg
package edu.uw.tacoma.piggy.model.dao;
import java.sql.Date;
import java.util.Calendar;
import java.util.List;
import junit.framework.Assert;
import junit.framework.TestCase;
import edu.uw.tacoma.piggy.model.entity.RoleEntity;
/**
* The test case for the Role DAO
* @author <NAME>
*/
public class RoleDAOTest
extends TestCase
{
public void testRole()
{
RoleEntity entity;
List<RoleEntity> list = RoleDAO.listRole();
Assert.assertEquals("The test list Role method failed ", 4, list.size());
// should set different field values
entity = new RoleEntity();
entity.setRoleID(10);
entity.setRoleName("");
entity.setDescription("");
entity.setDateCreated(new Date(Calendar.getInstance().getTime().getTime()));
Assert.assertTrue("The test insert method failed ", RoleDAO.insert(entity));
entity.setRoleID(10);
entity.setRoleName("");
entity.setDescription("");
entity.setDateCreated(new Date(Calendar.getInstance().getTime().getTime()));
Assert.assertTrue("The test update method failed ", RoleDAO.update(entity));
Assert.assertTrue("The test delete method failed ", RoleDAO.delete(entity));
}
}
|
#include <iostream>
#include <vector>
#include <cstring>
#include <acl/CoreSocket.h>
void networkStressTest(const std::string& host, int port, size_t numSockets, size_t packetSize) {
std::cout << "Testing connecting " << numSockets << " sockets..." << std::endl;
std::vector<acl::CoreSocket::SOCKET> socks;
for (size_t i = 0; i < numSockets; i++) {
acl::CoreSocket::SOCKET sock;
if (!connect_tcp_to(host.c_str(), port, nullptr, &sock)) {
std::cerr << "Error opening write socket " << i << std::endl;
// Handle error and clean up opened sockets
for (auto& s : socks) {
close_socket(s);
}
return;
}
if (!set_tcp_socket_options(sock)) {
std::cerr << "Error setting TCP socket options on socket " << i << std::endl;
// Handle error and clean up opened sockets
for (auto& s : socks) {
close_socket(s);
}
close_socket(sock);
return;
}
socks.push_back(sock);
}
// Send packet to each connection
for (auto& sock : socks) {
char* packet = new char[packetSize];
// Populate packet with data
// ...
if (send(sock, packet, packetSize, 0) != packetSize) {
std::cerr << "Error sending packet on socket " << sock << std::endl;
// Handle error and continue sending to other sockets
}
delete[] packet;
}
// Close all opened sockets
for (auto& sock : socks) {
close_socket(sock);
}
} |
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const mysql = require('mysql');
const app = express();
app.use(bodyParser.json());
app.use(session({
secret: 'secret-key',
resave: false,
saveUninitialized: false,
}));
let con = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'database',
});
app.post('/register', (req, res) => {
let sqlQuery = `INSERT INTO users (username, password) VALUES (?, ?)`;
con.query(sqlQuery, [req.body.username, req.body.password], (err, result) => {
if(err) throw err;
req.session.user = req.body;
res.send({message: 'User registered'});
});
});
app.post('/login', (req, res) => {
let sqlQuery = `SELECT * FROM users WHERE username = ? and password = ?`;
con.query(sqlQuery, [req.body.username, req.body.password], (err, result) => {
if(err) throw err;
if (result.length > 0) {
req.session.user = result[0];
res.send({message: 'Logged in'});
} else {
res.send({message: 'Invalid username or password'});
}
});
});
app.get('/protected', (req, res) => {
if (req.session.user) {
res.send({message: 'You are authorized'});
} else {
res.send({message: 'You are not authorized'});
}
});
app.listen(3000, () => console.log('Server started')); |
<reponame>dbatten5/dagster
# pylint: disable=unused-argument, no-value-for-parameter
# start_marker
import random
from dagster import Output, OutputDefinition, pipeline, solid
@solid(
output_defs=[
OutputDefinition(name="branch_1", is_required=False),
OutputDefinition(name="branch_2", is_required=False),
]
)
def branching_solid():
num = random.randint(0, 1)
if num == 0:
yield Output(1, "branch_1")
else:
yield Output(2, "branch_2")
@solid
def branch_1_solid(_input):
pass
@solid
def branch_2_solid(_input):
pass
@pipeline
def branching_pipeline():
branch_1, branch_2 = branching_solid()
branch_1_solid(branch_1)
branch_2_solid(branch_2)
# end_marker
|
sudo bash -c 'echo "{ \"cgroup-parent\": \"/actions_job\",\"experimental\":true}" > /etc/docker/daemon.json'
sudo systemctl restart docker.service |
/**
* Module: http-mock
*
* The interface for this entire module that just exposes the exported
* functions from the other libraries.
*/
var request = require( './mockRequest' ),
response = require( './mockResponse' );
exports.createRequest = request.createRequest;
exports.createResponse = response.createResponse; |
import { DataMapper } from "../../src";
const data: DataMapper = {
"/api/setCounter": [
{
request: {
method: "POST",
data: /"id":3,"operate":-1/,
},
response: {
status: 200,
json: {
result: -100,
},
},
},
],
};
export default data;
|
<gh_stars>0
package cn.finalteam.rxgalleryfinalprovider.presenter;
/**
* Desction:activity fragment presenter
* Author:pengjianbo
* Date:16/5/14 下午11:12
*/
public interface ActivityFragmentPresenter {
}
|
#!/bin/bash
echo "------ Thank you for choosing node-rest-api-starter template -------"
echo "------ Setting up your node-project -------"
cp .env.example .env
# generate keys
cd keys
echo "------ Generating private and public keys-------"
openssl genrsa -out private.pem 512
openssl rsa -in private.pem -outform PEM -pubout -out public.pem
openssl genrsa -out privater.pem 512
openssl rsa -in privater.pem -outform PEM -pubout -out publicr.pem
cd ..
npm install
echo "------ Please setup your project-------"
printf "Enter your project name: "
read -r pj_name
printf "Enter your github username: "
read -r gh_uname
#echo $pj_name
file=$(<package.json)
#echo $o_file
#file = sed -e "s/node-rest-api-starter/$pj_name/g" package.json
#file = sed -e "s/fayaz07/$gh_uname/g" file
#echo $file
file="${file//node-rest-api-starter/$pj_name}"
file="${file//fayaz07/$gh_uname}"
file="${file//Mohammad Fayaz/ }"
#echo $f1
echo $file > "package.json"
npm run format
echo "------ Your project has been setup, please star our repo if you like it. -------" |
#!/bin/bash
CLIPBOARD_DIR="/Clipboard"
# system detection
unameOut="$(uname -s)"
case "${unameOut}" in
Linux*) machine=Linux;;
Darwin*) machine=Mac;;
CYGWIN*) machine=Cygwin;;
MINGW*) machine=MinGw;;
*) machine="UNKNOWN:${unameOut}"
esac
case "${machine}" in
Linux)
;;
*)
echo "Unsupported system. Linux only for now."
exit
;;
esac
# check if /clipboard folder not exists
if [ ! -d "${CLIPBOARD_DIR}" ]; then
sudo mkdir "${CLIPBOARD_DIR}"
sudo chmod 777 "${CLIPBOARD_DIR}"
echo "Created open access clipboard folder in /"
fi
# reading arguments
mode="$1" # first arg, mode
shift # remove the first argument (mode) from the list
case "$mode" in
-c|--copy)
echo "Copy"
for file in "$@" ; do
cp "$file" "${CLIPBOARD_DIR}"
done
;;
-x|--cut)
echo "Cut"
for file in "$@" ; do
mv "$file" "${CLIPBOARD_DIR}"
done
;;
-v|-p|--paste)
echo "Paste"
mv "${CLIPBOARD_DIR}"/* "$PWD"
;;
*) # unknown option
echo "Unknown options"
;;
esac |
#!/bin/bash
# check :
# bash script.sh
# tmux attach -t script_mol_opt
# tmux detach
# pkill python
# bash script_main_superpixels_graph_classification_CIFAR10.sh
############
# GNNs
############
#GatedGCN
#GCN
#GraphSage
#MLP
#GIN
#MoNet
#GAT
#DiffPool
############
# CIFAR - 4 RUNS
############
seed0=41
seed1=95
seed2=12
seed3=35
code=main_superpixels_graph_classification.py
tmux new -s benchmark_superpixels_graph_classification -d
tmux send-keys "source activate benchmark_gnn" C-m
dataset=CIFAR10
tmux send-keys "
python $code --dataset $dataset --gpu_id 0 --seed $seed0 --config 'configs/superpixels_graph_classification_MLP_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 1 --seed $seed1 --config 'configs/superpixels_graph_classification_MLP_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 2 --seed $seed2 --config 'configs/superpixels_graph_classification_MLP_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 3 --seed $seed3 --config 'configs/superpixels_graph_classification_MLP_CIFAR10.json' &
wait" C-m
tmux send-keys "
python $code --dataset $dataset --gpu_id 0 --seed $seed0 --config 'configs/superpixels_graph_classification_MLP_GATED_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 1 --seed $seed1 --config 'configs/superpixels_graph_classification_MLP_GATED_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 2 --seed $seed2 --config 'configs/superpixels_graph_classification_MLP_GATED_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 3 --seed $seed3 --config 'configs/superpixels_graph_classification_MLP_GATED_CIFAR10.json' &
wait" C-m
tmux send-keys "
python $code --dataset $dataset --gpu_id 0 --seed $seed0 --config 'configs/superpixels_graph_classification_GIN_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 1 --seed $seed1 --config 'configs/superpixels_graph_classification_GIN_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 2 --seed $seed2 --config 'configs/superpixels_graph_classification_GIN_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 3 --seed $seed3 --config 'configs/superpixels_graph_classification_GIN_CIFAR10.json' &
wait" C-m
tmux send-keys "
python $code --dataset $dataset --gpu_id 0 --seed $seed0 --config 'configs/superpixels_graph_classification_GCN_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 1 --seed $seed1 --config 'configs/superpixels_graph_classification_GCN_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 2 --seed $seed2 --config 'configs/superpixels_graph_classification_GCN_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 3 --seed $seed3 --config 'configs/superpixels_graph_classification_GCN_CIFAR10.json' &
wait" C-m
tmux send-keys "
python $code --dataset $dataset --gpu_id 0 --seed $seed0 --config 'configs/superpixels_graph_classification_GraphSage_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 1 --seed $seed1 --config 'configs/superpixels_graph_classification_GraphSage_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 2 --seed $seed2 --config 'configs/superpixels_graph_classification_GraphSage_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 3 --seed $seed3 --config 'configs/superpixels_graph_classification_GraphSage_CIFAR10.json' &
wait" C-m
tmux send-keys "
python $code --dataset $dataset --gpu_id 0 --seed $seed0 --config 'configs/superpixels_graph_classification_GatedGCN_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 1 --seed $seed1 --config 'configs/superpixels_graph_classification_GatedGCN_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 2 --seed $seed2 --config 'configs/superpixels_graph_classification_GatedGCN_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 3 --seed $seed3 --config 'configs/superpixels_graph_classification_GatedGCN_CIFAR10.json' &
wait" C-m
tmux send-keys "
python $code --dataset $dataset --gpu_id 0 --seed $seed0 --config 'configs/superpixels_graph_classification_GAT_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 1 --seed $seed1 --config 'configs/superpixels_graph_classification_GAT_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 2 --seed $seed2 --config 'configs/superpixels_graph_classification_GAT_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 3 --seed $seed3 --config 'configs/superpixels_graph_classification_GAT_CIFAR10.json' &
wait" C-m
tmux send-keys "
python $code --dataset $dataset --gpu_id 0 --seed $seed0 --config 'configs/superpixels_graph_classification_DiffPool_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 1 --seed $seed1 --config 'configs/superpixels_graph_classification_DiffPool_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 2 --seed $seed2 --config 'configs/superpixels_graph_classification_DiffPool_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 3 --seed $seed3 --config 'configs/superpixels_graph_classification_DiffPool_CIFAR10.json' &
wait" C-m
tmux send-keys "
python $code --dataset $dataset --gpu_id 0 --seed $seed0 --config 'configs/superpixels_graph_classification_MoNet_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 1 --seed $seed1 --config 'configs/superpixels_graph_classification_MoNet_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 2 --seed $seed2 --config 'configs/superpixels_graph_classification_MoNet_CIFAR10.json' &
python $code --dataset $dataset --gpu_id 3 --seed $seed3 --config 'configs/superpixels_graph_classification_MoNet_CIFAR10.json' &
wait" C-m
tmux send-keys "tmux kill-session -t benchmark_superpixels_graph_classification" C-m
|
python ./codes/main.py --exp_dir ./experiments_BD/EGVSR/001 --mode test --model EGVSR --opt test.yml --gpu_id 0
python ./codes/main.py --exp_dir ./experiments_BD/FRVSR/001 --mode test --model FRVSR --opt test.yml --gpu_id 0
python ./codes/main.py --exp_dir ./experiments_BD/TecoGAN/001 --mode test --model TecoGAN --opt test.yml --gpu_id 0
python ./codes/main.py --exp_dir ./experiments_BD/VESPCN/001 --mode test --model VESPCN --opt test.yml --gpu_id 0
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import './Homes.css';
import HomeForm from './HomeForm';
import HomeCard from '../components/HomeCard';
import { getHomes } from '../actions/homes';
import { getZPID } from '../actions/searches';
import { deleteHome } from '../actions/homes';
class Homes extends Component {
componentDidMount() {
if (this.props.user) {
this.props.getHomes(this.props.user)
}
}
componentDidUpdate(prevProps) {
if (this.props.user !== prevProps.user) {
this.props.getHomes(this.props.user)
}
}
render() {
return (
<div className="HomesContainer">
{ this.props.user ?
<div>
<HomeForm />
{this.props.homes.map(home =>
<HomeCard key={home.id} home={home} deleteHome={this.props.deleteHome} user={this.props.user} getZPID={this.props.getZPID} />
)}
</div>
:
<h2>Please log in to save searches.</h2>
}
</div>
);
}
}
const mapStateToProps = (state) => {
return ({
homes: state.homes,
user: state.user.user.id
})
}
export default connect(mapStateToProps, { getHomes, getZPID, deleteHome })(Homes);
|
#!/bin/bash
export LC_ALL=C
# Begin configuration section.
dataset=data/dev
# End configuration options.
echo "$0 $@" # Print the command line for logging
[ -f path.sh ] && . ./path.sh # source the path.
. parse_options.sh || exit 1;
if [ $# -lt 3 ]; then
echo "usage: common/recognize.sh am_models base_lm big_lm"
echo "e.g.: common/recognize.sh tri2b,tri4a data/recog_langs/word_s_20k_2gram data/recog_langs/word_s_20k_5gram"
echo "main options (for others, see top of script file)"
exit 1;
fi
. ./cmd.sh ## You'll want to change cmd.sh to something that will work on your system.
## This relates to the queue.
#. common/slurm_dep_graph.sh
job=echo
JOB_PREFIX=$(cat id)_
ammodels=$1
smalllm=$2
biglm=$3
sname=$(basename $smalllm)
bname=$(basename $biglm)
prev=NONE
IFS=,
ams=(${ammodels})
#nj=$(cat ${dataset}/spk2utt | wc -l)
nj=10
extra_args=""
for am in "${ams[@]}"; do
sam=$(basename ${am})
case $am in
mono*)
echo ${sam} 50 2 $prev -- utils/mkgraph.sh --mono ${smalllm} exp/${am} exp/${am}/graph_${sname}
;;
tri*|nnet*)
echo ${sam} 50 2 $prev -- utils/mkgraph.sh ${smalllm} exp/${am} exp/${am}/graph_${sname}
;;
chain*)
echo ${sam} 50 2 $prev -- utils/mkgraph.sh --left-biphone --self-loop-scale 1.0 ${smalllm} exp/${am} exp/${am}/graph_${sname}
esac
case $am in
mono*|tri[1-2]*)
echo dec_bl_${am} 1 40 LAST -- steps/decode_biglm.sh --nj ${nj} --cmd "$big_decode_cmd" exp/${am}/graph_${sname} $smalllm/G.fst ${biglm}/G.fst ${dataset} exp/${am}/decode_${sname}_bl_${bname}
;;
tri[3-4]*)
echo dec_${am} 1 40 LAST -- steps/decode_fmllr.sh --nj ${nj} --cmd "$decode_cmd" --max-fmllr-jobs ${nj} exp/${am}/graph_${sname} ${dataset} exp/${am}/decode_${sname}
echo dec_rs_${am} 1 40 dec_${am} -- steps/lmrescore.sh --cmd "$big_decode_cmd" $smalllm ${biglm} ${dataset} exp/${am}/decode_${sname} exp/${am}/decode_${sname}_rs_${bname}
;;
nnet3*)
nndir=$(dirname ${am})
suffix=$(echo "$nndir" | grep -o "_.*")
echo dec_${sam} 1 40 LAST -- steps/nnet3/decode.sh --nj ${nj} --cmd "$decode_cmd" --num-threads 4 --online-ivector-dir exp/nnet3${suffix}/ivectors_$(basename ${dataset})_hires exp/${am}/graph_${sname} ${dataset}_hires exp/${am}/decode_${sname}
echo dec_rs_${sam} 1 40 LAST -- steps/lmrescore.sh --cmd "$big_decode_cmd" $smalllm ${biglm} ${dataset}_hires exp/${am}/decode_${sname} exp/${am}/decode_${sname}_rs_${bname}
;;
chain*)
nndir=$(dirname ${am})
suffix=$(echo "$nndir" | grep -o "_.*")
echo dec_${sam} 1 40 LAST -- steps/nnet3/decode.sh --nj ${nj} --cmd "$decode_cmd" --post-decode-acwt 10.0 --acwt 1.0 --scoring-opts "--min-lmwt 1" --num-threads 4 --online-ivector-dir exp/nnet3${suffix}/ivectors_$(basename ${dataset})_hires exp/${am}/graph_${sname} ${dataset}_hires exp/${am}/decode_${sname}
echo dec_rs_${sam} 1 40 LAST -- steps/lmrescore.sh --self-loop-scale 1.0 --cmd "$big_decode_cmd" $smalllm ${biglm} ${dataset}_hires exp/${am}/decode_${sname} exp/${am}/decode_${sname}_rs_${bname}
;;
esac
prev=$sam
done
|
<gh_stars>10-100
package io.opensphere.mantle.data.geom.style.impl.ui;
import java.util.Set;
import java.util.stream.Collectors;
import javax.swing.JPanel;
import io.opensphere.core.util.WeakChangeSupport;
import io.opensphere.core.util.collections.CollectionUtilities;
import io.opensphere.core.util.collections.New;
import io.opensphere.core.util.swing.EventQueueUtilities;
import io.opensphere.mantle.data.VisualizationSupport;
import io.opensphere.mantle.data.geom.style.FeatureVisualizationControlPanel;
import io.opensphere.mantle.data.geom.style.MutableVisualizationStyle;
import io.opensphere.mantle.data.geom.style.VisualizationStyle;
import io.opensphere.mantle.data.geom.style.VisualizationStyleParameter;
import io.opensphere.mantle.data.geom.style.VisualizationStyleParameterChangeEvent;
import io.opensphere.mantle.data.geom.style.VisualizationStyleParameterChangeListener;
import io.opensphere.mantle.data.geom.style.VisualizationStyleUtilities;
/**
* The Class AbstractVisualizationControlPanel.
*
*/
public abstract class AbstractVisualizationControlPanel extends JPanel
implements FeatureVisualizationControlPanel, VisualizationStyleParameterChangeListener
{
/**
* serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/** The Change support. */
private final WeakChangeSupport<FeatureVisualizationControlPanelListener> myChangeSupport;
/** The Live update previewable. */
private final boolean myLiveUpdatePreviewableParameters;
/** The Style. */
private final MutableVisualizationStyle myStyle;
/** The Style copy. */
private MutableVisualizationStyle myStyleCopy;
/** The Visibility dependencies. */
private final Set<EditorPanelVisibilityDependency> myVisibilityDependencies;
/**
* Instantiates a new abstract visualization control panel.
*
* @param visualizationStyle the visualization style
*/
public AbstractVisualizationControlPanel(MutableVisualizationStyle visualizationStyle)
{
this(visualizationStyle, false);
}
/**
* Instantiates a new abstract visualization control panel.
*
* @param visualizationStyle the visualization style
* @param liveUpdatePreviwable the live update previwable parameters
*/
public AbstractVisualizationControlPanel(MutableVisualizationStyle visualizationStyle, boolean liveUpdatePreviwable)
{
super();
myLiveUpdatePreviewableParameters = liveUpdatePreviwable;
myStyle = visualizationStyle;
myStyle.addStyleParameterChangeListener(this);
myStyleCopy = (MutableVisualizationStyle)myStyle.clone();
myStyleCopy.addStyleParameterChangeListener(this);
myVisibilityDependencies = New.set();
myChangeSupport = new WeakChangeSupport<>();
}
@Override
public final void addListener(FeatureVisualizationControlPanelListener listener)
{
myChangeSupport.addListener(listener);
}
/**
* Adds the visibility dependency.
*
* @param dependency the dependency
*/
public void addVisibilityDependency(EditorPanelVisibilityDependency dependency)
{
myVisibilityDependencies.add(dependency);
}
@Override
public void applyChanges()
{
Set<VisualizationStyleParameter> params = getChangedParameters();
if (params != null && !params.isEmpty())
{
myStyle.setParameters(params, this);
fireAcceptCancel(true);
}
}
@Override
public void cancelChanges()
{
myStyleCopy.removeStyleParameterChangeListener(this);
myStyleCopy = (MutableVisualizationStyle)myStyle.clone();
myStyleCopy.addStyleParameterChangeListener(this);
update();
fireAcceptCancel(false);
}
@Override
public Set<VisualizationStyleParameter> getChangedParameters()
{
return VisualizationStyleUtilities.getChangedParameters(myStyle, myStyleCopy);
}
@Override
public final MutableVisualizationStyle getChangedStyle()
{
return myStyleCopy;
}
@Override
public JPanel getPanel()
{
return this;
}
@Override
public final MutableVisualizationStyle getStyle()
{
return myStyle;
}
@Override
public boolean hasChanges()
{
return VisualizationStyleUtilities.hasChangedParameters(myStyle, myStyleCopy);
}
@Override
public final boolean isUpdateWithPreviewable()
{
return myLiveUpdatePreviewableParameters;
}
@Override
public final void removeListener(FeatureVisualizationControlPanelListener listener)
{
myChangeSupport.removeListener(listener);
}
@Override
public void styleParametersChanged(VisualizationStyleParameterChangeEvent evt)
{
if (evt.getStyle() == myStyle)
{
if (evt.getSource() != this)
{
Set<VisualizationStyleParameter> changedParams = evt.getChangedParameterSet();
if (changedParams != null && !changedParams.isEmpty())
{
myStyleCopy.setParameters(changedParams, evt.getSource());
}
}
}
else
{
if (myLiveUpdatePreviewableParameters)
{
Set<VisualizationStyleParameter> changedParams = evt.getChangedParameterSet();
if (changedParams != null && !changedParams.isEmpty())
{
Set<VisualizationStyleParameter> updateSet = changedParams.stream()
.filter(p -> p.getHint() != null && p.getHint().isRenderPropertyChangeOnly())
.collect(Collectors.toSet());
if (!updateSet.isEmpty())
{
String dtiKey = myStyle.getDTIKey();
Class<? extends VisualizationSupport> convertedClass = myStyle.getConvertedClassType();
Class<? extends VisualizationStyle> vsClass = myStyle.getClass();
performLiveParameterUpdate(dtiKey, convertedClass, vsClass, updateSet);
}
}
}
EventQueueUtilities.runOnEDT(() ->
{
update();
fireControlPanelStyleChanged();
});
}
}
/**
* Update.
*/
public abstract void update();
/**
* Update sync.
*/
public void updateSync()
{
EventQueueUtilities.runOnEDT(() ->
{
update();
if (CollectionUtilities.hasContent(myVisibilityDependencies))
{
myVisibilityDependencies.forEach(EditorPanelVisibilityDependency::evaluateStyle);
}
});
}
/**
* Fire accept cancel.
*
* @param accept the accept
*/
protected void fireAcceptCancel(final boolean accept)
{
myChangeSupport.notifyListeners(listener ->
{
if (accept)
{
listener.styleChangesAccepted();
}
else
{
listener.styleChangesCancelled();
}
});
}
/**
* Fire control panel style changed.
*/
protected void fireControlPanelStyleChanged()
{
final boolean hasChanges = hasChanges();
myChangeSupport.notifyListeners(listener -> listener.styleChanged(hasChanges));
}
/**
* Perform live parameter update.
*
* @param dtiKey the dti key
* @param convertedClass the converted class
* @param vsClass the vs class
* @param updateSet the update set
*/
private void performLiveParameterUpdate(final String dtiKey, final Class<? extends VisualizationSupport> convertedClass,
final Class<? extends VisualizationStyle> vsClass, final Set<VisualizationStyleParameter> updateSet)
{
myChangeSupport
.notifyListeners(listener -> listener.performLiveParameterUpdate(dtiKey, convertedClass, vsClass, updateSet));
}
}
|
def generate_random_number
num = ""
10.times{ num << rand(0..9).to_s }
num
end
puts generate_random_number |
require_relative 'SVGObject'
module SVGAbstract
class SVGContainer < SVGObject
#Import the svg elements that can be in the container
#We need to import them within the class to break the circular
#dependency, some of these classes require the class SVGContainer
#to be available
content_classes = [:rect, :line, :polyline, :polygon, :circle,
:path, :ellipse, :image, :text, :tspan, :tref, :textpath,
:anchor, :group, :style, :use]
content_classes.each do |c|
require_relative "../SVGElements/#{c.to_s.capitalize}"
end
def initialize
super()
@svg_objects = []
end
def <<(obj)
@svg_objects << obj
end
#The following methods are for adding shapes, etc. Initially I
#tried metaprogramming these methods, but it doesn't work well
#due to the difficulties of using block_given? and yield inside
#define_method. Thus we need to write all the methods out "long
# hand". At least this is better for generating documentation.
def rect(*args)
s = SVG::Rect.new(*args)
yield s if block_given?
@svg_objects << s
return s
end
def line(*args)
s = SVG::Line.new(*args)
yield s if block_given?
@svg_objects << s
return s
end
def polyline(*args)
s = SVG::Polyline.new(*args)
yield s if block_given?
@svg_objects << s
return s
end
def polygon(*args)
s = SVG::Polygon.new(*args)
yield s if block_given?
@svg_objects << s
return s
end
def circle(*args)
s = SVG::Circle.new(*args)
yield s if block_given?
@svg_objects << s
return s
end
def path(*args)
s = SVG::Path.new(*args)
yield s if block_given?
@svg_objects << s
return s
end
def ellipse(*args)
s = SVG::Ellipse.new(*args)
yield s if block_given?
@svg_objects << s
return s
end
def image(*args)
s = SVG::Image.new(*args)
yield s if block_given?
@svg_objects << s
return s
end
def text(*args)
s = SVG::Text.new(*args)
yield s if block_given?
@svg_objects << s
return s
end
def tspan(*args)
s = SVG::Tspan.new(*args)
yield s if block_given?
@svg_objects << s
return s
end
def tref(*args)
s = SVG::Tref.new(*args)
yield s if block_given?
@svg_objects << s
return s
end
def textpath(*args)
s = SVG::Textpath.new(*args)
yield s if block_given?
@svg_objects << s
return s
end
def anchor(*args)
s = SVG::Anchor.new(*args)
yield s if block_given?
@svg_objects << s
return s
end
alias_method :a, :anchor
def style(*args)
s = SVG::Style.new(*args)
yield s if block_given?
@svg_objects << s
return s
end
def group
g = SVG::Group.new
yield g if block_given?
@svg_objects << g
return g
end
#For RVG compatability, the group method should be aliased as g
alias_method :g, :group
#A container can "use" a group or other SVGObject
def use(svg_object,x=0,y=0)
#If the svg_object has been added to the defs section of the
#document, it will have an id. If there's an id, we'll just
#reference the object from the defs section
#
#If there's no id, make a clone of the object, and copy it into
#the container directly (inefficient for making lots of copies)
#
#The user can also assign an id themselves if they want. To avoid
#conflicts, the id should NOT have the form id_123
begin
id = svg_object.id #this may trigger a NoMethodError if there's no id
use = SVG::Use.new(svg_object,x,y)
yield use if block_given?
@svg_objects << use
return use
rescue NoMethodError, e
#Copy object into container
#We need to make a copy of the group here to prevent the original
#being mutated
copy = svg_object.deep_copy
copy.translate(x, y) unless (x == 0 && y == 0)
@svg_objects << copy
yield copy if block_given?
return copy
end
end
def to_xml
xml = "<#{@name} #{attributes_string}>\n"
xml += @svg_objects.map{|o| o.to_xml}.join("\n")
xml += "\n</#{@name}>"
return xml
end
end
end
|
<filename>packages/reader/src/decoders/iso-8859-1.spec.ts
import test from 'ava';
import { BinaryReader } from '../binary-reader.js';
import { DataType } from '../data/data-type.js';
import { Encoding } from '../encoding.js';
import { ReadError } from '../read-error.js';
const type = DataType.char(Encoding.ISO88591);
test('valid', ({ deepEqual }) => {
const reader = new BinaryReader(new Uint8Array([0x20, 0x7e, 0xa0, 0xff]));
deepEqual(reader.next(type), { value: ' ', byteLength: 1 });
deepEqual(reader.next(type), { value: '~', byteLength: 1 });
deepEqual(reader.next(type), { value: '\xa0', byteLength: 1 });
deepEqual(reader.next(type), { value: 'ÿ', byteLength: 1 });
});
test('invalid', ({ deepEqual, throws }) => {
const message = 'invalid ISO 8859-1 bytes';
deepEqual(
throws(() => new BinaryReader(new Uint8Array([0x00])).next(type)),
new ReadError(message, type, new Uint8Array([0x00])),
);
deepEqual(
throws(() => new BinaryReader(new Uint8Array([0x1f])).next(type)),
new ReadError(message, type, new Uint8Array([0x1f])),
);
deepEqual(
throws(() => new BinaryReader(new Uint8Array([0x7f])).next(type)),
new ReadError(message, type, new Uint8Array([0x7f])),
);
deepEqual(
throws(() => new BinaryReader(new Uint8Array([0x9f])).next(type)),
new ReadError(message, type, new Uint8Array([0x9f])),
);
});
|
function alertMessage(message) {
// Display message in an alert
console.log("Message: " + message);
const alertTemplateDom = document.querySelector("#alert-template");
const alert = alertTemplateDom.cloneNode(true);
const alertText = alert.querySelector("#alert-text");
alertText.innerHTML = message;
document.querySelector("#alert-holder").appendChild(alert);
alert.style.display = "block";
window.setTimeout(function(){
alert.style.animationPlayState = 'running';
alert.addEventListener('animationend', function() {
alert.remove();
});
}, 3000);
}
|
/*
* Copyright 2012 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.om.core.api.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map;
/**
* Maps a collection of {@link Entity}s to a {@link Collection} or one of its
* subtypes.
*
* <p>
* In order to map a collection, you need at least to add the this annotation.
* Also, you'll need to indicate what the type of the elements in the collection
* are by setting the {@link #targetType()}, or, if the target type is different
* than the
*
* Please note that depending on the concrete collection implementation in use,
* you'll want to make sure that your collection entries implement
* {@link #hashCode()} and {@link #equals(Object)}.
*
* @author <NAME>
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Collection {
public static final String LOCATION_RELATIVE_USING_FIELDNAME = "";
/**
* Describes the location of where to load the collection from. This has
* implications as of how the actual backend will load the data.
*
* There are two possible ways of specifying a path to a collection. It can
* either be an absolute location, starting with a slash, or relative,
* without a beginning slash. If the location is relative, it will be
* resolved relative to the node of the containing {@link Entity}.
*
* The default is to use the field name as a relative path.
*/
String location() default LOCATION_RELATIVE_USING_FIELDNAME;
/**
* Declares the type of the collection items. Each item will be represented
* by the given type.
* <p>
* The referenced type must be a valid {@link Entity}.
*/
Class<?> targetType();
/**
* Defines from what the collection should be constructed. Collections can
* be created from the child nodes of {@link #location()}, from a
* multi-value property indicated by {@link #location()} or by taking all
* properties from under {@link #location()}.
*
* @see CollectionMode for more details.
* @return
*/
CollectionMode mode() default CollectionMode.Children;
/**
* Defines how to generate the keys if the collection type is {@link Map}.
* Per default {@link MapKeyStrategy#Name} is used. Obviously this setting
* will only be used if you're using a Map.
*
* @return
*/
MapKeyStrategy keyStrategy() default MapKeyStrategy.Name;
}
|
#!/usr/bin/env bash
#SBATCH -p fpgasyn
#SBATCH -o build.log
#SBATCH -J StencilStream-synthesis-test
#SBATCH --mail-type=ALL
#SBATCH --mem=90000MB
#SBATCH --time=24:00:00
source /cm/shared/opt/intel_oneapi/2021.1.1/setvars.sh
module load compiler/GCC nalla_pcie
make synthesis_hw |
<filename>server/subscriptions.js
'use strict'
const { PubSub, SubscriptionManager } = require('graphql-subscriptions')
const schema = require('./schema')
const pubsub = new PubSub()
const subscriptionManager = new SubscriptionManager({
schema,
pubsub,
setupFunctions: {
// map of subscription names to channel names and filter functions
// e.g. commentAdded: (options, args) => ({ commentAddedChannel: comment => comment.repository_name === args.repoFullName })
},
})
exports.subscriptionManager = subscriptionManager
exports.pubsub = pubsub
|
#!/bin/sh
config_path='/etc/security/limits.conf'
# Update config
mv /tmp/file-provisioner${config_path} ${config_path}
chmod 644 ${config_path}
chown root:root ${config_path}
chcon -u system_u -t etc_t ${config_path}
|
<reponame>alvarodelvalle/devops-scripts
import boto
class S3():
def __init__(self):
self.client = boto.Conn('s3', 'client').connection()
def get_bucket_keys(self, *args):
r = self.client.list_buckets()
for b in r:
r = self.client.get_bucket_encryption(Bucket=b)
print(f'[INFO] Bucket: {b} has a key of {r["ServerSideEncryptionConfiguration"]["Rules"][0]["ApplyServerSideEncryptionByDefault"]["KMSMasterKeyID"]}')
def get_buckets(self):
r = self.client.list_buckets()
print("Buckets: ")
for b in r["Buckets"]:
print(f'{b["Name"]} : {b["CreationDate"]}')
def main():
s = S3()
# s.get_bucket_keys('mt2-mhmd-storage')
s.get_buckets()
if __name__ == "__main__":
main()
|
#!/bin/sh
#Created on 2017-12-15
#作用:目前metaserver提供了7类查询接口,分别用来查询逻辑机房、物理机房、实例信息、权限信息# namespace datable table信息
echo -e '\n'
echo -e "查询当前系统中某个或全部逻辑机房下有哪些物理机房"
curl -d '{
"op_type" : "QUERY_LOGICAL",
"logical_room" : "bj"
}' http://$1/MetaService/query
echo -e '\n'
echo -e "查询某个或全部物理机房信息,包括所属的逻辑机房和物理机房下机器的信息"
curl -d '{
"op_type" : "QUERY_PHYSICAL",
"physical_room" : "bjyz"
}' http://$1/MetaService/query
echo -e '\n'
echo -e "查询某个或者全部store信息,如果查询全部,则不显示region的分布信息"
curl -d '{
"op_type" : "QUERY_INSTANCE",
"instance_address" : "127.0.0.1:8010"
}' http://$1/MetaService/query
echo -e '\n'
echo -e "查询某个或者全部的用户权限信息"
curl -d '{
"op_type" : "QUERY_USERPRIVILEG",
"user_name" : "test"
}' http://$1/MetaService/query
echo -e '\n'
echo -e "查询某个或者全部的namespace"
curl -d '{
"op_type" : "QUERY_NAMESPACE",
"namespace_name" : "Test"
}' http://$1/MetaService/query
echo -e '\n'
echo -e "查询某个或者全部的database"
curl -d '{
"op_type" : "QUERY_DATABASE",
"database" : "FC_Content"
}' http://$1/MetaService/query
echo -e '\n'
echo -e "查询某个或者全部的table"
curl -d '{
"op_type" : "QUERY_SCHEMA",
"table_name" : "ideacontent"
}' http://$1/MetaService/query
echo -e '\n'
echo -e "查询某个或者全部的region"
curl -d '{
"op_type" : "QUERY_REGION",
"region_id" : 1
}' http://$1/MetaService/query
|
<filename>src/main/java/net/romvoid95/curseforge/data/config/Config.java
package net.romvoid95.curseforge.data.config;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.apache.commons.collections4.ListUtils;
import lombok.Getter;
import net.romvoid95.curseforge.data.FileLink;
@Getter
public class Config {
private boolean developmentMode = true;
private String devChannel = "908273329549479936";
private String token = "INSERT-TOKEN";
private String owner = "owner";
private String[] prefixes = new String[] {">>"};
private boolean debug = false;
private String defaultChannel = "SET ID";
private String defulatRole = "none";
private FileLink updateFileLink = FileLink.DEFAULT;
private String defaultDescription = "New File Detected For CurseForge Project";
private String discordFormat = "css";
private List<Integer> projects = new ArrayList<>();
public Config() {}
/**
* @param token
* @param defaultChannel
* @param defulatRole
* @param updateFileLink
* @param defaultDescription
* @param discordFormat
* @param projects
*/
public Config(Boolean developmentMode, String token, String owner, String[] prefixes, Boolean debug, String defaultChannel, String defulatRole, FileLink updateFileLink, String defaultDescription, String discordFormat, List<Integer> projects) {
super();
this.developmentMode = developmentMode;
this.token = token;
this.owner = owner;
this.prefixes = prefixes;
this.debug = debug;
this.defaultChannel = defaultChannel;
this.defulatRole = defulatRole;
this.updateFileLink = updateFileLink;
this.defaultDescription = defaultDescription;
this.discordFormat = discordFormat;
this.projects = projects;
}
public boolean addProject(Integer project) {
return this.projects.add(project);
}
public boolean removeProject(Integer project) {
return this.projects.remove(project);
}
public boolean equals(Config obj) {
Config other = obj;
return Objects.equals(debug, other.debug) && Objects.equals(defaultChannel, other.defaultChannel)
&& Objects.equals(defaultDescription, other.defaultDescription)
&& Objects.equals(defulatRole, other.defulatRole) && Objects.equals(discordFormat, other.discordFormat)
&& ListUtils.isEqualList(projects, other.projects) && Objects.equals(token, other.token)
&& Arrays.equals(prefixes, other.prefixes) && updateFileLink == other.updateFileLink;
}
@Override
public String toString() {
return String.format("Config [token=%s, owner=%s, prefixes=%s, debug=%s, defaultChannel=%s, defulatRole=%s, updateFileLink=%s, defaultDescription=%s, discordFormat=%s, projects=%s]", token, owner, Arrays.toString(prefixes), debug, defaultChannel, defulatRole,
updateFileLink, defaultDescription, discordFormat, projects);
}
}
|
for f in *.png; do
convert ./"$f" ./"${f%.png}.jpg"
done |
/*
* Copyright 2000-2016 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 org.intellij.plugins.hcl.terraform.config;
import com.intellij.testFramework.InspectionFixtureTestCase;
import org.intellij.plugins.hcl.terraform.config.inspection.*;
import org.intellij.plugins.hil.inspection.HILMissingSelfInContextInspection;
import org.intellij.plugins.hil.inspection.HILOperationTypesMismatchInspection;
import org.intellij.plugins.hil.inspection.HILUnresolvedReferenceInspection;
public class TerraformInspectionsTestCase extends InspectionFixtureTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
myFixture.setTestDataPath(getBasePath());
}
@Override
protected String getBasePath() {
return "test-data/terraform/inspections/";
}
public void testResourcePropertyReferences() throws Exception {
doTest("resource_property_reference", new HILUnresolvedReferenceInspection());
}
public void testMappingVariableReference() throws Exception {
doTest("mapping_variable_reference", new HILUnresolvedReferenceInspection());
}
public void testWeirdBlockComputedPropertyReference() throws Exception {
doTest("weird_block_computed_property_reference", new HILUnresolvedReferenceInspection());
}
public void testKnownBlockNameFromModel() throws Exception {
doTest("unknown_block_name", new HCLUnknownBlockTypeInspection());
}
// Test for issue #198
public void testNoUnknownBlocksForNomad() throws Exception {
doTest("no_unknown_blocks_for_nomad", new HCLUnknownBlockTypeInspection());
}
public void testIncorrectTFVARS() throws Exception {
doTest("incorrect_tfvars", new TFVARSIncorrectElementInspection());
}
public void testIncorrectVariableType() throws Exception {
doTest("incorrect_variable_type", new TFIncorrectVariableTypeInspection());
}
public void testDuplicatedProvider() throws Exception {
doTest("duplicated_provider", new TFDuplicatedProviderInspection());
}
public void testDuplicatedOutput() throws Exception {
doTest("duplicated_output", new TFDuplicatedOutputInspection());
}
public void testDuplicatedVariable() throws Exception {
doTest("duplicated_variable", new TFDuplicatedVariableInspection());
}
public void testDuplicatedBlockProperty() throws Exception {
doTest("duplicated_block_property", new TFDuplicatedBlockPropertyInspection());
}
public void testInterpolationsInWrongPlaces() throws Exception {
doTest("interpolations_in_wrong_places", new TFNoInterpolationsAllowedInspection());
}
public void testMissingBlockProperty() throws Exception {
doTest("missing_properties", new HCLBlockMissingPropertyInspection());
}
public void testConflictingBlockProperty() throws Exception {
doTest("conflicting_properties", new HCLBlockConflictingPropertiesInspection());
}
public void testMissingSelfInContext() throws Exception {
doTest("reference_to_self", new HILMissingSelfInContextInspection());
}
public void testInterpolationBinaryExpressionsTypesCheck() throws Exception {
doTest("interpolation_operations_types", new HILOperationTypesMismatchInspection());
}
}
|
#!/bin/bash
cd /home/nlpserver/zzilong/kaldi/egs/supermarket-product
. ./path.sh
( echo '#' Running on `hostname`
echo '#' Started at `date`
echo -n '# '; cat <<EOF
nnet-shuffle-egs --buffer-size=5000 --srand=116 ark:exp/nnet4a/egs/egs.${SGE_TASK_ID}.8.ark ark:- | nnet-train-parallel --num-threads=8 --minibatch-size=128 --srand=116 exp/nnet4a/116.mdl ark:- exp/nnet4a/117.${SGE_TASK_ID}.mdl
EOF
) >exp/nnet4a/log/train.116.$SGE_TASK_ID.log
time1=`date +"%s"`
( nnet-shuffle-egs --buffer-size=5000 --srand=116 ark:exp/nnet4a/egs/egs.${SGE_TASK_ID}.8.ark ark:- | nnet-train-parallel --num-threads=8 --minibatch-size=128 --srand=116 exp/nnet4a/116.mdl ark:- exp/nnet4a/117.${SGE_TASK_ID}.mdl ) 2>>exp/nnet4a/log/train.116.$SGE_TASK_ID.log >>exp/nnet4a/log/train.116.$SGE_TASK_ID.log
ret=$?
time2=`date +"%s"`
echo '#' Accounting: time=$(($time2-$time1)) threads=1 >>exp/nnet4a/log/train.116.$SGE_TASK_ID.log
echo '#' Finished at `date` with status $ret >>exp/nnet4a/log/train.116.$SGE_TASK_ID.log
[ $ret -eq 137 ] && exit 100;
touch exp/nnet4a/q/done.1940.$SGE_TASK_ID
exit $[$ret ? 1 : 0]
## submitted with:
# qsub -v PATH -cwd -S /bin/bash -j y -l arch=*64* -o exp/nnet4a/q/train.116.log -l mem_free=10G,ram_free=2G,arch=*64 -l mem_free=1G,ram_free=1G -pe smp 4 -t 1:8 /home/nlpserver/zzilong/kaldi/egs/supermarket-product/exp/nnet4a/q/train.116.sh >>exp/nnet4a/q/train.116.log 2>&1
|
import math
def sine_deg(degree):
rad = math.radians(degree)
return math.sin(rad) |
#!/bin/sh
if [ -z "${GOPHERWX_CONFIG}" ]; then
echo The env var GOPHERWX_CONFIG needs to be defined.
echo This variable points gopherwx towards its config file.
echo This image accepts a volume, /config, that you can
echo use for passing in a config file externally.
echo Exiting...
exit 1
fi
if [ "$GOPHERWX_DEBUG" = "true" ]; then
exec /gopherwx -config=$GOPHERWX_CONFIG -debug
else
exec /gopherwx -config=$GOPHERWX_CONFIG
fi
|
## Test Config
#domain: 127.0.0.1
#port: 8000
#ssl_private_key: null
#ssl_cert_chain: null
#workers: 10
#secret: '72558847d57c22a2f19d711537cdc446'
#basic_auth_user: "test"
#basic_auth_password: "testtest"
#basic_auth_and_secret: false
#webhooks:
# -
# name: 'ls'
# command: '/bin/ls {{param1}} {{param2}}'
# cwd: '/home/nuke'
# mode: ''
# parallel_processes: 2
# -
# name: 'lshome'
# command: '/bin/ls /home'
# cwd: '/home/nuke'
# mode: ''
# parallel_processes: 2
echo -n '{"parameters":{"param1":"-al","param2":"/tmp"}}' | http POST localhost:8000/ls \
X-Hub-Signature:'sha1=d762407ca7fb309dfbeb73c080caf6394751f0a4' \
Authorization:'Basic dGVzdDp0ZXN0dGVzdA=='
echo -n '{"parameters":{"param1":"-al","param2":"/tmp"}}' | http POST localhost:8000/ls \
X-Hub-Signature:'sha1=d762407ca7fb309dfbeb73c080caf6394751f0a4'
echo -n '{"parameters":{"param1":"-al","param2":"/tmp"}}' | http POST localhost:8000/ls \
Signature:'sha1=d762407ca7fb309dfbeb73c080caf6394751f0a4'
http GET localhost:8000/lshome \
Authorization:'Basic dGVzdDp0ZXN0dGVzdA=='
|
# This shell script executes Slurm jobs for training
# deep context-adaptive convolutional neural networks
# on BirdVox-70k with PCEN input.
# Trial ID: 4.
# Augmentation kind: all.
sbatch 062_aug-all_unit01_trial-4.sbatch
sbatch 062_aug-all_unit02_trial-4.sbatch
sbatch 062_aug-all_unit03_trial-4.sbatch
sbatch 062_aug-all_unit05_trial-4.sbatch
sbatch 062_aug-all_unit07_trial-4.sbatch
sbatch 062_aug-all_unit10_trial-4.sbatch
|
export * from "./components";
export * from "./edit_account";
export * from "./user_account";
|
from datetime import date
from typing import Dict, List, Optional, Union
from belvo.enums import TaxReturnType
from belvo.resources.base import Resource
class TaxReturns(Resource):
endpoint = "/api/tax-returns/"
def create(
self,
link: str,
year_from: str = None,
year_to: str = None,
*,
attach_pdf: bool = False,
save_data: bool = True,
raise_exception: bool = False,
type_: Optional[TaxReturnType] = None,
date_from: str = None,
date_to: str = None,
**kwargs: Dict,
) -> Union[List[Dict], Dict]:
type_ = type_ if type_ else TaxReturnType.YEARLY
data = {"link": link, "attach_pdf": attach_pdf, "save_data": save_data, "type": type_.value}
if data["type"] == "yearly":
year_to = year_to or str(date.today().year)
data.update(year_to=year_to, year_from=year_from)
else:
data.update(date_to=date_to, date_from=date_from)
return self.session.post(
self.endpoint, data=data, raise_exception=raise_exception, **kwargs
)
def resume(
self,
session: str,
token: str,
*,
link: str = None,
raise_exception: bool = False,
**kwargs: Dict,
) -> Dict:
raise NotImplementedError()
|
/// <reference path="ITexture.ts"/>
/// <reference path="Quad.ts"/>
/// <reference path="RenderCommandBase.ts"/>
/// <reference path="ILayerManager.ts"/>
/// <reference path="../utils/ObjectPool.ts"/>
module WOZLLA.renderer {
var quadCommandPool;
/**
* @class WOZLLA.renderer.QuadCommand
* @extends WOZLLA.renderer.RenderCommandBase
*/
export class QuadCommand extends RenderCommandBase implements WOZLLA.utils.Poolable {
public static init(globalZ:number, layer:string, texture:ITexture, materialId:string, quad:Quad):QuadCommand {
var quadCommand = quadCommandPool.retain();
quadCommand.initWith(globalZ, layer, texture, materialId, quad);
return quadCommand;
}
isPoolable:boolean = true;
get texture():ITexture { return this._texture; }
get materialId():string { return this._materialId; }
get quad():Quad { return this._quad; }
_texture:ITexture;
_materialId:string;
_quad:Quad;
constructor(globalZ:number, layer:string) {
super(globalZ, layer);
}
initWith(globalZ:number, layer:string, texture:ITexture, materialId:string, quad):void {
this._globalZ = globalZ;
this._layer = layer;
this._texture = texture;
this._materialId = materialId;
this._quad = quad;
}
release() {
quadCommandPool.release(this);
}
}
quadCommandPool = new WOZLLA.utils.ObjectPool<QuadCommand>(200, ():QuadCommand => {
return new QuadCommand(0, ILayerManager.DEFAULT);
});
} |
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#define DEVICE_NAME "memory"
#define DEVICE_MAJOR 60
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
static char memory_buffer[1024]; // Internal memory buffer for the device
static int memory_open(struct inode *inode, struct file *file) {
return 0;
}
static int memory_release(struct inode *inode, struct file *file) {
return 0;
}
static ssize_t memory_read(struct file *file, char *buffer, size_t length, loff_t *offset) {
if (*offset >= sizeof(memory_buffer)) // Check if offset is within bounds
return 0;
if (*offset + length > sizeof(memory_buffer)) // Adjust length if it exceeds buffer size
length = sizeof(memory_buffer) - *offset;
if (copy_to_user(buffer, memory_buffer + *offset, length) != 0) // Copy data to user space
return -EFAULT;
*offset += length; // Update offset
return length;
}
static ssize_t memory_write(struct file *file, const char *buffer, size_t length, loff_t *offset) {
if (*offset >= sizeof(memory_buffer)) // Check if offset is within bounds
return -ENOSPC;
if (*offset + length > sizeof(memory_buffer)) // Adjust length if it exceeds buffer size
length = sizeof(memory_buffer) - *offset;
if (copy_from_user(memory_buffer + *offset, buffer, length) != 0) // Copy data from user space
return -EFAULT;
*offset += length; // Update offset
return length;
}
static struct file_operations fops = {
.owner = THIS_MODULE,
.open = memory_open,
.release = memory_release,
.read = memory_read,
.write = memory_write,
};
static int __init memory_init(void) {
int result = register_chrdev(DEVICE_MAJOR, DEVICE_NAME, &fops);
if (result < 0) {
printk(KERN_ALERT "Failed to register device: %s\n", DEVICE_NAME);
return result;
}
printk(KERN_INFO "Memory device registered: %s, major number: %d\n", DEVICE_NAME, DEVICE_MAJOR);
return 0;
}
static void __exit memory_exit(void) {
unregister_chrdev(DEVICE_MAJOR, DEVICE_NAME);
printk(KERN_INFO "Memory device unregistered: %s\n", DEVICE_NAME);
}
module_init(memory_init);
module_exit(memory_exit); |
<reponame>google/private-membership
// Copyright 2021 Google 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef PRIVATE_MEMBERSHIP_RLWE_BATCH_CPP_PRNG_H_
#define PRIVATE_MEMBERSHIP_RLWE_BATCH_CPP_PRNG_H_
#include <memory>
#include <string>
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "shell_encryption/prng/prng.h"
namespace private_membership {
namespace batch {
// Create a PRNG with a random seed.
absl::StatusOr<std::unique_ptr<rlwe::SecurePrng>> CreatePrng();
// Struct holding a pair of PRNG and seed.
struct PrngWithSeed {
std::unique_ptr<rlwe::SecurePrng> prng;
std::string seed;
};
// Create a PRNG with a random seed and store seed in parameter.
absl::StatusOr<PrngWithSeed> CreatePrngWithSeed();
// Create a PRNG using the given seed.
absl::StatusOr<std::unique_ptr<rlwe::SecurePrng>> CreatePrngFromSeed(
absl::string_view seed);
} // namespace batch
} // namespace private_membership
#endif // PRIVATE_MEMBERSHIP_RLWE_BATCH_CPP_PRNG_H_
|
/**
* Copyright 2017 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.swarm.microprofile.openapi.runtime;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import org.eclipse.microprofile.openapi.annotations.OpenAPIDefinition;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.callbacks.Callback;
import org.eclipse.microprofile.openapi.annotations.callbacks.Callbacks;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
import org.eclipse.microprofile.openapi.annotations.parameters.Parameters;
import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement;
import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirements;
import org.eclipse.microprofile.openapi.annotations.security.SecurityScheme;
import org.eclipse.microprofile.openapi.annotations.security.SecuritySchemes;
import org.eclipse.microprofile.openapi.annotations.servers.Server;
import org.eclipse.microprofile.openapi.annotations.servers.Servers;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
import org.eclipse.microprofile.openapi.annotations.tags.Tags;
import org.jboss.jandex.DotName;
/**
* @author <EMAIL>
*/
public final class OpenApiConstants {
public static final String OPEN_API_VERSION = "3.0.1";
public static final String SCAN_DEPENDENCIES_DISABLE = "mp.openapi.extensions.scan-dependencies.disable";
public static final String SCAN_DEPENDENCIES_JARS = "mp.openapi.extensions.scan-dependencies.jars";
public static final String CLASS_SUFFIX = ".class";
public static final String JAR_SUFFIX = ".jar";
public static final String WEB_ARCHIVE_CLASS_PREFIX = "/WEB-INF/classes/";
public static final String EXTENSION_PROPERTY_PREFIX = "x-";
private static final String MIME_ANY = "*/*";
public static final String[] DEFAULT_PARAMETER_MEDIA_TYPES = {MIME_ANY};
public static final String[] DEFAULT_REQUEST_BODY_TYPES = {MIME_ANY};
public static final String PROP_TRACE = "trace";
public static final String PROP_PATCH = "patch";
public static final String PROP_HEAD = "head";
public static final String PROP_OPTIONS = "options";
public static final String PROP_DELETE = "delete";
public static final String PROP_POST = "post";
public static final String PROP_PUT = "put";
public static final String PROP_GET = "get";
public static final String PROP_SERVER = "server";
public static final String PROP_REQUEST_BODY = "requestBody";
public static final String PROP_OPERATION_ID = "operationId";
public static final String PROP_OPERATION_REF = "operationRef";
public static final String PROP_SCOPES = "scopes";
public static final String PROP_REFRESH_URL = "refreshUrl";
public static final String PROP_TOKEN_URL = "tokenUrl";
public static final String PROP_AUTHORIZATION_URL = "authorizationUrl";
public static final String PROP_AUTHORIZATION_CODE = "authorizationCode";
public static final String PROP_CLIENT_CREDENTIALS = "clientCredentials";
public static final String PROP_PASSWORD = "password";
public static final String PROP_IMPLICIT = "implicit";
public static final String PROP_OPEN_ID_CONNECT_URL = "openIdConnectUrl";
public static final String PROP_FLOWS = "flows";
public static final String PROP_BEARER_FORMAT = "bearerFormat";
public static final String PROP_SCHEME = "scheme";
public static final String PROP_EXTERNAL_VALUE = "externalValue";
public static final String PROP_VALUE = "value";
public static final String PROP_SUMMARY = "summary";
public static final String PROP_ALLOW_EMPTY_VALUE = "allowEmptyValue";
public static final String PROP_IN = "in";
public static final String PROP_ALLOW_RESERVED = "allowReserved";
public static final String PROP_EXPLODE = "explode";
public static final String PROP_STYLE = "style";
public static final String PROP_CONTENT_TYPE = "contentType";
public static final String PROP_ENCODING = "encoding";
public static final String PROP_SCHEMA = "schema";
public static final String PROP_CONTENT = "content";
public static final String PROP_MAPPING = "mapping";
public static final String PROP_PROPERTY_NAME = "propertyName";
public static final String PROP_WRAPPED = "wrapped";
public static final String PROP_ATTRIBUTE = "attribute";
public static final String PROP_PREFIX = "prefix";
public static final String PROP_NAMESPACE = "namespace";
public static final String PROP_DEPRECATED = "deprecated";
public static final String PROP_WRITE_ONLY = "writeOnly";
public static final String PROP_NULLABLE = "nullable";
public static final String PROP_DISCRIMINATOR = "discriminator";
public static final String PROP_ANY_OF = "anyOf";
public static final String PROP_ONE_OF = "oneOf";
public static final String PROP_EXAMPLE = "example";
public static final String PROP_XML = "xml";
public static final String PROP_READ_ONLY = "readOnly";
public static final String PROP_ADDITIONAL_PROPERTIES = "additionalProperties";
public static final String PROP_PROPERTIES = "properties";
public static final String PROP_ALL_OF = "allOf";
public static final String PROP_NOT = "not";
public static final String PROP_ITEMS = "items";
public static final String PROP_TYPE = "type";
public static final String PROP_REQUIRED = "required";
public static final String PROP_MIN_PROPERTIES = "minProperties";
public static final String PROP_MAX_PROPERTIES = "maxProperties";
public static final String PROP_UNIQUE_ITEMS = "uniqueItems";
public static final String PROP_MIN_ITEMS = "minItems";
public static final String PROP_MAX_ITEMS = "maxItems";
public static final String PROP_PATTERN = "pattern";
public static final String PROP_MIN_LENGTH = "minLength";
public static final String PROP_MAX_LENGTH = "maxLength";
public static final String PROP_EXCLUSIVE_MINIMUM = "exclusiveMinimum";
public static final String PROP_MINIMUM = "minimum";
public static final String PROP_EXCLUSIVE_MAXIMUM = "exclusiveMaximum";
public static final String PROP_MAXIMUM = "maximum";
public static final String PROP_MULTIPLE_OF = "multipleOf";
public static final String PROP_FORMAT = "format";
public static final String PROP_$REF = "$ref";
public static final String PROP_CALLBACKS = "callbacks";
public static final String PROP_LINKS = "links";
public static final String PROP_SECURITY_SCHEMES = "securitySchemes";
public static final String PROP_HEADERS = "headers";
public static final String PROP_REQUEST_BODIES = "requestBodies";
public static final String PROP_EXAMPLES = "examples";
public static final String PROP_PARAMETERS = "parameters";
public static final String PROP_RESPONSES = "responses";
public static final String PROP_SCHEMAS = "schemas";
public static final String PROP_DEFAULT = "default";
public static final String PROP_ENUM = "enum";
public static final String PROP_VARIABLES = "variables";
public static final String PROP_EMAIL = "email";
public static final String PROP_URL = "url";
public static final String PROP_NAME = "name";
public static final String PROP_VERSION = "version";
public static final String PROP_LICENSE = "license";
public static final String PROP_CONTACT = "contact";
public static final String PROP_TERMS_OF_SERVICE = "termsOfService";
public static final String PROP_DESCRIPTION = "description";
public static final String PROP_TITLE = "title";
public static final String PROP_COMPONENTS = "components";
public static final String PROP_PATHS = "paths";
public static final String PROP_TAGS = "tags";
public static final String PROP_SECURITY = "security";
public static final String PROP_SERVERS = "servers";
public static final String PROP_EXTERNAL_DOCS = "externalDocs";
public static final String PROP_INFO = "info";
public static final String PROP_OPENAPI = "openapi";
public static final String PROP_REF = "ref";
public static final String PROP_REFS = "refs";
public static final String PROP_METHOD = "method";
public static final String PROP_CALLBACK_URL_EXPRESSION = "callbackUrlExpression";
public static final String PROP_OPERATIONS = "operations";
public static final String PROP_EXTENSIONS = "extensions";
public static final String PROP_EXPRESSION = "expression";
public static final String PROP_HIDDEN = "hidden";
public static final String PROP_MEDIA_TYPE = "mediaType";
public static final String PROP_REQUIRED_PROPERTIES = "requiredProperties";
public static final String PROP_DEFAULT_VALUE = "defaultValue";
public static final String PROP_DISCRIMINATOR_MAPPING = "discriminatorMapping";
public static final String PROP_SECURITY_SCHEME_NAME = "securitySchemeName";
public static final String PROP_API_KEY_NAME = "apiKeyName";
public static final String PROP_RESPONSE_CODE = "responseCode";
public static final String PROP_IMPLEMENTATION = "implementation";
public static final String PROP_ENUMERATION = "enumeration";
public static final DotName DOTNAME_OPEN_API_DEFINITION = DotName.createSimple(OpenAPIDefinition.class.getName());
public static final DotName DOTNAME_SECURITY_SCHEME = DotName.createSimple(SecurityScheme.class.getName());
public static final DotName DOTNAME_SECURITY_SCHEMES = DotName.createSimple(SecuritySchemes.class.getName());
public static final DotName DOTNAME_SECURITY_REQUIREMENT = DotName.createSimple(SecurityRequirement.class.getName());
public static final DotName DOTNAME_SECURITY_REQUIREMENTS = DotName.createSimple(SecurityRequirements.class.getName());
public static final DotName DOTNAME_CALLBACK = DotName.createSimple(Callback.class.getName());
public static final DotName DOTNAME_CALLBACKS = DotName.createSimple(Callbacks.class.getName());
public static final DotName DOTNAME_SCHEMA = DotName.createSimple(Schema.class.getName());
public static final DotName DOTNAME_TAG = DotName.createSimple(Tag.class.getName());
public static final DotName DOTNAME_TAGS = DotName.createSimple(Tags.class.getName());
public static final DotName DOTNAME_OPERATION = DotName.createSimple(Operation.class.getName());
public static final DotName DOTNAME_API_RESPONSE = DotName.createSimple(APIResponse.class.getName());
public static final DotName DOTNAME_API_RESPONSES = DotName.createSimple(APIResponses.class.getName());
public static final DotName DOTNAME_PARAMETER = DotName.createSimple(Parameter.class.getName());
public static final DotName DOTNAME_PARAMETERS = DotName.createSimple(Parameters.class.getName());
public static final DotName DOTNAME_REQUEST_BODY = DotName.createSimple(RequestBody.class.getName());
public static final DotName DOTNAME_SERVER = DotName.createSimple(Server.class.getName());
public static final DotName DOTNAME_SERVERS = DotName.createSimple(Servers.class.getName());
public static final DotName DOTNAME_APPLICATION = DotName.createSimple(Application.class.getName());
public static final DotName DOTNAME_APPLICATION_PATH = DotName.createSimple(ApplicationPath.class.getName());
public static final DotName DOTNAME_PATH = DotName.createSimple(Path.class.getName());
public static final DotName DOTNAME_PRODUCES = DotName.createSimple(Produces.class.getName());
public static final DotName DOTNAME_CONSUMES = DotName.createSimple(Consumes.class.getName());
public static final DotName DOTNAME_QUERY_PARAM = DotName.createSimple(QueryParam.class.getName());
public static final DotName DOTNAME_FORM_PARAM = DotName.createSimple(FormParam.class.getName());
public static final DotName DOTNAME_COOKIE_PARAM = DotName.createSimple(CookieParam.class.getName());
public static final DotName DOTNAME_PATH_PARAM = DotName.createSimple(PathParam.class.getName());
public static final DotName DOTNAME_HEADER_PARAM = DotName.createSimple(HeaderParam.class.getName());
public static final DotName DOTNAME_MATRIX_PARAM = DotName.createSimple(MatrixParam.class.getName());
public static final DotName DOTNAME_BEAN_PARAM = DotName.createSimple(BeanParam.class.getName());
public static final DotName DOTNAME_GET = DotName.createSimple(GET.class.getName());
public static final DotName DOTNAME_PUT = DotName.createSimple(PUT.class.getName());
public static final DotName DOTNAME_POST = DotName.createSimple(POST.class.getName());
public static final DotName DOTNAME_DELETE = DotName.createSimple(DELETE.class.getName());
public static final DotName DOTNAME_HEAD = DotName.createSimple(HEAD.class.getName());
public static final DotName DOTNAME_OPTIONS = DotName.createSimple(OPTIONS.class.getName());
public static final DotName DOTNAME_RESPONSE = DotName.createSimple(Response.class.getName());
public static final String[] DEFAULT_CONSUMES = new String[] {MIME_ANY};
public static final String[] DEFAULT_PRODUCES = new String[] {MIME_ANY};
public static final String REF_PREFIX_API_RESPONSE = "#/components/responses/";
public static final String REF_PREFIX_CALLBACK = "#/components/callbacks/";
public static final String REF_PREFIX_EXAMPLE = "#/components/examples/";
public static final String REF_PREFIX_HEADER = "#/components/headers/";
public static final String REF_PREFIX_LINK = "#/components/links/";
public static final String REF_PREFIX_PARAMETER = "#/components/parameters/";
public static final String REF_PREFIX_REQUEST_BODY = "#/components/requestBodies/";
public static final String REF_PREFIX_SCHEMA = "#/components/schemas/";
public static final String REF_PREFIX_SECURITY_SCHEME = "#/components/securitySchemes/";
/**
* Constructor.
*/
private OpenApiConstants() {
}
}
|
package workers
import (
"crypto/rand"
"encoding/binary"
"runtime"
"sync"
"time"
)
type WorkerFunc func(job *Job) (interface{}, error)
type TimingFunc func(jobID int64, inQueue, inWorker time.Duration)
type Job struct {
ID int64
inTime int64 // inserted timestamp
inWorkerTime int64
outWorkerTime int64
Data interface{}
//failureCount uint32
}
type Result struct {
JobID int64
Data interface{}
Err error
}
type WorkerPool struct {
size uint32
workerFunc WorkerFunc
in chan *Job
out chan *Result
doneWg sync.WaitGroup
TimingLogger TimingFunc
}
var (
DefaultWorkerPoolSize = runtime.NumCPU()
)
func NewWokerPool(size uint32, workerFunc WorkerFunc) *WorkerPool {
if workerFunc == nil {
return nil
}
return &WorkerPool{size: size, workerFunc: workerFunc,
in: make(chan *Job, size), out: make(chan *Result, size*4)}
}
func (w *WorkerPool) Start() {
for i := uint32(0); i < w.size; i++ {
w.doneWg.Add(1)
go func() {
WorkerLoop:
for {
select {
case job, ok := <-w.in:
if job != nil {
job.inWorkerTime = timestamp()
result, err := w.workerFunc(job)
job.outWorkerTime = timestamp()
w.out <- &Result{Data: result, JobID: job.ID, Err: err}
if w.TimingLogger != nil {
w.TimingLogger(job.ID, time.Duration(job.inWorkerTime-job.inTime)*time.Nanosecond,
time.Duration(job.outWorkerTime-job.inWorkerTime)*time.Nanosecond)
}
}
if !ok {
break WorkerLoop
}
default:
}
}
w.doneWg.Done()
}()
}
}
func (w *WorkerPool) CreateAndSubmitJob(data interface{}) *Job {
job := w.CreateJob(data)
w.SubmitJob(job)
return job
}
// CreateJob will build a job that needs to be submitted
func (w *WorkerPool) CreateJob(data interface{}) *Job {
job := &Job{ID: makeID(), Data: data, inTime: timestamp()}
return job
}
// SubmitJob will add a job to the worker queue, but if there
// is no room available, it will block.
func (w *WorkerPool) SubmitJob(job *Job) {
w.in <- job
}
// Result will return the result from the worker, but if no result
// is available, then it will block
func (w *WorkerPool) Result() *Result {
return <-w.out
}
func (w *WorkerPool) HasResult() bool {
return len(w.out) > 0
}
func (w *WorkerPool) OutChannel() chan *Result {
return w.out
}
func (w *WorkerPool) Stop() {
close(w.in)
w.doneWg.Wait()
}
func (w *WorkerPool) Len() int {
return int(w.size)
}
func makeID() int64 {
b := make([]byte, 8)
_, err := rand.Read(b)
if err != nil {
return -1
}
result, _ := binary.Varint(b)
return result
}
func timestamp() int64 {
return time.Now().UTC().UnixNano()
}
|
from typing import List, Optional
from asyncpg.exceptions import (
InvalidRowCountInLimitClauseError,
InvalidRowCountInResultOffsetClauseError,
StringDataRightTruncationError,
)
from dateutil import parser
from fastapi import APIRouter, File, Form, Query, UploadFile
from pydantic import Json
from src.schemas.post import Post, UpdatePost
from src.services.archfolio import Archfolio
from src.utils import errors
router = APIRouter()
@router.post("")
async def create_post(
text: Json[Post] = Form(...),
file: Optional[UploadFile] = File(None),
):
post_dict = text.dict()
post_dict["thumbnail"] = file
try:
result = await Archfolio.get_instance().create_post(post_dict)
except StringDataRightTruncationError:
errors.raise_error_response(errors.ErrorResourceDataInvalid)
except Exception:
errors.raise_error_response(errors.ErrorInternal)
return result
@router.get("")
async def get_posts(
author: Optional[int] = None,
tags: Optional[List[str]] = Query(None),
title: Optional[str] = None,
username: Optional[str] = None,
name: Optional[str] = None,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
offset: Optional[int] = None,
fetch: Optional[int] = None,
):
try:
start_datetime = parser.parse(start_date) if start_date is not None else None
end_datetime = parser.parse(end_date) if end_date is not None else None
except Exception:
errors.raise_error_response(errors.ErrorResourceDataInvalid)
fields = {
"author": author,
"tags": tags,
"title": title,
"username": username,
"name": name,
"start_date": start_datetime,
"end_date": end_datetime,
"offset": offset,
"fetch": fetch,
}
try:
result = await Archfolio.get_instance().get_posts(fields)
except (
InvalidRowCountInResultOffsetClauseError,
InvalidRowCountInLimitClauseError,
):
errors.raise_error_response(errors.ErrorResourceDataInvalid)
except Exception:
errors.raise_error_response(errors.ErrorInternal)
if not result:
errors.raise_error_response(errors.ErrorResourceNotFound)
return result
@router.patch("/{id}")
async def update_post(
id: int,
text: Json[UpdatePost] = Form(...),
file: Optional[UploadFile] = File(None),
):
post_dict = text.dict()
post_dict["id"] = id
post_dict["thumbnail"] = file
try:
result = await Archfolio.get_instance().update_post(post_dict)
except StringDataRightTruncationError:
errors.raise_error_response(errors.ErrorResourceDataInvalid)
except Exception:
errors.raise_error_response(errors.ErrorInternal)
if result is None:
errors.raise_error_response(errors.ErrorResourceNotFound)
return result
@router.delete("/{id}")
async def delete_post(
id: int,
):
fields = {
"id": id,
}
try:
result = await Archfolio.get_instance().delete_posts(fields)
except Exception:
errors.raise_error_response(errors.ErrorInternal)
if result is None:
errors.raise_error_response(errors.ErrorResourceNotFound)
return result
|
#!/bin/bash
# Set to exit on error
set -e
CWD=$(pwd)
INSTALLATION_DIR="$CWD/deps/libcouchbase/inst/"
UNAME=$(uname)
if [[ $UNAME != "Linux" ]]; then
echo "Only install Couchbase with SSL support on Linux"
echo "Default to using regular version of couchbase"
exit 0
fi
# Test existance of needed utils
REQUIRED=( "git" "cmake" )
for cmd in "${REQUIRED[@]}"; do
command -v $cmd >/dev/null 2>&1 || { echo >&2 "panoply-couchbase requires $cmd to build but it's not installed. Aborting."; exit 1; }
done
if [[ ! -d "$CWD/deps/libcouchbase" ]]; then
mkdir -p "$CWD/deps"
echo "Cloning libcouchbase from github"
git clone --branch 2.5.4 --depth 1 git://github.com/couchbase/libcouchbase.git ./deps/libcouchbase >/dev/null 2>&1
else
echo "libcouchbase directory already exists. Skipping git clone"
fi
if [[ ! -d "$CWD/deps/libcouchbase/build" ]]; then
if [[ ! -d "$INSTALLATION_DIR" ]]; then
echo "Creating installation directory"
mkdir -p $INSTALLATION_DIR
fi
echo "Running configure script"
cd ./deps/libcouchbase && ./configure.pl --prefix=$INSTALLATION_DIR >/dev/null 2>&1
echo "Running build"
(make && make install) >/dev/null 2>&1
else
echo "Installaton directory already exists. Skipping build"
fi
# Return to root directory
cd $CWD
echo "Using couchbase root: $INSTALLATION_DIR"
echo "Executing: 'npm install --build-from-source --couchbase-root=$INSTALLATION_DIR couchbase@2.1.3'"
npm install --build-from-source --couchbase-root=$INSTALLATION_DIR couchbase@2.1.3
|
package com.chequer.axboot.core.utils;
import com.chequer.axboot.core.code.AXBootTypes;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class PhaseUtils implements EnvironmentAware {
private static Environment environment;
@Override
public void setEnvironment(Environment _environment) {
environment = _environment;
}
public static String phase() {
String[] activeProfiles = environment.getActiveProfiles();
String activeProfile = AXBootTypes.ApplicationProfile.LOCAL;
if (activeProfiles != null && activeProfiles.length > 0) {
activeProfile = activeProfiles[0];
}
return activeProfile;
}
public static boolean isLocal() {
return phase().equals(AXBootTypes.ApplicationProfile.LOCAL);
}
public static boolean isAlpha() {
return phase().equals(AXBootTypes.ApplicationProfile.ALPHA);
}
public static boolean isBeta() {
return phase().equals(AXBootTypes.ApplicationProfile.BETA);
}
public static boolean isProduction() {
return phase().equals(AXBootTypes.ApplicationProfile.PRODUCTION);
}
public static Environment getEnvironment() {
return environment;
}
public static boolean isDevelopmentMode() {
return isLocal() || Boolean.parseBoolean(System.getProperty("axboot.profiles.development"));
}
}
|
<reponame>Rohitm619/Softuni-Python-Basic<filename>ForLoop/NumbersEndingIn7.py
for number in range(1, 1001):
if number % 10 == 7:
print(number) |
using System;
public class Program
{
public static void Main()
{
string[] words = {"lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit"};
string longestWord = "";
foreach (string word in words)
{
if (word.Length > longestWord.Length)
{
longestWord = word;
}
}
Console.WriteLine("Longest word is " + longestWord);
}
} |
package com.infamous.framework.persistence.utils;
import java.util.Arrays;
import java.util.function.Function;
public enum SupportedMethod {
CHECK_STATUS("checkStatus", ExecutionUtils::checkStatus),
CREATE_DATABASE("createDatabase", ExecutionUtils::createDatabase),
GET_DATABASE_NAME("getDatabaseName", argumentFacade -> {
String dbName = ExecutionUtils.getDatabaseName(argumentFacade);
return new StatusMessage(dbName);
});
private String m_method;
private Function<ArgumentFacade, StatusMessage> m_executeFunction;
SupportedMethod(String method, Function<ArgumentFacade, StatusMessage> executeFunction) {
this.m_method = method;
this.m_executeFunction = executeFunction;
}
public String getMethod() {
return m_method;
}
public Function<ArgumentFacade, StatusMessage> getExecuteFunction() {
return m_executeFunction;
}
public static SupportedMethod fromString(String methodAsString) {
return Arrays.stream(SupportedMethod.values())
.filter(method -> method.getMethod().equalsIgnoreCase(methodAsString))
.findAny().orElse(null);
}
}
|
<filename>Algorithm/src/main/java/com/leetcode/NumArray.java<gh_stars>0
package com.leetcode;
public class NumArray {
int[] preSum;
public NumArray(int[] nums) {
preSum = new int[nums.length + 1];
for (int i = 0; i < nums.length; i++) {
preSum[i + 1] = preSum[i] + nums[i];
}
}
public int sumRange(int left, int right) {
return preSum[right + 1] - preSum[left];
}
}
|
import { Injectable } from '@angular/core';
import { OktaAuthService } from '@okta/okta-angular';
import { HttpClient, HttpHeaders, HttpRequest, HttpParams } from '@angular/common/http';
import { FormBuilder, FormGroup } from '@angular/forms';
@Injectable({
providedIn: 'root'
})
export class InsertSuspectsService {
constructor(
private oktaAuth: OktaAuthService,
private http: HttpClient,
private formBuilder: FormBuilder
) {}
images = [];
async createSuspect(suspect) {
let user = await this.oktaAuth.getUser();
let accessToken = await this.oktaAuth.getAccessToken();
let url = 'http://localhost:5000/suspect';
let formData = new FormData();
suspect.images.forEach(img => {
formData.append('files', img);
});
formData.append('suspectName', suspect.name);
formData.append('user', user.name);
let options = {
reportProgress: true,
params: new HttpParams(),
init: {
responseType: "text"
}
};
console.log(formData);
let req = new HttpRequest(
'POST',
url,
formData,
options
);
req = req.clone({
setHeaders: {
'Authorization': `Bearer ${accessToken}`
}
})
return this.http.request(req).toPromise();
}
deleteVideo(video) {
return this.perform('delete', `/video/${video.id}`);
}
updateVideo(video) {
return this.perform('put', `/video/${video.id}`, video);
}
getVideos() {
return this.perform('get', '/videos');
}
getVideo(video) {
return this.perform('get', `/video/${video.id}`);
}
async perform (method, resource, data = {}, typeMIME="") {
const accessToken = await this.oktaAuth.getAccessToken();
const url = `http://localhost:5000${resource}`;
const contentType = typeMIME === "" ? 'application/json' : typeMIME;
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': contentType,
'Authorization': `Bearer ${accessToken}`
})
};
switch (method) {
case 'delete':
return this.http.delete(url, httpOptions).toPromise();
case 'get':
return this.http.get(url, httpOptions).toPromise();
default:
return this.http[method](url, data, httpOptions).toPromise();
}
}
} |
/*
* Copyright (c) 2002-2008 LWJGL Project
* 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 'LWJGL' 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.
*/
package org.lwjglx.util.glu;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;
/**
* Util.java
* <p/>
* <p/>
* Created 7-jan-2004
*
* @author <NAME>
*/
public class Util {
/**
* temp IntBuffer of one for getting an int from some GL functions
*/
private static IntBuffer scratch = BufferUtils.createIntBuffer(16);
/**
* Return ceiling of integer division
*
* @param a
* @param b
*
* @return int
*/
protected static int ceil(int a, int b) {
return (a % b == 0 ? a / b : a / b + 1);
}
/**
* Normalize vector
*
* @param v
*
* @return float[]
*/
protected static float[] normalize(float[] v) {
float r;
r = (float) Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
if (r == 0.0) {
return v;
}
r = 1.0f / r;
v[0] *= r;
v[1] *= r;
v[2] *= r;
return v;
}
/**
* Calculate cross-product
*
* @param v1
* @param v2
* @param result
*/
protected static void cross(float[] v1, float[] v2, float[] result) {
result[0] = v1[1] * v2[2] - v1[2] * v2[1];
result[1] = v1[2] * v2[0] - v1[0] * v2[2];
result[2] = v1[0] * v2[1] - v1[1] * v2[0];
}
/**
* Method compPerPix.
*
* @param format
*
* @return int
*/
protected static int compPerPix(int format) {
/* Determine number of components per pixel */
switch (format) {
case GL_COLOR_INDEX:
case GL_STENCIL_INDEX:
case GL_DEPTH_COMPONENT:
case GL_RED:
case GL_GREEN:
case GL_BLUE:
case GL_ALPHA:
case GL_LUMINANCE:
return 1;
case GL_LUMINANCE_ALPHA:
return 2;
case GL_RGB:
case GL_BGR:
return 3;
case GL_RGBA:
case GL_BGRA:
return 4;
default:
return -1;
}
}
/**
* Method nearestPower.
* <p/>
* Compute the nearest power of 2 number. This algorithm is a little strange, but it works quite well.
*
* @param value
*
* @return int
*/
protected static int nearestPower(int value) {
int i;
i = 1;
/* Error! */
if (value == 0) {
return -1;
}
for (;;) {
if (value == 1) {
return i;
} else if (value == 3) {
return i << 2;
}
value >>= 1;
i <<= 1;
}
}
/**
* Method bytesPerPixel.
*
* @param format
* @param type
*
* @return int
*/
protected static int bytesPerPixel(int format, int type) {
int n, m;
switch (format) {
case GL_COLOR_INDEX:
case GL_STENCIL_INDEX:
case GL_DEPTH_COMPONENT:
case GL_RED:
case GL_GREEN:
case GL_BLUE:
case GL_ALPHA:
case GL_LUMINANCE:
n = 1;
break;
case GL_LUMINANCE_ALPHA:
n = 2;
break;
case GL_RGB:
case GL_BGR:
n = 3;
break;
case GL_RGBA:
case GL_BGRA:
n = 4;
break;
default:
n = 0;
}
switch (type) {
case GL_UNSIGNED_BYTE:
m = 1;
break;
case GL_BYTE:
m = 1;
break;
case GL_BITMAP:
m = 1;
break;
case GL_UNSIGNED_SHORT:
m = 2;
break;
case GL_SHORT:
m = 2;
break;
case GL_UNSIGNED_INT:
m = 4;
break;
case GL_INT:
m = 4;
break;
case GL_FLOAT:
m = 4;
break;
default:
m = 0;
}
return n * m;
}
/**
* Convenience method for returning an int, rather than getting it out of a buffer yourself.
*
* @param what
*
* @return int
*/
protected static int glGetIntegerv(int what) {
scratch.rewind();
GL11.glGetIntegerv(what, scratch);
// glGetInteger(what, scratch);
return scratch.get();
}
}
|
<gh_stars>1-10
package io.github.hotspacode.neeza.test.springboot.controller;
import io.github.hotspacode.neeza.base.annotation.NeezaMock;
import io.github.hotspacode.neeza.core.serialization.FastJSONSerialization;
import io.github.hotspacode.neeza.test.springboot.pojo.Order;
import io.github.hotspacode.neeza.test.springboot.pojo.OrderItem;
import io.github.hotspacode.neeza.test.springboot.service.IOrderService;
import io.github.hotspacode.neeza.test.springboot.service.OrderWorkerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("order")
public class OrderController {
@Autowired
private IOrderService orderService;
@Autowired
private OrderWorkerService orderWorkerService;
@GetMapping("getOrder")
public Order getOrder(@RequestParam(value = "orderId") Long orderId) {
// orderWorkerService.addOrderWorker(null);
// orderWorkerService.addOrderWorker();
return orderService.getOrder(orderId);
}
@GetMapping("listOrderItem")
public List<OrderItem> listOrderItem() {
return orderService.listOrderItem();
}
@GetMapping("orderMap")
public Map orderMap(@RequestParam(value = "key")String key,@RequestParam(value = "value") String value) {
return orderService.orderMap(key,value);
}
/* public static void main(String[] args) {
FastJSONSerialization fastJSONSerialization = new FastJSONSerialization();
Order order = new Order();
order.setId(5438843L);
order.setMarketName("service内部");
order.setShopName("shop内部name");
System.out.println(new String(fastJSONSerialization.serialize(order)));
}*/
}
|
class VideoManager:
def __init__(self):
self.duration = 0
def add_clip_duration(self, clip_duration):
self.duration += clip_duration
return self.duration |
/**
* The component registry allows to store
* gondel components by an unique name
*/
import { IGondelComponent } from './GondelComponent';
export declare const enum RegistryBootMode {
/**
* The Registry was already booted
*/
alreadyBooted = 0,
/**
* The registry has to be booted by explicitly calling startComponents()
*/
manual = 1,
/**
* The registry will start once the dom was load
*/
onDomReady = 2
}
export declare class GondelComponentRegistry {
_components: {
[componentName: string]: IGondelComponent;
};
_activeComponents: {
[componentName: string]: boolean;
};
_bootMode: RegistryBootMode;
constructor();
registerComponent(name: string, gondelComponent: IGondelComponent): void;
unregisterComponent(name: string): void;
getComponent(name: string): IGondelComponent<HTMLElement>;
/**
* Set if a component is used
*/
setActiveState(name: string, isActive: boolean): void;
setBootMode(bootMode: RegistryBootMode): void;
}
export declare function getComponentRegistry(namespace: string): GondelComponentRegistry;
export declare function registerComponent(componentName: string, component: IGondelComponent): void;
export declare function registerComponent(componentName: string, namespace: string | undefined, component: IGondelComponent): void;
|
import re
def parse_migration_file(migration_file_content: str) -> dict:
model_field_map = {}
add_field_pattern = r"migrations\.AddField\(model_name='(\w+)', name='(\w+)'"
matches = re.findall(add_field_pattern, migration_file_content)
for match in matches:
model_name = match[0]
field_name = match[1]
if model_name in model_field_map:
model_field_map[model_name].append(field_name)
else:
model_field_map[model_name] = [field_name]
return model_field_map |
#!/bin/bash
# download and unpack the NCBI nt database
# Mark Stenglein 1.9.2021
# Doing it this way because update_blastdb.pl [from NCBI] continually dropped connection
# create a list of nt files
# assume the dbs will go up to 99 sub-files - may have to up this in the future
# if goes beyond 99 will have to make sure numbering is ok, w/ regards to 0 padding...
# have to do this cd command in case this script is run as a cron job
# in which case it would normally excute w/ home dir as pwd
DATABASE_DIR=$HOME/NCBI_databases/nt/
mkdir -p $DATABASE_DIR
cd $DATABASE_DIR
echo "***************************************************************"
echo "** downloading taxonomy info so blast will be taxonomy aware **
echo "***************************************************************"
# first, get and unpack the taxdb file blast cli applications need to be 'taxonomically aware'
wget ftp://ftp.ncbi.nlm.nih.gov/blast/db/taxdb.tar.gz
tar xvf taxdb.tar.gz
rm -f taxdb.tar.gz
# setup BLASTDB environmental variable so blast knows where to find nt database and taxonomy info
# delete any such matching lines
sed -i '/BLASTDB/d' ~/.bashrc
echo "export BLASTDB=$DATABASE_DIR" >> ~/.bashrc
echo "***************************************************"
echo "** downloading and updating nt files and indexes **"
echo "***************************************************"
date
num_subfiles=99
subfile_nums=(`seq -s " " -w 0 $num_subfiles`)
nt_files=()
subfile=1
for subfile in ${subfile_nums[@]}
do
nt_file="nt.${subfile}.tar.gz"
nt_files+=($nt_file)
done
echo "starting download and unpacking of files"
date
echo "fetching nt files from NCBI FTP server"
for f in ${nt_files[@]}
do
wget -N ftp://ftp.ncbi.nlm.nih.gov/blast/db/$f
done
echo "unpacking nt files"
for f in `ls nt.??.tar.gz`
do
tar xfzv $f
done
echo "finished downloading and unpacking files"
date
date >> nr_nt_updated_dates.txt
# remove tar.gz files
echo "deleting .tar.gz files"
rm -f nt*.tar.gz
|
<gh_stars>0
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { ValidationError, withFormHandling } from '@jbknowledge/react-form';
const Input = ({ value, setValue, error, label }) => {
const [blurred, setBlurred] = useState(false);
return (
<Container>
<Label>{label}</Label>
<TextInput
value={value}
onChange={(e) => setValue(e.target.value)}
onBlur={() => setBlurred(true)}
className={error && blurred ? 'error' : ''}
/>
{error && blurred && <Error>{error}</Error>}
</Container>
);
};
const onFormChange = (value, { regex, defaultErrorMessage }) => {
if (!value.match(regex)) {
throw new ValidationError(defaultErrorMessage);
}
};
Input.propTypes = {
value: PropTypes.string,
setValue: PropTypes.func,
error: PropTypes.string,
label: PropTypes.string
};
export default withFormHandling(Input, onFormChange);
const Container = styled.div`
padding-bottom: 10px;
`;
const Label = styled.div`
color: dimgray;
padding-bottom: 2px;
`;
const Error = styled.div`
color: #d9534f;
font-size: 14px;
`;
const TextInput = styled.input`
width: 25%;
line-height: 1.5;
padding: 0.375rem 0.5rem;
height: calc(1.5em + 0.75rem + 2px);
margin: 2px 0;
border: 1px solid #ced4da;
box-sizing: border-box;
border-radius: 0.25rem;
&.error {
border: 1px solid #d9534f;
}
`;
|
<reponame>kkrull/javaspec<gh_stars>1-10
package info.javaspec.console;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(
format = { "pretty", "html:build/reports/cucumber", "rerun:build/cucumber-jvm-rerun.txt" },
strict = true,
tags = { "~@wip" })
public final class FeatureTest { }
|
#!/bin/bash
INSTALL_DIR=$HOME/.nefi2
SHORTCUT=/usr/local/bin/nefi2
echo "Copying files..."
# copy files
if [ -d "$INSTALL_DIR" ]; then
rm -r $INSTALL_DIR
fi
mkdir $HOME/.nefi2
cp -r nefi2 $HOME/.nefi2
cp -r sample_images $HOME/.nefi2
cp nefi2.py $HOME/.nefi2
cp LICENSE $HOME/.nefi2
cp README.md $HOME/.nefi2
# create a symlink
if [ -L "$SHORTCUT" ]; then
sudo rm /usr/local/bin/nefi2
fi
sudo ln -s $HOME/.nefi2/nefi2.py /usr/local/bin/nefi2
echo "Installing dependencies..."
# install python dependencies
pip install numpy networkx demjson QDarkStyle thinning_py3 zope.event --user
echo "Done"
|
<filename>core/docz-theme-default/src/components/ui/Editor/index.tsx
import * as React from 'react'
import { useMemo, useCallback, useState } from 'react'
import { useConfig, UseConfigObj } from 'docz'
import loadable from '@loadable/component'
import styled from 'styled-components'
import getter from 'lodash/get'
import { ClipboardAction } from './elements'
import { get } from '@utils/theme'
const CodeMirror = loadable(() => import('../CodeMirror'))
const getLanguage = (children: any) => {
const defaultLanguage = 'jsx'
if (typeof children === 'string') return defaultLanguage
const language = getter(children, 'props.props.className') || defaultLanguage
const result = language.replace('language-', '')
if (result === 'js' || result === 'javascript') return 'jsx'
if (result === 'ts' || result === 'tsx' || result === 'typescript') {
return 'text/typescript'
}
return result
}
const getChildren = (children: any) =>
children && typeof children !== 'string'
? getter(children, 'props.children')
: children
const Wrapper = styled.div`
margin: 30px 0;
position: relative;
width: 100%;
border: 1px solid ${get('colors.border')};
`
const Actions = styled.div`
z-index: 999;
position: absolute;
top: 0;
right: 0;
display: flex;
flex-direction: column;
align-items: center;
padding: 5px 10px;
background: transparent;
`
export interface EditorProps {
children: any
className?: string
editorClassName?: string
actions?: React.ReactNode
readOnly?: boolean
mode?: string
matchBrackets?: boolean
indentUnit?: number
onChange?: (code: string) => any
language?: string
withLastLine?: boolean
}
export const Editor: React.SFC<EditorProps> = ({
mode,
children,
actions,
onChange,
className,
editorClassName,
language: defaultLanguage,
...props
}) => {
const config = useConfig()
const initialCode = useMemo(() => getChildren(children), [children])
const [code, setCode] = useState(initialCode)
const language = defaultLanguage || getLanguage(children)
const options = {
...props,
tabSize: 2,
mode: language || mode,
lineNumbers: true,
lineWrapping: true,
autoCloseTags: true,
theme: 'docz-light',
}
const onEditorDidMount = (editor: any) => {
if (editor) removeLastLine(editor)
}
const removeLastLine = useCallback(
(editor: any) => {
if (editor && !props.withLastLine && props.readOnly) {
const lastLine = editor.lastLine()
editor.doc.replaceRange('', { line: lastLine - 1 }, { line: lastLine })
}
},
[props.withLastLine, props.readOnly]
)
const handleChange = useCallback(
(editor: any, data: any, code: string) => {
onChange && onChange(code)
setCode(code)
},
[code]
)
const editorProps = (config: UseConfigObj) => ({
value: code,
className: editorClassName,
editorDidMount: onEditorDidMount,
onBeforeChange: handleChange,
options: {
...options,
theme:
config && config.themeConfig
? config.themeConfig.codemirrorTheme
: options.theme,
},
})
return (
<Wrapper className={className}>
<CodeMirror {...editorProps(config)} />
<Actions>{actions || <ClipboardAction content={code} />}</Actions>
</Wrapper>
)
}
Editor.defaultProps = {
mode: 'js',
readOnly: true,
matchBrackets: true,
indentUnit: 2,
}
|
SELECT *
FROM company_db.customers
WHERE total_spent_last_month > 200; |
<reponame>awoodworth/StarRezApi
require 'httparty'
require 'xmlsimple'
class StarRezAccount
include HTTParty
base_uri STARREZ_CONFIG['base_uri']
headers 'StarRezUsername' => STARREZ_CONFIG['username'], 'StarRezPassword' => STARREZ_CONFIG['password']
attr_accessor :name, :results, :total_amount, :total_tax_amount, :total_tax_amount2, :entry_id
def self.get_balance(*args)
options = args.extract_options!
entry = args[0] || @entry_id
charge_group = args[1] || options[:charge_group]
if entry.blank?
raise IOError, "Must include an Entry ID to search"
end
url = "#{base_uri}/accounts/getbalance/#{entry}/#{charge_group}"
response = get(url)
if options[:return].eql? :response
return response
else
if response.code.eql? 404
raise ArgumentError, "Invalid Entry ID"
elsif response.code.eql? 403
raise SecurityError, 'Access Denied to API'
elsif response.code.eql? 200
doc = Hpricot(response)
account = StarRezAccount.new
account.name = doc.at("Entry").at("title").inner_html
account.total_amount = "%.2f" % doc.at("totalamount").inner_html
account.total_tax_amount = "%.2f" % doc.at("totaltaxamount").inner_html
account.total_tax_amount2 = "%.2f" % doc.at("totaltaxamount2").inner_html
account
else
return false
end
end
end
def self.create_transaction(entry,amount,conditions={},options={})
conditions[:transaction_type_enum] ||= "Payment"
url = "#{base_uri}/accounts/createtransaction/#{entry}"
transaction_xml =
"<?xml version='1.0' encoding='utf-16' ?>
<Transaction>
<TransactionTypeEnum>#{conditions[:transaction_type_enum]}</TransactionTypeEnum>
<Amount>#{amount}</Amount>
<Description>#{conditions[:description]}</Description>
<TermSessionID>#{conditions[:term_session_id]}</TermSessionID>
<ExternalID>#{conditions[:external_id]}</ExternalID>
<Comments>#{conditions[:comments]}</Comments>
<ChargeGroupID>#{conditions[:charge_group_id]}</ChargeGroupID>
<ChargeItemID>#{conditions[:charge_item_id]}</ChargeItemID>
<SecurityUserID>6</SecurityUserID>
</Transaction>"
response = post(url, :body => transaction_xml)
if options[:return].eql? :response
return response
else
if response.code.eql? 409
raise ArgumentError, "Duplicate Transaction Found"
elsif response.code.eql? 404
raise ArgumentError, "Invalid Entry ID"
elsif response.code.eql? 403
raise SecurityError, 'Access Denied to API'
elsif response.code.eql? 400
raise ArgumentError, "Bad Request"
elsif response.code.eql? 200
doc = Hpricot(response.body)
doc.search("transactionid").inner_html
else
return false
end
end
end
def self.create_payment(entry,amount,conditions={},options={})
conditions[:description] ||= "Deposit"
url = "#{base_uri}/accounts/createpayment/#{entry}"
charge_groups_string = ""
if conditions[:charge_groups].any?
# round to 2 decimals due to float inconsistencies
break_up_total = conditions[:charge_groups].collect { |g| g[:amount] }.reduce(&:+).round(2)
raise ArgumentError, "Payment amount and charge group breakup amounts must be equal" unless break_up_total == amount
conditions[:charge_groups].each do |charge_group|
if charge_group[:id].present?
charge_groups_string += %(<BreakUp ChargeGroupID="#{charge_group[:id]}">)
elsif charge_group[:name].present?
charge_groups_string += %(<BreakUp ChargeGroup="#{charge_group[:name]}">)
else
raise ArgumentError, "Charge group ID or name must be provided"
end
raise ArgumentError, "Amount must be provided for payment breakup" if charge_group[:amount].blank?
charge_groups_string += %(<Amount>#{charge_group[:amount]}</Amount>)
if charge_group[:tag].present?
charge_groups_string += %(<TransactionTag>#{charge_group[:tag]}</TransactionTag>)
end
charge_groups_string += %(<TransactionExternalID>#{charge_group[:external_id]}</TransactionExternalID>) if charge_group[:external_id].present?
charge_groups_string += %(<TransactionTermSessionID>#{charge_group[:term_session_id]}</TransactionTermSessionID>) if charge_group[:term_session_id].present?
charge_groups_string += %(</BreakUp>)
end
else
raise ArgumentError, "At least one charge group must be provided in :charge_groups"
end
amount_string = %(<Amount>#{amount}</Amount>)
description_string = %(<Description>#{conditions[:description]}</Description>)
payment_xml =
"<?xml version='1.0' encoding='utf-16' ?>
<Payment>
<TransactionTypeEnum>Payment</TransactionTypeEnum>
<PaymentTypeID>8</PaymentTypeID>
<SecurityUserID>6</SecurityUserID>
#{description_string}
#{amount_string}
#{charge_groups_string}
</Payment>"
response = post(url, body: payment_xml)
if options[:return].eql? :response
return response
elsif options[:return].eql? :xml
return payment_xml
else
if response.code.eql? 409
raise ArgumentError, "Duplicate Transaction Found"
elsif response.code.eql? 404
raise ArgumentError, "Invalid Entry ID"
elsif response.code.eql? 403
raise SecurityError, 'Access Denied to API'
elsif response.code.eql? 400
raise ArgumentError, "Bad Request"
elsif response.code.eql? 200
doc = Hpricot(response.body)
doc.search("paymentid").inner_html
else
return false
end
end
end
private
def self.get_condition_string(conditions)
queries = Array.new
if conditions.is_a?(Hash)
conditions.each_pair do |column, value|
query = column.to_s.camelize
if value.is_a?(Hash)
query += "[_operator%3D#{value.keys.first.to_s}]=#{self.parse_value(value[value.keys.first])}"
else
query += "=#{self.parse_value(value)}"
end
queries << query
end
return queries.join('&')
else
raise ArgumentError, "Condition needs to be a hash of values, Please review the source code"
end
end
#Just a quick method used in get_condition_string that would have been repeated
#Just takes the array and converts it into a formatted string for StarRezAPI
def self.parse_value(values)
if values.is_a?(Array)
return URI::encode(values.join(','))
else
return URI::encode(values.to_s)
end
end
end
|
<filename>src/main/java/com/aya/financegateway/channel/swift/model/message/mt/SwiftBlock5.java
package com.aya.financegateway.channel.swift.model.message.mt;
public class SwiftBlock5 {
}
|
#!/bin/sh
mv ./package.json ./fake.package.json
mkdir dist
# This is a contrivance, using the transformer, as there is no alternative other than process.env
# being manipulated another way
browserify --outfile logger.js -t [ envify --NODE_ENV production ] --standalone logger --entry ./lib/index.js
# Minify the code
google-closure-compiler --js logger.js --js_output_file logger.min.js --strict_mode_input=false
# Minify the logger code
cp ./lib/index.d.ts ./dist/index.d.ts
google-closure-compiler --js ./lib/index.js --js_output_file ./dist/index.js --strict_mode_input=false
mv ./fake.package.json ./package.json
|
import { IData } from './IData';
export interface IMongoData extends IData<string> {
_id: string;
} |
#!/bin/bash
# Clean sysctl config directories
rm -rf /usr/lib/sysctl.d/* /run/sysctl.d/* /etc/sysctl.d/*
sed -i "/net.ipv6.conf.all.accept_ra/d" /etc/sysctl.conf
echo "net.ipv6.conf.all.accept_ra = 1" >> /etc/sysctl.conf
# Setting correct runtime value
sysctl -w net.ipv6.conf.all.accept_ra=0
|
import Vue from "vue";
import App from "./App";
import router from "./router";
import store from "./store";
import VueResource from "vue-resource";
import Notification from "./components/common/Notification";
import LoadingScreen from "./components/common/LoadingScreen";
Vue.use(VueResource);
Vue.component("app-notification", Notification);
Vue.component("app-loading-screen", LoadingScreen);
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
el: "#app",
router,
store,
components: { App },
template: "<App/>"
});
|
if [ "$#" -ne 2 ]; then
echo -e "Usage: ch3.sh \$SOLR_IN_ACTION \$SOLR_INSTALL"
exit 0
fi
echo -e "----------------------------------------"
echo -e "CHAPTER 3"
echo -e "----------------------------------------"
echo -e "No examples to run for chapter 3." |
"use strict";
/**
* Pagination.
* @todo setToPageEvent
*/
Egf.Pagination = function Pagination() {
/** @type {Egf.Pagination} That this. */
var that = this;
/** @type {string} The cssClass of container elements. */
this.containerElementsCssClass = '';
/** @type {string} Unique identifier of pagination block. */
this.uniqueIdentifier = '';
/** @type {object} Translations. */
this.translations = {
first: 'First',
previous: 'Previous',
next: 'Next',
last: 'Last'
};
/** @type {object} */
this.containerElements = [];
/** @type {number} The current page. */
this.currentPage = 1;
/** @type {number} The max page. */
this.maxPage = 1;
/** @type {object} The event functions on clicking pagination buttons. */
this.events = {
toFirst: function () {
},
toPrevious: function () {
},
toNext: function () {
},
toLast: function () {
}
};
/**************************************************************************************************************************************************************
* ** ** ** ** ** ** ** ** ** **
* Setters/Init ** ** ** ** ** ** ** ** ** **
* ** ** ** ** ** ** ** ** ** **
*************************************************************************************************************************************************************/
/**
* Set element referrers. Adds dot prefix if it's not there.
* @param containerElementsCssClass {string}
* @return {Egf.Pagination}
*/
this.setContainerElementsCssClass = function (containerElementsCssClass) {
this.containerElementsCssClass = (Egf.Util.startsWith(containerElementsCssClass, '.') ? containerElementsCssClass : '.' + containerElementsCssClass);
return this;
};
/**
* Set translations.
* @param translations {object}
* @return {Egf.Pagination}
*/
this.setTranslations = function (translations) {
this.translations = Egf.Util.objectAssign(this.translations, translations);
return this;
};
/**
* Initialize.
* @return {Egf.Pagination}
*/
this.init = function () {
this.containerElements = Egf.Elem.find(this.containerElementsCssClass);
this.uniqueIdentifier = Egf.Util.getRandomString(8, 'alpha');
return this;
};
/**************************************************************************************************************************************************************
* ** ** ** ** ** ** ** ** ** **
* Refresh ** ** ** ** ** ** ** ** ** **
* ** ** ** ** ** ** ** ** ** **
*************************************************************************************************************************************************************/
/**
* Refresh the content of pagination containers.
* @return {Egf.Pagination}
*/
this.refresh = function () {
Egf.Util.forEach(this.containerElements, function (containerElement) {
Egf.Template.toElementByTemplate(containerElement, 'js-template-egf-pagination', {
uniqueIdentifier: that.uniqueIdentifier,
currentPage: that.currentPage,
maxPage: that.maxPage,
text: {
first: that.translations.first,
previous: that.translations.previous,
next: that.translations.next,
last: that.translations.last
}
});
});
that.addEvents();
return this;
};
/**************************************************************************************************************************************************************
* ** ** ** ** ** ** ** ** ** **
* Events ** ** ** ** ** ** ** ** ** **
* ** ** ** ** ** ** ** ** ** **
*************************************************************************************************************************************************************/
/**
* Add events to buttons.
* @return {Egf.Pagination}
*/
this.addEvents = function () {
console.log('pagination addEvents');
// To first.
Egf.Elem.addEvent('.' + this.uniqueIdentifier + '-egf-pagination-button-to-first', 'click', function (e) {
e.preventDefault();
that.events.toFirst();
});
// To previous.
Egf.Elem.addEvent('.' + this.uniqueIdentifier + '-egf-pagination-button-to-previous', 'click', function (e) {
e.preventDefault();
that.events.toPrevious();
});
// To next.
Egf.Elem.addEvent('.' + this.uniqueIdentifier + '-egf-pagination-button-to-next', 'click', function (e) {
e.preventDefault();
that.events.toNext();
});
// To last.
Egf.Elem.addEvent('.' + this.uniqueIdentifier + '-egf-pagination-button-to-last', 'click', function (e) {
e.preventDefault();
that.events.toLast();
});
return this;
};
/**
* Set the event of clicking first button.
* @param fnToFirst {function}
* @return {Egf.Pagination}
*/
this.setToFirstEvent = function (fnToFirst) {
that.events.toFirst = fnToFirst;
return this;
};
/**
* Set the event of clicking previous button.
* @param fnToPrevious {function}
* @return {Egf.Pagination}
*/
this.setToPreviousEvent = function (fnToPrevious) {
that.events.toPrevious = fnToPrevious;
return this;
};
/**
* Set the event of clicking next button.
* @param fnToNext {function}
* @return {Egf.Pagination}
*/
this.setToNextEvent = function (fnToNext) {
that.events.toNext = fnToNext;
return this;
};
/**
* Set the event of clicking last button.
* @param fnToLast {function}
* @return {Egf.Pagination}
*/
this.setToLastEvent = function (fnToLast) {
that.events.toLast = fnToLast;
return this;
}
}
|
package frc.robot;
import edu.wpi.first.wpilibj.Joystick;
public class OI {
public Joystick joystick = new Joystick(0);
}
|
<gh_stars>0
/* - Coeus web framework -------------------------
*
* Licensed under the Apache License, Version 2.0.
*
* Ported from Apache Jakarta Commons Validator,
* http://commons.apache.org/validator/
*
* Author: <NAME>
*/
package com.tzavellas.coeus.validation.vspec.constraint
import org.junit.Test
class IsbnConstraintTest {
import ConstraintAssertions._
import IsbnConstraintTest._
val constraint = new IsbnConstraint
@Test
def invalid_isbn_numbers() {
assertInvalid(constraint,
"", "1", "12345678901234","dsasdsadsads",
"535365", "I love sparrows!", "--1 930110 99 5",
"1 930110 99 5--", "1 930110-99 5-", INVALID_ISBN)
}
@Test
def valid_isbn_numbers() {
assertValid(constraint,
null, VALID_ISBN_RAW, VALID_ISBN_DASHES,
VALID_ISBN_SPACES, VALID_ISBN_X, VALID_ISBN_x)
}
}
private object IsbnConstraintTest {
val VALID_ISBN_RAW = "1930110995"
val VALID_ISBN_DASHES = "1-930110-99-5"
val VALID_ISBN_SPACES = "1 930110 99 5"
val VALID_ISBN_X = "0-201-63385-X"
val VALID_ISBN_x = "0-201-63385-x"
val INVALID_ISBN = "068-556-98-45"
}
|
<reponame>Antloup/workflow-js<filename>src/index.ts
import Loader from './Loader';
import Parser from './Parser';
import Workflow from './Workflow';
export * from './Workflow';
export * from './Parser';
export * from './Loader';
export * from './Providers';
export * from './Elements'
export {Workflow, Parser, Loader};
|
<gh_stars>0
package dial
import (
"errors"
"net"
"sync"
"github.com/cloudfstrife/gpool"
)
var (
pool *gpool.Pool
once sync.Once
)
func init() {
once.Do(func() {
pool = gpool.DefaultPool(NewConnection)
err := pool.Config.LoadToml("general.toml")
if err != nil {
panic(err)
}
pool.Initial()
})
}
//NewConnection 获取新连接
func NewConnection() gpool.Item {
return &Connection{}
}
//GetConnection 获取连接
func GetConnection() (net.Conn, error) {
item, err := pool.GetOne()
if err != nil {
return nil, err
}
con, ok := item.(*Connection)
if ok {
return con.TCPConn, nil
}
return nil, errors.New("类型转换错误")
}
//CloseConnection 关闭连接
func CloseConnection(conn net.Conn) {
pool.BackOne(&Connection{
TCPConn: conn,
})
}
//ClosePool 关闭连接池
func ClosePool() {
wg := &sync.WaitGroup{}
wg.Add(1)
pool.Shutdown(wg)
wg.Wait()
}
|
#!/bin/bash
[[ "${VDI_launchIDE:-pycharm}" != pycharm ]] && exit 0
# Launch IDE with cloned repo, if Selkies file exists, otherwise, launch and pass arguments.
CLONE_FILE="${HOME}/.config/selkies-user-init/git_repo_cloned"
if [[ -e ${CLONE_FILE} ]]; then
REPO_DIR=$(cat ${CLONE_FILE})
rm -f ${CLONE_FILE}
exec /opt/PyCharm-CE/bin/pycharm.sh ${REPO_DIR}
exit
fi
# If no clone file exists, just launch the IDE with the given arguments.
exec /opt/PyCharm-CE/bin/pycharm.sh $@
exit |
__all__ = ['to_bytes', 'to_text']
def to_bytes(obj, encoding='utf-8', errors='strict'):
"""Makes sure that a string is a byte string.
Args:
obj: An object to make sure is a byte string.
encoding: The encoding to use to transform from a text string to
a byte string. Defaults to using 'utf-8'.
errors: The error handler to use if the text string is not
encodable using the specified encoding. Any valid codecs error
handler may be specified.
Returns: Typically this returns a byte string.
"""
if isinstance(obj, bytes):
return obj
return bytes(obj, encoding=encoding, errors=errors)
def to_text(obj, encoding='utf-8', errors='strict'):
"""Makes sure that a string is a text string.
Args:
obj: An object to make sure is a text string.
encoding: The encoding to use to transform from a byte string to
a text string. Defaults to using 'utf-8'.
errors: The error handler to use if the byte string is not
decodable using the specified encoding. Any valid codecs error
handler may be specified.
Returns: Typically this returns a text string.
"""
if isinstance(obj, str):
return obj
return str(obj, encoding=encoding, errors=errors)
|
#!/bin/sh
./config shared zlib-dynamic --prefix=$PREFIX
make
make install
|
<reponame>zhuzilin/monkey<gh_stars>10-100
#include "../header/token.h"
namespace monkey {
std::unordered_map<std::string, TokenType> keywords({
{"let", LET},
{"fn", FUNCTION},
{"true", TRUE},
{"false", FALSE},
{"if", IF},
{"else", ELSE},
{"return", RETURN},
{"while", WHILE}
});
TokenType LookupIdent(std::string ident) {
if(keywords.find(ident)== keywords.end())
return IDENT;
return keywords[ident];
}
} // namespace monkey
|
import { UiState } from '@app/core/state';
import { Store } from '@ngxs/store';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'sketch-settings-layer-properties',
template: `
<mat-expansion-panel expanded="false" [disabled]="!currentLayer?.name">
<mat-expansion-panel-header>
<mat-panel-title>
Properties
</mat-panel-title>
</mat-expansion-panel-header>
<mat-form-field class="large">
<input disabled matInput type="text" placeholder="Name" [ngModel]="currentLayer?.name">
</mat-form-field>
<mat-form-field class="large">
<input disabled matInput type="text" placeholder="Kind" [ngModel]="currentLayer?._class">
</mat-form-field>
</mat-expansion-panel>
`,
styles: [`
:host {
text-align: center;
}
mat-form-field {
padding: 14px;
}
`]
})
export class SettingsLayerPropertiesComponent implements OnInit {
currentLayer: SketchMSLayer;
constructor(private store: Store) { }
ngOnInit() {
this.store.select(UiState.currentLayer).subscribe(currentLayer => {
this.currentLayer = currentLayer;
});
}
}
|
#!/bin/bash
NUM1=$1
NUM2=$2
RESULT=$(expr $NUM1 + $NUM2)
echo "The result of $NUM1 + $NUM2 is $RESULT" |
<gh_stars>1-10
import { connect } from 'react-redux';
import { compose } from 'redux';
import { reduxForm } from 'redux-form';
import { inntektskildetyper as inntektskildetypeEnums, sykepengesoknadstatuser, toDatePrettyPrint } from '@navikt/digisyfo-npm';
import history from '../../history';
import { onSubmitFail } from '../../components/skjema/feiloppsummering/FeiloppsummeringContainer';
import { mapAktiviteter } from './sykepengesoknadUtils';
import mapBackendsoknadToSkjemasoknad from '../mappers/mapBackendsoknadToSkjemasoknad';
import { getSoknadSkjemanavn } from '../../enums/skjemanavn';
import { getTidligsteSendtDato } from './sorterSoknader';
import { selectSykepengesoknaderData } from '../data/sykepengesoknader/sykepengesoknaderSelectors';
const sendTilFoerDuBegynner = (sykepengesoknad) => {
history.replace(`${process.env.REACT_APP_CONTEXT_ROOT}/soknader/${sykepengesoknad.id}`);
};
export const andreInntektskilderDefault = Object.keys(inntektskildetypeEnums).map((key) => {
return {
annenInntektskildeType: inntektskildetypeEnums[key],
};
});
const getSisteSoknadISammeSykeforloep = (soknad, soknader) => {
return soknader
.filter((s) => {
return s.id !== soknad.id;
})
.filter((s) => {
return s.identdato.getTime() === soknad.identdato.getTime();
})
.filter((s) => {
return s.status === sykepengesoknadstatuser.SENDT || s.status === sykepengesoknadstatuser.TIL_SENDING;
})
.filter((s) => {
return s.arbeidsgiver.orgnummer === soknad.arbeidsgiver.orgnummer;
})
.sort((a, b) => {
return getTidligsteSendtDato(a) - getTidligsteSendtDato(b);
})[0];
};
const preutfyllSoknad = (soknad, sisteSoknadISammeSykeforlop) => {
if (!sisteSoknadISammeSykeforlop || soknad.status === sykepengesoknadstatuser.UTKAST_TIL_KORRIGERING) {
return soknad;
}
const bruktEgenmeldingsdagerFoerLegemeldtFravaer = sisteSoknadISammeSykeforlop.egenmeldingsperioder.length > 0;
const _erInntektskilderPreutfylt = true;
const _erEgenmeldingsperioderPreutfylt = true;
const egenmeldingsperioder = [...sisteSoknadISammeSykeforlop.egenmeldingsperioder]
.sort((periodeA, periodeB) => {
return periodeA.fom - periodeB.fom;
})
.map((periode) => {
return {
fom: toDatePrettyPrint(periode.fom),
tom: toDatePrettyPrint(periode.tom),
};
});
const mappetSoknad = mapBackendsoknadToSkjemasoknad(sisteSoknadISammeSykeforlop);
const { utdanning, harAndreInntektskilder, andreInntektskilder } = mappetSoknad;
const _utdanning = utdanning.underUtdanningISykmeldingsperioden
? utdanning
: {};
const _erUtdanningPreutfylt = utdanning.underUtdanningISykmeldingsperioden;
return bruktEgenmeldingsdagerFoerLegemeldtFravaer
? {
...soknad,
utdanning: _utdanning,
bruktEgenmeldingsdagerFoerLegemeldtFravaer,
egenmeldingsperioder,
harAndreInntektskilder,
andreInntektskilder,
_erInntektskilderPreutfylt,
_erEgenmeldingsperioderPreutfylt,
_erUtdanningPreutfylt,
}
: {
...soknad,
utdanning: _utdanning,
bruktEgenmeldingsdagerFoerLegemeldtFravaer,
harAndreInntektskilder,
andreInntektskilder,
_erInntektskilderPreutfylt,
_erEgenmeldingsperioderPreutfylt,
_erUtdanningPreutfylt,
};
};
export const mapToInitialValues = (soknad, soknader = []) => {
const aktiviteter = mapAktiviteter(soknad).aktiviteter;
const initialValues = {
...soknad,
aktiviteter: aktiviteter.map((aktivitet) => {
return {
...aktivitet,
avvik: {},
};
}),
utdanning: {},
andreInntektskilder: andreInntektskilderDefault,
utenlandsopphold: {
perioder: [],
},
};
const sisteSoknadISammeSykeforlop = getSisteSoknadISammeSykeforloep(soknad, soknader);
return preutfyllSoknad(initialValues, sisteSoknadISammeSykeforlop);
};
export const getInitialValuesSykepengesoknad = (sykepengesoknad, state) => {
return sykepengesoknad.status === sykepengesoknadstatuser.UTKAST_TIL_KORRIGERING
? mapBackendsoknadToSkjemasoknad(sykepengesoknad)
: mapToInitialValues(sykepengesoknad, selectSykepengesoknaderData(state));
};
export const mapStateToProps = (state, ownProps) => {
const { sykepengesoknad } = ownProps;
return {
key: sykepengesoknad.id,
form: getSoknadSkjemanavn(sykepengesoknad.id),
sykepengesoknad: mapAktiviteter(sykepengesoknad),
};
};
export const mapStateToPropsMedInitialValues = (state, ownProps) => {
const initialValues = getInitialValuesSykepengesoknad(ownProps.sykepengesoknad, state);
return {
...mapStateToProps(state, ownProps),
initialValues,
};
};
const reduxFormSetup = (validate, Component, initialize = false) => {
return compose(
connect(initialize ? mapStateToPropsMedInitialValues : mapStateToProps),
reduxForm({
validate,
destroyOnUnmount: false,
forceUnregisterOnUnmount: true,
sendTilFoerDuBegynner,
onSubmitFail: (errors, dispatch, submitError, props) => {
onSubmitFail(errors, dispatch, getSoknadSkjemanavn(props.sykepengesoknad.id));
},
}),
)(Component);
};
export default reduxFormSetup;
|
package com.haufelexware.gocd.service;
import com.google.gson.Gson;
import com.haufelexware.gocd.dto.GoPipelineConfig;
import com.haufelexware.util.Streams;
import com.thoughtworks.go.plugin.api.logging.Logger;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import java.io.IOException;
import java.net.URLEncoder;
/**
* This class encapsulates the API call to get an complete pipeline configuration from Go.
* This API service is available since Go Version 15.3.0
* @see <a href="https://api.gocd.org/current/#get-pipeline-config">Get Pipeline Config</a>
*/
public class GoGetPipelineConfig {
private static final Logger Log = Logger.getLoggerFor(GoGetPipelineConfig.class);
private final GoApiClient goApiClient;
public GoGetPipelineConfig(GoApiClient goApiClient) {
this.goApiClient = goApiClient;
}
public GoPipelineConfig get(final String pipelineName) {
try {
HttpGet request = new HttpGet("/go/api/admin/pipelines/" + URLEncoder.encode(pipelineName, "UTF-8"));
request.addHeader("Accept", "application/vnd.go.cd.v4+json");
HttpResponse response = goApiClient.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String content = Streams.readAsString(response.getEntity().getContent());
return new Gson().fromJson(content, GoPipelineConfig.class);
} else {
Log.error("Request got HTTP-" + response.getStatusLine().getStatusCode());
}
} catch (IOException e) {
Log.error("Could not perform request", e);
}
return null;
}
}
|
<gh_stars>0
module.exports = process.argv[2]
|
<filename>tests/unit/models/plugins/toJSON.plugin.test.js
const mongoose = require('mongoose');
const { toJSON } = require('../../../../server/models/plugins');
describe('toJSON plugin', () => {
let connection;
beforeEach(() => {
connection = mongoose.createConnection();
});
it('should replace _id with id', () => {
const schema = mongoose.Schema();
schema.plugin(toJSON);
const Model = connection.model('Model', schema);
const doc = new Model();
expect(doc.toJSON()).not.toHaveProperty('_id');
expect(doc.toJSON()).toHaveProperty('id', doc._id.toString());
});
it('should remove __v', () => {
const schema = mongoose.Schema();
schema.plugin(toJSON);
const Model = connection.model('Model', schema);
const doc = new Model();
expect(doc.toJSON()).not.toHaveProperty('__v');
});
it('should remove createdAt and updatedAt', () => {
const schema = mongoose.Schema({}, { timestamps: true });
schema.plugin(toJSON);
const Model = connection.model('Model', schema);
const doc = new Model();
expect(doc.toJSON()).not.toHaveProperty('createdAt');
expect(doc.toJSON()).not.toHaveProperty('updatedAt');
});
it('should remove any path set as private', () => {
const schema = mongoose.Schema({
public: { type: String },
private: { type: String, private: true },
});
schema.plugin(toJSON);
const Model = connection.model('Model', schema);
const doc = new Model({ public: 'some public value', private: 'some private value' });
expect(doc.toJSON()).not.toHaveProperty('private');
expect(doc.toJSON()).toHaveProperty('public');
});
it('should remove any nested paths set as private', () => {
const schema = mongoose.Schema({
public: { type: String },
nested: {
private: { type: String, private: true },
},
});
schema.plugin(toJSON);
const Model = connection.model('Model', schema);
const doc = new Model({
public: 'some public value',
nested: {
private: 'some nested private value',
},
});
expect(doc.toJSON()).not.toHaveProperty('nested.private');
expect(doc.toJSON()).toHaveProperty('public');
});
it('should also call the schema toJSON transform function', () => {
const schema = mongoose.Schema(
{
public: { type: String },
private: { type: String },
},
{
toJSON: {
transform: (doc, ret) => {
// eslint-disable-next-line no-param-reassign
delete ret.private;
},
},
}
);
schema.plugin(toJSON);
const Model = connection.model('Model', schema);
const doc = new Model({ public: 'some public value', private: 'some private value' });
expect(doc.toJSON()).not.toHaveProperty('private');
expect(doc.toJSON()).toHaveProperty('public');
});
});
|
package org.firstinspires.ftc.teamcode.hardware.robots.old;
import static java.lang.Double.isInfinite;
import static java.lang.Double.isNaN;
/**
* Simple PID controller used to respond to a input accordingly. Certain custom features like Integral
* Range and Output Range were incorporated to support more intelligent drive support.
*/
public class OldPID {
/**
* This is the coefficient used to calculate the effect of the proportional of the robot.
* <p>
* Increase the P gain until the response to a disturbance is steady oscillation.
*/
private double kP;
/**
* This is the coefficient used to calculate the effect of the integral of the robot.
* <p>
* Increase the I gain until it brings you to the setpoint with the number of oscillations
* desired (normally zero but a quicker response can be had if you don't mind a couple
* oscillations of overshoot)
*/
private double kI;
/**
* This is the coefficient used to calculate the effect of the derivative of the robot.
* <p>
* Increase the D gain until the the oscillations go away (i.e. it's critically damped).
*/
private double kD;
private double proportional, integral, derivative;
/**
* Information required to calculate each PID Loop
*/
private double previousError;
private double setPoint, delay, integralRange, outputRange;
/**
* How often will the new PID value be calculated.
*/
private double dt, cycleTime;
public OldPID(double kP, double kI, double kD, double delay, double integralRange, double outputRange) {
this.kP = kP;
this.kI = kI;
this.kD = kD;
this.delay = delay;
this.integralRange = integralRange;
this.outputRange = Math.abs(outputRange);
reset();
}
/**
* Update the target value of the PID loop so that the algorithm can respond in a new way
* the new target value will be used in the queue.
*
* @param target the new value
*/
public void setTarget(double target) {
this.setPoint = target;
}
/**
* Update PID loop based off previous results. This number will be stored in a queue. As well as
* being returned to the user
*
* @param measured what is the measured value? This will give us info based off the target
* @return the error correction value from the PID loop
*/
public double update(double measured) {
//grab the error for caching or use in other calculates
double error = setPoint - measured;
//if the PID has yet to execute more than once grab a timestamp to use in the future
if (cycleTime == 0) {
this.cycleTime = System.currentTimeMillis();
previousError = error;
return 0;
}
//calculate error and then find proprtional through adjusting
proportional = kP * error;
//check if integral is in range otherwise zero it out
if ((integralRange == 0 || Math.abs(error) < integralRange)) integral += kI * error * dt;
else integral = 0;
double previousPosition = (previousError < 0 ? -1 : previousError > 0 ? 1 : 0), currentPosition = (error < 0 ? -1 : error > 0 ? 1 : 0);
if (previousPosition != currentPosition) {
integral = 0;
}
//calculate derivative and then increase it by its kD
derivative = kD * (error - previousError) / dt;
//sanity check to prevent errors in the derivative
derivative = (isNaN(derivative) || isInfinite(derivative) ? 0 : derivative);
//save previous error for next integral
previousError = error;
//ensure that the PID is only calculating at certain intervals otherwise halt till next time
if (this.delay > 0)
pause((long) (this.delay - (System.currentTimeMillis() - this.cycleTime)));
dt = System.currentTimeMillis() - this.cycleTime;
cycleTime = System.currentTimeMillis();
//calculate the PID result
double result = proportional + integral + derivative;
//limit the PID result if range is present
if (outputRange != 0) result = Math.max(-outputRange, Math.min(outputRange, result));
return result;
}
/**
* Reset the PID loop. Clearing all previous results
*/
public void reset() {
this.previousError = 0;
this.integral = 0;
this.dt = 0;
this.cycleTime = 0;
this.proportional = 0;
}
private void pause(long period) {
if (period <= 0) return;
long end = System.currentTimeMillis() + period;
do {
try {
Thread.sleep(period);
} catch (InterruptedException e) {
//ignore
}
period = end - System.currentTimeMillis();
} while (period > 0);
}
public double getKP() {
return this.kP;
}
public void setKP(double kP) {
this.kP = kP;
}
public double getKI() {
return this.kI;
}
public void setKI(double kI) {
this.kI = kI;
}
public double getKD() {
return this.kD;
}
public void setKD(double kD) {
this.kD = kD;
}
public double getProportional() {
return this.proportional;
}
public double getIntegral() {
return this.integral;
}
public double getDerivative() {
return this.derivative;
}
public double getSetPoint() {
return this.setPoint;
}
public void setSetPoint(double setPoint) {
this.setPoint = setPoint;
}
public double getDelay() {
return this.delay;
}
public void setDelay(double delay) {
this.delay = delay;
}
public double getIntegralRange() {
return this.integralRange;
}
public void setIntegralRange(double integralRange) {
this.integralRange = integralRange;
}
public double getOutputRange() {
return this.outputRange;
}
public void setOutputRange(double outputRange) {
this.outputRange = outputRange;
}
} |
# Copyright 2022 The Google Research 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.
#!/bin/bash
set -e
set -x
virtualenv -p python3 .
source ./bin/activate
pip install tensorflow
pip install -r keypose/requirements.txt
python -m keypose.run_test_load
|
<reponame>talkback-foss-team/talkback-foss
/*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.google.android.accessibility.talkback.eventprocessor;
import static com.google.android.accessibility.talkback.Feedback.CURSOR_STATE;
import static com.google.android.accessibility.utils.Performance.EVENT_ID_UNTRACKED;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import androidx.core.view.accessibility.AccessibilityEventCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import androidx.core.view.accessibility.AccessibilityRecordCompat;
import androidx.core.view.accessibility.AccessibilityWindowInfoCompat;
import android.text.TextUtils;
import android.view.accessibility.AccessibilityEvent;
import com.google.android.accessibility.compositor.GlobalVariables;
import com.google.android.accessibility.talkback.Feedback;
import com.google.android.accessibility.talkback.NodeBlockingOverlay;
import com.google.android.accessibility.talkback.NodeBlockingOverlay.OnDoubleTapListener;
import com.google.android.accessibility.talkback.Pipeline;
import com.google.android.accessibility.talkback.R;
import com.google.android.accessibility.talkback.TalkBackService;
import com.google.android.accessibility.utils.AccessibilityEventListener;
import com.google.android.accessibility.utils.AccessibilityNodeInfoUtils;
import com.google.android.accessibility.utils.Performance.EventId;
import com.google.android.accessibility.utils.Role;
import com.google.android.accessibility.utils.output.FeedbackItem;
import com.google.android.accessibility.utils.output.SpeechController;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Works around an issue with explore-by-touch where the cursor position snaps to the middle of the
* edit field when the field is focused or double-tapped. The workaround has two parts: (1) Reset
* the cursor position to the end when it is moved during a focus event. (2) Prevent double-taps on
* an editing edit field by using a touchable accessibility overlay. Since explore-by-touch
* double-taps dispatch a click to the center of the accessibility- focused node, an overlay that
* sits atop an edit field can catch the touch events that are dispatched when the edit field is
* double-tapped.
*/
public class ProcessorCursorState implements AccessibilityEventListener, OnDoubleTapListener {
private static String TAG = "ProcessorCursorState";
/**
* Delay (in ms) after which to provide cursor position feedback. We want a value that is not too
* long, but it is OK if the delay is slightly noticeable. Mostly, we just want to avoid
* preempting more important feedback.
*/
protected static final int SPEECH_DELAY = 150;
/** Event types that are handled by ProcessorCursorState. */
private static final int MASK_EVENTS_HANDLED_BY_PROCESSOR_CURSOR_STATE =
AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
| AccessibilityEvent.TYPE_VIEW_FOCUSED
| AccessibilityEvent.TYPE_VIEW_SCROLLED
| AccessibilityEvent.TYPE_TOUCH_INTERACTION_START
| AccessibilityEvent.TYPE_TOUCH_INTERACTION_END;
private final Context context;
private final Pipeline.FeedbackReturner pipeline;
private final NodeBlockingOverlay overlay;
private final GlobalVariables globalVariables;
@Nullable private AccessibilityNodeInfoCompat focusedNode = null;
private boolean registered = false;
public ProcessorCursorState(
TalkBackService service,
Pipeline.FeedbackReturner pipeline,
GlobalVariables globalVariables) {
context = service;
this.pipeline = pipeline;
overlay = new NodeBlockingOverlay(service, this);
// Set an identifier to the overlay so that we know its added by Talkback.
overlay.setRootViewClassName(Role.TALKBACK_EDIT_TEXT_OVERLAY_CLASSNAME);
this.globalVariables = globalVariables;
}
@Override
public int getEventTypes() {
return MASK_EVENTS_HANDLED_BY_PROCESSOR_CURSOR_STATE;
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event, EventId eventId) {
switch (event.getEventType()) {
case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED:
// Keep track of the accessibility focused EditText.
overlay.hide();
saveFocusedNode(AccessibilityEventCompat.asRecord(event));
break;
case AccessibilityEvent.TYPE_VIEW_SCROLLED:
// Hide the overlay so it doesn't interfere with scrolling.
overlay.hide();
break;
default: // fall out
}
}
public void onReloadPreferences(TalkBackService service) {
boolean supported = NodeBlockingOverlay.isSupported(service);
if (registered && !supported) {
service.postRemoveEventListener(this);
reset();
registered = false;
} else if (!registered && supported) {
service.addEventListener(this);
registered = true;
}
}
private void reset() {
pipeline.returnFeedback(
EVENT_ID_UNTRACKED,
Feedback.Part.builder()
.setInterruptGroup(CURSOR_STATE)
.setInterruptLevel(1)
.setSenderName(TAG));
focusedNode = null;
overlay.hide();
}
private void touchStart(AccessibilityEvent event, EventId eventId) {
// Detect if the node is visible and editing; if so, then show the overlay with a delay.
AccessibilityNodeInfoCompat refreshedNode = AccessibilityNodeInfoUtils.refreshNode(focusedNode);
if (refreshedNode != null) {
boolean focused;
AccessibilityWindowInfoCompat window = AccessibilityNodeInfoUtils.getWindow(refreshedNode);
focused =
refreshedNode.isVisibleToUser()
&& refreshedNode.isFocused()
&& window != null
&& window.isFocused();
if (focused) {
Rect r = new Rect();
refreshedNode.getBoundsInScreen(r);
overlay.showDelayed(r);
}
refreshedNode.recycle();
overlay.onAccessibilityEvent(event, eventId);
}
}
private void touchEnd(AccessibilityEvent event, EventId eventId) {
AccessibilityNodeInfoCompat refreshedNode = AccessibilityNodeInfoUtils.refreshNode(focusedNode);
if (refreshedNode != null) {
refreshedNode.recycle();
overlay.onAccessibilityEvent(event, eventId);
}
// Hide the overlay with a delay if it is visible or is pending visibility.
if (overlay.isVisibleOrShowPending()) {
overlay.hideDelayed();
}
}
@Override
public void onDoubleTap(EventId eventId) {
// Show the soft IME (if the user's using a soft IME) when double-clicking.
// This callback method is invoked when a double-tap action is detected, even if the overlay is
// not displayed on screen, in which case a11y framework will handle the action and we should
// not manually perform click action.
// Logically in this case, overlay.isVisibleOrShowPending() is equivalent to
// (focusedNode.isVisibleToUser() && focusedNode.isFocused()). The latter one is used in
// touchStart() to show overlay.
if (focusedNode != null && overlay.isVisibleOrShowPending()) {
// All of the benefits of clicking without the pain of resetting the cursor!
pipeline.returnFeedback(
eventId, Feedback.nodeAction(focusedNode, AccessibilityNodeInfoCompat.ACTION_CLICK));
pipeline.returnFeedback(
eventId,
Feedback.nodeAction(
focusedNode, // Needed for Chrome browser.
AccessibilityNodeInfoCompat.ACTION_FOCUS));
}
}
private void saveFocusedNode(AccessibilityRecordCompat record) {
if (focusedNode != null) {
focusedNode.recycle();
focusedNode = null;
}
AccessibilityNodeInfoCompat source = record.getSource();
if (source != null) {
if (Role.getRole(source) == Role.ROLE_EDIT_TEXT) {
focusedNode = source;
} else {
source.recycle();
}
}
}
private void resetNodeCursor(AccessibilityRecordCompat record, EventId eventId) {
AccessibilityNodeInfoCompat source = record.getSource();
if (source != null) {
if (source.equals(focusedNode)) {
// Reset cursor to end if there's text.
@Nullable CharSequence sourceText = AccessibilityNodeInfoUtils.getText(source);
if (!TextUtils.isEmpty(sourceText)) {
int end = sourceText.length();
Bundle bundle = new Bundle();
bundle.putInt(AccessibilityNodeInfoCompat.ACTION_ARGUMENT_SELECTION_START_INT, end);
bundle.putInt(AccessibilityNodeInfoCompat.ACTION_ARGUMENT_SELECTION_END_INT, end);
globalVariables.setFlag(GlobalVariables.EVENT_SKIP_SELECTION_CHANGED_AFTER_FOCUSED);
globalVariables.setFlag(GlobalVariables.EVENT_SKIP_SELECTION_CHANGED_AFTER_CURSOR_RESET);
pipeline.returnFeedback(
eventId,
Feedback.nodeAction(
source, AccessibilityNodeInfoCompat.ACTION_SET_SELECTION, bundle));
SpeechController.SpeakOptions speakOptions =
SpeechController.SpeakOptions.create()
.setQueueMode(SpeechController.QUEUE_MODE_QUEUE)
.setFlags(
FeedbackItem.FLAG_FORCED_FEEDBACK_AUDIO_PLAYBACK_ACTIVE
| FeedbackItem.FLAG_FORCED_FEEDBACK_MICROPHONE_ACTIVE
| FeedbackItem.FLAG_FORCED_FEEDBACK_SSB_ACTIVE);
Feedback.Part.Builder part =
Feedback.Part.builder()
.speech(context.getString(R.string.notification_type_end_of_field), speakOptions)
.setDelayMs(SPEECH_DELAY)
.setInterruptGroup(CURSOR_STATE)
.setInterruptLevel(1)
.setSenderName(TAG);
// Not tracking performance because field feedback should already be
// provided when field is focused.
pipeline.returnFeedback(EVENT_ID_UNTRACKED, part);
}
}
source.recycle();
}
}
}
|
<gh_stars>0
import express, {RequestHandler} from "express"
import path from "path"
import cookieParser from "cookie-parser"
import * as fs from "fs";
import {v4 as uuid} from "uuid"
const port = 3000
const SiteA =`
<form action="http://localhost:3000/toBRedirect">
<input type="submit" value="Redirect To B"/>
</form>
<form action="/">
<input type="submit" value="Refresh">
</form>
<form action="http://192.168.1.31:3000/DirectB">
<input type="submit" value="Direct to B"/>
</form>
`
const SiteB=`
<form action="http://localhost:3000/toARedirect">
<input type="submit" value="Redirect to A"/>
</form>
<form action="/B">
<input type="submit" value="Refresh">
</form>
<form action="http://192.168.10.8:3000/DirectA">
<input type="submit" value="Direct to A"/>
</form>
`
const server = express()
// const staticPath = path.join(__dirname, "./dist")
// server.use(express.static(staticPath,{
// cacheControl: false
// }))
// server.get("/", (req, res) => {
// // res.write("OK")
// const indexFile = fs.readFileSync("./dist/index.html")
// res.write(indexFile)
// })
server.use(cookieParser())
/**
\* Cross-Origin Resource Sharingを有効にする記述(HTTPレスポンスヘッダの追加)
\*/
server.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Max-Age', '86400');
next();
});
/**
\* OPTIONSメソッドの実装
\*/
server.options('*', function (req, res) {
res.sendStatus(200);
})
const sessionHandler: RequestHandler = (req, res, next) => {
console.log('Cookies: ', req.cookies)
next()
}
server.use(sessionHandler)
server.get("/", (req, res) => {
// res.write("OK")
res.cookie('ByRoot', new Date().getMilliseconds(), {path: "/", httpOnly: true, secure: false})
res.cookie('byRootNotHttpOnly', new Date().getMilliseconds(), {path: "/", httpOnly: false, secure: false})
res.send(SiteA)
})
server.get("/toBRedirect", (req, res) => {
res.writeHead(302, {
'Location': 'http://192.168.1.31:3000/DirectB'
})
res.end()
})
const authsUUID: Array<string> = []
server.get("/B", (req, res) => {
if (authsUUID.includes(req.cookies.sessionId)) {
console.log(`auth ok`)
// auth OK
res.writeHead(302, {
'Location': `http://192.168.10.8:3000/?sessionId=${req.cookies.sessionId}`
})
res.end()
return
}
console.log(`auth ng`)
console.log(`auth session`)
console.log(`request session ${req.cookies.sessionId}`)
authsUUID.forEach(e => console.log(e))
res.cookie('byB', new Date().getMilliseconds(), {path: "/B", httpOnly: true, secure: false})
res.cookie('byBNotHttpOnly', new Date().getMilliseconds(), {path: "/B", httpOnly: false, secure: false})
const sessionId = uuid()
authsUUID.push(sessionId)
// res.cookie('sessionId', sessionId, {secure:true, httpOnly:true, sameSite: "lax"})
res.cookie('sessionId', sessionId, {secure: false, httpOnly: true})
res.cookie('sessionIdLax', sessionId, {sameSite: "lax"})
res.cookie('sessionIdStrict', sessionId, {sameSite: "strict"})
res.send(SiteB)
})
server.get("/toARedirect", (req, res) => {
res.writeHead(302, {
'Location': 'http://192.168.10.8:3000/'
})
res.end()
})
server.get("/DirectA",(req,res)=>{
res.send(SiteA)
})
server.get("/DirectB",(req,res)=>{
res.send(SiteB)
})
server.listen(port)
console.log(`http://localhost:${port}`)
console.log(`http://localhost:${port}/a`)
|
const Trigger = require('../models/trigger');
const trigger = async (message) => {
const data = await Trigger.find({});
let msg = message.content.toLowerCase();
let result = data.find(text => msg.includes(text.trigger))
if(typeof result !== 'undefined'){
if(Math.floor(Math.random() * 10) !== 6) return;
let responses = result.responses
message.reply(responses[Math.round(Math.random() * (responses.length - 1))])
}
}
module.exports = trigger; |
#!/bin/sh
set -e
cd "${0%/*}" || return
echo "Destroy everything? (Y/N)"
read CHOICE
if [ "$CHOICE" = "Y" ]; then
echo "----------------------------------------"
echo "Starting destroy application ..."
cd ../terraform || return
terraform destroy -auto-approve
echo "Starting destroy application ..."
cd ../bucket-remote-state || return
terraform destroy -auto-approve
echo "----------------------------------------"
else
echo "finishing ..."
exit 1
fi
|
/**
* Options providers for security components.
*/
package io.opensphere.core.security.options;
|
import 'chai/register-should';
import WooCurrencies from '../../lib/wc/WooCurrencies';
describe('WooCurrencies', () => {
const currencies = [
{
name: 'US Dollar',
code: 'usd',
symbol: '$',
},
{
name: 'US Dollar 2',
code: 'usd2',
symbol: 'US$',
},
];
describe('constructor', () => {
const result = new WooCurrencies(currencies);
it('should return an object with getSymbol()', () => {
result.should.be.an('object');
result.getSymbol.should.be.a('function');
});
it('should return "$" for "usd"', () => {
result.should.be.an('object');
result.getSymbol('usd').should.equal('$');
});
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.