text
stringlengths 27
775k
|
|---|
/*
* Copyright (c) 2017-2019 TIBCO Software Inc. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package io.snappydata.cluster
import java.net.URL
import java.util
import scala.collection.mutable
import scala.util.control.NonFatal
import com.gemstone.gemfire.CancelException
import com.gemstone.gemfire.distributed.internal.MembershipListener
import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl
import com.pivotal.gemfirexd.internal.engine.Misc
import com.pivotal.gemfirexd.internal.engine.distributed.utils.GemFireXDUtils
import com.pivotal.gemfirexd.internal.engine.store.ServerGroupUtils
import io.snappydata.gemxd.ClusterCallbacksImpl
import org.apache.spark.deploy.SparkHadoopUtil
import org.apache.spark.executor.SnappyCoarseGrainedExecutorBackend
import org.apache.spark.memory.SnappyUnifiedMemoryManager
import org.apache.spark.sql.SnappyContext
import org.apache.spark.sql.collection.Utils
import org.apache.spark.util.LocalDirectoryCleanupUtil
import org.apache.spark.{Logging, SparkCallbacks, SparkEnv}
/**
* This class is responsible for initiating the executor process inside
* the jvm. Also, if an executor has to be stopped, driverURL can be set as None
* and it will take care of stopping the executor.
*/
object ExecutorInitiator extends Logging {
val SNAPPY_MEMORY_MANAGER: String = classOf[SnappyUnifiedMemoryManager].getName
private var executorRunnable: ExecutorRunnable = new ExecutorRunnable
var executorThread: Thread = new Thread(executorRunnable)
@volatile var snappyExecBackend: SnappyCoarseGrainedExecutorBackend = _
class ExecutorRunnable() extends Runnable {
private var driverURL: Option[String] = None
private var driverDM: InternalDistributedMember = _
@volatile private[cluster] var stopTask = false
@volatile private[cluster] var stopped = true
private[cluster] var retryTask: Boolean = false
private[cluster] val lock = new Object()
private[cluster] val testLock = new Object()
@volatile private[cluster] var testStartDone = false
val membershipListener: MembershipListener = new MembershipListener {
override def quorumLost(failures: util.Set[InternalDistributedMember],
remaining: util.List[InternalDistributedMember]): Unit = {}
override def memberJoined(id: InternalDistributedMember): Unit = {}
override def memberSuspect(id: InternalDistributedMember,
whoSuspected: InternalDistributedMember): Unit = {}
override def memberDeparted(id: InternalDistributedMember, crashed: Boolean): Unit = {
executorRunnable.memberDeparted(id)
}
}
def memberDeparted(departedDM: InternalDistributedMember): Unit = lock.synchronized {
if (departedDM.equals(driverDM)) {
setDriverDetails(None, null)
}
}
def setRetryFlag(retry: Boolean = true): Unit = lock.synchronized {
retryTask = retry
lock.notifyAll()
}
def getRetryFlag: Boolean = lock.synchronized {
retryTask
}
def getDriverURL: Option[String] = lock.synchronized {
driverURL
}
def setDriverDetails(url: Option[String],
dm: InternalDistributedMember): Unit = lock.synchronized {
driverURL = url
driverDM = dm
SnappyContext.clearStaticArtifacts()
lock.notifyAll()
}
override def run(): Unit = {
LocalDirectoryCleanupUtil.clean()
stopped = false
var prevDriverURL = ""
var env: SparkEnv = null
var numTries = 0
try {
GemFireXDUtils.getGfxdAdvisor.getDistributionManager
.addMembershipListener(membershipListener)
while (!stopTask) {
try {
Misc.checkIfCacheClosing(null)
if (prevDriverURL == getDriverURLString && !getRetryFlag) {
lock.synchronized {
while (!stopTask && prevDriverURL == getDriverURLString && !getRetryFlag) {
lock.wait(1000)
}
}
} else {
if (getRetryFlag) {
if (numTries >= 50) {
logError("Exhausted number of retries to connect to the driver. Exiting.")
return
}
// if it's a retry, wait for sometime before we retry.
// This is a measure to ensure that some unforeseen circumstance
// does not lead to continous retries and the thread hogs the CPU.
numTries += 1
Thread.sleep(3000)
}
// kill if an executor is already running.
SparkCallbacks.stopExecutor(env)
env = null
getDriverURL match {
case Some(url) =>
/**
* The executor initialization code has been picked from
* CoarseGrainedExecutorBackend.
* We need to track the changes there and merge them here on a regular basis.
*/
val myId = GemFireCacheImpl.getExisting.getMyId
val executorHost = myId.getHost
val memberId = myId.canonicalString()
SparkHadoopUtil.get.runAsSparkUser { () =>
// Fetch the driver's Spark properties.
val executorConf = Utils.newClusterSparkConf()
Utils.setDefaultSerializerAndCodec(executorConf)
val port = executorConf.getInt("spark.executor.port", 0)
val (ioEncryptionKey, props) =
SparkCallbacks.fetchDriverProperty(memberId, executorHost,
executorConf, port, url)
val driverConf = Utils.newClusterSparkConf()
Utils.setDefaultSerializerAndCodec(driverConf)
for ((key, value) <- props) {
// this is required for SSL in standalone mode
if (SparkCallbacks.isExecutorStartupConf(key)) {
driverConf.setIfMissing(key, value)
} else {
driverConf.set(key, value)
}
}
// TODO: Hemant: add executor specific properties from local
// TODO: conf to this conf that was received from driver.
// If memory manager is not set, use Snappy unified memory manager
driverConf.setIfMissing("spark.memory.manager",
SNAPPY_MEMORY_MANAGER)
val cores = driverConf.getInt("spark.executor.cores",
Runtime.getRuntime.availableProcessors() * 2)
env = SparkCallbacks.createExecutorEnv(driverConf,
memberId, executorHost, port, cores, ioEncryptionKey, isLocal = false)
LocalDirectoryCleanupUtil.save()
// This is not required with snappy
val userClassPath = new mutable.ListBuffer[URL]()
val rpcenv = SparkCallbacks.getRpcEnv(env)
val executor = new SnappyCoarseGrainedExecutorBackend(
rpcenv, url, memberId, executorHost,
cores, userClassPath, env)
snappyExecBackend = executor
rpcenv.setupEndpoint("Executor", executor)
}
prevDriverURL = url
testStartDone = true
testLock.synchronized(testLock.notifyAll())
case None =>
// If driver url is none, already running executor is stopped.
prevDriverURL = ""
}
setRetryFlag(false)
}
} catch {
case e@(NonFatal(_) | _: InterruptedException) =>
try {
Misc.checkIfCacheClosing(e)
// log any exception other than those due to cache closing
logWarning("Unexpected exception in ExecutorInitiator", e)
} catch {
case NonFatal(_) => stopTask = true // just stop the task
}
}
} // end of while(true)
} catch {
case e: Throwable =>
logWarning("ExecutorInitiator failing with exception: ", e)
} finally {
testStartDone = false
// kill if an executor is already running.
SparkCallbacks.stopExecutor(env)
lock.synchronized {
stopped = true
lock.notifyAll()
}
try {
Misc.checkIfCacheClosing(null)
GemFireXDUtils.getGfxdAdvisor.getDistributionManager
.removeMembershipListener(membershipListener)
} catch {
case _: CancelException => // do nothing
}
}
}
def getDriverURLString: String = getDriverURL match {
case Some(x) => x
case None => ""
}
}
/**
* This should be called only when the process is terminating.
* If a process ceases to be an executor, only startOrTransmuteExecutor should be called
* with None.
*/
def stop(): Unit = {
executorRunnable.stopTask = true
executorRunnable.setDriverDetails(None, null)
Utils.clearDefaultSerializerAndCodec()
val lock = executorRunnable.lock
lock.synchronized {
lock.notifyAll()
var maxTries = 50
while (maxTries > 0 && !executorRunnable.stopped) {
maxTries -= 1
lock.wait(1000)
}
}
}
def restartExecutor(): Unit = {
executorRunnable.setRetryFlag()
}
// Test hook. Not to be used in other situations
def testWaitForExecutor(): Unit = {
var maxTries = 100
while (maxTries > 0) {
val runnable = executorRunnable
if (!runnable.testStartDone) {
maxTries -= 1
runnable.testLock.synchronized {
runnable.wait(500)
}
} else {
// break the loop
maxTries = 0
}
}
}
/**
* Set the new driver url and start the thread if not already started
*/
def startOrTransmuteExecutor(driverURL: Option[String],
driverDM: InternalDistributedMember): Unit = {
// Avoid creation of executor inside the Gem accessor
// that is a Spark driver but has joined the gem system
// in the non embedded mode
if (SparkCallbacks.isDriver) {
logInfo("Executor cannot be instantiated in this " +
"VM as a Spark driver is already running. ")
return
}
if (ServerGroupUtils.isGroupMember(ClusterCallbacksImpl.getLeaderGroup())) {
logInfo("Executor cannot be instantiated in a lead vm.")
return
}
executorRunnable.setDriverDetails(driverURL, driverDM)
// start the executor thread if driver URL is set and the thread
// is not already started.
driverURL match {
case Some(_) =>
if (executorThread.getState == Thread.State.NEW) {
logInfo("About to start thread " + executorThread.getName)
executorThread.setDaemon(true)
executorThread.start()
} else if (executorThread.getState == Thread.State.TERMINATED) {
// Restart a thread after it has been stopped
// This is required for dunit case mainly.
executorRunnable = new ExecutorRunnable
executorThread = new Thread(executorRunnable)
logInfo("Spawning new thread " + executorThread.getName + " and starting")
executorRunnable.setDriverDetails(driverURL, driverDM)
executorThread.setDaemon(true)
executorThread.start()
}
case None =>
}
}
}
|
<?php
function checkNonchangeAbleIdentifier($identifier){
$noChangeIdentifier = ['podcast', 'video', 'openwriting', 'openreading'];
if(in_array($identifier, $noChangeIdentifier)){
return true;
}else {
return false;
}
}
?>
|
{% extends '//mix/template/c_std.sh' %}
{% block fetch %}
https://ftp.mozilla.org/pub/security/nss/releases/NSS_3_66_RTM/src/nss-3.66-with-nspr-4.30.tar.gz
4addeabd4aedc1d589cc836577938da6
{% endblock %}
{% block lib_deps %}
lib/c
lib/z
lib/c++
{% endblock %}
{% block bld_tool %}
bld/bash
bin/gyp
bin/make
bin/ninja
{% endblock %}
{% block setup_tools %}
ln -s $(which python2) python
{% endblock %}
{% block build %}
bash nss/build.sh -v --gyp --disable-tests --static
{% endblock %}
|
# Product-Management
A mini project on Product Management using php.
[![Release][release-shield]][release-url]
[![Forks][forks-shield]][forks-url]
[![Downloads][downloads-shield]][downloads-url]
[![Stargazers][stars-shield]][stars-url]
[![MIT License][license-shield]][license-url]
## Features
* Homepage
* Registtration
* Login
* Dashboard
* Product table with Actions
* Add Product
* Update Product
* Delete Product
* User Profile
* View Profile
* Edit Profile
* Change Profile Picture
* Change Password
## Built With
* [Bootstrap](https://getbootstrap.com)
* [php](https://www.php.net/)
* [html](https://html.com/)
* [css](https://www.w3.org/Style/CSS/Overview.en.html)
## Version
Stable version release [v1.0.0](https://github.com/sahaavi/Product-Management/releases)
## License
Distributed under the MIT License. See `LICENSE` for more information.
<!-- MARKDOWN LINKS & IMAGES -->
[release-shield]: https://img.shields.io/github/v/release/sahaavi/Product-Management.svg?style=flat-square
[release-url]: https://github.com/sahaavi/Product-Management/releases
[forks-shield]: https://img.shields.io/github/forks/sahaavi/Product-Management.svg?style=flat-square
[forks-url]: https://github.com/sahaavi/Product-Management/network/members
[downloads-shield]: https://img.shields.io/github/downloads/sahaavi/Product-Management/total.svg?style=flat-square
[downloads-url]: https://github.com/sahaavi/Product-Management
[stars-shield]: https://img.shields.io/github/stars/sahaavi/Product-Management.svg?style=flat-square
[stars-url]: https://github.com/sahaavi/Product-Management/stargazers
[license-shield]: https://img.shields.io/github/license/sahaavi/Product-Management.svg?style=flat-square
[license-url]: https://github.com/sahaavi/Product-Management/blob/master/LICENSE
|
# Contribution Guidelines
## Creating issues
Feature requests and bug reports should be made by using the [issue tracker](https://github.com/cachethq/Docker/issues). This "Dockerized" version of Cachet is maintained by members the Cachet community, so support issues will be address on a best effort basis.
**Always be respectful.** Organization members reserve the right to lock topics if they feel necessary.
## Branch and Tag Structure
* `master`: Cachet with the upstream Cachet `master` codebase.
* Minor version branches
* Tags are used to denote a Cachet release, and correspond to Docker Hub automatic builds.
# Releasing a new Cachet Docker image version
The below example shows creating a `v2.3.1` release.
```
git checkout 2.3
git checkout -b rel-2.3.1
Set `ENV cachetversion v2.3.1` in Dockerfile
git commit -am "Cachet v2.3.1 release"
git tag -a v2.3.1 -m "Cachet Release v2.3.1"
git push origin v2.3.1
```
Then to finish the process:
* Add [Release on GitHub](https://github.com/CachetHQ/Docker/releases)
* Add automated build for the new tag on [Docker Hub](https://hub.docker.com/r/cachethq/docker/builds/)
Periodically back-port changes from most recent minor version branch to `master`.
## Multiple releases
Sometimes we get a little behind the upstream Cachet project, and need to make a few releases at once.
```
gsed s/v2.3.7/v2.3.8/g -i Dockerfile
git commit -am "Cachet v2.3.8 release"
git tag -a v2.3.8 -m "Cachet Release v2.3.8"
git push origin v2.3.8
gsed s/v2.3.8/v2.3.9/g -i Dockerfile
git commit -am "Cachet v2.3.9 release"
git tag -a v2.3.9 -m "Cachet Release v2.3.9"
git push origin v2.3.9
gsed s/v2.3.9/v2.3.10/g -i Dockerfile
git commit -am "Cachet v2.3.10 release"
git tag -a v2.3.10 -m "Cachet Release v2.3.10"
git push origin v2.3.10
```
Then setup releases on GitHub.
|
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, cast
import httpx
import networkx
from intents.utils import OnosRoute
from intent_deployer import config
from intent_deployer.hosts import Hosts
from intent_deployer.links import Links
from intent_deployer.switches import Switches
@dataclass
class IntentPath:
src: str
dst: str
switch_path: list[str]
@property
def path(self):
return [self.src, *self.switch_path, self.dst]
def as_tuple(self) -> tuple[tuple[str, str], IntentPath]:
return ((self.src, self.dst), self)
@classmethod
def parse(cls, data: dict[str, Any]) -> IntentPath:
src, *switch_path, dst = cast(list[str], data["path"])
src = Hosts.name_from_mac(src.removesuffix("/None"))
dst = Hosts.name_from_mac(dst.removesuffix("/None"))
switch_path = [Switches.name_from_id(s) for s in switch_path]
return cls(src, dst, switch_path)
def as_onos_route(self, hosts: Hosts, switches: Switches) -> OnosRoute:
src, dst = hosts.get_host_id(self.src), hosts.get_host_id(self.dst)
switch_path = cast(
list[str], [switches.get_switch_id(s) for s in self.switch_path]
)
return OnosRoute(key=f"{src}{dst}", route=[src, *switch_path, dst])
@dataclass
class Intent:
"""A point-to-point intent or whatever"""
paths: list[IntentPath]
@classmethod
def parse(cls, data: dict[str, Any]) -> Intent:
paths = [IntentPath.parse(x) for x in data["paths"]]
return cls(paths)
def as_onos_intent(self, hosts: Hosts, switches: Switches) -> list[OnosRoute]:
return [p.as_onos_route(hosts, switches) for p in self.paths]
# TODO: keep track of bandwidth
@dataclass
class Topology:
network: networkx.Graph
intents: list[Intent]
@classmethod
async def from_current_state(cls) -> Topology:
links = await Links.from_api()
network = networkx.Graph(links.links)
async with httpx.AsyncClient() as client:
resp = await client.post(
str(config.ngcdi_url / "get_intents"),
json={"api_key": config.api_key},
)
resp.raise_for_status()
intents = [Intent.parse(i) for i in resp.json()["routingList"]]
return cls(network, intents)
|
package com.kode.formscreatorlib.Model;
import java.util.ArrayList;
public class RepeatBlock {
private String repeatField;
private ArrayList<String> repeatValueFrom = new ArrayList<>();
private String repeatHeader;
public String getRepeatField() {
return repeatField;
}
public ArrayList<String> getRepeatValueFrom() {
return repeatValueFrom;
}
public String getRepeatHeader() {
return repeatHeader;
}
}
|
using NPOI.HSSF.Util;
using System;
using System.Collections.Generic;
using System.Text;
namespace NPOI.OOXML.XSSF.UserModel
{
public class DefaultIndexedColorMap:IIndexedColorMap
{
public byte[] GetRGB(int index)
{
return GetDefaultRGB(index);
}
public static byte[] GetDefaultRGB(int index)
{
HSSFColor hssfColor = HSSFColor.GetIndexHash()[index];
if (hssfColor == null) return null;
byte[] rgbShort = hssfColor.GetTriplet();
return rgbShort;
}
}
}
|
#!/usr/bin/env bash
export GPC_CONSUMER_SERVER_PORT="8090"
export GPC_CONSUMER_GPC_GET_URL="https://orange.testlab.nhs.uk"
export GPC_CONSUMER_URL="http://localhost:8090"
export GPC_CONSUMER_SDS_URL="https://sandbox.api.service.nhs.uk/spine-directory/"
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
public class TrackedImage : MonoBehaviour
{
private List<ARTrackedImage> _arTrackedImages = new List<ARTrackedImage>();
private ARTrackedImageManager ARTrackedImageManager
{
get
{
if (_arTrackedImageManager == null)
{
_arTrackedImageManager = FindObjectOfType<ARTrackedImageManager>();
}
return _arTrackedImageManager;
}
}
private void TrackImage(bool value)
{
this.enabled = value;
}
[SerializeField] private ARTrackedImageManager _arTrackedImageManager;
// Start is called before the first frame update
void OnEnable()
{
if (ARTrackedImageManager)
ARTrackedImageManager.trackedImagesChanged += ARTrackedImageManager_trackedImagesChanged;
}
// Start is called before the first frame update
void OnDisable()
{
if(ARTrackedImageManager)
ARTrackedImageManager.trackedImagesChanged -= ARTrackedImageManager_trackedImagesChanged;
}
private void ARTrackedImageManager_trackedImagesChanged(ARTrackedImagesChangedEventArgs obj)
{
_arTrackedImages.Clear();
for (int i = 0; i < obj.added.Count; i++)
{
_arTrackedImages.Add(obj.added[i]);
}
for (int i = 0; i < obj.updated.Count; i++)
{
if (!_arTrackedImages.Contains(obj.updated[i]))
{
_arTrackedImages.Add(obj.updated[i]);
}
}
for (int i = 0; i < _arTrackedImages.Count; i++)
{
var image = _arTrackedImages[i];
if (image.trackingState == TrackingState.Tracking)
{
transform.position = image.transform.position;
transform.rotation = image.transform.rotation;
break;
}
}
}
}
|
//
// test_unit.h
//
// Created by Alberto Lerner, then edited by Jonathan Tompson on 4/26/12.
//
#pragma once
#include <unordered_map>
#include <iostream>
#include <string>
#include <vector>
#include "test_unit/param_map.h"
extern bool TESTS_exit_on_fatal;
extern bool TESTS_has_fatal_message;
namespace tests {
using std::string;
#ifdef _WIN32
using std::tr1::unordered_map;
#else
using std::unordered_map;
#endif
using std::vector;
class TestCase {
public:
virtual ~TestCase() {}
virtual void testBody() = 0;
virtual void clear() = 0;
const string& group() const { return group_; }
const string& name() const { return name_; }
string fullName() const { return group_ + "(" + name_ + ")"; }
int errors() const { return errors_; }
protected:
TestCase(const string& group, const string& name)
: group_(group), name_(name), errors_(0) {}
void incErrors() { ++errors_; }
private:
string group_;
string name_;
int errors_;
};
class TestRegistry {
public:
~TestRegistry() {}
static TestRegistry* getInstance();
TestCase* registerCase(TestCase* test);
int runAndResetWithArgs(int argc, const char * const * argv);
private:
typedef vector<TestCase*> Tests;
static TestRegistry* instance_;
Tests tests_; // owned by this
ParamMap args_; // --case to be run
void runListCases(int* errors);
void runSomeCases(int* errors, const string& cases);
TestRegistry();
};
TestRegistry::TestRegistry() {
args_.addParam("case", "all", "csv list of test cases to run");
args_.addParam("listcases", "false", "list the test cases for this test");
}
TestRegistry* TestRegistry::instance_ = nullptr;
TestRegistry* TestRegistry::getInstance() {
if (instance_ == nullptr) instance_ = new TestRegistry;
return instance_;
}
TestCase* TestRegistry::registerCase(TestCase* test) {
tests_.push_back(test);
return test;
}
void TestRegistry::runListCases(int* errors) {
for (Tests::const_iterator it = tests_.begin(); it != tests_.end(); ++it) {
std::cout << (*it)->fullName() << std::endl;
}
}
void TestRegistry::runSomeCases(int* errors, const string& cases) {
unordered_map<string, bool> filter;
if (cases != "all") {
string::size_type pos;
string curr = cases;
do {
pos = curr.find(",");
filter.insert(make_pair(curr.substr(0, pos), false /* executed yet? */));
curr = curr.substr(pos+1);
} while (pos != string::npos);
}
for (Tests::const_iterator itt = tests_.begin(); itt != tests_.end(); ++itt) {
TestCase* test = *itt;
// If a filter is set, check if this test should be skipped. Also
// keep track that all requested test cases execute.
unordered_map<string, bool>::iterator iti = filter.find(test->name());
if (!filter.empty()) {
if (iti == filter.end()) {
continue;
} else {
iti->second = true /* executed */;
}
}
std::cout << "Running " << test->fullName() << ": " << std::flush;
test->testBody();
if (test->errors()) {
(*errors) += test->errors();
std::cout << std::endl;
} else {
std::cout << "PASSED" << std::endl;
}
}
// Any test in --case that was not executed?
for (unordered_map<string, bool>::iterator iti = filter.begin();
iti != filter.end();
++iti) {
if (iti->second == false /* have not executed */) {
std::cout << "Wrong test case name: " << iti->first << std::endl;
(*errors)++;
}
}
}
int TestRegistry::runAndResetWithArgs(int argc, const char * const * argv) {
int errors = 0;
bool exit = false;
TESTS_exit_on_fatal = false;
if (argv != nullptr && !args_.parseArgv(argc, argv)) {
args_.printUsage();
errors += 1 /* one error, parsing */;
exit = true;
}
// Check if we just want to learn the names of the test's cases.
string list_only;
if (!exit && args_.getParam("listcases", &list_only)) {
if (list_only == "true") {
runListCases(&errors);
exit = true;
}
}
// Check if we'd like to execute only some of the tests cases, as
// indicated by the --cases parameter.
string cases;
if (!exit && args_.getParam("case", &cases)) {
runSomeCases(&errors, cases);
exit = true;
}
for (Tests::const_iterator it = tests_.begin(); it != tests_.end(); ++it) {
(*it)->clear();
}
tests_.clear();
TestRegistry* me = instance_;
instance_ = nullptr;
delete me;
return errors;
}
} // namespace base
#define EXPECT_TRUE(a) \
if (!(a)) { \
if (errors() == 0) std::cout << "FAILED"; \
std::cout << "\n Line " << __LINE__ \
<< " Expected true " << # a << ": " << (a); \
incErrors(); \
}
#define EXPECT_FALSE(a) \
if (a) { \
if (errors() == 0) std::cout << "FAILED"; \
std::cout << "\n Line " << __LINE__ \
<< " Expected false " << # a << ": " << (a); \
incErrors(); \
}
#define EXPECT_EQ(a, b) \
if ((a) != (b)) { \
if (errors() == 0) std::cout << "FAILED"; \
std::cout << "\n Line " << __LINE__ \
<< " Expected equal " << # a << " and " << # b << ": (" \
<< (a) << " " << (b) << ")"; \
incErrors(); \
}
#define EXPECT_APPROX_EQ(a, b, precision) \
if (fabsf((a) - (b)) > precision) { \
if (errors() == 0) std::cout << "FAILED"; \
std::cout << "\n Line " << __LINE__ \
<< " Expected approx equal " << # a << " and " << # b << ": (" \
<< (a) << " " << (b) << ", precision " << precision << ")"; \
incErrors(); \
}
#define EXPECT_NEQ(a, b) \
if ((a) == (b)) { \
if (errors() == 0) std::cout << "FAILED"; \
std::cout << "\n Line " << __LINE__ \
<< " Expected different " << # a << " and " << # b << ": (" \
<< (a) << " " << (b) << ")"; \
incErrors(); \
}
#define EXPECT_GT(a, b) \
if ((a) <= (b)) { \
if (errors() == 0) std::cout << "FAILED"; \
std::cout << "\n Line " << __LINE__ \
<< " Expected greater " << # a << " and " << # b << ": (" \
<< (a) << " " << (b) << ")"; \
incErrors(); \
}
#define EXPECT_GE(a, b) \
if ((a) < (b)) { \
if (errors() == 0) std::cout << "FAILED"; \
std::cout << "\n Line " << __LINE__ \
<< " Expected greater equal " << # a << " and " << # b << ": (" \
<< (a) << " " << (b) << ")"; \
incErrors(); \
}
#define EXPECT_LT(a, b) \
if ((a) >= (b)) { \
if (errors() == 0) std::cout << "FAILED"; \
std::cout << "\n Line " << __LINE__ \
<< " Expected less " << # a << " and " << # b << ": (" \
<< (a) << " " << (b) << ")"; \
incErrors(); \
}
#define EXPECT_LE(a, b) \
if ((a) > (b)) { \
if (errors() == 0) std::cout << "FAILED"; \
std::cout << "\n Line " << __LINE__ \
<< " Expected less equal " << # a << " and " << # b << ": (" \
<< (a) << " " << (b) << ")"; \
incErrors(); \
}
#define EXPECT_FATAL(a) \
MCP_BASE_has_fatal_message = false; \
(a); \
if (!MCP_BASE_has_fatal_message) { \
if (errors() == 0) std::cout << "FAILED"; \
std::cout << "\n Line " << __LINE__ << " Expected fatal " << # a; \
incErrors(); \
}
#define TEST_CLASS_NAME(test_group, test_name) \
test_group ## _ ## test_name ## _Test
#define TEST(test_group, test_name) \
class TEST_CLASS_NAME(test_group, test_name) : public tests::TestCase { \
public: \
TEST_CLASS_NAME(test_group, test_name)(); \
virtual void testBody(); \
virtual void clear(); \
private: \
static TestCase* me_; \
}; \
\
tests::TestCase* TEST_CLASS_NAME(test_group, test_name)::me_ = \
tests::TestRegistry::getInstance()->registerCase( \
new TEST_CLASS_NAME(test_group, test_name)); \
\
TEST_CLASS_NAME(test_group, test_name)::\
TEST_CLASS_NAME(test_group, test_name)() \
: TestCase(# test_group, # test_name) {} \
\
void TEST_CLASS_NAME(test_group, test_name)::clear() { \
TestCase* me = me_; \
me_ = nullptr; \
delete me; \
} \
\
void TEST_CLASS_NAME(test_group, test_name)::testBody()
#define RUN_TESTS(argc, argv) \
(tests::TestRegistry::getInstance()->runAndResetWithArgs(argc, argv))
|
package at.aau.itec.esop18.lesson03;
public class BooleanFun {
public static void main(String[] args) {
boolean p = false;
boolean q = true;
System.out.println(p && q);
}
}
|
package compose.icons.lineawesomeicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.DrumSolid: ImageVector
get() {
if (_drumSolid != null) {
return _drumSolid!!
}
_drumSolid = Builder(name = "DrumSolid", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp,
viewportWidth = 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(27.1875f, 5.0938f)
lineTo(16.125f, 10.3438f)
curveTo(15.8047f, 10.1289f, 15.4141f, 10.0f, 15.0f, 10.0f)
curveTo(13.8945f, 10.0f, 13.0f, 10.8945f, 13.0f, 12.0f)
curveTo(13.0f, 13.1055f, 13.8945f, 14.0f, 15.0f, 14.0f)
curveTo(16.0508f, 14.0f, 16.9219f, 13.1875f, 17.0f, 12.1563f)
lineTo(23.0625f, 9.2813f)
curveTo(24.8789f, 10.0469f, 26.0f, 11.0469f, 26.0f, 12.0f)
curveTo(26.0f, 13.8867f, 21.7227f, 16.0f, 16.0f, 16.0f)
curveTo(10.2773f, 16.0f, 6.0f, 13.8867f, 6.0f, 12.0f)
curveTo(6.0f, 10.1133f, 10.2773f, 8.0f, 16.0f, 8.0f)
curveTo(16.1719f, 8.0f, 16.3281f, 7.9961f, 16.5f, 8.0f)
lineTo(20.0313f, 6.3438f)
curveTo(18.7773f, 6.1328f, 17.4336f, 6.0f, 16.0f, 6.0f)
curveTo(9.1602f, 6.0f, 4.0f, 8.5781f, 4.0f, 12.0f)
lineTo(4.0f, 22.0f)
curveTo(4.0f, 22.9883f, 4.4453f, 23.8945f, 5.125f, 24.625f)
curveTo(5.8047f, 25.3555f, 6.7305f, 25.9453f, 7.8125f, 26.4375f)
curveTo(9.9766f, 27.4219f, 12.8398f, 28.0f, 16.0f, 28.0f)
curveTo(19.1602f, 28.0f, 22.0234f, 27.4219f, 24.1875f, 26.4375f)
curveTo(25.2695f, 25.9453f, 26.1953f, 25.3555f, 26.875f, 24.625f)
curveTo(27.5547f, 23.8945f, 28.0f, 22.9883f, 28.0f, 22.0f)
lineTo(28.0f, 12.0f)
curveTo(28.0f, 10.5234f, 27.0234f, 9.2109f, 25.375f, 8.1875f)
lineTo(28.0313f, 6.9063f)
close()
moveTo(6.0f, 15.4063f)
curveTo(7.0156f, 16.1719f, 8.3789f, 16.8008f, 10.0f, 17.25f)
lineTo(10.0f, 25.1563f)
curveTo(9.5f, 25.0f, 9.043f, 24.8164f, 8.625f, 24.625f)
curveTo(7.7188f, 24.2109f, 7.0273f, 23.7148f, 6.5938f, 23.25f)
curveTo(6.1602f, 22.7852f, 6.0f, 22.3945f, 6.0f, 22.0f)
close()
moveTo(26.0f, 15.4063f)
lineTo(26.0f, 22.0f)
curveTo(26.0f, 22.3945f, 25.8398f, 22.7852f, 25.4063f, 23.25f)
curveTo(24.9727f, 23.7148f, 24.2813f, 24.2109f, 23.375f, 24.625f)
curveTo(22.957f, 24.8164f, 22.5f, 25.0f, 22.0f, 25.1563f)
lineTo(22.0f, 17.25f)
curveTo(23.6211f, 16.8008f, 24.9844f, 16.1719f, 26.0f, 15.4063f)
close()
moveTo(12.0f, 17.6875f)
curveTo(13.2422f, 17.8945f, 14.582f, 18.0f, 16.0f, 18.0f)
curveTo(17.418f, 18.0f, 18.7578f, 17.8945f, 20.0f, 17.6875f)
lineTo(20.0f, 25.625f)
curveTo(18.7695f, 25.8555f, 17.4219f, 26.0f, 16.0f, 26.0f)
curveTo(14.5781f, 26.0f, 13.2305f, 25.8555f, 12.0f, 25.625f)
close()
}
}
.build()
return _drumSolid!!
}
private var _drumSolid: ImageVector? = null
|
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Mail;
use App\Mail\Forms;
use App\Mail\Welcome;
use Validator;
class ApiController extends Controller
{
public function ts(Request $req)
{
return response()->json(number_format($req->ts));
}
public function users()
{
$data = [
'user_name' => 'user_name',
'msg' => 'test'
];
$mail = Mail::to('aizazkalwar46@gmail.com')
->cc('francisgill1000@gmail.com')
->send(new Forms($data));
//dd($mail);
return empty($mail) ? 'mail sent' : 'mail not sent';
}
public function save_customer_info(Request $req)
{
$cnic_attachment = null;
if($req->hasFile('cnic_attachment')){
$cnic_attachment = $req->cnic_attachment->getClientOriginalName();
$req->cnic_attachment->move(public_path('uploads/cnic_attachment/'),$cnic_attachment);
}
$soi_attachment = null;
if($req->hasFile('soi_attachment')){
$soi_attachment = $req->soi_attachment->getClientOriginalName();
$req->soi_attachment->move(public_path('uploads/soi_attachment/'),$soi_attachment);
}
$zakat_certificate = 'no_image.png';
if($req->hasFile('zakat_certificate')){
$zakat_certificate = $req->zakat_certificate->getClientOriginalName();
$req->zakat_certificate->move(public_path('uploads/zakat_certificates/'),$zakat_certificate);
}
$arr = [
"qq" => $req->qq,
"name" => $req->name,
"father_name" => $req->father_name,
"mother_name" => $req->mother_name,
"dob" => $req->dob,
"cnic" => $req->cnic,
"cnic_attachment" => $cnic_attachment,
"cnic_issue_date" => $req->cnic_issue_date,
"pob_country" => $req->pob_country,
"pob_city" => $req->pob_city,
"email" => $req->email,
"cell" => $req->cell,
"occupation" => $req->occupation,
"occ_name" => $req->occ_name,
"soi" => $req->soi,
"soi_attachment" => $soi_attachment,
"address" => $req->address,
"country1" => $req->country1,
"city1" => $req->city1,
"zakat" => $req->zakat,
"zakat_options" => $req->zakat_options,
"zakat_certificate" => $zakat_certificate,
"designation" => $req->designation,
"department" => $req->department,
"org_emp_bes_name" => $req->org_emp_bes_name,
"working_experience" => $req->working_experience,
"age_of_business" => $req->age_of_business,
"education" => $req->education,
"marital_status" => $req->marital_status,
"no_of_dependants" => $req->no_of_dependants,
"public_figure" => $req->public_figure,
"average_annual_income" => $req->average_annual_income,
"refused_account_by_institute" => $req->refused_account_by_institute,
"high_value_item" => $req->high_value_item,
"created_at" => now(),
"updated_at" => now(),
];
$inserted = DB::table('customers')->insertGetId($arr);
$mail_data = [
'customer_name' => $req->name,
'cnic' => $req->cnic,
"qq" => $req->qq,
"email" => $req->email
];
$mail = new Welcome($mail_data);
Mail::to($req->email)->send($mail);
return response()->json($inserted);
}
public function save_bank_details(Request $req){
$arr = [
"bank_name" => $req->bankname1,
"branch_name" => $req->branch_name,
"account_title" => $req->account_title,
"iban_number" => $req->iban_number,
"customer_id" => $req->customer_id,
"created_at" => now(),
"updated_at" => now(),
];
$inserted = DB::table('bank_details')->insert($arr);
return response()->json(200);
}
public function save_investment_details(Request $req){
$attachment = 'no_iamge.png';
if($req->hasFile('attachment')){
$attachment = $req->attachment->getClientOriginalName();
$req->attachment->move(public_path('uploads/investment_detail_attachments/'),$attachment);
}
$arr = [
"fund_name" => $req->fund_name,
"amount" => $req->amount,
"amount_in_words" => $req->amount_in_words,
"front_end_load" => $req->front_end_load,
"payment_mode" => $req->payment_mode,
"attachment" => $attachment,
"bank_name" => $req->bank_name,
"instrument_number" => $req->instrument_number,
"customer_id" => $req->customer_id,
"created_at" => now(),
"updated_at" => now(),
];
$inserted = DB::table('investment_details')->insert($arr);
return response()->json(200);
}
public function save_other_details(Request $req){
$arr = [
"asf" => $req->asf,
"dpo" => $req->dpo,
"type_of_units" => $req->type_of_units,
"customer_id" => $req->customer_id,
"created_at" => now(),
"updated_at" => now(),
];
$inserted = DB::table('other_details')->insert($arr);
return response()->json(200);
}
public function save_fatca_details(Request $req){
$wf_name = 'no_image.png';
if($req->hasFile('wform')){
$wf_name = $req->wform->getClientOriginalName();
$req->wform->move(public_path('uploads/wforms/'),$wf_name);
}
$arr = [
"multiple_nat" => $req->multiple_nat,
"nats" => $req->nats,
"green_card" => $req->green_card,
"tax_resi" => $req->tax_resi,
"for_citi" => $req->for_citi,
"co_ma" => $req->co_ma,
"co_mp" => $req->co_mp,
"attor" => $req->attor,
"attor_addr" => $req->attor_addr,
"trans_fund" => $req->trans_fund,
"wf" => $req->wf,
"wform" => $wf_name,
"wform_options" => $req->wform_options,
"customer_id" => $req->customer_id,
"created_at" => now(),
"updated_at" => now(),
];
$inserted = DB::table('fatca_details')->insert($arr);
return response()->json(200);
}
public function generate_form(Request $req)
{
$arr = [
"form_id" => $req->channel.substr(time(),6),
"channel" => $req->channel,
"status" => 0,
"customer_id" => $req->customer_id,
"user_id" => $req->user_id,
"assigned_to" => 0,
"created_at" => now(),
"updated_at" => now(),
];
$inserted = DB::table('forms')->insert($arr);
return $inserted ? 200 : 500 ;
}
public function send_mail(Request $req){
$mail_data = [
'customer_name' => $req->customer_name,
'cnic' => $req->cnic,
"qq" => $req->qq,
"email" => $req->email
];
$send = '';
$sales_email = \DB::table('users')->where('id',$req->user_id)->first()->email;
//dd($sales_email);
$recipients = [$sales_email,$req->email];
foreach ($recipients as $recipient) {
$send = Mail::to($recipient)->send(new Welcome($mail_data));
}
$recipients = \DB::table('users')->select('email')->where('role_id',3)->get();
foreach ($recipients as $recipient) {
$send = Mail::to($recipient)->send(new Welcome($mail_data));
}
return empty($send)?200:500;
}
}
|
#compdef pyenv
if [[ ! -o interactive ]]; then
return
fi
local state line
typeset -A opt_args
_arguments -C \
{--help,-h}'[Show help]' \
{--version,-v}'[Show pyenv version]' \
'(-): :->command' \
'*:: :->option-or-argument'
case "$state" in
(command)
local -a commands
commands=(${(f)"$(pyenv commands)"})
_describe -t commands 'command' commands
;;
(option-or-argument)
local -a args
args=(${(f)"$(pyenv completions ${line[1]})"})
_describe -t args 'arg' args
;;
esac
return 0
|
<?php
return [
// Service Factories
'service_manager' => [
'invokables' => [
'auth_adapter' => 'Library\Service\AuthAdapter'
],
'abstract_factories' => [
'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
'Zend\Log\LoggerAbstractServiceFactory',
'Library\Service\AbstractService'
],
'factories' => [
'entity_manager' => 'Library\Service\DB\EntityManagerSingleton',
'mongo_db' => 'Library\Service\DB\MongoDBClientSingleton',
'db_connection' => 'Library\Service\DB\Connection',
]
],
// Session settings
'session_settings' => [
'cache_expire' => '10',
'remember_me_seconds' => 864000,
'cookie_lifetime' => 864000,
'use_cookies' => true,
'cookie_httponly' => false,
'name' => \Library\Service\Settings::get('session_name')
],
// View Helpers
'view_helpers' => [
'invokables' => [
'print_shipping_price' => 'Library\ViewHelper\PrintShippingPrice',
]
]
];
|
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017-2020 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include <iostream>
#include <cstdlib>
#include <libcouchbase/couchbase.h>
static void die(const char *msg, lcb_STATUS err)
{
std::cerr << "[ERROR] " << msg << ": " << lcb_strerror_short(err) << "\n";
exit(EXIT_FAILURE);
}
static void store_with_observe_callback(lcb_INSTANCE *, int, const lcb_RESPSTORE *resp)
{
lcb_STATUS rc = lcb_respstore_status(resp);
int store_ok, exists_master, persisted_master;
uint16_t num_responses, num_replicated, num_persisted;
lcb_respstore_observe_stored(resp, &store_ok);
lcb_respstore_observe_master_exists(resp, &exists_master);
lcb_respstore_observe_master_persisted(resp, &persisted_master);
lcb_respstore_observe_num_responses(resp, &num_responses);
lcb_respstore_observe_num_replicated(resp, &num_replicated);
lcb_respstore_observe_num_persisted(resp, &num_persisted);
std::cout << "Got status of operation: " << lcb_strerror_short(rc) << "\n";
std::cout << "Stored: " << (store_ok ? "true" : "false") << "\n";
std::cout << "Number of round-trips: " << num_responses << "\n";
std::cout << "In memory on master: " << (exists_master ? "true" : "false") << "\n";
std::cout << "Persisted on master: " << (persisted_master ? "true" : "false") << "\n";
std::cout << "Nodes have value replicated: " << num_replicated << "\n";
std::cout << "Nodes have value persisted (including master): " << num_persisted << "\n";
}
static void do_store_with_observe_durability(lcb_INSTANCE *instance)
{
lcb_install_callback(instance, LCB_CALLBACK_STORE, reinterpret_cast<lcb_RESPCALLBACK>(store_with_observe_callback));
std::string key = "docid";
std::string value = "[1,2,3]";
// tag::durability[]
lcb_CMDSTORE *cmd;
lcb_cmdstore_create(&cmd, LCB_STORE_UPSERT);
lcb_cmdstore_key(cmd, key.data(), key.size());
lcb_cmdstore_value(cmd, value.data(), value.size());
lcb_cmdstore_durability_observe(cmd, -1, -1);
// end::durability[]
lcb_sched_enter(instance);
lcb_STATUS err = lcb_store(instance, nullptr, cmd);
lcb_cmdstore_destroy(cmd);
if (err != LCB_SUCCESS) {
printf("Unable to schedule store+durability operation: %s\n", lcb_strerror_short(err));
lcb_sched_fail(instance);
return;
}
lcb_sched_leave(instance);
lcb_wait(instance, LCB_WAIT_DEFAULT);
}
static void store_callback(lcb_INSTANCE *, int, const lcb_RESPSTORE *resp)
{
lcb_STATUS rc = lcb_respstore_status(resp);
std::cout << "Got status of operation: " << lcb_strerror_short(rc) << "\n";
}
static void do_store_with_server_durability(lcb_INSTANCE *instance)
{
lcb_install_callback(instance, LCB_CALLBACK_STORE, reinterpret_cast<lcb_RESPCALLBACK>(store_callback));
std::string key = "docid";
std::string value = "[1,2,3]";
lcb_CMDSTORE *cmd;
lcb_cmdstore_create(&cmd, LCB_STORE_UPSERT);
lcb_cmdstore_key(cmd, key.data(), key.size());
lcb_cmdstore_value(cmd, value.data(), value.size());
lcb_cmdstore_durability(cmd, LCB_DURABILITYLEVEL_MAJORITY);
lcb_sched_enter(instance);
lcb_STATUS err = lcb_store(instance, nullptr, cmd);
lcb_cmdstore_destroy(cmd);
if (err != LCB_SUCCESS) {
printf("Unable to schedule store+durability operation: %s\n", lcb_strerror_short(err));
lcb_sched_fail(instance);
return;
}
lcb_sched_leave(instance);
lcb_wait(instance, LCB_WAIT_DEFAULT);
}
int main(int, char **)
{
lcb_STATUS rc;
std::string connection_string = "couchbase://localhost";
std::string username = "Administrator";
std::string password = "password";
lcb_CREATEOPTS *create_options = nullptr;
lcb_createopts_create(&create_options, LCB_TYPE_BUCKET);
lcb_createopts_connstr(create_options, connection_string.data(), connection_string.size());
lcb_createopts_credentials(create_options, username.data(), username.size(), password.data(), password.size());
lcb_INSTANCE *instance;
rc = lcb_create(&instance, create_options);
lcb_createopts_destroy(create_options);
if (rc != LCB_SUCCESS) {
die("Couldn't create couchbase handle", rc);
}
rc = lcb_connect(instance);
if (rc != LCB_SUCCESS) {
die("Couldn't schedule connection", rc);
}
lcb_wait(instance, LCB_WAIT_DEFAULT);
rc = lcb_get_bootstrap_status(instance);
if (rc != LCB_SUCCESS) {
die("Couldn't bootstrap from cluster", rc);
}
std::cout << "--- Performing store with observe-based durability check\n";
do_store_with_observe_durability(instance);
std::cout << "--- Performing store server-side durability check\n";
do_store_with_server_durability(instance);
lcb_destroy(instance);
return 0;
}
|
import { isUnknownArray } from "../../helpers/is-unknown-array"
import { isUnknownObject } from "../../helpers/is-unknown-object"
import { modifyJsonFile, toArray, toObject } from "../../helpers/json-files"
import { install, packages } from "../packages"
import { Step } from "../step"
export const setUpEmotionStep: Step = {
description: "setting up Emotion",
shouldRun: async ({ flags }) => flags.styling === "emotion",
didRun: false,
run: async ({ flags }) => {
await install(
[packages["@emotion/react"], packages["@emotion/styled"]],
flags["package-manager"]
)
await install(packages["@emotion/babel-plugin"], flags["package-manager"], {
dev: true,
})
await addCssPropSupportAsPerEmotionDocs()
await addTypeScriptSupportForTheEmotionCssProp()
},
}
/**
* Add `css` prop support as per the Emotion docs.
*/
const addCssPropSupportAsPerEmotionDocs = async () => {
await modifyJsonFile(".babelrc", (babelConfig) => {
// Add css-prop support as per Next.js-specific Emotion docs: https://emotion.sh/docs/css-prop#babel-preset
const { presets } = babelConfig
if (!isUnknownArray(presets)) {
throw new TypeError("Expected babelConfig.presets to be an array.")
}
const [nextBabelPresetTuple] = presets
if (!isUnknownArray(nextBabelPresetTuple)) {
throw new TypeError("Expected babelConfig.presets[0] to be an array.")
}
const [nextBabelTextField, nextBabelConfig] = nextBabelPresetTuple
if (nextBabelTextField !== "next/babel") {
throw new TypeError(
`Expected babelConfig.presets[0][0] to be "next/babel".`
)
}
if (!isUnknownObject(nextBabelConfig)) {
throw new TypeError("Expected babelConfig.presets[0][1] to be an object.")
}
const presetNameToConfigMap = nextBabelConfig
presetNameToConfigMap["preset-react"] = {
runtime: "automatic",
importSource: "@emotion/react",
}
// Add Emotion's Babel plugin as per their docs: https://emotion.sh/docs/install#babelrc
// Note quote from the docs:
// > "@emotion" must be the first plugin in your babel config `plugins` list.
babelConfig["plugins"] = ["@emotion", ...toArray(babelConfig["plugins"])]
return babelConfig
})
}
/**
* Add TypeScript support for the css-prop as per the docs: https://emotion.sh/docs/typescript#css-prop
*/
const addTypeScriptSupportForTheEmotionCssProp = async () => {
await modifyJsonFile("tsconfig.json", (tsConfig) => ({
...tsConfig,
compilerOptions: {
...toObject(tsConfig["compilerOptions"]),
jsxImportSource: "@emotion/react",
},
}))
}
|
# AWS
## CloudFront
https://stackoverflow.com/questions/38735306/aws-cloudfront-redirecting-to-s3-bucket
https://serverfault.com/questions/145859/how-can-i-limit-cloudfront-downloads
https://aws.amazon.com/premiumsupport/knowledge-center/cloudfront-serving-outdated-content-s3/
## Amplify
https://aws.amazon.com/getting-started/hands-on/build-react-app-amplify-graphql/
https://docs.amplify.aws/start/q/integration/react
https://medium.com/@mim3dot/aws-amplify-pros-and-cons-bf77a98da5db
https://docs.amplify.aws/lib/q/platform/js
## Terraform Setup
https://rangle.io/blog/frontend-app-in-aws-with-terraform/
https://github.com/rangle/tutorial-frontend-site-terraform
https://www.davidbegin.com/deploying-a-react-app-to-s3-with-terrraform-and-bash/
https://notes.webutvikling.org/s3-bucket-cloudfront-using-terraform/
## DynamoDB
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html
https://www.alexdebrie.com/posts/dynamodb-single-table/
https://www.youtube.com/watch?v=HaEPXoXVf2k
# Frontend
## Architecture
https://www.youtube.com/watch?v=o8THlN8hgcw
## React
https://reactjs.org/docs/react-component.html
https://reactjs.org/docs/thinking-in-react.html
## Redux
https://redux.js.org/
https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367
https://redux.js.org/advanced/async-actions
https://www.youtube.com/watch?v=_OfJZfmZCgU
https://www.youtube.com/watch?v=AslncyG8whg
https://blog.logrocket.com/data-fetching-in-redux-apps-a-100-correct-approach-4d26e21750fc/
https://github.com/redux-saga/redux-saga
## Testing
https://medium.com/@rickhanlonii/understanding-jest-mocks-f0046c68e53c
https://codeburst.io/how-to-call-api-in-a-smart-way-2ca572c6fe86
https://blog.bitsrc.io/7-react-testing-libraries-you-should-know-b20ca97422a4
https://redux-saga.js.org/docs/advanced/Testing.html
https://blog.scottlogic.com/2018/01/16/evaluating-redux-saga-test-libraries.html
https://github.com/wix/redux-saga-tester
https://medium.com/@radzserg/how-to-test-redux-saga-with-dependencies-b3f21aa3c240
https://github.com/freshollie/jest-dynalite
https://blog.caplin.com/2017/01/04/screenplay-pattern-a-solid-alternative-pattern-to-page-objects/
https://codewithhugo.com/mocking-the-current-date-in-jest-tests/
https://jestjs.io/docs/en/timer-mocks
## UI
https://react-bootstrap.github.io/components
https://serverless-stack.com/chapters/handle-routes-with-react-router.html
https://reactjs.org/docs/forms.html
|
import { Manager, SearchQuery, SearchResult } from "./Manager";
import { Node } from "./Node";
import { Queue } from "./Queue";
import { Sizes, State, VoiceState } from "./Utils";
export declare class Player {
options: PlayerOptions;
/** The Queue for the Player. */
readonly queue: Queue;
/** Whether the queue repeats the track. */
trackRepeat: boolean;
/** Whether the queue repeats the queue. */
queueRepeat: boolean;
/** The time the player is in the track. */
position: number;
/** Whether the player is playing. */
playing: boolean;
/** Whether the player is paused. */
paused: boolean;
/** Whether the player is playing. */
volume: number;
/** The Node for the Player. */
node: Node;
/** The guild the player. */
guild: string;
/** The voice channel for the player. */
voiceChannel: string | null;
/** The text channel for the player. */
textChannel: string | null;
/** The current state of the player. */
state: State;
/** The equalizer bands array. */
bands: number[];
/** The voice state object from Discord. */
voiceState: VoiceState;
/** The Manager. */
manager: Manager;
private static _manager;
private readonly data;
/**
* Set custom data.
* @param key
* @param value
*/
set(key: string, value: unknown): void;
/**
* Get custom data.
* @param key
*/
get<T>(key: string): T;
/** @hidden */
static init(manager: Manager): void;
/**
* Creates a new player, returns one if it already exists.
* @param options
*/
constructor(options: PlayerOptions);
/**
* Same as Manager#search() but a shortcut on the player itself.
* @param query
* @param requester
*/
search(query: string | SearchQuery, requester?: unknown): Promise<SearchResult>;
/**
* Sets the players equalizer band on-top of the existing ones.
* @param bands
*/
setEQ(...bands: EqualizerBand[]): this;
/** Clears the equalizer bands. */
clearEQ(): this;
/** Connect to the voice channel. */
connect(): this;
/** Disconnect from the voice channel. */
disconnect(): this;
/** Destroys the player. */
destroy(): void;
/**
* Sets the player voice channel.
* @param channel
*/
setVoiceChannel(channel: string): this;
/**
* Sets the player text channel.
* @param channel
*/
setTextChannel(channel: string): this;
/** Plays the next track. */
play(): Promise<void>;
/**
* Plays the specified track.
* @param track
*/
play(track: Track | UnresolvedTrack): Promise<void>;
/**
* Plays the next track with some options.
* @param options
*/
play(options: PlayOptions): Promise<void>;
/**
* Plays the specified track with some options.
* @param track
* @param options
*/
play(track: Track | UnresolvedTrack, options: PlayOptions): Promise<void>;
/**
* Sets the player volume.
* @param volume
*/
setVolume(volume: number): this;
/**
* Sets the track repeat.
* @param repeat
*/
setTrackRepeat(repeat: boolean): this;
/**
* Sets the queue repeat.
* @param repeat
*/
setQueueRepeat(repeat: boolean): this;
/** Stops the current track, optionally give an amount to skip to, e.g 5 would play the 5th song. */
stop(amount?: number): this;
/**
* Pauses the current track.
* @param pause
*/
pause(pause: boolean): this;
/**
* Seeks to the position in the current track.
* @param position
*/
seek(position: number): this;
}
export interface PlayerOptions {
/** The guild the Player belongs to. */
guild: string;
/** The text channel the Player belongs to. */
textChannel: string;
/** The voice channel the Player belongs to. */
voiceChannel?: string;
/** The node the Player uses. */
node?: string;
/** The initial volume the Player will use. */
volume?: number;
/** If the player should mute itself. */
selfMute?: boolean;
/** If the player should deaf itself. */
selfDeafen?: boolean;
}
/** If track partials are set some of these will be `undefined` as they were removed. */
export interface Track {
/** The base64 encoded track. */
readonly track: string;
/** The title of the track. */
readonly title: string;
/** The identifier of the track. */
readonly identifier: string;
/** The author of the track. */
readonly author: string;
/** The duration of the track. */
readonly duration: number;
/** If the track is seekable. */
readonly isSeekable: boolean;
/** If the track is a stream.. */
readonly isStream: boolean;
/** The uri of the track. */
readonly uri: string;
/** The thumbnail of the track or null if it's a unsupported source. */
readonly thumbnail: string | null;
/** The user that requested the track. */
readonly requester: unknown | null;
/** Displays the track thumbnail with optional size or null if it's a unsupported source. */
displayThumbnail(size?: Sizes): string;
}
/** Unresolved tracks can't be played normally, they will resolve before playing into a Track. */
export interface UnresolvedTrack extends Partial<Track> {
/** The title to search against. */
title: string;
/** The author to search against. */
author?: string;
/** The duration to search within 1500 milliseconds of the results from YouTube. */
duration?: number;
/** Resolves into a Track. */
resolve(): Promise<void>;
}
export interface PlayOptions {
/** The position to start the track. */
readonly startTime?: number;
/** The position to end the track. */
readonly endTime?: number;
/** Whether to not replace the track if a play payload is sent. */
readonly noReplace?: boolean;
}
export interface EqualizerBand {
/** The band number being 0 to 14. */
band: number;
/** The gain amount being -0.25 to 1.00, 0.25 being double. */
gain: number;
}
|
using System;
using System.ComponentModel.Composition;
namespace CarBMW
{
[Export(typeof(CarHost.ICarContract))]
public class BMW : CarHost.ICarContract
{
private BMW()
{
Console.WriteLine("BMW constructor");
}
[ImportingConstructor]
private BMW([Import("ConstructorParameter")]int parameter)
{
Console.WriteLine(String.Format("Parameter: {0}.", parameter));
}
public string StartEngine(string name)
{
return String.Format("{0} starts the BMW.", name);
}
}
}
|
package com.sin.java.plot.util;
final public class XLog {
public static void log(String log) {
System.out.println(log);
}
public static void log(String format, Object ...args) {
log(String.format(format, args));
}
}
|
# Copyright 2016 Google Inc. All rights reserved.
#
# 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.
require "google/cloud/translate/service"
require "google/cloud/translate/translation"
require "google/cloud/translate/detection"
require "google/cloud/translate/language"
module Google
module Cloud
module Translate
##
# # Api
#
# Represents top-level access to the Google Translate API. Each instance
# requires a public API access key. To create a key, follow the general
# instructions at [Identifying your application to
# Google](https://cloud.google.com/translate/v2/using_rest#auth), and the
# specific instructions for [Server
# keys](https://cloud.google.com/translate/v2/using_rest#creating-server-api-keys).
# See {Google::Cloud#translate}.
#
# @see https://cloud.google.com/translate/v2/getting_started Translate API
# Getting Started
#
# @example
# require "google/cloud"
#
# gcloud = Google::Cloud.new
# translate = gcloud.translate
#
# translation = translate.translate "Hello world!", to: "la"
#
# puts translation #=> Salve mundi!
#
# translation.from #=> "en"
# translation.origin #=> "Hello world!"
# translation.to #=> "la"
# translation.text #=> "Salve mundi!"
#
class Api
##
# @private The Service object.
attr_accessor :service
##
# @private Creates a new Translate Api instance.
#
# See {Google::Cloud.translate}
def initialize service
@service = service
end
##
# Returns text translations from one language to another.
#
# @see https://cloud.google.com/translate/v2/using_rest#Translate
# Translate Text
#
# @param [String] text The text or texts to translate.
# @param [String] to The target language into which the text should be
# translated. This is required. The value must be an [ISO
# 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
# language code.
# @param [String] from The source language of the text or texts. This is
# an [ISO
# 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
# language code. This is optional.
# @param [String] format The format of the text. Possible values include
# `:text` and `:html`. This is optional. The Translate API default is
# `:html`.
# @param [String] cid The customization id for translate. This is
# optional.
#
# @return [Translation, Array<Translation>] A single {Translation}
# object if just one text was given, or an array of {Translation}
# objects if multiple texts were given.
#
# @example
# require "google/cloud"
#
# gcloud = Google::Cloud.new
# translate = gcloud.translate
#
# translation = translate.translate "Hello world!", to: "la"
#
# puts translation #=> Salve mundi!
#
# translation.detected? #=> true
# translation.from #=> "en"
# translation.origin #=> "Hello world!"
# translation.to #=> "la"
# translation.text #=> "Salve mundi!"
#
# @example Setting the `from` language.
# require "google/cloud"
#
# gcloud = Google::Cloud.new
# translate = gcloud.translate
#
# translation = translate.translate "Hello world!",
# from: :en, to: :la
# translation.detected? #=> false
# translation.text #=> "Salve mundi!"
#
# @example Retrieving multiple translations.
# require "google/cloud"
#
# gcloud = Google::Cloud.new
# translate = gcloud.translate
#
# translations = translate.translate "Hello my friend.",
# "See you soon.",
# from: "en", to: "la"
# translations.count #=> 2
# translations[0].text #=> "Salve amice."
# translations[1].text #=> "Vide te mox."
#
# @example Preserving HTML tags.
# require "google/cloud"
#
# gcloud = Google::Cloud.new
# translate = gcloud.translate
#
# translation = translate.translate "<strong>Hello</strong> world!",
# to: :la
# translation.text #=> "<strong>Salve</strong> mundi!"
#
def translate *text, to: nil, from: nil, format: nil, cid: nil
return nil if text.empty?
fail ArgumentError, "to is required" if to.nil?
to = to.to_s
from = from.to_s if from
format = format.to_s if format
text = Array(text).flatten
gapi = service.translate text, to: to, from: from,
format: format, cid: cid
Translation.from_gapi_list gapi, text, to, from
end
##
# Detect the most likely language or languages of a text or multiple
# texts.
#
# @see https://cloud.google.com/translate/v2/using_rest#detect-language
# Detect Language
#
# @param [String] text The text or texts upon which language detection
# should be performed.
#
# @return [Detection, Array<Detection>] A single {Detection} object if
# just one text was given, or an array of {Detection} objects if
# multiple texts were given.
#
# @example
# require "google/cloud"
#
# gcloud = Google::Cloud.new
# translate = gcloud.translate
#
# detection = translate.detect "Hello world!"
# puts detection.language #=> en
# puts detection.confidence #=> 0.7100697
#
# @example Detecting multiple texts.
# require "google/cloud"
#
# gcloud = Google::Cloud.new
# translate = gcloud.translate
#
# detections = translate.detect "Hello world!",
# "Bonjour le monde!"
# puts detections.count #=> 2
# puts detection.first.language #=> en
# puts detection.first.confidence #=> 0.7100697
# puts detection.last.language #=> fr
# puts detection.last.confidence #=> 0.40440267
#
def detect *text
return nil if text.empty?
text = Array(text).flatten
gapi = service.detect(text)
Detection.from_gapi gapi, text
end
##
# List the languages supported by the API. These are the languages to
# and from which text can be translated.
#
# @see https://cloud.google.com/translate/v2/using_rest#supported-languages
# Discover Supported Languages
#
# @param [String] language The language and collation in which the names
# of the languages are returned. If this is `nil` then no names are
# returned.
#
# @return [Array<Language>] An array of {Language} objects supported by
# the API.
#
# @example
# require "google/cloud"
#
# gcloud = Google::Cloud.new
# translate = gcloud.translate
#
# languages = translate.languages
# languages.count #=> 104
#
# english = languages.detect { |l| l.code == "en" }
# english.name #=> nil
#
# @example Get all languages with their names in French.
# require "google/cloud"
#
# gcloud = Google::Cloud.new
# translate = gcloud.translate
#
# languages = translate.languages "fr"
# languages.count #=> 104
#
# english = languages.detect { |l| l.code == "en" }
# english.name #=> "Anglais"
#
def languages language = nil
language = language.to_s if language
gapi = service.languages language
Array(gapi.languages).map { |g| Language.from_gapi g }
end
end
end
end
end
|
///
/// \file Crc16Ccitt1021.hpp
/// \author Geoffrey Hunter <gbmhunter@gmail.com> (www.mbedded.ninja)
/// \edited n/a
/// \created 2017-06-10
/// \last-modified 2018-01-25
/// \brief Contains the Crc16Ccitt1021 class.
/// \details
/// See README.rst in root dir for more info.
#ifndef MN_SERIAL_FILLER_CRC16_CCITT_1021_H_
#define MN_SERIAL_FILLER_CRC16_CCITT_1021_H_
// Local includes
#include "SerialFiller/SerialFiller.hpp"
namespace mn {
namespace SerialFiller {
class Crc16Ccitt1021 {
public:
static uint16_t Calc(ByteArray data);
};
} // namespace SerialFiller
} // namespace mn
#endif // #ifndef MN_SERIAL_FILLER_CRC16_CCITT_1021_H_
|
{-# LANGUAGE FlexibleContexts, FunctionalDependencies, MultiParamTypeClasses, OverloadedLabels, UndecidableInstances,
OverloadedStrings, TemplateHaskell, TypeApplications, TypeFamilies, DataKinds, TypeOperators, FlexibleInstances #-}
module Generated.Support where
import Godot
import GHC.TypeLits
class SceneNode (scene :: Symbol) (s :: Symbol) where
type SceneNodeType scene s :: *
type SceneNodeName scene s :: Symbol
class NodeInScheme (scene :: Symbol) (s :: Symbol) n | scene s -> n, n -> scene s
|
package ttt.cli;
import java.util.*;
import javax.xml.ws.*;
import static javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY;
import pt.ulisboa.tecnico.sdis.ws.uddi.UDDINaming;
import ttt.*; // classes generated from WSDL
public class Game {
public static void main(String[] args) throws Exception {
// Check arguments
if (args.length < 2) {
System.err.println("Argument(s) missing!");
System.err.printf("Usage: java %s uddiURL name%n", Game.class.getName());
return;
}
String uddiURL = args[0];
String name = args[1];
System.out.printf("Contacting UDDI at %s%n", uddiURL);
UDDINaming uddiNaming = new UDDINaming(uddiURL);
System.out.printf("Looking for '%s'%n", name);
String endpointAddress = uddiNaming.lookup(name);
if (endpointAddress == null) {
System.out.println("Not found!");
return;
} else {
System.out.printf("Found %s%n", endpointAddress);
}
System.out.println("Creating stub ...");
TTTImplService service = new TTTImplService();
TTT port = service.getTTTImplPort();
System.out.println("Setting endpoint address ...");
BindingProvider bindingProvider = (BindingProvider) port;
Map<String, Object> requestContext = bindingProvider.getRequestContext();
requestContext.put(ENDPOINT_ADDRESS_PROPERTY, endpointAddress);
// Start game
Game g = new Game(port);
g.playGame();
g.congratulate();
}
private TTT ttt;
private Scanner keyboardSc;
private int winner = 0;
private int player = 1;
private int[ ] superPlays = {1, 1};
public Game(TTT port) {
this.ttt = port;
keyboardSc = new Scanner(System.in);
}
public int readPlay() {
int play;
do {
System.out.printf(
"\nPlayer %d, please enter the number of the square "
+ "where you want to place your %c (or 0 to refresh the board): %n",
player, (player == 1) ? 'X' : 'O');
play = keyboardSc.nextInt();
} while (play > 9 || play < -9);
return play;
}
public void playGame() {
int play;
boolean playAccepted;
do {
player = ++player % 2;
do {
System.out.println(ttt.currentBoard());
play = readPlay();
if (play != 0) {
if( play < 0){
play = superPlay(play);
playAccepted = ttt.superPlay(--play / 3, play % 3, player);
}else
playAccepted = ttt.play(--play / 3, play % 3, player);
if (!playAccepted)
System.out.println("Invalid play! Try again.");
} else {
playAccepted = false;
}
} while (!playAccepted);
winner = ttt.checkWinner();
} while (winner == -1);
}
public void congratulate() {
if (winner == 2)
System.out.printf("\nHow boring, it is a draw\n");
else
System.out.printf("\nCongratulations, player %d, YOU ARE THE WINNER!\n", winner);
}
public int superPlay(int play){
if(superPlays[player] > 0){
System.out.println("This is your SUPER PLAYYYYY!");
superPlays[player] = 0;
return -play;
}else{
System.out.println("YOU HAVE NO MORE SUPER PLAYSSSS");
return 0;
}
}
}
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NegativeLiterals #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE InstanceSigs #-}
module HulkanEngine3D.Render.RenderObject where
import qualified Data.Text as Text
import qualified Data.Vector as Vector
import Numeric.DataFrame
import qualified HulkanEngine3D.Render.Mesh as Mesh
import HulkanEngine3D.Render.Model
import HulkanEngine3D.Render.TransformObject
import HulkanEngine3D.Utilities.Logger
import HulkanEngine3D.Utilities.System()
data RenderObjectCreateData = RenderObjectCreateData
{ _modelData' :: ModelData
, _position' :: Vec3f
, _rotation' :: Vec3f
, _scale' :: Vec3f
, _has_animation_data' :: Bool
} deriving Show
data RenderObjectData = RenderObjectData
{ _renderObjectName :: Text.Text
, _modelData :: ModelData
, _transformObject :: TransformObjectData
, _animation_play_info :: AnimationPlayInfo
} deriving Show
data AnimationPlayInfo
= EmptyAnimationPlayInfo
| AnimationPlayInfo
{ _last_animation_frame :: Float
, _animation_loop :: Bool
, _animation_blend_time :: Float
, _animation_elapsed_time :: Float
, _animation_speed :: Float
, _animation_frame :: Float
, _animation_start_time :: Float
, _animation_end_time :: Float
, _is_animation_end :: Bool
, _animation_buffers :: Vector.Vector Mat44f
, _prev_animation_buffers :: Vector.Vector Mat44f
, _blend_animation_buffers :: Vector.Vector Mat44f
, _animation_count :: Int
, _animation_mesh :: Mesh.MeshData
}
deriving Show
defaultRenderObjectCreateData :: RenderObjectCreateData
defaultRenderObjectCreateData = RenderObjectCreateData
{ _modelData' = EmptyModelData
, _position' = vec3 0 0 0
, _rotation' = vec3 0 0 0
, _scale' = vec3 1 1 1
, _has_animation_data' = False
}
default_animation_play_info :: AnimationPlayInfo
default_animation_play_info = AnimationPlayInfo
{ _last_animation_frame = 0.0
, _animation_loop = True
, _animation_blend_time = 0.5
, _animation_elapsed_time = 0.0
, _animation_speed = 1.0
, _animation_frame = 0.0
, _animation_start_time = 0.0
, _animation_end_time = -1.0
, _is_animation_end = False
, _animation_buffers = Vector.empty
, _prev_animation_buffers = Vector.empty
, _blend_animation_buffers = Vector.empty
, _animation_count = 0
, _animation_mesh = Mesh.EmptyMeshData
}
class RenderObjectInterface a where
createRenderObjectData :: Text.Text -> RenderObjectCreateData -> IO a
getModelData :: a -> ModelData
getTransformObjectData :: a -> TransformObjectData
updateRenderObjectData :: a -> IO ()
instance RenderObjectInterface RenderObjectData where
createRenderObjectData :: Text.Text -> RenderObjectCreateData -> IO RenderObjectData
createRenderObjectData renderObjectName renderObjectCreateData = do
logInfo $ "createRenderObjectData :: " ++ show renderObjectName
transformObjectData <- newTransformObjectData
setPosition transformObjectData $ _position' renderObjectCreateData
setRotation transformObjectData $ _rotation' renderObjectCreateData
setScale transformObjectData $ _scale' renderObjectCreateData
return RenderObjectData
{ _renderObjectName = renderObjectName
, _modelData = _modelData' renderObjectCreateData
, _transformObject = transformObjectData
, _animation_play_info =
case _has_animation_data' renderObjectCreateData of
True -> default_animation_play_info
otherwise -> EmptyAnimationPlayInfo
}
getModelData :: RenderObjectData -> ModelData
getModelData renderObjectData = _modelData renderObjectData
getTransformObjectData :: RenderObjectData -> TransformObjectData
getTransformObjectData renderObjectData = _transformObject renderObjectData
updateRenderObjectData :: RenderObjectData -> IO ()
updateRenderObjectData renderObjectData = do
updateTransformObject (_transformObject renderObjectData)
return ()
|
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rails'
require 'capybara/rspec'
require 'capybara/poltergeist'
#require 'factory_girl'
Capybara.configure do |c|
c.run_server = true
c.javascript_driver = :poltergeist
c.default_driver = :poltergeist
end
RSpec.configure do |config|
config.render_views
end
#DatabaseCleaner.strategy = :truncation
feature 'Home page' do
before(:each) do
#DatabaseCleaner.clean
end
scenario 'test' do
visit '/'
end
end
|
#SassCompiler
Compile sass/scss to css directly within Codiad.
##Installation
- Download the zip file and unzip it to your plugin folder.
##Credits
[Sass.js - Version 0.9.2](https://github.com/medialize/sass.js) - MIT License
|
(ns clojuresque.hiccup.util
"Utility functions for Hiccup."
(:require [clojure.string :as str])
(:import java.net.URI
java.net.URLEncoder))
(def ^:dynamic *base-url* nil)
(defmacro with-base-url
"Sets a base URL that will be prepended onto relative URIs. Note that for this
to work correctly, it needs to be placed outside the html macro."
[base-url & body]
`(binding [*base-url* ~base-url]
~@body))
(defprotocol ToString
(^String to-str [x] "Convert a value into a string."))
(extend-protocol ToString
clojure.lang.Keyword
(to-str [k] (name k))
clojure.lang.Ratio
(to-str [r] (str (float r)))
java.net.URI
(to-str [u]
(if (or (.isAbsolute u)
(not (-> (.getPath u) (.startsWith "/"))))
(str u)
(str *base-url* u)))
Object
(to-str [x] (str x))
nil
(to-str [_] ""))
(defn ^String as-str
"Converts its arguments into a string using to-str."
[& xs]
(apply str (map to-str xs)))
(defprotocol ToURI
(^URI to-uri [x] "Convert a value into a URI."))
(extend-protocol ToURI
java.net.URI
(to-uri [u] u)
String
(to-uri [s] (URI. s)))
(defn escape-html
"Change special characters into HTML character entities."
[text]
(.. ^String (as-str text)
(replace "&" "&")
(replace "<" "<")
(replace ">" ">")
(replace "\"" """)))
(def ^:dynamic *encoding* "UTF-8")
(defmacro with-encoding
"Sets a default encoding for URL encoding strings. Defaults to UTF-8."
[encoding & body]
`(binding [*encoding* ~encoding]
~@body))
(defprotocol URLEncode
(url-encode [x] "Turn a value into a URL-encoded string."))
(extend-protocol URLEncode
String
(url-encode [s] (URLEncoder/encode s *encoding*))
java.util.Map
(url-encode [m]
(str/join "&"
(for [[k v] m]
(str (url-encode k) "=" (url-encode v)))))
Object
(url-encode [x] (url-encode (to-str x))))
(defn url
"Creates a URL string from a variable list of arguments and an optional
parameter map as the last argument. For example:
(url \"/group/\" 4 \"/products\" {:page 9})
=> \"/group/4/products?page=9\""
[& args]
(let [params (last args), args (butlast args)]
(to-uri
(str (apply str args)
(if (map? params)
(str "?" (url-encode params))
params)))))
|
// <auto-generated>
// This code was generated by the UnitCodeGenerator tool
//
// Changes to this file will be lost if the code is regenerated
// </auto-generated>
package com.putridparrot.units;
import net.jqwik.api.constraints.DoubleRange;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import net.jqwik.api.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TemperatureTests {
@Property(tries = 100)
public void testFromCelsiusToFahrenheitAndBack(@ForAll @DoubleRange(min = -1E12, max = 1E12) double value) {
final double convertTo = Temperature.Celsius.toFahrenheit(value);
final double convertBack = Temperature.Fahrenheit.toCelsius(convertTo);
assertEquals(value, convertBack, 0.01);
}
@ParameterizedTest
@CsvSource({ "32.0,89.6","0.9,33.62","0.0,32.0" })
public void testConvertKnownCelsiusToFahrenheit(double input, double expectation) {
final double result = Temperature.Celsius.toFahrenheit(input);
assertEquals(expectation, result, 0.01);
}
@Property(tries = 100)
public void testFromCelsiusToKelvinAndBack(@ForAll @DoubleRange(min = -1E12, max = 1E12) double value) {
final double convertTo = Temperature.Celsius.toKelvin(value);
final double convertBack = Temperature.Kelvin.toCelsius(convertTo);
assertEquals(value, convertBack, 0.01);
}
@ParameterizedTest
@CsvSource({ "1.0,274.15","9.9,283.05","100.0,373.15" })
public void testConvertKnownCelsiusToKelvin(double input, double expectation) {
final double result = Temperature.Celsius.toKelvin(input);
assertEquals(expectation, result, 0.01);
}
@Property(tries = 100)
public void testFromCelsiusToRankineAndBack(@ForAll @DoubleRange(min = -1E12, max = 1E12) double value) {
final double convertTo = Temperature.Celsius.toRankine(value);
final double convertBack = Temperature.Rankine.toCelsius(convertTo);
assertEquals(value, convertBack, 0.01);
}
@ParameterizedTest
@CsvSource({ "900.0,2111.67","12.0,513.27","-3.0,486.27" })
public void testConvertKnownCelsiusToRankine(double input, double expectation) {
final double result = Temperature.Celsius.toRankine(input);
assertEquals(expectation, result, 0.01);
}
@Property(tries = 100)
public void testFromFahrenheitToCelsiusAndBack(@ForAll @DoubleRange(min = -1E12, max = 1E12) double value) {
final double convertTo = Temperature.Fahrenheit.toCelsius(value);
final double convertBack = Temperature.Celsius.toFahrenheit(convertTo);
assertEquals(value, convertBack, 0.01);
}
@ParameterizedTest
@CsvSource({ "109.0,42.7778","56.9,13.83333","102.0,38.8889" })
public void testConvertKnownFahrenheitToCelsius(double input, double expectation) {
final double result = Temperature.Fahrenheit.toCelsius(input);
assertEquals(expectation, result, 0.01);
}
@Property(tries = 100)
public void testFromFahrenheitToKelvinAndBack(@ForAll @DoubleRange(min = -1E12, max = 1E12) double value) {
final double convertTo = Temperature.Fahrenheit.toKelvin(value);
final double convertBack = Temperature.Kelvin.toFahrenheit(convertTo);
assertEquals(value, convertBack, 0.01);
}
@ParameterizedTest
@CsvSource({ "34.5,274.5389","901.0,755.928","23.9,268.65" })
public void testConvertKnownFahrenheitToKelvin(double input, double expectation) {
final double result = Temperature.Fahrenheit.toKelvin(input);
assertEquals(expectation, result, 0.01);
}
@Property(tries = 100)
public void testFromFahrenheitToRankineAndBack(@ForAll @DoubleRange(min = -1E12, max = 1E12) double value) {
final double convertTo = Temperature.Fahrenheit.toRankine(value);
final double convertBack = Temperature.Rankine.toFahrenheit(convertTo);
assertEquals(value, convertBack, 0.01);
}
@ParameterizedTest
@CsvSource({ "123.0,582.67","9.2,468.87","0.2,459.87" })
public void testConvertKnownFahrenheitToRankine(double input, double expectation) {
final double result = Temperature.Fahrenheit.toRankine(input);
assertEquals(expectation, result, 0.01);
}
@Property(tries = 100)
public void testFromKelvinToCelsiusAndBack(@ForAll @DoubleRange(min = -1E12, max = 1E12) double value) {
final double convertTo = Temperature.Kelvin.toCelsius(value);
final double convertBack = Temperature.Celsius.toKelvin(convertTo);
assertEquals(value, convertBack, 0.01);
}
@ParameterizedTest
@CsvSource({ "80.0,-193.15","0.9,-272.25","305.15,32.0" })
public void testConvertKnownKelvinToCelsius(double input, double expectation) {
final double result = Temperature.Kelvin.toCelsius(input);
assertEquals(expectation, result, 0.01);
}
@Property(tries = 100)
public void testFromKelvinToFahrenheitAndBack(@ForAll @DoubleRange(min = -1E12, max = 1E12) double value) {
final double convertTo = Temperature.Kelvin.toFahrenheit(value);
final double convertBack = Temperature.Fahrenheit.toKelvin(convertTo);
assertEquals(value, convertBack, 0.01);
}
@ParameterizedTest
@CsvSource({ "123.4,-237.55","800.0,980.33","99.999,-279.6718" })
public void testConvertKnownKelvinToFahrenheit(double input, double expectation) {
final double result = Temperature.Kelvin.toFahrenheit(input);
assertEquals(expectation, result, 0.01);
}
@Property(tries = 100)
public void testFromKelvinToRankineAndBack(@ForAll @DoubleRange(min = -1E12, max = 1E12) double value) {
final double convertTo = Temperature.Kelvin.toRankine(value);
final double convertBack = Temperature.Rankine.toKelvin(convertTo);
assertEquals(value, convertBack, 0.01);
}
@ParameterizedTest
@CsvSource({ "156.0,280.8","8.2,14.76","0.8,1.44" })
public void testConvertKnownKelvinToRankine(double input, double expectation) {
final double result = Temperature.Kelvin.toRankine(input);
assertEquals(expectation, result, 0.01);
}
@Property(tries = 100)
public void testFromRankineToCelsiusAndBack(@ForAll @DoubleRange(min = -1E12, max = 1E12) double value) {
final double convertTo = Temperature.Rankine.toCelsius(value);
final double convertBack = Temperature.Celsius.toRankine(convertTo);
assertEquals(value, convertBack, 0.01);
}
@ParameterizedTest
@CsvSource({ "190.0,-167.59444444","0.7,-272.76111111","900.0,226.85" })
public void testConvertKnownRankineToCelsius(double input, double expectation) {
final double result = Temperature.Rankine.toCelsius(input);
assertEquals(expectation, result, 0.01);
}
@Property(tries = 100)
public void testFromRankineToFahrenheitAndBack(@ForAll @DoubleRange(min = -1E12, max = 1E12) double value) {
final double convertTo = Temperature.Rankine.toFahrenheit(value);
final double convertBack = Temperature.Fahrenheit.toRankine(convertTo);
assertEquals(value, convertBack, 0.01);
}
@ParameterizedTest
@CsvSource({ "109.0,-350.67","3567.0,3107.33","9.0,-450.67" })
public void testConvertKnownRankineToFahrenheit(double input, double expectation) {
final double result = Temperature.Rankine.toFahrenheit(input);
assertEquals(expectation, result, 0.01);
}
@Property(tries = 100)
public void testFromRankineToKelvinAndBack(@ForAll @DoubleRange(min = -1E12, max = 1E12) double value) {
final double convertTo = Temperature.Rankine.toKelvin(value);
final double convertBack = Temperature.Kelvin.toRankine(convertTo);
assertEquals(value, convertBack, 0.01);
}
@ParameterizedTest
@CsvSource({ "123.0,68.333333333","0.9,0.5","23.0,12.777777778" })
public void testConvertKnownRankineToKelvin(double input, double expectation) {
final double result = Temperature.Rankine.toKelvin(input);
assertEquals(expectation, result, 0.01);
}
}
|
<?php
/**
* STI - Project Web
* WeChat
* Description: web site to send mails between users
* Authors: Loan Lassalle, Wojciech Myszkorowski
*/
/**
* Gère la communication avec la base de données
*
* @author Lassalle Loan, Wojciech Myszkorowski
* @since 27.09.2017
*/
class Database {
private static $_instance;
private $_database;
private function __construct() {
$this->connection();
}
public static function getInstance() {
if (is_null(self::$_instance )) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Récupère la connexion à la base de données
*/
public function connection($file = 'sqlite:./weChat.sqlite') {
try {
$this->_database = new PDO($file);
$this->_database->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo $ex->getMessage();
exit();
}
}
/**
* Ferme la connexion à la base de données
*/
public function deconnection() {
$this->_database = null;
}
/**
* Récupère le résultat d'une requête
*/
public function query($sql) {
if (!isset($this->_database)) {
$this->connection();
}
if (substr($sql, 0, 6) === 'SELECT') {
$results = $this->_database->query($sql);
} else {
$results = $this->_database->exec($sql);
}
return $results;
}
}
?>
|
module TwilioCapability
def self.generate(agent_id)
# To find TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN visit
# https://www.twilio.com/user/account
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
capability = Twilio::JWT::ClientCapability.new(account_sid, auth_token)
incomingScope = Twilio::JWT::ClientCapability::IncomingClientScope.new agent_id
capability.add_scope incomingScope
capability.to_s
end
end
|
-- 627. 变更性别 https://leetcode-cn.com/problems/swap-salary/
DROP TABLE IF EXISTS `salary`;
CREATE TABLE `salary` (
`id` int NULL DEFAULT NULL,
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`sex` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`salary` int NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
INSERT INTO `salary` VALUES (1, 'A', 'f', 2500);
INSERT INTO `salary` VALUES (2, 'B', 'm', 1500);
INSERT INTO `salary` VALUES (3, 'C', 'f', 5500);
INSERT INTO `salary` VALUES (4, 'D', 'm', 500);
UPDATE salary
SET sex = IF(sex="m","f","m")
|
import redis
import os
import sdk
r = redis.StrictRedis(host=sdk.config.state.host,
port=sdk.config.state.port, db=0)
def load(appname, state):
"""Loads app state from Jarvis into |state|.
Returns:
Flag indicating whether or not a saved state was found.
"""
msg_str = r.get(appname)
if msg_str:
state.ParseFromString(msg_str)
return True
return False
def update(appname, new_state):
msg_str = new_state.SerializeToString()
r.set(appname, msg_str)
|
package io.github.ppdzm.utils.spark
import io.github.ppdzm.utils.universal.base.Logging
import org.apache.spark.sql.SparkSession
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.{SparkConf, SparkContext}
/**
* Created by Stuart Alex on 2016/5/26.
*/
object SparkUtils extends Logging {
def getSparkContext(conf: Map[String, String] = Map[String, String]()): SparkContext = {
val sparkSession = this.getSparkSession(conf)
this.logInfo("Get SparkContext ...")
sparkSession.sparkContext
}
def getSparkSession(conf: Map[String, String] = Map[String, String]()): SparkSession = {
this.logInfo("Get SparkSession ...")
val builder = SparkSession.builder()
builder.master("local[*]")
.appName("unnamed")
.config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
.config("spark.kryo.registrationRequired", "false")
.config("spark.hadoop.hive.exec.dynamic.partition.mode", "nonstrict")
.config("spark.blacklist.enabled", "false")
sys.props.get("os.name").getOrElse("") match {
case "Linux" => builder.enableHiveSupport()
case "Ubuntu" => builder.enableHiveSupport()
case "Mac OS X" =>
if (System.getProperty("spark.hive.enabled", "false").toBoolean)
builder.enableHiveSupport()
case _ =>
}
conf.foreach { case (key, value) => builder.config(key, value) }
builder.getOrCreate()
}
def getStreamingContext(sparkConf: SparkConf, seconds: Int): StreamingContext = {
new StreamingContext(sparkConf, Seconds(seconds))
}
def getMaster(sparkSession: SparkSession): String = sparkSession.sparkContext.master
def getApplicationId(sparkSession: SparkSession): String = sparkSession.sparkContext.applicationId
}
|
package main
import (
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
"testing"
)
func Test_mergeConfigs(t *testing.T) {
t.Parallel()
a := &Config{
ListenAddr: "localhost:8080",
Verbose: false,
Commands: []*Command{
{Cmd: "echo"},
},
}
b := &Config{
ListenAddr: "localhost:8081",
Verbose: true,
Commands: []*Command{
{Cmd: "/bin/echo"},
},
}
merged := mergeConfigs(a, b)
if merged.ListenAddr != b.ListenAddr {
t.Errorf("Wrong ListenAddr for merged config; got %s, want %s", merged.ListenAddr, b.ListenAddr)
}
if merged.Verbose != b.Verbose {
t.Errorf("Wrong Verbose for merged config; got %v, want %v", merged.Verbose, b.Verbose)
}
allCmds := make([]*Command, 0)
allCmds = append(allCmds, a.Commands...)
allCmds = append(allCmds, b.Commands...)
for _, cmd := range allCmds {
if !merged.HasCommand(cmd) {
t.Errorf("Missing command %#v", cmd)
}
}
yamlFile := `---
listen_address: ":23222"
verbose: false
commands:
- cmd: echo
args: ["banana", "tomato"]
match_labels:
"env": "testing"
"owner": "me"
- cmd: /bin/true
match_labels:
"beep": "boop"
`
yamlConf := &Config{}
err := yaml.Unmarshal([]byte(yamlFile), yamlConf)
if err != nil {
t.Errorf("Failed to unmarshal yaml config file; %v", err)
}
mergedAgain := mergeConfigs(merged, yamlConf)
if mergedAgain.ListenAddr != yamlConf.ListenAddr {
t.Errorf("Wrong ListenAddr for merged config; got %s, want %s", mergedAgain.ListenAddr, yamlConf.ListenAddr)
}
if mergedAgain.Verbose != (merged.Verbose || yamlConf.Verbose) {
t.Errorf("Wrong Verbose for merged config; got %v, want %v", mergedAgain.Verbose, (merged.Verbose || yamlConf.Verbose))
}
allCmds = append(allCmds, yamlConf.Commands...)
for _, cmd := range allCmds {
if !mergedAgain.HasCommand(cmd) {
t.Errorf("Missing command %#v", cmd)
}
}
}
func Test_readConfigFile(t *testing.T) {
tempfile, err := ioutil.TempFile("", "am-executor_readConfigFile-*.yml")
if err != nil {
t.Error(err)
}
defer func() {
_ = os.Remove(tempfile.Name())
}()
yamlFile := `---
listen_address: ":23222"
verbose: true
commands:
- cmd: echo
args: ["banana", "tomato"]
match_labels:
"env": "testing"
"owner": "me"
notify_on_failure: false
resolved_signal: sigusr2
- cmd: /bin/true
match_labels:
"beep": "boop"
ignore_resolved: true
`
_, err = tempfile.Write([]byte(yamlFile))
if err != nil {
t.Fatal(err)
}
err = tempfile.Close()
if err != nil {
t.Fatal(err)
}
c, err := readConfigFile(tempfile.Name())
if err != nil {
t.Fatalf("Failed to read configuration file from %s: %v", tempfile.Name(), err)
}
if c.ListenAddr != ":23222" {
t.Errorf("Wrong ListenAddr; got %s, want %s", c.ListenAddr, ":23222")
}
if c.Verbose != true {
t.Errorf("Wrong Verbose value; got %v, want %v", c.Verbose, true)
}
if len(c.Commands) != 2 {
t.Errorf("Wrong number of commands defined; got %d, want %d", len(c.Commands), 2)
}
// We can create pointers to variables, but not to primitive values like true/false directly.
var alsoTrue = true
var alsoFalse = false
var cases = []struct {
cmd *Command
shouldNotify bool
shouldIgnoreResolved bool
}{
{
cmd: &Command{
Cmd: "echo",
Args: []string{"banana", "tomato"},
MatchLabels: map[string]string{
"env": "testing",
"owner": "me",
},
NotifyOnFailure: &alsoFalse,
ResolvedSig: "sigusr2",
},
shouldNotify: false,
shouldIgnoreResolved: false,
},
{
cmd: &Command{
Cmd: "/bin/true",
MatchLabels: map[string]string{
"beep": "boop",
},
IgnoreResolved: &alsoTrue,
},
shouldNotify: true,
shouldIgnoreResolved: true,
},
}
for i, tc := range cases {
if !c.Commands[i].Equal(tc.cmd) {
t.Errorf("Commands not equal; %q and %q", c.Commands[i], tc.cmd.String())
}
if c.Commands[i].ShouldNotify() != tc.shouldNotify {
t.Errorf("Wrong NotifyOnFailure value for %q; got %v, want %v", c.Commands[i].String(), c.Commands[i].ShouldNotify(), tc.shouldNotify)
}
if c.Commands[i].ShouldIgnoreResolved() != tc.shouldIgnoreResolved {
t.Errorf("Wrong IgnoreResolved value for %q; got %v, want %v", c.Commands[i].String(), c.Commands[i].ShouldIgnoreResolved(), tc.shouldIgnoreResolved)
}
if c.Commands[i].ResolvedSig != tc.cmd.ResolvedSig {
t.Errorf("Wrong ResolvedSig value for %q; got %s, want %s", c.Commands[i].String(), c.Commands[i].ResolvedSig, tc.cmd.ResolvedSig)
}
_, err := c.Commands[i].ParseSignal()
if err != nil {
t.Fatalf("Failed to convert command %q ResolvedSig value %s to signal: %v", c.Commands[i].String(), c.Commands[i].ResolvedSig, err)
}
}
}
func TestConfig_HasCommand(t *testing.T) {
t.Parallel()
a := &Command{
Cmd: "echo",
Args: []string{"banana", "lemon"},
MatchLabels: map[string]string{"env": "test", "owner": "me"},
}
c := Config{}
if c.HasCommand(a) {
t.Errorf("Config should not have command")
}
c.Commands = append(c.Commands, a)
if !c.HasCommand(a) {
t.Errorf("Config should have command")
}
}
|
use strict;
use warnings;
use lib 't/lib';
use TestHelper qw( doc );
use Test::More;
my ($doc) = doc(
filename => 'test-data/socket.pl',
);
my $expected = <<'EOF';
use strict;
use warnings;
use IO::Socket::INET ();
use Socket qw( SO_REUSEPORT SOL_SOCKET );
foo( SO_REUSEPORT, SOL_SOCKET );
sub foo { }
EOF
is(
$doc->tidied_document,
$expected,
'Two modules with the same exports do not get conflated'
);
done_testing;
|
plugins {
id("au.com.dius.pact")
}
pact {
serviceProviders {
"Activity Service" {
port = 5050
}
}
publish {
pactBrokerUrl = "http://localhost:80"
}
}
|
<?php
return [
'GESTAO' => 'GESTAO',
'apellido'=>'Apellido',
'codigoDeClaseRepetido' => 'Codigo o nombre de clase repetidos! clase no creada !',
'codigoDeAulaRepetido' => 'Codigo o nombre de aula repetidos! aula no creada !',
'estado'=>'Estado',
'aprobado'=>'Aprobado',
'profesores' => 'Profesores',
'ingresaAdministrador' => 'Ingresa administrador',
'correo' => 'Correo',
'eliminarAsiganacion'=>'Eliminar Asignacion',
'ingresaCorreo' => 'Ingresa tu correo',
'contrasena' => 'Contraseña',
'ingresaContrasena' => 'Ingresa tu contraseña',
'iniciar' => 'Iniciar',
'cerrarSesion' => 'Cerrar sesion',
'perfil' => 'Perfil',
'aulas' => 'Aulas',
'clases' => 'Clases',
'crear' => 'Crear',
'id' => 'Id',
'Configuracion' => 'Configuracion',
'fechas' => 'Ingrese el rango de Fechas',
'ConstanteDeAsignacion' => 'Constante de asignacion',
'nombre' => 'Nombre',
'cantidadDePersonas' => 'Cantidad de personas',
'cantidadDeEquipos' => 'Cantidad de equipos',
'piso' => 'Piso',
'VerCalendarioAcademico' => 'Ver Calendario Academico',
'codigoDeAula' => 'Codigo de aula',
'nombreDeLaAula' => 'Nombre de la aula',
'actualizar' => 'Actualizar',
'eliminar' => 'Eliminar',
'editar'=>'Editar',
'aulaModificada' => 'Aula Modificada!',
'aulaEliminada' => 'Aula Eliminada!',
'establecerParametros' => 'Establecer parametros',
'registrar' => 'Registrar',
'aulaCreadaCorrectamente' => 'Aula creada correctamente!',
'claseModificada' => 'Clase Modificada!',
'claseEliminada' => 'Clase Eliminada!',
'claseCreadaCorrectamente' => 'Clase creada correctamente!',
'grupo' => 'Grupo',
'creditos' => 'Creditos',
'cantidadDeEstudiantes' => 'Cantidad de estudiantes',
'requerimientos' => 'Requerimientos',
'codigoDeLaClase' => 'Codigo de la clase',
'nombreDeLaClase' => 'Nombre de la clase',
'numeroDeCreditos' => 'Numero de creditos',
'semestre' => 'Semestre',
'ejemSalaI'=>'Ejem: Sala I',
'ejemComputacionGrafica'=>'Ejem: Computacion Grafica',
'ejemSis501'=>'Ejem: SIS501',
'datosSonIncorrectos'=>'Datos son incorrectos',
'horario'=>'Horario',
'diaDeLaSemana'=>'Dia de la semana',
'lunes'=>'Lunes',
'martes'=>'Martes',
'miercoles'=>'Miercoles',
'jueves'=>'Jueves',
'viernes'=>'Viernes',
'sabado'=>'Sabado',
'domingo'=>'Domingo',
'horaInicial'=>'Hora inicial',
'horaFinal'=>'Hora final',
'ocurrencias'=>'Ocurrencias',
'todoElSemestre'=>'Todo el semestre',
'unaSolaVes'=>'Una sola vez',
'ocurrenciaCreadaCorrectamente' => 'Ocurrencia creada correctamente',
'anadirOcurrencia' => 'Añadir Ocurrencia',
'nombre1'=>'Primer nombre',
'nombre2'=>'Segundo nombre',
'apellido1'=>'Primer apellido',
'apellido2'=>'Segundo apellido',
'mantengaVacioSiNoVaAActualizarSuContrasena'=>'Mantenga Vacio si no se va a actualizar su contraseña',
'confirmeSuNuevaContrasena'=>'Confirme su nueva contraseña',
'telefono'=>'Telefono',
'programa'=>'Programa',
'lasContrasenasNoCoinciden'=>'Las contraseñas no coinciden',
'perfilModificado'=>'Perfil modificado!',
'AsignarClasesDe'=>'Asignar clases de: ',
'hasta'=>'Hasta',
'horas'=>'Horas',
'fecha'=>'Fecha',
'asignar'=>'Asignar',
'planilla'=>'Planilla',
'mostrarPor'=>'Mostrar Por',
'dia'=>'Dia',
'semana'=>'Semana',
'numeroSala'=>'Numero Sala',
'al'=>'Al',
'mostrar'=>'Mostrar',
'reservar'=>'Reservar',
'aula1'=>'Aula 1',
'aula2'=>'Aula 2',
'aula3'=>'Aula 3',
'aula4'=>'Aula 4',
'aula5'=>'Aula 5',
'aula6'=>'Aula 6',
'aula7'=>'Aula 7',
'aula8'=>'Aula 8',
'aula9'=>'Aula 9',
'aula10'=>'Aula 10',
'opcionesGenerales'=>'Opciones generales',
'inicioSemestre'=>'Inicio de semestre',
'finSemestre'=>'Fin de semestre',
'peticion'=>'Peticiones',
'algoritmo'=>'Algoritmo',
'clase'=>'Clase',
'responsable'=>'Responsable',
'ocurrenciaEliminadaCorrectamente'=>'Ocurrencia Eliminada Correctamente',
'irAHorario'=>'Ir a horario',
'eliminarOcurrencia'=>'Eliminar Ocurrencia',
'profesorAprobadoCorrectamente'=>'Profesor aprobado correctamente',
'aprobar'=>'Aprobar',
'noAprobado'=>'No aprobado',
'claseEliminadaCorrectamente'=>'Clase eliminada correctamente',
'claseAsignadaCorrectamente'=>'Clase asignada correctamente',
'docente'=>'Docente',
'desvincularDocente'=>'Desvincular docente',
'docenteDesvinculado'=>'Docente desvinculado',
'eliminarHorario'=>'Eliminar horario',
'profesorEliminadoCorrectamente'=>'Profesor eliminado correctamente',
];
?>
|
# print-json-with-jekyll
print JSON with Jekyll
## Setup
install dependencies.
```sh
$ rake install
```
start jekyll.
```
$ rake preview
```
open `http://localhost:4000/` with the browser.
## License
The MIT license.
|
import argparse
import json
import os
import time
import unittest
from selenium import webdriver
driver = None
def setUpModule():
"""Create the test browser only once to avoid overhead."""
global driver
parser = argparse.ArgumentParser()
parser.add_argument('--chrome', action='store_true')
parser.add_argument('--firefox', action='store_true')
flags = parser.parse_args()
if flags.firefox:
driver = webdriver.Firefox()
else:
driver = webdriver.Chrome()
def tearDownModule():
driver.close()
class Page(object):
def __init__(self):
driver.get('file://{}/index.html#testing'.format(os.getcwd()))
self._main_page = driver.find_element_by_id('mainPage')
self._account_password_page = driver.find_element_by_id('accountPasswordPage')
self._nickname = driver.find_element_by_id('nickname')
self._master_password = driver.find_element_by_id('masterPassword')
self._new_nickname = driver.find_element_by_id('newNickname')
self._master_password2 = driver.find_element_by_id(
'validateMasterPassword')
self._create_button = driver.find_element_by_id('createAccountPassword')
self._account_password = driver.find_element_by_id('accountPassword')
@property
def nickname(self):
return self._nickname.get_attribute('value')
@nickname.setter
def nickname(self, value):
self._nickname.send_keys(value)
@property
def master_password(self):
return self._master_password.get_attribute('value')
@master_password.setter
def master_password(self, value):
self._master_password.send_keys(value)
@property
def new_nickname(self):
return self._new_nickname.get_attribute('checked') == 'true'
@new_nickname.setter
def new_nickname(self, value):
if value:
self._new_nickname.send_keys(' ')
else:
raise ValueError('cannot turn off checkbox')
@property
def master_password2(self):
return self._master_password2.get_attribute('value')
@master_password2.setter
def master_password2(self, value):
self._master_password2.send_keys(value)
@property
def account_password(self):
return self._account_password.get_attribute('value')
def create_account_password(self):
self._create_button.click()
return self.account_password
class AlgorithmTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
with open('selenium/testdata.json') as file:
cls.test_data = json.load(file)
def test_algorithm(self):
for test in self.test_data:
page = Page()
page.nickname = test['label']
page.master_password = test['master']
account_password = page.create_account_password()
self.assertEqual(test['password'], account_password, test['why'])
class UXTest(unittest.TestCase):
nickname = 'nickname'
master_password = 'master password'
account_password = '7CsZ--jK'
def setUp(self):
self.page = Page()
def _verify_no_master_passwords(self):
"""Check that no master password fields contain data."""
self.assertFalse(self.page.master_password)
self.assertFalse(self.page.master_password2)
def verify_success(self):
"""Check that after a successful creation of an account password that
sensitive data has been cleared."""
self.assertFalse(self.page.nickname)
self._verify_no_master_passwords()
self.assertTrue(self.page.account_password)
self.assertFalse(self.page._main_page.is_displayed())
self.assertTrue(self.page._account_password_page.is_displayed())
def verify_failure(self):
"""Check that after a failed attempt to create an account password there
are no master password fields filled."""
self.assertTrue(self.page.nickname)
self._verify_no_master_passwords()
self.assertFalse(self.page.account_password)
self.assertTrue(self.page._main_page.is_displayed())
self.assertFalse(self.page._account_password_page.is_displayed())
def test_new_nickname_click(self):
"""Check that the UI is in the expected state when choosing to make a
new nickname."""
self.assertTrue(self.page._new_nickname.is_displayed())
self.assertFalse(self.page._master_password2.is_displayed())
self.page.new_nickname = True
self.assertFalse(self.page._new_nickname.is_displayed())
self.assertTrue(self.page._master_password2.is_displayed())
def test_typical(self):
"""Nick + Master = Account"""
self.page.nickname = self.nickname
self.page.master_password = self.master_password
found = self.page.create_account_password()
self.assertEqual(self.account_password, found)
self.verify_success()
def test_new_nickname(self):
"""Nick + Master + New + Master2 = Account"""
self.page.nickname = self.nickname
self.page.master_password = self.master_password
self.page.new_nickname = True
self.page.master_password2 = self.master_password
found = self.page.create_account_password()
self.assertEqual(self.account_password, found)
self.verify_success()
def test_bad_master(self):
"""Nick +!Master + New + Master2 = ERROR"""
self.page.nickname = self.nickname
self.page.master_password = self.master_password
self.page.new_nickname = True
self.page.master_password2 = self.master_password + '!'
found = self.page.create_account_password()
self.assertEqual('', found)
self.verify_failure()
self.assertFalse(self.page._new_nickname.is_displayed())
self.assertTrue(self.page._master_password2.is_displayed())
def test_bad_master_then_good(self):
"""Nick + !Master + New + Master2 + Master = Account"""
self.test_bad_master()
self.page.master_password = self.master_password
self.page.master_password2 = self.master_password
found = self.page.create_account_password()
self.assertEqual(self.account_password, found)
self.verify_success()
if __name__ == '__main__':
loader = unittest.defaultTestLoader
suite = loader.loadTestsFromName('__main__')
unittest.TextTestRunner().run(suite)
|
#if NET5_0 || NET5_0_OR_GREATER
using System.Numerics;
using System.Runtime.CompilerServices;
#endif
namespace K4os.Data.TimSort.Internals
{
/// <summary>
/// All the bit hacks needed for quick integer math.
/// See: https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn
/// </summary>
public static class BitTwiddlingHacks
{
#if NET5_0 || NET5_0_OR_GREATER
/// <summary>Calculates log2(n) of given integer value.</summary>
/// <param name="n">Value of n.</param>
/// <returns>Log2(n).</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Log2(uint n) => BitOperations.Log2(n);
#else
private static readonly int[] MultiplyDeBruijnBitPosition = {
0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31,
};
/// <summary>Calculates log2(n) of given integer value.</summary>
/// <param name="n">Value of n.</param>
/// <returns>Log2(n).</returns>
public static int Log2(uint n)
{
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return MultiplyDeBruijnBitPosition[n * 0x07C4ACDDu >> 27];
}
#endif
}
}
|
<?php
namespace think\middleware\throttle;
use Psr\SimpleCache\CacheInterface;
/**
* 计数器滑动窗口算法
* Class CouterSlider
* @package think\middleware\throttle
*/
class CounterSlider extends ThrottleAbstract
{
public function allowRequest(string $key, float $micronow, int $max_requests, int $duration, CacheInterface $cache): bool
{
$history = $cache->get($key, []);
$now = (int) $micronow;
// 移除过期的请求的记录
$history = array_values(array_filter($history, function ($val) use ($now, $duration) {
return $val >= $now - $duration;
}));
$this->cur_requests = count($history);
if ($this->cur_requests < $max_requests) {
// 允许访问
$history[] = $now;
$cache->set($key, $history, $duration);
return true;
}
if ($history) {
$wait_seconds = $duration - ($now - $history[0]) + 1;
$this->wait_seconds = $wait_seconds > 0 ? $wait_seconds : 0;
}
return false;
}
}
|
<#
.SYNOPSIS
Restores Azure v2 ARM virtual machines from a backup VHD location.
Does not work with VMs configured with managed disks because they allow snapshots.
Requires AzureRM module version 4.2.1 or later.
.DESCRIPTION
Copies VHD files from a backup location - from using the associated script Backup-AzureRMvm.ps1. Since VHDs have a lease on them
from being attached to a VM, the VM must first be deleted. The VHD is copied over the original location and then the VM
is recreated using the same configuration.
VMs must be shutdown prior to running this script. It will halt if they are still running.
.EXAMPLE
.\Restore-AzureRMvm.ps1 -ResourceGroupName 'CONTOSO'
.EXAMPLE
.\Restore-AzureRMvm.ps1 -ResourceGroupName 'CONTOSO' -BackupContainer 'vhd-backups-9021' -VhdContainer 'MyVMs'
.PARAMETER -ResourceGroupName [string]
Name of resource group being copied
.PARAMETER -BackupContainer [string]
Name of container that holds the backup VHD blobs
.PARAMETER -VhdContainer [string]
Name of container that will hold VHD blobs attached to VMs
.PARAMETER -Environment [string]
Name of Environment e.g. AzureUSGovernment. Defaults to AzureCloud
.NOTES
Original Author: https://github.com/JeffBow
------------------------------------------------------------------------
Copyright (C) 2016 Microsoft Corporation
You have a royalty-free right to use, modify, reproduce and distribute
this sample script (and/or any modified version) in any way
you find useful, provided that you agree that Microsoft has no warranty,
obligations or liability for any sample application or script files.
------------------------------------------------------------------------
#>
#Requires -Version 4.0
param(
[Parameter(Mandatory=$true)]
[string]$ResourceGroupName,
[Parameter(Mandatory=$false)]
[string]$BackupContainer= 'vhd-backups',
[Parameter(Mandatory=$false)]
[string]$VhdContainer= 'vhds',
[Parameter(Mandatory=$false)]
[string]$Environment= "AzureCloud"
)
$ProgressPreference = 'SilentlyContinue'
$resourceGroupVMjsonPath = "$env:TEMP\$ResourceGroupName.resourceGroupVMs.json"
import-module AzureRM
if ((Get-Module AzureRM).Version -lt "4.2.1") {
Write-warning "Old version of Azure PowerShell module $((Get-Module AzureRM).Version.ToString()) detected. Minimum of 4.2.1 required. Run Update-Module AzureRM"
BREAK
}
<###############################
Get Storage Context function
################################>
function Get-StorageObject
{ param($resourceGroupName, $srcURI)
$split = $srcURI.Split('/')
$strgDNS = $split[2]
$splitDNS = $strgDNS.Split('.')
$storageAccountName = $splitDNS[0]
$StorageAccountKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $resourceGroupName -Name $StorageAccountName).Value[0]
$StorageContext = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey
return $StorageContext
} # end of Get-StorageObject function
<###############################
Copy blob function
################################>
function copy-azureBlob
{ param($srcUri, $srcContext, $destContext, $containerName)
$split = $srcURI.Split('/')
$blobName = $split[($split.count -1)]
$blobSplit = $blobName.Split('.')
$extension = $blobSplit[($blobSplit.count -1)]
if($($extension.tolower()) -eq 'status' ){Write-Output "Status file blob $blobname skipped";return}
if(! $containerName){$containerName = $split[3]}
# add full path back to blobname
if($split.count -gt 5)
{
$i = 4
do
{
$path = $path + "/" + $split[$i]
$i++
}
while($i -lt $split.length -1)
$blobName= $path + '/' + $blobName
$blobName = $blobName.Trim()
$blobName = $blobName.Substring(1, $blobName.Length-1)
}
# create container if doesn't exist
if (!(Get-AzureStorageContainer -Context $destContext -Name $containerName -ea SilentlyContinue))
{
try
{
$newRtn = New-AzureStorageContainer -Context $destContext -Name $containerName -Permission Off -ea Stop
Write-Output "Container $($newRtn.name) was created."
}
catch
{
$_ ; break
}
}
try
{
$blobCopy = Start-AzureStorageBlobCopy `
-srcUri $srcUri `
-SrcContext $srcContext `
-DestContainer $containerName `
-DestBlob $blobName `
-DestContext $destContext `
-Force -ea Stop
write-output "$srcUri is being copied to $containerName"
}
catch
{
$_ ; write-warning "Failed to copy to $srcUri to $containerName"
}
} # end of copy-azureBlob function
# get Azure creds
write-host "Enter credentials for your Azure Subscription..." -F Yellow
$login= Connect-AzureRmAccount -EnvironmentName $Environment
$loginID = $login.context.account.id
$sub = Get-AzureRmSubscription
$SubscriptionId = $sub.Id
# check for multiple subs under same account and force user to pick one
if($sub.count -gt 1) {
$SubscriptionId = (Get-AzureRmSubscription | select * | Out-GridView -title "Select Target Subscription" -OutputMode Single).Id
Select-AzureRmSubscription -SubscriptionId $SubscriptionId| Out-Null
$sub = Get-AzureRmSubscription -SubscriptionId $SubscriptionId
$SubscriptionId = $sub.Id
}
# check for valid sub
if(! $SubscriptionId)
{
write-warning "The provided credentials failed to authenticate or are not associcated to a valid subscription. Exiting the script."
break
}
write-verbose "Logged into $($sub.Name) with subscriptionID $SubscriptionId as $loginID" -verbose
# check for valid source resource group
if(-not ($sourceResourceGroup = Get-AzureRmResourceGroup -ResourceGroupName $resourceGroupName))
{
write-warning "The provided resource group $resourceGroupName could not be found. Exiting the script."
break
}
# get configuration details for all VMs
[string] $location = $sourceResourceGroup.location
$resourceGroupVMs = Get-AzureRMVM -ResourceGroupName $resourceGroupName
if(! $resourceGroupVMs){write-warning "No virtual machines found in resource group $resourceGroupName"; break}
$resourceGroupVMs | %{
$status = ((get-azurermvm -ResourceGroupName $resourceGroupName -Name $_.name -status).Statuses|where{$_.Code -like 'PowerState*'}).DisplayStatus
write-output "$($_.name) status is $status"
if($status -eq 'VM running'){write-warning "All virtual machines in this resource group are not stopped. Please stop all VMs and try again"; break}
}
#save off VM config to temp drive for drive
$resourceGroupVMs | ConvertTo-Json -depth 10 | Out-File $resourceGroupVMjsonPath
# remove each VM, copy in new copy of disk and recreate the VM
foreach($srcVM in $resourceGroupVMs)
{
# get source VM attributes
$VMName = $srcVM.Name
$VMSize = $srcVM.HardwareProfile.VMSize
$OSDiskName = $srcVM.StorageProfile.OsDisk.Name
$OSType = $srcVM.storageprofile.osdisk.OsType
$OSDiskCaching = $srcVM.StorageProfile.OsDisk.Caching
$avSetRef = ($srcVM.AvailabilitySetReference.id).Split('/')
$avSetName = $avSetRef[($avSetRef.count -1)]
$AvailabilitySet = Get-AzureRmAvailabilitySet -ResourceGroupName $ResourceGroupName -Name $avSetName
$CreateOption = "Attach"
# remove VM
write-verbose "Restoring Virtual Machine $vmName" -verbose
try
{
Remove-AzureRmVM -Name $vmName -ResourceGroupName $resourceGroupName -Force -ea Stop | out-null
write-output "Removed $vmName"
}
catch
{
$_
Write-Warning "Failed to remove Virtual Machine $vmName"
break
}
# over-write existing disk from backup location
# get storage account context from $srcVM.storageprofile.osdisk.vhd.uri
$OSDiskUri = $null
$OSDiskUri = $srcVM.storageprofile.osdisk.vhd.uri
$OSsplit = $OSDiskUri.Split('/')
$OSblobName = $OSsplit[($OSsplit.count -1)]
$OScontainerName = $OSsplit[3]
$OSstorageContext = Get-StorageObject -resourceGroupName $resourceGroupName -srcURI $OSDiskUri
$backupURI = $OSDiskUri.Replace($vhdContainer, $backupContainer)
copy-azureBlob -srcUri $backupURI -srcContext $OSstorageContext -destContext $OSstorageContext -containerName $vhdContainer
# check on copy status
do{
$rtn = $null
$rtn = Get-AzureStorageBlob -Context $OSstorageContext -container $OScontainerName -Blob $OSblobName | Get-AzureStorageBlobCopyState
$rtn | select Source, Status, BytesCopied, TotalBytes | fl
if($rtn.status -ne 'Success'){
write-verbose "Waiting for blob copy $OSblobName to complete" -verbose
Sleep 10
}
}
while($rtn.status -ne 'Success')
# exit script if user breaks out of above loop
if($rtn.status -ne 'Success'){EXIT}
# get the Network Interface Card we created previously based on the original source name
$NICRef = ($srcVM.NetworkInterfaceIDs).Split('/')
$NICName = $NICRef[($NICRef.count -1)]
$NIC = Get-AzureRmNetworkInterface -Name $NICName -ResourceGroupName $ResourceGroupName
# create VM Config
if($AvailabilitySet)
{
$VirtualMachine = New-AzureRmVMConfig -VMName $VMName -VMSize $VMSize -AvailabilitySetID $AvailabilitySet.Id -wa SilentlyContinue
}
else
{
$VirtualMachine = New-AzureRmVMConfig -VMName $VMName -VMSize $VMSize -wa SilentlyContinue
}
# Set OS Disk based on OS type
if($OStype -eq 'Windows' -or $OStype -eq '0'){
$VirtualMachine = Set-AzureRmVMOSDisk -VM $VirtualMachine -Name $OSDiskName -VhdUri $OSDiskUri -Caching $OSDiskCaching -CreateOption $createOption -Windows
}
else
{
$VirtualMachine = Set-AzureRmVMOSDisk -VM $VirtualMachine -Name $OSDiskName -VhdUri $OSDiskUri -Caching $OSDiskCaching -CreateOption $createOption -Linux
}
# add NIC
$VirtualMachine = Add-AzureRmVMNetworkInterface -VM $VirtualMachine -Id $NIC.Id
# copy and readd data disk if they were present
if($srcVM.storageProfile.datadisks)
{
foreach($disk in $srcVM.storageProfile.DataDisks)
{
$dataDiskName = $null
$dataDiskUri = $null
$diskBlobName = $null
$dataDiskName = $disk.Name
$dataDiskLUN = $disk.Lun
$diskCaching = $disk.Caching
$DiskSizeGB = $disk.DiskSizeGB
$dataDiskUri = $disk.vhd.uri
$split = $dataDiskUri.Split('/')
$diskBlobName = $split[($split.count -1)]
$diskContainerName = $split[3]
$diskStorageContext = Get-StorageObject -resourceGroupName $resourceGroupName -srcURI $dataDiskUri
$backupDiskURI = $dataDiskUri.Replace($vhdContainer, $backupContainer)
copy-azureBlob -srcUri $backupDiskURI -srcContext $diskStorageContext -destContext $diskStorageContext -containerName $vhdContainer
# check copy status
do
{
$drtn = $null
$drtn = Get-AzureStorageBlob -Context $diskStorageContext -container $diskContainerName -Blob $diskBlobName | Get-AzureStorageBlobCopyState
$drtn| select Source, Status, BytesCopied, TotalBytes|fl
if($rtn.status -ne 'Success')
{
write-verbose "Waiting for blob copy $diskBlobName to complete" -verbose
Sleep 10
}
}
while($drtn.status -ne 'Success')
# exit script if user breaks out of above loop
if($rtn.status -ne 'Success'){EXIT}
Add-AzureRmVMDataDisk -VM $VirtualMachine -Name $dataDiskName -DiskSizeInGB $DiskSizeGB -Lun $dataDiskLUN -VhdUri $dataDiskUri -Caching $diskCaching -CreateOption $CreateOption | out-null
}
}
# create the VM from the config
try
{
write-verbose "Recreating Virtual Machine $VMName in resource group $resourceGroupName at location $location" -verbose
# $VirtualMachine
New-AzureRmVM -ResourceGroupName $ResourceGroupName -Location $location -VM $VirtualMachine -ea Stop -wa SilentlyContinue | out-null
write-output "Successfully recreated Virtual Machine $VMName"
}
catch
{
$_
write-warning "Failed to create Virtual Machine $VMName"
}
}
|
<?php
namespace Symfony\Cmf\Bundle\CoreBundle\Slugifier;
/**
* @deprecated Since 1.0, to be removed in 2.0. Use Symfony\Cmf\Api\Slugifier\SlugifierInterface instead.
*/
interface SlugifierInterface
{
/**
* Return a slugified (or urlized) representation of a given string.
*
* @param string $string
*
* @return string
*/
public function slugify($string);
}
|
import starkbank
from unittest import TestCase, main
from datetime import date, timedelta
from tests.utils.user import exampleProject
from tests.utils.taxPayment import generateExampleTaxPaymentsJson
from tests.utils.boletoPayment import generateExampleBoletoPaymentsJson
from tests.utils.brcodePayment import generateExampleBrcodePaymentsJson
from tests.utils.utilityPayment import generateExampleUtilityPaymentsJson
starkbank.user = exampleProject
class TestPaymentPreviewCreate(TestCase):
def test_success(self):
brcodePayment = generateExampleBrcodePaymentsJson(n=1)[0]
boletoPayment = generateExampleBoletoPaymentsJson(n=1)[0]
utilityPayment = generateExampleUtilityPaymentsJson(n=1)[0]
taxPayment = generateExampleTaxPaymentsJson(n=1)[0]
types = ["brcode-payment", "boleto-payment", "utility-payment", "tax-payment"]
previews = [
starkbank.PaymentPreview(id=brcodePayment.brcode),
starkbank.PaymentPreview(id=boletoPayment.bar_code or boletoPayment.line),
starkbank.PaymentPreview(id=utilityPayment.bar_code or utilityPayment.line),
starkbank.PaymentPreview(id=taxPayment.bar_code or taxPayment.line),
]
previewedTypes = []
for preview in starkbank.paymentpreview.create(previews=previews):
print(preview)
previewedTypes.append(preview.type)
self.assertEqual(types, previewedTypes)
for preview in previews:
preview.scheduled = date.today() + timedelta(days=100)
previewedTypes = []
for preview in starkbank.paymentpreview.create(previews=previews):
print(preview)
previewedTypes.append(preview.type)
self.assertEqual(types, previewedTypes)
if __name__ == '__main__':
main()
|
module Rx.Observable.DoTest where
import Data.IORef (atomicModifyIORef', newIORef, readIORef)
import qualified Rx.Observable as Rx
import Test.HUnit
import Test.Hspec
tests :: Spec
tests = do
describe "Rx.Observable.doOnCompleted" $
it "does a side effect when observable is completed" $ do
var <- newIORef (0 :: Int)
let source =
Rx.doOnCompleted (atomicModifyIORef' var (\v -> (v + 1, ())))
$ Rx.fromList Rx.currentThread ([1..10] :: [Int])
eResult <- Rx.toList source
case eResult of
Left err ->
assertFailure $ "received unexpected error: " ++ show err
Right _ -> do
result <- readIORef var
assertEqual "doOnCompleted wasn't called exactly once"
(1 :: Int)
result
describe "Rx.Observable.doOnError" $
it "does a side effect when an error happens" $ do
var <- newIORef (0 :: Int)
let source =
Rx.doOnError (const $ atomicModifyIORef' var (\v -> (v + 1, ())))
$ do v <- Rx.fromList Rx.newThread ([1..10] :: [Int])
if (v > 5) then fail "value greater than 5" else return v
eResult <- Rx.toList source
case eResult of
Right _ -> assertFailure "Didn't receive expected error"
Left _ -> do
result <- readIORef var
assertEqual "doOnError wasn't called exactly once"
1
result
describe "Rx.Observable.doAction" $
it "performs side effect per element" $ do
var <- newIORef []
let source =
Rx.doAction (\v -> atomicModifyIORef' var (\acc -> (v : acc, ())))
$ Rx.fromList Rx.newThread ([1..10] :: [Int])
eResult <- Rx.toList source
case eResult of
Left err ->
assertFailure $
"Received unexpected error: " ++ show err
Right _ -> do
acc <- readIORef var
assertEqual "side-effects didn't happen"
[1..10]
(reverse acc)
|
package br.ufs.hiring.stone.domain.tests
import br.ufs.architecture.core.errors.InfrastructureError.LocalDatabaseAccessError
import br.ufs.architecture.core.errors.NetworkingIssue.InternetUnreachable
import br.ufs.hiring.stone.domain.*
import com.nhaarman.mockito_kotlin.*
import io.reactivex.Observable
import org.junit.Before
import org.junit.Test
/**
*
* Created by @ubiratanfsoares
*
*/
class HomeInformationCoordinatorTests {
lateinit var persister: OfflineHomeSupport
lateinit var updater: RetrieveHomeInformation
lateinit var coordinator: HomeInformationCoordinator
@Before fun `before each test`() {
persister = mock()
updater = mock()
coordinator = HomeInformationCoordinator(persister, updater)
}
@Test fun `at first access, should cache lastest information for home screen`() {
`no previous information stored on local database`()
`home information retrieved from remote`()
`actual data will be saved into database`()
coordinator.lastInformationAvailable()
.test()
.assertComplete()
.assertNoErrors()
`verify cache accessed only once`()
`verify information stored only once`()
`attempt to fetch remote only once`()
`no more interactions`()
}
@Test fun `at returning access, shows cached information first and updated information after`() {
`previous information cached`()
`home information retrieved from remote`()
`actual data will be saved into database`()
coordinator.lastInformationAvailable()
.test()
.assertComplete()
.assertNoErrors()
.assertValueCount(2)
`verify cache accessed only once`()
`verify information stored only once`()
`attempt to fetch remote only once`()
`no more interactions`()
}
@Test fun `at returning access, shows cached information and forward error from remote`() {
`previous information cached`()
`gathering home information from remote fails`()
coordinator.lastInformationAvailable()
.test()
.assertError { it == InternetUnreachable }
`verify cache accessed only once`()
`attempt to fetch remote only once`()
`verify no attempts to store information`()
`no more interactions`()
}
@Test fun `at returning access, overrides broken cache with new state information`() {
`previous information corrupted`()
`home information retrieved from remote`()
coordinator.lastInformationAvailable()
.test()
.assertComplete()
.assertNoErrors()
`verify cache accessed only once`()
`attempt to fetch remote only once`()
`verify information stored only once`()
`no more interactions`()
}
private fun `no more interactions`() {
verifyNoMoreInteractions(persister)
verifyNoMoreInteractions(updater)
}
private fun `attempt to fetch remote only once`() {
verify(updater, times(1)).execute()
}
private fun `verify information stored only once`() {
verify(persister, times(1)).save(any())
}
private fun `verify no attempts to store information`() {
verify(persister, never()).save(any())
}
private fun `verify cache accessed only once`() {
verify(persister, times(1)).previousInformation()
}
private fun `actual data will be saved into database`() {
whenever(persister.save(any())).thenAnswer { Unit }
}
private fun `home information retrieved from remote`() {
whenever(updater.execute()).thenReturn(homeInformationFromRemote())
}
private fun `gathering home information from remote fails`() {
whenever(updater.execute()).thenReturn(noInternet())
}
private fun `no previous information stored on local database`() {
whenever(persister.previousInformation()).thenReturn(Observable.empty())
}
private fun `previous information cached`() {
whenever(persister.previousInformation()).thenReturn(homeInformationFromLocal())
}
private fun `previous information corrupted`() {
whenever(persister.previousInformation()).thenReturn(brokenCache())
}
private fun homeInformationFromRemote() = Observable.just(
HomeInformation(
brokings = emptyList(),
savings = emptyList(),
transactions = emptyList()
)
)
private fun homeInformationFromLocal() = Observable.just(
HomeInformation(
brokings = listOf(
BrokingInformation(Currency.Brita, 3.3f, 3.3f)
),
savings = emptyList(),
transactions = emptyList()
)
)
private fun noInternet() = Observable.error<HomeInformation>(InternetUnreachable)
private fun brokenCache() = Observable.error<HomeInformation>(LocalDatabaseAccessError)
}
|
import reduce from 'lodash/reduce'
import { load } from './load'
import { UserFnMapInput, LoadingMapState } from '../../types'
const loadMap = (map: UserFnMapInput): LoadingMapState => {
const state: Omit<LoadingMapState, 'promise'> & { [name: string]: any } = {
loading: true,
loaded: {},
error: null,
}
const promises = reduce(
map,
(acc, val, key) => {
const result = load(val, true)
const promise = result.promise
.then((loaded) => {
state.loaded[key] = loaded
return loaded
})
.catch((err) => {
state.loaded[key] = null
state.error = err
})
acc.push(promise)
return acc
},
[] as Promise<any>[]
)
state.promise = Promise.all(promises)
.then((results) => {
state.loading = false
return results
})
.catch((err) => {
state.loading = false
state.error = err
})
return state as LoadingMapState
}
export { loadMap }
|
/*
* Copyright (c) 2019.
* Neato Robotics Inc.
*/
package com.neatorobotics.sdk.android.robotservices.spotcleaning
import com.neatorobotics.sdk.android.robotservices.RobotServices
object SpotCleaningServiceFactory {
fun get(serviceVersion: String): SpotCleaningService? {
return when {
RobotServices.VERSION_BASIC_1.equals(serviceVersion, ignoreCase = true) -> SpotCleaningBasic1Service()
RobotServices.VERSION_BASIC_3.equals(serviceVersion, ignoreCase = true) -> SpotCleaningBasic3Service()
RobotServices.VERSION_MINIMAL_2.equals(serviceVersion, ignoreCase = true) -> SpotCleaningMinimal2Service()
RobotServices.VERSION_MICRO_2.equals(serviceVersion, ignoreCase = true) -> SpotCleaningMicro2Service()
else -> null
}
}
}
|
#![no_std]
#![no_main]
extern crate metro_m0 as hal;
extern crate panic_rtt;
use cortex_m_rt::{exception, ExceptionFrame};
use hal::clock::GenericClockController;
use hal::hal::usb::usb_device::bus::UsbBusWrapper;
use hal::hal::usb::usb_device::prelude::*;
use hal::prelude::*;
use hal::{dbgprint, entry};
use hal::{interrupt, CorePeripherals, Peripherals};
static mut USB_BUS: Option<UsbBusWrapper<hal::UsbBus>> = None;
static mut USB_DEV: Option<UsbDevice<hal::UsbBus>> = None;
static mut USB_SERIAL: Option<cdc_acm::SerialPort<hal::UsbBus>> = None;
// Minimal CDC-ACM implementation
mod cdc_acm {
use core::cmp::min;
use hal::hal::usb::usb_device::class_prelude::*;
use hal::hal::usb::usb_device::utils::AtomicMutex;
use hal::hal::usb::usb_device::Result;
pub const USB_CLASS_CDC: u8 = 0x02;
const USB_CLASS_DATA: u8 = 0x0a;
const CDC_SUBCLASS_ACM: u8 = 0x02;
const CDC_PROTOCOL_AT: u8 = 0x01;
const CS_INTERFACE: u8 = 0x24;
const CDC_TYPE_HEADER: u8 = 0x00;
const CDC_TYPE_CALL_MANAGEMENT: u8 = 0x01;
const CDC_TYPE_ACM: u8 = 0x02;
const CDC_TYPE_UNION: u8 = 0x06;
const REQ_SET_LINE_CODING: u8 = 0x20;
const REQ_SET_CONTROL_LINE_STATE: u8 = 0x22;
const BUFSIZ: usize = 16;
struct Buf {
buf: [u8; BUFSIZ],
len: usize,
}
pub struct SerialPort<'a, B: 'a + UsbBus + Sync> {
comm_if: InterfaceNumber,
comm_ep: EndpointIn<'a, B>,
data_if: InterfaceNumber,
read_ep: EndpointOut<'a, B>,
write_ep: EndpointIn<'a, B>,
read_buf: AtomicMutex<Buf>,
}
impl<'a, B: UsbBus + Sync> SerialPort<'a, B> {
pub fn new(bus: &'a UsbBusWrapper<B>) -> SerialPort<'a, B> {
SerialPort {
comm_if: bus.interface(),
comm_ep: bus.interrupt(8, 255),
data_if: bus.interface(),
read_ep: bus.bulk(BUFSIZ as u16),
write_ep: bus.bulk(BUFSIZ as u16),
read_buf: AtomicMutex::new(Buf {
buf: [0; BUFSIZ],
len: 0,
}),
}
}
pub fn write(&self, data: &[u8]) -> Result<usize> {
match self.write_ep.write(data) {
Ok(count) => Ok(count),
Err(UsbError::Busy) => Ok(0),
e => e,
}
}
pub fn read(&self, data: &mut [u8]) -> Result<usize> {
let mut guard = self.read_buf.try_lock();
let buf = match guard {
Some(ref mut buf) => buf,
None => return Ok(0),
};
// Terrible buffering implementation for brevity's sake
if buf.len == 0 {
buf.len = match self.read_ep.read(&mut buf.buf) {
Ok(count) => count,
Err(UsbError::NoData) => return Ok(0),
e => return e,
};
}
if buf.len == 0 {
return Ok(0);
}
let count = min(data.len(), buf.len);
&data[..count].copy_from_slice(&buf.buf[0..count]);
buf.buf.rotate_left(count);
buf.len -= count;
Ok(count)
}
}
impl<'a, B: UsbBus + Sync> UsbClass for SerialPort<'a, B> {
fn get_configuration_descriptors(&self, writer: &mut DescriptorWriter) -> Result<()> {
// TODO: make a better DescriptorWriter to make it harder to make invalid
// descriptors
writer.interface(
self.comm_if,
1,
USB_CLASS_CDC,
CDC_SUBCLASS_ACM,
CDC_PROTOCOL_AT,
)?;
writer.write(CS_INTERFACE, &[CDC_TYPE_HEADER, 0x10, 0x01])?;
writer.write(
CS_INTERFACE,
&[CDC_TYPE_CALL_MANAGEMENT, 0x00, self.data_if.into()],
)?;
writer.write(CS_INTERFACE, &[CDC_TYPE_ACM, 0x00])?;
writer.write(
CS_INTERFACE,
&[CDC_TYPE_UNION, self.comm_if.into(), self.data_if.into()],
)?;
writer.endpoint(&self.comm_ep)?;
writer.interface(self.data_if, 2, USB_CLASS_DATA, 0x00, 0x00)?;
writer.endpoint(&self.write_ep)?;
writer.endpoint(&self.read_ep)?;
Ok(())
}
fn control_out(&self, req: &control::Request, buf: &[u8]) -> ControlOutResult {
let _ = buf;
if req.request_type == control::RequestType::Class
&& req.recipient == control::Recipient::Interface
{
return match req.request {
REQ_SET_LINE_CODING => ControlOutResult::Ok,
REQ_SET_CONTROL_LINE_STATE => ControlOutResult::Ok,
_ => ControlOutResult::Ignore,
};
}
ControlOutResult::Ignore
}
}
}
#[entry]
fn main() -> ! {
dbgprint!("main entered");
let mut peripherals = Peripherals::take().unwrap();
let mut clocks = GenericClockController::with_external_32kosc(
peripherals.GCLK,
&mut peripherals.PM,
&mut peripherals.SYSCTRL,
&mut peripherals.NVMCTRL,
);
let mut pins = hal::Pins::new(peripherals.PORT);
let mut core = CorePeripherals::take().unwrap();
/* let mut delay = Delay::new(core.SYST, &mut clocks);
*/
let mut red_led = pins.d13.into_open_drain_output(&mut pins.port);
red_led.set_high();
dbgprint!("make usb_bus");
let bus = unsafe {
USB_BUS = Some(hal::usb_bus(
peripherals.USB,
&mut clocks,
&mut peripherals.PM,
pins.usb_dm,
pins.usb_dp,
&mut pins.port,
));
USB_BUS.as_ref().unwrap()
};
dbgprint!("make serial");
let serial = unsafe {
USB_SERIAL = Some(cdc_acm::SerialPort::new(bus));
USB_SERIAL.as_ref().unwrap()
};
dbgprint!("make dev");
unsafe {
USB_DEV = Some(
UsbDevice::new(bus, UsbVidPid(0x5824, 0x27dd))
.manufacturer("Wez Furlong")
.product("Serial port")
.serial_number("RUST")
.device_class(cdc_acm::USB_CLASS_CDC)
.build(&[serial]),
);
}
unsafe {
core.NVIC.set_priority(hal::Interrupt::USB, 0);
}
core.NVIC.enable(hal::Interrupt::USB);
dbgprint!("do loop");
loop {}
}
fn poll_usb() {
unsafe { USB_DEV.as_ref() }.map(|dev| {
dev.poll();
if dev.state() == UsbDeviceState::Configured {
let mut buf = [0u8; 8];
let serial = unsafe { USB_SERIAL.as_ref().unwrap() };
match serial.read(&mut buf) {
Ok(count) if count > 0 => {
// Echo back in upper case
for c in buf[0..count].iter_mut() {
if 0x61 <= *c && *c <= 0x7a {
*c &= !0x20;
}
}
serial.write(&buf[0..count]).ok();
}
_ => {}
}
}
});
}
#[exception]
fn HardFault(ef: &ExceptionFrame) -> ! {
dbgprint!("hard_fault");
panic!("{:#?}", ef);
}
#[interrupt]
fn USB() {
poll_usb();
}
#[exception]
fn DefaultHandler(irqn: i16) {
dbgprint!("default_handler");
panic!("Unhandled exception (IRQn = {})", irqn);
}
|
#
# Cookbook:: push-jobs
# resource:: service_sysvinit
#
# Author:: Jennifer Davis <sigje@chef.io>
# Copyright:: 2017, Chef Software, Inc.
#
resource_name :push_jobs_service_sysvinit
provides :push_jobs_service, platform: 'debian' do |node|
node['platform_version'].to_i == 7
end
provides :push_jobs_service, platform: 'suse' do |node|
node['platform_version'].to_i < 12
end
action :start do
delete_runit
create_init
service 'chef-push-jobs-client' do
supports restart: true, status: true
action :start
subscribes :restart, "template[#{PushJobsHelper.config_path}]"
end
end
action :stop do
service 'chef-push-jobs-client' do
supports status: true
action :stop
only_if { ::File.exist?('/etc/init.d/chef-push-jobs-client.conf') }
end
end
action :restart do
service 'chef-push-jobs-client' do
supports restart: true, status: true
action :restart
end
end
action :enable do
create_init
service 'chef-push-jobs-client' do
supports status: true
action :enable
only_if { ::File.exist?('/etc/init.d/chef-push-jobs-client') }
subscribes :restart, "template[#{PushJobsHelper.config_path}]"
end
end
action :disable do
service 'chef-push-jobs-client' do
supports status: true
action :disable
only_if { ::File.exist?('/etc/init.d/chef-push-jobs-client.conf') }
end
end
action_class do
def create_init
include_recipe 'push-jobs::package'
platform_lock_dir = value_for_platform_family(
%w(rhel fedora suse amazon) => '/var/lock/subsys',
'debian' => '/var/lock',
'default' => '/var/lock'
)
package 'redhat-lsb-core' if platform_family?('rhel', 'fedora', 'amazon')
template '/etc/init.d/chef-push-jobs-client' do
mode '0755'
source 'init_sysv.erb'
cookbook 'push-jobs'
variables(
cli_command: PushJobsHelper.cli_command(node),
lock_dir: platform_lock_dir,
log_dir: "#{node['push_jobs']['logging_dir']}/push-jobs-client.log"
)
notifies :restart, 'service[chef-push-jobs-client]', :immediately
end
end
def delete_runit
return unless ::File.exist?('/etc/sv/opscode-push-jobs-client/run')
# disable the old service
runit_service 'opscode-push-jobs-client' do
action [:stop, :disable]
not_if { ::File.zero?('/etc/sv/opscode-push-jobs-client/supervise/pid') }
end
# remove the old service configs
directory '/etc/sv/opscode-push-jobs-client' do
recursive true
action :delete
end
# remove old init script link
file '/etc/init.d/opscode-push-jobs-client' do
action :delete
end
end
end
|
{-# language DataKinds #-}
{-# language KindSignatures #-}
{-# language GADTs #-}
{-# language TypeFamilies #-}
module Lib where
-- A marking on the game board is either X, O, or empty
data Mark = X | O | E
deriving (Show)
-- A row on the game board
data Row = Row Mark Mark Mark
deriving (Show)
-- Coordinates for rows and columns
data CoordType = First | Second | Third
-- A type-level representation of previous moves
data PreviousMoves = Empty | Cons Mark CoordType CoordType PreviousMoves
-- The game board state consists of the board and all previous moves
data Board (prev :: PreviousMoves) = Board Row Row Row
-- New empty game board with no previous moves
newBoard :: Board Empty
newBoard = Board (Row E E E) (Row E E E) (Row E E E)
-- String representation for the game board
instance Show (Board prev) where
show (Board r1 r2 r3) = show r1 ++ "\n" ++ show r2 ++ "\n" ++ show r3 ++ "\n"
-- Make a play in a row
playRow :: Mark -> CoordType -> Row -> Row
playRow move col (Row c1 c2 c3) =
case col of
First -> Row move c2 c3
Second -> Row c1 move c3
Third -> Row c1 c2 move
-- Given a sequence of previous moves, determine whose turn is next
-- This is a type-level function PreviousMoves -> Mark
type family NextTurn (prev :: PreviousMoves) :: Mark where
NextTurn (Cons 'X _ _ _) = 'O
NextTurn (Cons 'O _ _ _) = 'X
NextTurn Empty = 'X -- assume X plays first
-- Given a sequence of previous moves, determine if a position has been played already
type family Played (row :: CoordType) (col :: CoordType) (prev :: PreviousMoves) :: Bool where
Played _ _ 'Empty = 'False
Played row col ('Cons _ row col _) = 'True
Played row col ('Cons _ _ _ prev) = Played row col prev
-- Lift our Coord type up to a Coord "kind". Allows us to use coordinates at the type
-- level, which is required to describe previous moves
data CoordKind (a :: CoordType) where
First' :: CoordKind 'First
Second' :: CoordKind 'Second
Third' :: CoordKind 'Third
-- Lower a *type* in the Coord kind back down to a *term* in the Coord type
-- Note: in a full dependently typed language like Idris, we don't have to care about
-- the difference between terms, types, and kinds anymore
coordVal :: CoordKind a -> CoordType
coordVal First' = First
coordVal Second' = Second
coordVal Third' = Third
-- If the position was not already played, and player X has next turn, allow a play
-- that updates the board with an X
xPlay :: (Played row col prev ~ 'False, NextTurn prev ~ 'X) =>
(CoordKind row, CoordKind col) -> Board prev -> Board ('Cons 'X row col prev)
xPlay (row, col) (Board r1 r2 r3) =
let (valRow, valCol) = (coordVal row, coordVal col)
in case valRow of
First -> Board (playRow X valCol r1) r2 r3
Second -> Board r1 (playRow X valCol r2) r3
Third -> Board r1 r2 (playRow X valCol r3)
-- If the position was not already played, and player O has next turn, allow a play
-- that updates the board with an O
oPlay :: (Played row col prev ~ 'False, NextTurn prev ~ 'O) =>
(CoordKind row, CoordKind col) -> Board prev -> Board ('Cons 'O row col prev)
oPlay (row, col) (Board r1 r2 r3) =
let (valRow, valCol) = (coordVal row, coordVal col)
in case valRow of
First -> Board (playRow O valCol r1) r2 r3
Second -> Board r1 (playRow O valCol r2) r3
Third -> Board r1 r2 (playRow O valCol r3)
-- Examples:
-- xPlay (First',First') newBoard
-- oPlay (First',First') newBoard
-- xPlay (First',First') (xPlay (Third',Second') newBoard) -- type error!
-- oPlay (First',First') $ xPlay (Third',Second') newBoard
-- oPlay (Third',Second') $ xPlay (Third',Second') newBoard
-- What we have so far:
-- Each board location must be one of: X, O, or E
-- Safe indexing into the board via coordinates
-- Enforce who moves first
-- Turns alternate between X and O players
-- Protection from repeated plays or overwrites of previous moves
-- What we don't have:
-- More turns not allowed even if a player has already won
|
# hacky hacky hacky -- generated by src/spec_gen.rb, then hand-tweaked
# this spec is only looking to check each ts_ call doesn't raise or crash and
# returns the right type, given acceptable args
describe "node_spec.rb" do
before do
end
it "type() # => String" do
ret = node_0.type()
ret.should_not == nil
ret.is_a?(String).should == true
end
it "symbol() # => Integer" do
ret = node_0.symbol()
ret.should_not == nil
ret.is_a?(Integer).should == true
end
it "start_byte() # => Integer" do
ret = node_0.start_byte()
ret.should_not == nil
ret.is_a?(Integer).should == true
end
it "start_point() # => Point" do
ret = node_0.start_point()
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Point).should == true
end
it "end_byte() # => Integer" do
ret = node_0.end_byte()
ret.should_not == nil
ret.is_a?(Integer).should == true
end
it "end_point() # => Point" do
ret = node_0.end_point()
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Point).should == true
end
it "string() # => Array" do
ret = node_0.string()
ret.should_not == nil
ret.is_a?(Array).should == true
end
it "is_null() # => :bool" do
ret = node_0.is_null()
[true, false].include?(ret).should == true
end
it "is_named() # => :bool" do
ret = node_0.is_named()
[true, false].include?(ret).should == true
end
it "is_missing() # => :bool" do
ret = node_0.is_missing()
[true, false].include?(ret).should == true
end
it "is_extra() # => :bool" do
ret = node_0.is_extra()
[true, false].include?(ret).should == true
end
it "has_changes() # => :bool" do
ret = node_0.has_changes()
[true, false].include?(ret).should == true
end
it "has_error() # => :bool" do
ret = node_0.has_error()
[true, false].include?(ret).should == true
end
it "parent() # => Node" do
ret = node_0.parent()
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "child(Integer) # => Node" do
ret = node_0.child(arg_1)
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "field_name_for_child(Integer) # => String" do
ret = node_0.field_name_for_child(arg_1)
ret.should_not == nil
ret.is_a?(String).should == true
end
it "child_count() # => Integer" do
ret = node_0.child_count()
ret.should_not == nil
ret.is_a?(Integer).should == true
end
it "named_child(Integer) # => Node" do
ret = node_0.named_child(arg_1)
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "named_child_count() # => Integer" do
ret = node_0.named_child_count()
ret.should_not == nil
ret.is_a?(Integer).should == true
end
it "child_by_field_name(String, Integer) # => Node" do
ret = node_0.child_by_field_name(arg_1, arg_2)
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "child_by_field_id(Integer) # => Node" do
ret = node_0.child_by_field_id(arg_1)
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "next_sibling() # => Node" do
ret = node_0.next_sibling()
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "prev_sibling() # => Node" do
ret = node_0.prev_sibling()
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "next_named_sibling() # => Node" do
ret = node_0.next_named_sibling()
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "prev_named_sibling() # => Node" do
ret = node_0.prev_named_sibling()
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "first_child_for_byte(Integer) # => Node" do
ret = node_0.first_child_for_byte(arg_1)
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "first_named_child_for_byte(Integer) # => Node" do
ret = node_0.first_named_child_for_byte(arg_1)
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "descendant_for_byte_range(Integer, Integer) # => Node" do
ret = node_0.descendant_for_byte_range(arg_1, arg_2)
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "descendant_for_point_range(Point, Point) # => Node" do
ret = node_0.descendant_for_point_range(arg_1, arg_2)
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "named_descendant_for_byte_range(Integer, Integer) # => Node" do
ret = node_0.named_descendant_for_byte_range(arg_1, arg_2)
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "named_descendant_for_point_range(Point, Point) # => Node" do
ret = node_0.named_descendant_for_point_range(arg_1, arg_2)
ret.should_not == nil
ret.is_a?(TreeSitterFFI::Node).should == true
end
it "edit(InputEdit) # => :void" do
ret = node_0.edit(arg_1)
# ret void
end
it "eq(Node) # => :bool" do
ret = node_0.eq(arg_1)
[true, false].include?(ret).should == true
end
end
|
#!/bin/bash
archive_path=/opt/tools/sum_1.6.0_Linux_x86_64_20160128.tar.gz
bin_path=/opt/tools/bin/sum
if [[ -x $bin_path ]]; then
echo "Supermicro Update Manager already installed"
elif ! [[ -f $archive_path ]]; then
echo "Missing $archive_path"
echo "Will not try to install Supermicro Update Manager"
else
tmpdir=$(mktemp -d "/tmp/sum-XXXXX")
(
cd "$tmpdir"
tar xzf "$archive_path"
mkdir -p /opt/tools/bin
cp */sum /opt/tools/bin
)
rm -rf $tmpdir
if ! [[ -x $bin_path ]]; then
echo "Failed to extract supermicro update manager binary"
sleep 300
exit 1
fi
fi
|
import * as api from '@app/api/_index';
import * as actionTypes from '@app/store-actions/action-types';
import * as types from '@app/types/_index';
const initialState: api.Mconfig[] = [];
export function mconfigsReducer(
state = initialState,
action: types.MconfigsActions
): api.Mconfig[] {
switch (action.type) {
case actionTypes.UPDATE_MCONFIGS_STATE: {
let newState = [...state];
action.payload.forEach(cv => {
let index = newState.findIndex(
mconfig => mconfig.mconfig_id === cv.mconfig_id
);
if (index >= 0) {
newState = [
...newState.slice(0, index),
cv,
...newState.slice(index + 1)
];
} else {
newState.push(cv);
}
});
return newState;
}
case actionTypes.RESET_MCONFIGS_STATE: {
return [...initialState];
}
case actionTypes.CLEAN_MCONFIGS_STATE: {
let newState = state.filter(
mconfig =>
mconfig.project_id !== action.payload.project_id ||
mconfig.repo_id !== action.payload.repo_id ||
mconfig.struct_id === action.payload.struct_id
);
return newState;
}
default: {
return state;
}
}
}
|
// ============================================================================
// Instruction-Level Abstraction of LeWiz Communications Ethernet MAC
//
// This Instruction-Level Abstraction (ILA) description is derived based on the
// LeWiz Communications Ethernet MAC (LMAC), which is licensed under GNU LGPL.
// Check "LICENSE" which comes with this distribution for more information.
// ============================================================================
//
// File Name: eqcheck.h
// Generate Verilog verification target for equivalence checking
// - SetVerifConfigs
// - GenVerifTarget
#ifndef LMAC_CORE2_EQCHECK_H__
#define LMAC_CORE2_EQCHECK_H__
#include <ilang/ilang++.h>
#include <ilang/vtarget-out/vtarget_gen.h>
namespace ilang {
// verilog generator configs
VerilogGeneratorBase::VlgGenConfig SetVlgGenConfig();
// verification target generator configs
VerilogVerificationTargetGenerator::vtg_config_t SetVerifGenConfig();
// generate Verilog verification target for reg instr
void GenVerifTargetReg(Ila& model, const std::string& design_path,
const std::string& instr_map, const std::string& var_map,
const std::string& output_path);
// generate Verilog verification target for tx fifo instr
void GenVerifTargetTX_FIFO(Ila& model, const std::string& design_path,
const std::string& instr_map, const std::string& var_map,
const std::string& output_path);
// generate Verilog verification target for tx func instr
void GenVerifTargetTX_FUNC(Ila& model, const std::string& design_path,
const std::string& instr_map, const std::string& var_map,
const std::string& output_path);
// generate Verilog verification target for tx func instr
void GenVerifTargetTX_FUNC_bug_hunting(Ila& model, const std::string& design_path,
const std::string& instr_map, const std::string& var_map,
const std::string& output_path);
// generate Verilog verification target for fifo test
void GenVerifTarget_FIFO_TEST(Ila& model, const std::string& design_path,
const std::string& instr_map, const std::string& var_map,
const std::string& output_path);
}; // namespace ilang
#endif // LMAC_CORE2_EQCHECK_H__
|
import {Component, Output, EventEmitter} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpModule, Http} from '@angular/http';
@Component({
selector: 'header',
templateUrl:'./app.header.component.html'
})
export class HeaderComponent {
searchText : string = "Search";
phrase : string = "";
@Output() search: EventEmitter<any> = new EventEmitter<any>();
@Output() filter: EventEmitter<any> = new EventEmitter<any>();
//includes http object to be used to get data in searchPhoto method
constructor(){
}
onSearch(phrase : string) {
this.phrase = phrase;
this.search.emit(phrase);
}
filterSearch(query : string) {
if(this.phrase === "")
{
query = query + '^' + query;
this.filter.emit(query);
}
query = this.phrase + '^' + query;
this.filter.emit(query);
}
}
|
package com.justai.jaicf.examples.viber
import com.justai.jaicf.BotEngine
import com.justai.jaicf.activator.regex.RegexActivator
import com.justai.jaicf.builder.Scenario
import com.justai.jaicf.channel.viber.api.CarouselElement
import com.justai.jaicf.channel.viber.api.ViberEvent
import com.justai.jaicf.channel.viber.api.isReceivedAsSilent
import com.justai.jaicf.channel.viber.contact
import com.justai.jaicf.channel.viber.conversationStarted
import com.justai.jaicf.channel.viber.delivered
import com.justai.jaicf.channel.viber.file
import com.justai.jaicf.channel.viber.location
import com.justai.jaicf.channel.viber.image
import com.justai.jaicf.channel.viber.sdk.api.KeyboardBuilder
import com.justai.jaicf.channel.viber.sdk.api.OpenMapButton
import com.justai.jaicf.channel.viber.sdk.api.RedirectButton
import com.justai.jaicf.channel.viber.sdk.api.ReplyButton
import com.justai.jaicf.channel.viber.sdk.api.ViberButton
import com.justai.jaicf.channel.viber.sdk.api.toKeyboard
import com.justai.jaicf.channel.viber.sdk.message.Location
import com.justai.jaicf.channel.viber.sdk.message.PictureMessage
import com.justai.jaicf.channel.viber.seen
import com.justai.jaicf.channel.viber.sticker
import com.justai.jaicf.channel.viber.subscribed
import com.justai.jaicf.channel.viber.text
import com.justai.jaicf.channel.viber.viber
import com.justai.jaicf.channel.viber.video
import java.io.File
val ViberTestScenario = Scenario {
state("new_conversation") {
activators {
event(ViberEvent.CONVERSATION_STARTED)
}
action(viber.conversationStarted) {
reactions.say("Greetings")
}
}
state("subscribed") {
activators {
event(ViberEvent.SUBSCRIBED)
}
action(viber.subscribed) {
reactions.say("Thank you for using us")
reactions.image("https://i.ytimg.com/vi/8W2njNW6hI0/hqdefault.jpg")
}
}
state("seen", noContext = true) {
activators {
event(ViberEvent.SEEN)
}
action(viber.seen) {
// You can do something
}
}
state("delivered", noContext = true) {
activators {
event(ViberEvent.DELIVERED)
}
action(viber.delivered) {
// You can do something
}
}
state("file") {
activators {
event(ViberEvent.FILE_MESSAGE)
}
action(viber.file) {
reactions.say("You sent me a file")
val fileMessage = request.message
reactions.file(fileMessage.url, File(fileMessage.filename))
}
}
state("image") {
activators {
event(ViberEvent.IMAGE_MESSAGE)
}
action(viber.image) {
reactions.say("You sent me a picture")
reactions.image(request.message.url)
}
}
state("video") {
activators {
event(ViberEvent.VIDEO_MESSAGE)
}
action(viber.video) {
reactions.say("You sent me a video")
reactions.video(request.message.url)
}
}
state("location") {
activators {
event(ViberEvent.LOCATION_MESSAGE)
}
action(viber.location) {
reactions.say("You sent me a location")
val (latitude, longitude) = request.message.location
reactions.location(latitude, longitude)
}
}
state("sticker") {
activators {
event(ViberEvent.STICKER_MESSAGE)
}
action(viber.sticker) {
reactions.say("You sent me a sticker")
reactions.sticker(request.message.stickerId)
}
}
state("contact") {
activators {
event(ViberEvent.CONTACT_MESSAGE)
}
action(viber.contact) {
reactions.say("You sent me a contact of ${request.message.contact.name}")
}
}
state("commands") {
activators {
regex("commands")
}
action(viber) {
reactions.keyboard {
row("Timer", "Message with keyboard")
reply("Inline buttons")
reply("Inline buttons without message")
row {
reply("Map")
reply("Carousel")
}
redirect("google", "google.com")
}
}
state("timer") {
activators {
regex("Timer")
}
action(viber.text) {
for (i in 5 downTo 1) {
reactions.say(i)
Thread.sleep(1000)
}
reactions.say("Timer is over")
}
}
state("message with keyboard") {
activators {
regex("Message with keyboard")
}
action(viber.text) {
val viberKeyboard = KeyboardBuilder(ViberButton.Style(backgroundColor = "#fdebd0")).apply {
row("1", "2", "3")
row("4")
}.build()
reactions.sendMessage(
PictureMessage(
"https://sun9-62.userapi.com/srBmxyK8e5SdZ2Yk2ZbqlNSk-966AC3mvMJJZA/xou0d6fBUO0.jpg",
keyboard = viberKeyboard.toKeyboard()
)
)
}
}
state("inline_buttons") {
activators {
regex("Inline buttons")
}
action(viber.text) {
val viberKeyboard = KeyboardBuilder(ViberButton.Style(backgroundColor = "#fdebd0")).apply {
row("1", "2", "3")
row("4")
}.build()
reactions.image("https://sun9-62.userapi.com/srBmxyK8e5SdZ2Yk2ZbqlNSk-966AC3mvMJJZA/xou0d6fBUO0.jpg")
reactions.inlineButtons(viberKeyboard = viberKeyboard)
}
}
state("inline_buttons_without_message") {
activators {
regex("Inline buttons without message")
}
action(viber.text) {
reactions.inlineButtons(ViberButton.Style(backgroundColor = "#fdebd0")) {
row("1", "2", "3")
row("4")
}
}
}
state("open_map") {
activators {
regex("Map")
}
action(viber.text) {
reactions.inlineButtons(ViberButton.Style(backgroundColor = "#fdebd0")) {
row {
button(OpenMapButton("Open map", location = Location(30.0, 60.0)))
}
}
}
}
state("carousel") {
activators {
regex("Carousel")
}
action(viber.text) {
reactions.say("Description for carousel element")
reactions.carousel(
CarouselElement(
"https://p1.zoon.ru/preview/nT8_s6xSaDEyjaBARdqrgw/504x270x85/1/4/b/original_52568bef40c08891208bc999_5c0a2f76d23b1.jpg",
"First mall title",
"Subtitle for first mall",
ReplyButton("Reply button")
),
CarouselElement(
"https://static.tildacdn.com/tild3262-6461-4161-b339-643136336265/7393505506535bbfc4e5.jpg",
"Title of second shop"
),
CarouselElement(
"https://40.img.avito.st/640x480/9202090740.jpg",
"Third title",
button = RedirectButton("Redirect button", redirectUrl = "https://5ka.ru/?100try.com")
)
)
}
}
}
fallback {
viber.text {
if (request.isReceivedAsSilent) {
return@text
}
reactions.say("You can send file, image, video, location, sticker, contact, text or test commands. To test commands write 'commands'")
viber.text {
reactions.say("You write ${request.message.text}")
}
}
}
}
val viberTestBot = BotEngine(
scenario = ViberTestScenario,
activators = arrayOf(
RegexActivator
)
)
|
# -*- encoding: utf-8 -*-
module Ackr
# Format strings to be displayed on terminal.
class Formatter
# Public:
#
# search_term - The String or Regexp to look for.
def initialize search_term
@search_term = search_term
end
# Public: format a line with matched term(s).
#
# line - The String line to be displayed.
# num - The Integer number of the line (in base 1).
#
# Returns a formatted String.
def line line, num
begin
line.strip!
rescue Exception => ex
puts "Error ".background(:red) + ex.message
end
"#{'%4i' % num}| #{Colorizer::for_line(line, @search_term)}"
end
end
end
|
package com.chipcerio.moovy.features.master_list
import android.support.v7.util.DiffUtil
class MoviesDiffCallback (
private val oldMovies: List<DisplayableMovie>,
private val newMovies: List<DisplayableMovie>
) : DiffUtil.Callback() {
override fun getOldListSize(): Int = oldMovies.size
override fun getNewListSize(): Int = newMovies.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldMovies[oldItemPosition].id == newMovies[newItemPosition].id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldMovies[oldItemPosition] == newMovies[newItemPosition]
}
}
|
namespace Ateliex.Areas.Cadastro.Enums
{
public enum ModeloRecursoTipo
{
Material = 1,
Transporte = 2,
Humano = 3
}
}
|
package ${package}.applicationmodel
object ${pascalCaseTransformerId}ParametersConstants {
object Mandatory {
const val NAME = "mandatory"
@JvmField
val CLASS = String::class.java
}
object Optional {
const val NAME = "optional"
@JvmField
val CLASS = String::class.java
}
object OptionalLimitedValue {
const val NAME = "optionalLimitedValue"
@JvmField
val CLASS = Int::class.java
}
}
|
---
title: "JS IIFE(즉시 호출 함수 표현식)"
excerpt: "JS IIFE(즉시 호출 함수 표현식)"
toc: true
toc_sticky: true
categories:
- js
tags:
- js
last_modified_at: 2020-03-14T08:06:00-05:00
---
## IIFE란?
IIFE(Immediately Invoked Function Expressions: "Iffy"라고 발음)는 **즉시 호출 함수 표현식**의 줄임말이다.
기본적인 형태
```js
(function(){
//Do fun stuff
})();
```
이것은 즉시 호출되는 익명함수 표현식이다. 이것은 javaScpript에 때에 따라 중요하게 사용됨
## 즉시 호출 함수 표현식은 어떻게 동작?
괄호쌍이 익명함수를 감싸서 함수선언을 함수표현식으로 표현할 수 있다.
그러므로 단순한 익명함수를 글로벌 스코프에 선언하지않고, 어디서든 익명함수 표현식을 가질 수 있다.
```js
//괄호 사용 안함
function() {
console.log('NO IIFE')
}(); //ERROR
//괄호 사용(즉시 호출함수 IIFE)
(function(){
console.log('IIFE');
})();
//함수 표현과 즉시함수
(showName = function(0 {
console.log(name || "NO Name");
})();
showName("Rich"); //Rich
showName(); //NO Name
```
### IIFE 예제 1
```js
const message = (function() {
const secret = "I m secret";
return `The Secret is ${secret.length} characters long.`
})();
console.log(message);
```
변수 secret은 IIFE의 스코프 안에서 안전하게 보호되면서 외부에서 접근 할수 없다.
IIFE는 함수 이므로 무엇이든 반환 할 수 있다.
### IIFE 예제 2
```js
// 호출된 함수를 가지고 있는 변수 f
const f = (function() {
let count = 0;
return function() {
return `i have been called ${++count} time(s).`
}
})();
f(); //1
f(); //2
```
## IIFE를 사용하는 이유와 언제사용?
**글로벌 스코프**를 오염시키지않게 하기 위해서 사용한다.
대표적인 라이브러리들은 IIFE패턴을 사용해서 충돌을 방지한다.
출처 : [https://sseambong.tistory.com/250](https://sseambong.tistory.com/250)
|
<?php
namespace DIServer\Interfaces;
Interface IEvent
{
/**
* 添加某个行为到指定标签
*
* @param string $tag 标签名
* @param mixed $behavior 行为定义(is_callable为true即可),可以是'函数名'、[对象,'方法名’]、闭包方法
*
* @throws \Exception
*/
function Add($tag, $behavior);
/**
* 添加一系列行为到指定标签
*
* @param string $tag 标签名
* @param array $behaviors 行为数组
*/
function AddRange($tag, array $behaviors);
/**
* 获取某个标签的所有行为
*
* @param $tag
*
* @return array
*/
function Get($tag = null);
/**
* 触发事件
*
* @param string $tag 标签名
* @param mixed $params 以引用方式传递于此标签行为的参数数组
*/
function Listen($tag, &$params = []);
}
|
"use strict";
var Cylon = require("cylon");
Cylon.robot({
connections: {
bluetooth: { adaptor: "central", uuid: "d03972a24e55", module: "cylon-ble" }
},
devices: {
playbulbcandle: { driver: "playbulb-candle" }
},
work: function(my) {
my.playbulbcandle.turnOff();
after((2).seconds(), function() {
my.playbulbcandle.turnOn();
});
after((3).seconds(), function() {
my.playbulbcandle.setColor('00', '00', 'ff', '00');
});
}
}).start();
|
package io.vertx.tp.ambient.uca.digital;
import cn.vertxup.ambient.domain.tables.daos.XTabularDao;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.up.eon.KName;
import io.vertx.up.eon.Values;
import io.vertx.up.unity.Ux;
import io.vertx.up.util.Ut;
import java.util.Objects;
/**
* @author <a href="http://www.origin-x.cn">Lang</a>
*/
public abstract class AbstractAide implements Aide {
// --------------- fetchArray method ------------------
/* X_TABULAR */
protected Future<JsonArray> fetchDict(final JsonObject criteria) {
return Ux.Jooq.on(XTabularDao.class).fetchAsync(criteria)
.compose(Ux::futureA)
.compose(Ut.ifJArray(KName.METADATA));
}
// --------------- condition building -----------------
protected JsonObject condApp(final String appId, final JsonArray types, final String code) {
final JsonObject criteria = Ux.whereAnd();
criteria.put(KName.APP_ID, appId);
this.condition(criteria, types, code);
return criteria;
}
protected JsonObject condApp(final String appId, final String type, final String code) {
return this.condApp(appId, new JsonArray().add(type), code);
}
protected JsonObject condSigma(final String sigma, final JsonArray types, final String code) {
final JsonObject criteria = Ux.whereAnd();
criteria.put(KName.SIGMA, sigma);
this.condition(criteria, types, code);
return criteria;
}
protected JsonObject condSigma(final String sigma, final String type, final String code) {
return this.condSigma(sigma, new JsonArray().add(type), code);
}
// -------------- private criteria --------------------
private void condition(final JsonObject criteria, final JsonArray types, final String code) {
Objects.requireNonNull(criteria);
final JsonArray typeArray = Ut.sureJArray(types);
criteria.put(KName.ACTIVE, Boolean.TRUE);
if (Values.ONE == typeArray.size()) {
final String firstArg = typeArray.getString(Values.IDX);
// ACTIVE = TRUE AND TYPE = ?
criteria.put(KName.TYPE, firstArg);
if (Ut.notNil(code)) {
/*
* Conflict to multi types, this code logical is
* available when you fetch one record only
*
* ACTIVE = TRUE AND TYPE = ? AND CODE = ?
* */
criteria.put(KName.CODE, code);
}
} else {
// ACTIVE = TRUE AND TYPE IN (?, ?)
criteria.put(KName.TYPE + ",i", types);
}
}
}
|
import styled from '@emotion/styled';
import React, { FunctionComponent } from 'react';
import { Aside, Header } from '@/components';
import { Main } from '@/styles/organisms/Main';
const Grid = styled.div`
display: grid;
grid-template-columns: 288px auto;
grid-template-rows: 80px auto;
grid-template-areas:
'aside header'
'aside main ';
`;
interface Props {
title: React.ReactNode;
children: React.ReactNode;
}
export const LayoutMain: FunctionComponent<Props> = ({
children,
title,
}: Props) => {
return (
<Grid>
<Header title={title} />
<Aside />
<Main className="container">{children}</Main>
</Grid>
);
};
export default LayoutMain;
|
module FloodgateSpec where
import Test.Hspec
import Polysemy
import Polysemy.Floodgate
import Polysemy.Trace
spec :: Spec
spec = describe "Floodgate" $ do
it "should delay held traces until release" $ do
let (ts, n) = run . runTraceList . runFloodgate $ do
hold $ trace "first1"
hold $ trace "first2"
trace "not held"
hold $ trace "second"
trace "not held again"
hold $ trace "third"
release
trace "finished"
pure $ id @Int 17
n `shouldBe` 17
ts `shouldBe`
[ "not held"
, "not held again"
, "first1"
, "first2"
, "second"
, "third"
, "finished"
]
|
INSERT INTO country (name) VALUES ('India');
INSERT INTO country (name) VALUES ('Brazil');
INSERT INTO country (name) VALUES ('USA');
INSERT INTO country (name) VALUES ('Italy');
COMMIT;
|
#Dir[File.join(File.dirname(__FILE__), 'active_record', 'models', 'login_attack_report', '*.rb')].each do |file|
# require "login_attack_report/frameworks/active_record/models/#{File.basename(file, '.rb')}"
#end
require "login_attack_report/frameworks/active_record/models/l_a_r_version.rb"
|
#include "stdafx.h"
#include "keyManager.h"
DEFINITION_SINGLE(KeyManager)
KeyManager::KeyManager()
{
}
KeyManager::~KeyManager()
{
}
HRESULT KeyManager::init()
{
//키가 전부 눌려있지 않은 상태로 초기화하자
for (int i = 0; i < KEYMAX; i++) {
_keyUp.set(i, false);
_keyDown.set(i, false);
}
playerKey[P1_UP] = VK_UP;
playerKey[P1_DOWN] = VK_DOWN;
playerKey[P1_LEFT] = VK_LEFT;
playerKey[P1_RIGHT] = VK_RIGHT;
playerKey[P1_EVENT] = VK_SPACE;
playerKey[P1_USEITEM] = VK_TAB;
playerKey[GAME_STAT] = 'E';
playerKey[GAME_INVEN] = 'I';
playerKey[GAME_SKILL] = 'S';
playerKey[GAME_1] = '1';
playerKey[GAME_2] = '2';
playerKey[GAME_3] = '3';
playerKey[GAME_4] = '4';
playerKey[GAME_A] = 'A';
playerKey[GAME_B] = 'B';
playerKey[GAME_C] = 'C';
playerKey[GAME_D] = 'D';
playerKey[GAME_E] = 'E';
playerKey[GAME_F] = 'F';
playerKey[GAME_G] = 'G';
playerKey[GAME_H] = 'H';
playerKey[GAME_I] = 'I';
playerKey[GAME_J] = 'J';
playerKey[GAME_K] = 'K';
playerKey[GAME_L] = 'L';
playerKey[GAME_M] = 'M';
playerKey[GAME_N] = 'N';
playerKey[GAME_O] = 'O';
playerKey[GAME_P] = 'P';
playerKey[GAME_Q] = 'Q';
playerKey[GAME_R] = 'R';
playerKey[GAME_S] = 'S';
playerKey[GAME_T] = 'T';
playerKey[GAME_U] = 'U';
playerKey[GAME_V] = 'V';
playerKey[GAME_W] = 'W';
playerKey[GAME_X] = 'X';
playerKey[GAME_Y] = 'Y';
playerKey[GAME_Z] = 'Z';
playerKey[GAME_BACK] = VK_BACK;
playerKey[GAME_SPACE] = VK_SPACE;
playerKey[GAME_SHOWFPS] = VK_F1;
playerKey[GAME_RECTMODE] = VK_F2;
playerKey[GAME_DEBUGMODE] = VK_F3;
playerKey[GAME_RTT] = VK_F4;
playerKey[GAME_LMOUSE] = VK_LBUTTON;
playerKey[GAME_RMOUSE] = VK_RBUTTON;
playerKey[GAME_ENTER] = VK_RETURN;
return S_OK;
}
void KeyManager::release()
{
}
bool KeyManager::isOnceKeyDown(int key)
{
//GetAsyncKeyState현재 키의 상태를 알아오는 녀석
//키가 눌려졌을때나 떨어졌을때 호출
//0x8000 이전에는 누른적이 없고 호출시점에서 눌린상태
if (GetAsyncKeyState(playerKey[key]) & 0x8000)
{
if (!_keyDown[playerKey[key]]) {
_keyDown.set(playerKey[key], true);
return true;
}
}
else _keyDown.set(playerKey[key], false);
return false;
}
bool KeyManager::isOnceKeyUp(int key)
{
if (GetAsyncKeyState(playerKey[key]) & 0x8000)
_keyUp.set(playerKey[key], true);
else {
if (_keyUp[playerKey[key]]) {
_keyUp.set(playerKey[key], false);
return true;
}
}
return false;
}
bool KeyManager::isStayKeyDown(int key)
{
if (GetAsyncKeyState(playerKey[key]) & 0x8000)
return true;
return false;
}
bool KeyManager::isToggleKey(int key)
{
//GetKeyState :현재 키의 토글상태
//0x0001이전에 누른적이 있고 호출시점에서 안눌린 상태
if (GetKeyState(playerKey[key]) & 0x0001)
return true;
return false;
}
void KeyManager::setCustomKey(int dest, int userKey)
{
playerKey[dest] = userKey;
}
|
---
id: developers
title: Guide for Developers
category: developers
---
Thorium is built on a number of technologies and tools:
* [React](https://facebook.github.io/react/) for the frontend
* [Apollo Client](http://www.apollostack.com/) for the data layer
* [GraphQL](http://graphql.org) for the transmission layer
* [NodeJS](http://nodejs.org) for the server
Be sure to learn about these technologies before diving in too deep.
Thorium also uses a number of patterns, such as:
* [Event Sourcing](https://dev.to/barryosull/event-sourcing-what-it-is-and-why-its-awesome)
* Subscriptions and PubSub - this provides reactive updates to the frontend
views.
* Dynamic frontend views which change and respond to backend data. This is what
allows Thorium to dynamically change what simulators, stations, and cards show
on an individual client.
Thorium uses a unique vocabulary:
* **Simulator**: a virtual representation of a spaceship or other vessel.
Simulators have **StationSets**, **Stations** **Systems**, Crew, Decks, Rooms,
Inventory, etc. Examples of Simulators include the USS Voyager, USS Odyssey,
etc.
* **Station**: an individual grouping of **Cards**. Belongs to a **Simulator**.
Stations have **Cards**. Examples of stations include Helm, Tactical, Command,
Communications, Operations, Engineer, etc.
* **StationSet**: a group of stations for a specific **Simulator**.
**Simulators** can have multiple StationSets for different groups and
missions. For example, you can have a station set for 8 crew members, 12 crew
members. You can have a station set for school flights (with simpler cards) or
you can have a level-3 station set for experienced groups.
* **Card**: an individual screen. Typically control a single aspect of the
simulator. Belongs to at least one **Station**. Examples include Targeting
Grid, Engine Control, Thrusters, Security Teams, etc.
* **System**: a representation of the capabilities of a simulator. Systems are
assigned to **Simulators**. Each system is different and unique and is
individually developed.
* **Mission**: a timeline of events which happen during the course of a
simulation. Missions have timeline items which execute **Macros**.
* **Macro**: An atomic, scripted operation with an event and arguments for the
event. Belongs to **Mission**.
* **Client**: A representation of an individual computer connected to Thorium.
Tracks information about that specific client, including the login state, the
login name, the offline state, etc. Also tracks the **Flight**, **Simulator**,
and **Station** assigned to the client.
* **Flight**: an individual instance of a simulated experience. Flights have at
least one **Simulator** (which you select a **StationSet** and [optionally] a
**Mission** on).
* **Set**: a representation of a physical configuration of **Client** computers.
Used to quickly and automatically set up the **Clients** with information
about their **Flight**, **Simulator**, and **Station** based on the
**Simulator** and **StationSet**
* **Asset**: an image associated with some information in the simulation.
Organized in Folders and Containers. Examples include Sensor Contacts, Ship
Images, Comm Images, etc.
_Please open an issue if you find another term that needs a definition_
## Event Sourcing
For the backend data, Thorium uses Event Sourcing to track data throughout the
simulations. An event describes something which happened in the simulation.
Events have arguments which describe how the event happened. Examples include
'Phaser Fired', 'Warp Engines Activated at Warp 3', 'Navigation System Damaged'.
Events are queued either through GraphQL mutations or internal processes.
Typically, mutations just queue events without any kind of processing. Mutations
also do not return any data. Events are fired async.
Events are stored in a log of events which can be audited at any time in the
future. Events are triggered immediately after they have been queued. The event
handlers then perform any actions necessary, such as updating information in an
in-memory data store or sending notifications to a client.
The most important aspect of the event handler is the subscription publication.
This sends an update to a specific channel about updates to the data which were
caused by the event. Clients subscribe to specific channels with arguments about
what data they want (for example, scoping the data to a specific simulator). The
publish function takes the provided data, filters it for the arguments supplied
by the clients, and then sends the data to the clients over WebSockets. The
clients then update based on the new data.
Here is a diagram depicting this process:

|
require_relative "../common"
namespace :snapshot do
@testname = "snapshot"
desc "check terraform is installed"
task :check => :environment do
system("command -v terraform > /dev/null") or raise("install terraform to provision powervc vm")
end
desc "snapshot a vm"
task :apply => :check do
@testname = "snapshot"
config = setup
snapshot(config)
apply
end
def snapshot(config)
@testname = "snapshot"
Dir.chdir(@test_dir)
RubyTerraform.plan(
:out => 'terraform.tfplan',
:auto_approve => true,
:vars => {
:ibmcloud_api_key => config[:secret]["api_key"],
:power_instance_id => config[:secret]["cloud_instance_id"],
:ibmcloud_region => config[:secret]["ibmcloud_region"],
:volume_name => config[:setting]["volume_name"],
:vm_name => config[:setting]["vm_name"]
}
)
end
end
|
# Hooks for [logrus](https://github.com/Sirupsen/logrus)
Example
```go
package main
import (
"net/http"
"github.com/Decentr-net/logrus/filename"
"github.com/Decentr-net/logrus/sentry"
log "github.com/sirupsen/logrus"
)
var (
dsn = "http://60a0257d7b5a429a8838e5f2ba873ec9@example.com/1"
)
func main() {
filenameHook := filename.NewHook()
filenameHook.Field = "custom_source_field" // Customize source field name
log.AddHook(filenameHook)
log.AddHook(sentry.NewHook(sentry.Options{
Dsn: dsn,
}, log.PanicLevel, log.FatalLevel, log.ErrorLevel))
log.WithError(err).Error("Dead beef")
}
```
|
/**
* Generated by scripts/generate-emojis.js.
* DO NOT EDIT!
*/
import * as Emojis from '../../people-body/person-role';
export const EMOJI_LIST = [
{ emoji: Emojis.PersonRole1, name: 'PersonRole1' },
{ emoji: Emojis.PersonRole10, name: 'PersonRole10' },
{ emoji: Emojis.PersonRole100, name: 'PersonRole100' },
{ emoji: Emojis.PersonRole101, name: 'PersonRole101' },
{ emoji: Emojis.PersonRole102, name: 'PersonRole102' },
{ emoji: Emojis.PersonRole103, name: 'PersonRole103' },
{ emoji: Emojis.PersonRole104, name: 'PersonRole104' },
{ emoji: Emojis.PersonRole105, name: 'PersonRole105' },
{ emoji: Emojis.PersonRole106, name: 'PersonRole106' },
{ emoji: Emojis.PersonRole107, name: 'PersonRole107' },
{ emoji: Emojis.PersonRole108, name: 'PersonRole108' },
{ emoji: Emojis.PersonRole109, name: 'PersonRole109' },
{ emoji: Emojis.PersonRole11, name: 'PersonRole11' },
{ emoji: Emojis.PersonRole110, name: 'PersonRole110' },
{ emoji: Emojis.PersonRole111, name: 'PersonRole111' },
{ emoji: Emojis.PersonRole112, name: 'PersonRole112' },
{ emoji: Emojis.PersonRole113, name: 'PersonRole113' },
{ emoji: Emojis.PersonRole114, name: 'PersonRole114' },
{ emoji: Emojis.PersonRole115, name: 'PersonRole115' },
{ emoji: Emojis.PersonRole116, name: 'PersonRole116' },
{ emoji: Emojis.PersonRole117, name: 'PersonRole117' },
{ emoji: Emojis.PersonRole118, name: 'PersonRole118' },
{ emoji: Emojis.PersonRole119, name: 'PersonRole119' },
{ emoji: Emojis.PersonRole12, name: 'PersonRole12' },
{ emoji: Emojis.PersonRole120, name: 'PersonRole120' },
{ emoji: Emojis.PersonRole121, name: 'PersonRole121' },
{ emoji: Emojis.PersonRole122, name: 'PersonRole122' },
{ emoji: Emojis.PersonRole123, name: 'PersonRole123' },
{ emoji: Emojis.PersonRole124, name: 'PersonRole124' },
{ emoji: Emojis.PersonRole125, name: 'PersonRole125' },
{ emoji: Emojis.PersonRole126, name: 'PersonRole126' },
{ emoji: Emojis.PersonRole127, name: 'PersonRole127' },
{ emoji: Emojis.PersonRole128, name: 'PersonRole128' },
{ emoji: Emojis.PersonRole129, name: 'PersonRole129' },
{ emoji: Emojis.PersonRole13, name: 'PersonRole13' },
{ emoji: Emojis.PersonRole130, name: 'PersonRole130' },
{ emoji: Emojis.PersonRole131, name: 'PersonRole131' },
{ emoji: Emojis.PersonRole132, name: 'PersonRole132' },
{ emoji: Emojis.PersonRole133, name: 'PersonRole133' },
{ emoji: Emojis.PersonRole134, name: 'PersonRole134' },
{ emoji: Emojis.PersonRole135, name: 'PersonRole135' },
{ emoji: Emojis.PersonRole136, name: 'PersonRole136' },
{ emoji: Emojis.PersonRole137, name: 'PersonRole137' },
{ emoji: Emojis.PersonRole138, name: 'PersonRole138' },
{ emoji: Emojis.PersonRole139, name: 'PersonRole139' },
{ emoji: Emojis.PersonRole14, name: 'PersonRole14' },
{ emoji: Emojis.PersonRole140, name: 'PersonRole140' },
{ emoji: Emojis.PersonRole141, name: 'PersonRole141' },
{ emoji: Emojis.PersonRole142, name: 'PersonRole142' },
{ emoji: Emojis.PersonRole143, name: 'PersonRole143' },
{ emoji: Emojis.PersonRole144, name: 'PersonRole144' },
{ emoji: Emojis.PersonRole145, name: 'PersonRole145' },
{ emoji: Emojis.PersonRole146, name: 'PersonRole146' },
{ emoji: Emojis.PersonRole147, name: 'PersonRole147' },
{ emoji: Emojis.PersonRole148, name: 'PersonRole148' },
{ emoji: Emojis.PersonRole149, name: 'PersonRole149' },
{ emoji: Emojis.PersonRole15, name: 'PersonRole15' },
{ emoji: Emojis.PersonRole150, name: 'PersonRole150' },
{ emoji: Emojis.PersonRole151, name: 'PersonRole151' },
{ emoji: Emojis.PersonRole152, name: 'PersonRole152' },
{ emoji: Emojis.PersonRole153, name: 'PersonRole153' },
{ emoji: Emojis.PersonRole154, name: 'PersonRole154' },
{ emoji: Emojis.PersonRole155, name: 'PersonRole155' },
{ emoji: Emojis.PersonRole156, name: 'PersonRole156' },
{ emoji: Emojis.PersonRole157, name: 'PersonRole157' },
{ emoji: Emojis.PersonRole158, name: 'PersonRole158' },
{ emoji: Emojis.PersonRole159, name: 'PersonRole159' },
{ emoji: Emojis.PersonRole16, name: 'PersonRole16' },
{ emoji: Emojis.PersonRole160, name: 'PersonRole160' },
{ emoji: Emojis.PersonRole161, name: 'PersonRole161' },
{ emoji: Emojis.PersonRole162, name: 'PersonRole162' },
{ emoji: Emojis.PersonRole163, name: 'PersonRole163' },
{ emoji: Emojis.PersonRole164, name: 'PersonRole164' },
{ emoji: Emojis.PersonRole165, name: 'PersonRole165' },
{ emoji: Emojis.PersonRole166, name: 'PersonRole166' },
{ emoji: Emojis.PersonRole167, name: 'PersonRole167' },
{ emoji: Emojis.PersonRole168, name: 'PersonRole168' },
{ emoji: Emojis.PersonRole169, name: 'PersonRole169' },
{ emoji: Emojis.PersonRole17, name: 'PersonRole17' },
{ emoji: Emojis.PersonRole170, name: 'PersonRole170' },
{ emoji: Emojis.PersonRole171, name: 'PersonRole171' },
{ emoji: Emojis.PersonRole172, name: 'PersonRole172' },
{ emoji: Emojis.PersonRole173, name: 'PersonRole173' },
{ emoji: Emojis.PersonRole174, name: 'PersonRole174' },
{ emoji: Emojis.PersonRole175, name: 'PersonRole175' },
{ emoji: Emojis.PersonRole176, name: 'PersonRole176' },
{ emoji: Emojis.PersonRole177, name: 'PersonRole177' },
{ emoji: Emojis.PersonRole178, name: 'PersonRole178' },
{ emoji: Emojis.PersonRole179, name: 'PersonRole179' },
{ emoji: Emojis.PersonRole18, name: 'PersonRole18' },
{ emoji: Emojis.PersonRole180, name: 'PersonRole180' },
{ emoji: Emojis.PersonRole181, name: 'PersonRole181' },
{ emoji: Emojis.PersonRole182, name: 'PersonRole182' },
{ emoji: Emojis.PersonRole183, name: 'PersonRole183' },
{ emoji: Emojis.PersonRole184, name: 'PersonRole184' },
{ emoji: Emojis.PersonRole185, name: 'PersonRole185' },
{ emoji: Emojis.PersonRole186, name: 'PersonRole186' },
{ emoji: Emojis.PersonRole187, name: 'PersonRole187' },
{ emoji: Emojis.PersonRole188, name: 'PersonRole188' },
{ emoji: Emojis.PersonRole189, name: 'PersonRole189' },
{ emoji: Emojis.PersonRole19, name: 'PersonRole19' },
{ emoji: Emojis.PersonRole190, name: 'PersonRole190' },
{ emoji: Emojis.PersonRole191, name: 'PersonRole191' },
{ emoji: Emojis.PersonRole192, name: 'PersonRole192' },
{ emoji: Emojis.PersonRole193, name: 'PersonRole193' },
{ emoji: Emojis.PersonRole194, name: 'PersonRole194' },
{ emoji: Emojis.PersonRole195, name: 'PersonRole195' },
{ emoji: Emojis.PersonRole196, name: 'PersonRole196' },
{ emoji: Emojis.PersonRole197, name: 'PersonRole197' },
{ emoji: Emojis.PersonRole198, name: 'PersonRole198' },
{ emoji: Emojis.PersonRole199, name: 'PersonRole199' },
{ emoji: Emojis.PersonRole2, name: 'PersonRole2' },
{ emoji: Emojis.PersonRole20, name: 'PersonRole20' },
{ emoji: Emojis.PersonRole200, name: 'PersonRole200' },
{ emoji: Emojis.PersonRole201, name: 'PersonRole201' },
{ emoji: Emojis.PersonRole202, name: 'PersonRole202' },
{ emoji: Emojis.PersonRole203, name: 'PersonRole203' },
{ emoji: Emojis.PersonRole204, name: 'PersonRole204' },
{ emoji: Emojis.PersonRole205, name: 'PersonRole205' },
{ emoji: Emojis.PersonRole206, name: 'PersonRole206' },
{ emoji: Emojis.PersonRole207, name: 'PersonRole207' },
{ emoji: Emojis.PersonRole208, name: 'PersonRole208' },
{ emoji: Emojis.PersonRole209, name: 'PersonRole209' },
{ emoji: Emojis.PersonRole21, name: 'PersonRole21' },
{ emoji: Emojis.PersonRole210, name: 'PersonRole210' },
{ emoji: Emojis.PersonRole211, name: 'PersonRole211' },
{ emoji: Emojis.PersonRole212, name: 'PersonRole212' },
{ emoji: Emojis.PersonRole213, name: 'PersonRole213' },
{ emoji: Emojis.PersonRole214, name: 'PersonRole214' },
{ emoji: Emojis.PersonRole215, name: 'PersonRole215' },
{ emoji: Emojis.PersonRole216, name: 'PersonRole216' },
{ emoji: Emojis.PersonRole217, name: 'PersonRole217' },
{ emoji: Emojis.PersonRole218, name: 'PersonRole218' },
{ emoji: Emojis.PersonRole219, name: 'PersonRole219' },
{ emoji: Emojis.PersonRole22, name: 'PersonRole22' },
{ emoji: Emojis.PersonRole220, name: 'PersonRole220' },
{ emoji: Emojis.PersonRole221, name: 'PersonRole221' },
{ emoji: Emojis.PersonRole222, name: 'PersonRole222' },
{ emoji: Emojis.PersonRole223, name: 'PersonRole223' },
{ emoji: Emojis.PersonRole224, name: 'PersonRole224' },
{ emoji: Emojis.PersonRole225, name: 'PersonRole225' },
{ emoji: Emojis.PersonRole226, name: 'PersonRole226' },
{ emoji: Emojis.PersonRole227, name: 'PersonRole227' },
{ emoji: Emojis.PersonRole228, name: 'PersonRole228' },
{ emoji: Emojis.PersonRole229, name: 'PersonRole229' },
{ emoji: Emojis.PersonRole23, name: 'PersonRole23' },
{ emoji: Emojis.PersonRole230, name: 'PersonRole230' },
{ emoji: Emojis.PersonRole231, name: 'PersonRole231' },
{ emoji: Emojis.PersonRole232, name: 'PersonRole232' },
{ emoji: Emojis.PersonRole233, name: 'PersonRole233' },
{ emoji: Emojis.PersonRole234, name: 'PersonRole234' },
{ emoji: Emojis.PersonRole235, name: 'PersonRole235' },
{ emoji: Emojis.PersonRole236, name: 'PersonRole236' },
{ emoji: Emojis.PersonRole237, name: 'PersonRole237' },
{ emoji: Emojis.PersonRole238, name: 'PersonRole238' },
{ emoji: Emojis.PersonRole239, name: 'PersonRole239' },
{ emoji: Emojis.PersonRole24, name: 'PersonRole24' },
{ emoji: Emojis.PersonRole240, name: 'PersonRole240' },
{ emoji: Emojis.PersonRole241, name: 'PersonRole241' },
{ emoji: Emojis.PersonRole242, name: 'PersonRole242' },
{ emoji: Emojis.PersonRole243, name: 'PersonRole243' },
{ emoji: Emojis.PersonRole244, name: 'PersonRole244' },
{ emoji: Emojis.PersonRole245, name: 'PersonRole245' },
{ emoji: Emojis.PersonRole246, name: 'PersonRole246' },
{ emoji: Emojis.PersonRole247, name: 'PersonRole247' },
{ emoji: Emojis.PersonRole248, name: 'PersonRole248' },
{ emoji: Emojis.PersonRole249, name: 'PersonRole249' },
{ emoji: Emojis.PersonRole25, name: 'PersonRole25' },
{ emoji: Emojis.PersonRole250, name: 'PersonRole250' },
{ emoji: Emojis.PersonRole251, name: 'PersonRole251' },
{ emoji: Emojis.PersonRole252, name: 'PersonRole252' },
{ emoji: Emojis.PersonRole253, name: 'PersonRole253' },
{ emoji: Emojis.PersonRole254, name: 'PersonRole254' },
{ emoji: Emojis.PersonRole255, name: 'PersonRole255' },
{ emoji: Emojis.PersonRole256, name: 'PersonRole256' },
{ emoji: Emojis.PersonRole257, name: 'PersonRole257' },
{ emoji: Emojis.PersonRole258, name: 'PersonRole258' },
{ emoji: Emojis.PersonRole259, name: 'PersonRole259' },
{ emoji: Emojis.PersonRole26, name: 'PersonRole26' },
{ emoji: Emojis.PersonRole260, name: 'PersonRole260' },
{ emoji: Emojis.PersonRole261, name: 'PersonRole261' },
{ emoji: Emojis.PersonRole262, name: 'PersonRole262' },
{ emoji: Emojis.PersonRole263, name: 'PersonRole263' },
{ emoji: Emojis.PersonRole264, name: 'PersonRole264' },
{ emoji: Emojis.PersonRole265, name: 'PersonRole265' },
{ emoji: Emojis.PersonRole266, name: 'PersonRole266' },
{ emoji: Emojis.PersonRole267, name: 'PersonRole267' },
{ emoji: Emojis.PersonRole268, name: 'PersonRole268' },
{ emoji: Emojis.PersonRole269, name: 'PersonRole269' },
{ emoji: Emojis.PersonRole27, name: 'PersonRole27' },
{ emoji: Emojis.PersonRole270, name: 'PersonRole270' },
{ emoji: Emojis.PersonRole271, name: 'PersonRole271' },
{ emoji: Emojis.PersonRole272, name: 'PersonRole272' },
{ emoji: Emojis.PersonRole273, name: 'PersonRole273' },
{ emoji: Emojis.PersonRole274, name: 'PersonRole274' },
{ emoji: Emojis.PersonRole275, name: 'PersonRole275' },
{ emoji: Emojis.PersonRole276, name: 'PersonRole276' },
{ emoji: Emojis.PersonRole277, name: 'PersonRole277' },
{ emoji: Emojis.PersonRole278, name: 'PersonRole278' },
{ emoji: Emojis.PersonRole279, name: 'PersonRole279' },
{ emoji: Emojis.PersonRole28, name: 'PersonRole28' },
{ emoji: Emojis.PersonRole280, name: 'PersonRole280' },
{ emoji: Emojis.PersonRole281, name: 'PersonRole281' },
{ emoji: Emojis.PersonRole282, name: 'PersonRole282' },
{ emoji: Emojis.PersonRole283, name: 'PersonRole283' },
{ emoji: Emojis.PersonRole284, name: 'PersonRole284' },
{ emoji: Emojis.PersonRole285, name: 'PersonRole285' },
{ emoji: Emojis.PersonRole286, name: 'PersonRole286' },
{ emoji: Emojis.PersonRole287, name: 'PersonRole287' },
{ emoji: Emojis.PersonRole288, name: 'PersonRole288' },
{ emoji: Emojis.PersonRole289, name: 'PersonRole289' },
{ emoji: Emojis.PersonRole29, name: 'PersonRole29' },
{ emoji: Emojis.PersonRole290, name: 'PersonRole290' },
{ emoji: Emojis.PersonRole291, name: 'PersonRole291' },
{ emoji: Emojis.PersonRole292, name: 'PersonRole292' },
{ emoji: Emojis.PersonRole293, name: 'PersonRole293' },
{ emoji: Emojis.PersonRole294, name: 'PersonRole294' },
{ emoji: Emojis.PersonRole295, name: 'PersonRole295' },
{ emoji: Emojis.PersonRole296, name: 'PersonRole296' },
{ emoji: Emojis.PersonRole297, name: 'PersonRole297' },
{ emoji: Emojis.PersonRole298, name: 'PersonRole298' },
{ emoji: Emojis.PersonRole299, name: 'PersonRole299' },
{ emoji: Emojis.PersonRole3, name: 'PersonRole3' },
{ emoji: Emojis.PersonRole30, name: 'PersonRole30' },
{ emoji: Emojis.PersonRole300, name: 'PersonRole300' },
{ emoji: Emojis.PersonRole301, name: 'PersonRole301' },
{ emoji: Emojis.PersonRole302, name: 'PersonRole302' },
{ emoji: Emojis.PersonRole303, name: 'PersonRole303' },
{ emoji: Emojis.PersonRole304, name: 'PersonRole304' },
{ emoji: Emojis.PersonRole305, name: 'PersonRole305' },
{ emoji: Emojis.PersonRole306, name: 'PersonRole306' },
{ emoji: Emojis.PersonRole307, name: 'PersonRole307' },
{ emoji: Emojis.PersonRole308, name: 'PersonRole308' },
{ emoji: Emojis.PersonRole309, name: 'PersonRole309' },
{ emoji: Emojis.PersonRole31, name: 'PersonRole31' },
{ emoji: Emojis.PersonRole310, name: 'PersonRole310' },
{ emoji: Emojis.PersonRole311, name: 'PersonRole311' },
{ emoji: Emojis.PersonRole312, name: 'PersonRole312' },
{ emoji: Emojis.PersonRole313, name: 'PersonRole313' },
{ emoji: Emojis.PersonRole314, name: 'PersonRole314' },
{ emoji: Emojis.PersonRole315, name: 'PersonRole315' },
{ emoji: Emojis.PersonRole316, name: 'PersonRole316' },
{ emoji: Emojis.PersonRole317, name: 'PersonRole317' },
{ emoji: Emojis.PersonRole318, name: 'PersonRole318' },
{ emoji: Emojis.PersonRole319, name: 'PersonRole319' },
{ emoji: Emojis.PersonRole32, name: 'PersonRole32' },
{ emoji: Emojis.PersonRole320, name: 'PersonRole320' },
{ emoji: Emojis.PersonRole321, name: 'PersonRole321' },
{ emoji: Emojis.PersonRole322, name: 'PersonRole322' },
{ emoji: Emojis.PersonRole323, name: 'PersonRole323' },
{ emoji: Emojis.PersonRole324, name: 'PersonRole324' },
{ emoji: Emojis.PersonRole325, name: 'PersonRole325' },
{ emoji: Emojis.PersonRole326, name: 'PersonRole326' },
{ emoji: Emojis.PersonRole327, name: 'PersonRole327' },
{ emoji: Emojis.PersonRole328, name: 'PersonRole328' },
{ emoji: Emojis.PersonRole329, name: 'PersonRole329' },
{ emoji: Emojis.PersonRole33, name: 'PersonRole33' },
{ emoji: Emojis.PersonRole330, name: 'PersonRole330' },
{ emoji: Emojis.PersonRole331, name: 'PersonRole331' },
{ emoji: Emojis.PersonRole332, name: 'PersonRole332' },
{ emoji: Emojis.PersonRole333, name: 'PersonRole333' },
{ emoji: Emojis.PersonRole334, name: 'PersonRole334' },
{ emoji: Emojis.PersonRole335, name: 'PersonRole335' },
{ emoji: Emojis.PersonRole336, name: 'PersonRole336' },
{ emoji: Emojis.PersonRole337, name: 'PersonRole337' },
{ emoji: Emojis.PersonRole338, name: 'PersonRole338' },
{ emoji: Emojis.PersonRole339, name: 'PersonRole339' },
{ emoji: Emojis.PersonRole34, name: 'PersonRole34' },
{ emoji: Emojis.PersonRole340, name: 'PersonRole340' },
{ emoji: Emojis.PersonRole341, name: 'PersonRole341' },
{ emoji: Emojis.PersonRole342, name: 'PersonRole342' },
{ emoji: Emojis.PersonRole343, name: 'PersonRole343' },
{ emoji: Emojis.PersonRole344, name: 'PersonRole344' },
{ emoji: Emojis.PersonRole345, name: 'PersonRole345' },
{ emoji: Emojis.PersonRole346, name: 'PersonRole346' },
{ emoji: Emojis.PersonRole347, name: 'PersonRole347' },
{ emoji: Emojis.PersonRole348, name: 'PersonRole348' },
{ emoji: Emojis.PersonRole349, name: 'PersonRole349' },
{ emoji: Emojis.PersonRole35, name: 'PersonRole35' },
{ emoji: Emojis.PersonRole350, name: 'PersonRole350' },
{ emoji: Emojis.PersonRole351, name: 'PersonRole351' },
{ emoji: Emojis.PersonRole352, name: 'PersonRole352' },
{ emoji: Emojis.PersonRole353, name: 'PersonRole353' },
{ emoji: Emojis.PersonRole354, name: 'PersonRole354' },
{ emoji: Emojis.PersonRole355, name: 'PersonRole355' },
{ emoji: Emojis.PersonRole356, name: 'PersonRole356' },
{ emoji: Emojis.PersonRole357, name: 'PersonRole357' },
{ emoji: Emojis.PersonRole358, name: 'PersonRole358' },
{ emoji: Emojis.PersonRole359, name: 'PersonRole359' },
{ emoji: Emojis.PersonRole36, name: 'PersonRole36' },
{ emoji: Emojis.PersonRole360, name: 'PersonRole360' },
{ emoji: Emojis.PersonRole361, name: 'PersonRole361' },
{ emoji: Emojis.PersonRole362, name: 'PersonRole362' },
{ emoji: Emojis.PersonRole363, name: 'PersonRole363' },
{ emoji: Emojis.PersonRole364, name: 'PersonRole364' },
{ emoji: Emojis.PersonRole365, name: 'PersonRole365' },
{ emoji: Emojis.PersonRole366, name: 'PersonRole366' },
{ emoji: Emojis.PersonRole367, name: 'PersonRole367' },
{ emoji: Emojis.PersonRole368, name: 'PersonRole368' },
{ emoji: Emojis.PersonRole369, name: 'PersonRole369' },
{ emoji: Emojis.PersonRole37, name: 'PersonRole37' },
{ emoji: Emojis.PersonRole370, name: 'PersonRole370' },
{ emoji: Emojis.PersonRole371, name: 'PersonRole371' },
{ emoji: Emojis.PersonRole372, name: 'PersonRole372' },
{ emoji: Emojis.PersonRole373, name: 'PersonRole373' },
{ emoji: Emojis.PersonRole374, name: 'PersonRole374' },
{ emoji: Emojis.PersonRole375, name: 'PersonRole375' },
{ emoji: Emojis.PersonRole376, name: 'PersonRole376' },
{ emoji: Emojis.PersonRole377, name: 'PersonRole377' },
{ emoji: Emojis.PersonRole378, name: 'PersonRole378' },
{ emoji: Emojis.PersonRole379, name: 'PersonRole379' },
{ emoji: Emojis.PersonRole38, name: 'PersonRole38' },
{ emoji: Emojis.PersonRole380, name: 'PersonRole380' },
{ emoji: Emojis.PersonRole381, name: 'PersonRole381' },
{ emoji: Emojis.PersonRole382, name: 'PersonRole382' },
{ emoji: Emojis.PersonRole383, name: 'PersonRole383' },
{ emoji: Emojis.PersonRole384, name: 'PersonRole384' },
{ emoji: Emojis.PersonRole385, name: 'PersonRole385' },
{ emoji: Emojis.PersonRole386, name: 'PersonRole386' },
{ emoji: Emojis.PersonRole387, name: 'PersonRole387' },
{ emoji: Emojis.PersonRole388, name: 'PersonRole388' },
{ emoji: Emojis.PersonRole389, name: 'PersonRole389' },
{ emoji: Emojis.PersonRole39, name: 'PersonRole39' },
{ emoji: Emojis.PersonRole390, name: 'PersonRole390' },
{ emoji: Emojis.PersonRole391, name: 'PersonRole391' },
{ emoji: Emojis.PersonRole392, name: 'PersonRole392' },
{ emoji: Emojis.PersonRole393, name: 'PersonRole393' },
{ emoji: Emojis.PersonRole394, name: 'PersonRole394' },
{ emoji: Emojis.PersonRole395, name: 'PersonRole395' },
{ emoji: Emojis.PersonRole396, name: 'PersonRole396' },
{ emoji: Emojis.PersonRole397, name: 'PersonRole397' },
{ emoji: Emojis.PersonRole398, name: 'PersonRole398' },
{ emoji: Emojis.PersonRole399, name: 'PersonRole399' },
{ emoji: Emojis.PersonRole4, name: 'PersonRole4' },
{ emoji: Emojis.PersonRole40, name: 'PersonRole40' },
{ emoji: Emojis.PersonRole400, name: 'PersonRole400' },
{ emoji: Emojis.PersonRole401, name: 'PersonRole401' },
{ emoji: Emojis.PersonRole402, name: 'PersonRole402' },
{ emoji: Emojis.PersonRole403, name: 'PersonRole403' },
{ emoji: Emojis.PersonRole404, name: 'PersonRole404' },
{ emoji: Emojis.PersonRole405, name: 'PersonRole405' },
{ emoji: Emojis.PersonRole406, name: 'PersonRole406' },
{ emoji: Emojis.PersonRole407, name: 'PersonRole407' },
{ emoji: Emojis.PersonRole408, name: 'PersonRole408' },
{ emoji: Emojis.PersonRole409, name: 'PersonRole409' },
{ emoji: Emojis.PersonRole41, name: 'PersonRole41' },
{ emoji: Emojis.PersonRole410, name: 'PersonRole410' },
{ emoji: Emojis.PersonRole411, name: 'PersonRole411' },
{ emoji: Emojis.PersonRole412, name: 'PersonRole412' },
{ emoji: Emojis.PersonRole413, name: 'PersonRole413' },
{ emoji: Emojis.PersonRole414, name: 'PersonRole414' },
{ emoji: Emojis.PersonRole415, name: 'PersonRole415' },
{ emoji: Emojis.PersonRole416, name: 'PersonRole416' },
{ emoji: Emojis.PersonRole417, name: 'PersonRole417' },
{ emoji: Emojis.PersonRole418, name: 'PersonRole418' },
{ emoji: Emojis.PersonRole419, name: 'PersonRole419' },
{ emoji: Emojis.PersonRole42, name: 'PersonRole42' },
{ emoji: Emojis.PersonRole420, name: 'PersonRole420' },
{ emoji: Emojis.PersonRole421, name: 'PersonRole421' },
{ emoji: Emojis.PersonRole422, name: 'PersonRole422' },
{ emoji: Emojis.PersonRole423, name: 'PersonRole423' },
{ emoji: Emojis.PersonRole424, name: 'PersonRole424' },
{ emoji: Emojis.PersonRole425, name: 'PersonRole425' },
{ emoji: Emojis.PersonRole426, name: 'PersonRole426' },
{ emoji: Emojis.PersonRole43, name: 'PersonRole43' },
{ emoji: Emojis.PersonRole44, name: 'PersonRole44' },
{ emoji: Emojis.PersonRole45, name: 'PersonRole45' },
{ emoji: Emojis.PersonRole46, name: 'PersonRole46' },
{ emoji: Emojis.PersonRole47, name: 'PersonRole47' },
{ emoji: Emojis.PersonRole48, name: 'PersonRole48' },
{ emoji: Emojis.PersonRole49, name: 'PersonRole49' },
{ emoji: Emojis.PersonRole5, name: 'PersonRole5' },
{ emoji: Emojis.PersonRole50, name: 'PersonRole50' },
{ emoji: Emojis.PersonRole51, name: 'PersonRole51' },
{ emoji: Emojis.PersonRole52, name: 'PersonRole52' },
{ emoji: Emojis.PersonRole53, name: 'PersonRole53' },
{ emoji: Emojis.PersonRole54, name: 'PersonRole54' },
{ emoji: Emojis.PersonRole55, name: 'PersonRole55' },
{ emoji: Emojis.PersonRole56, name: 'PersonRole56' },
{ emoji: Emojis.PersonRole57, name: 'PersonRole57' },
{ emoji: Emojis.PersonRole58, name: 'PersonRole58' },
{ emoji: Emojis.PersonRole59, name: 'PersonRole59' },
{ emoji: Emojis.PersonRole6, name: 'PersonRole6' },
{ emoji: Emojis.PersonRole60, name: 'PersonRole60' },
{ emoji: Emojis.PersonRole61, name: 'PersonRole61' },
{ emoji: Emojis.PersonRole62, name: 'PersonRole62' },
{ emoji: Emojis.PersonRole63, name: 'PersonRole63' },
{ emoji: Emojis.PersonRole64, name: 'PersonRole64' },
{ emoji: Emojis.PersonRole65, name: 'PersonRole65' },
{ emoji: Emojis.PersonRole66, name: 'PersonRole66' },
{ emoji: Emojis.PersonRole67, name: 'PersonRole67' },
{ emoji: Emojis.PersonRole68, name: 'PersonRole68' },
{ emoji: Emojis.PersonRole69, name: 'PersonRole69' },
{ emoji: Emojis.PersonRole7, name: 'PersonRole7' },
{ emoji: Emojis.PersonRole70, name: 'PersonRole70' },
{ emoji: Emojis.PersonRole71, name: 'PersonRole71' },
{ emoji: Emojis.PersonRole72, name: 'PersonRole72' },
{ emoji: Emojis.PersonRole73, name: 'PersonRole73' },
{ emoji: Emojis.PersonRole74, name: 'PersonRole74' },
{ emoji: Emojis.PersonRole75, name: 'PersonRole75' },
{ emoji: Emojis.PersonRole76, name: 'PersonRole76' },
{ emoji: Emojis.PersonRole77, name: 'PersonRole77' },
{ emoji: Emojis.PersonRole78, name: 'PersonRole78' },
{ emoji: Emojis.PersonRole79, name: 'PersonRole79' },
{ emoji: Emojis.PersonRole8, name: 'PersonRole8' },
{ emoji: Emojis.PersonRole80, name: 'PersonRole80' },
{ emoji: Emojis.PersonRole81, name: 'PersonRole81' },
{ emoji: Emojis.PersonRole82, name: 'PersonRole82' },
{ emoji: Emojis.PersonRole83, name: 'PersonRole83' },
{ emoji: Emojis.PersonRole84, name: 'PersonRole84' },
{ emoji: Emojis.PersonRole85, name: 'PersonRole85' },
{ emoji: Emojis.PersonRole86, name: 'PersonRole86' },
{ emoji: Emojis.PersonRole87, name: 'PersonRole87' },
{ emoji: Emojis.PersonRole88, name: 'PersonRole88' },
{ emoji: Emojis.PersonRole89, name: 'PersonRole89' },
{ emoji: Emojis.PersonRole9, name: 'PersonRole9' },
{ emoji: Emojis.PersonRole90, name: 'PersonRole90' },
{ emoji: Emojis.PersonRole91, name: 'PersonRole91' },
{ emoji: Emojis.PersonRole92, name: 'PersonRole92' },
{ emoji: Emojis.PersonRole93, name: 'PersonRole93' },
{ emoji: Emojis.PersonRole94, name: 'PersonRole94' },
{ emoji: Emojis.PersonRole95, name: 'PersonRole95' },
{ emoji: Emojis.PersonRole96, name: 'PersonRole96' },
{ emoji: Emojis.PersonRole97, name: 'PersonRole97' },
{ emoji: Emojis.PersonRole98, name: 'PersonRole98' },
{ emoji: Emojis.PersonRole99, name: 'PersonRole99' },
];
|
package fr.unice.polytech.al.trafficlight.graph;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by user on 12/01/17.
*/
public class WeightedDirectedGraphTest {
@Test
public void testAddNode() throws Exception {
WeightedDirectedGraph<String> graph = new WeightedDirectedGraph<>();
assertEquals(0, graph.getNumberOfNode());
graph.addNode("firstNode");
assertEquals(1, graph.getNumberOfNode());
assertEquals(0, graph.getNumberOfNeighbours("firstNode"));
assertEquals(0, graph.getNumberOfNeighbours("firstNode"));
assertTrue(graph.isPresent("firstNode"));
}
@Test
public void testRemoveNode() throws Exception {
WeightedDirectedGraph<String> graph = new WeightedDirectedGraph<>();
graph.addNode("firstNode");
graph.removeNode("firstNode");
assertFalse(graph.isPresent("firstNode"));
assertEquals(0, graph.getNumberOfNode());
}
@Test
public void testAddEdge() throws Exception {
WeightedDirectedGraph<String> graph = new WeightedDirectedGraph<>();
graph.addNode("firstNode");
graph.addNode("endNode");
graph.addEdge("edge","firstNode","endNode",12);
assertEquals(1, graph.getNumberOfNeighbours("firstNode"));
}
@Test
public void testAddEdgeWithoutNode() throws Exception {
WeightedDirectedGraph<String> graph = new WeightedDirectedGraph<>();
graph.addEdge("edge","nonExistingNode1","nonExistingNode2", 42);
assertEquals(2, graph.getNumberOfNode());
assertEquals(1, graph.getNumberOfNeighbours("nonExistingNode1"));
assertTrue(graph.isPresent("nonExistingNode1"));
assertTrue(graph.isPresent("nonExistingNode2"));
}
@Test
public void testRemoveEdge() throws Exception {
WeightedDirectedGraph<String> graph = new WeightedDirectedGraph<>();
graph.addNode("firstNode");
graph.addNode("endNode");
graph.addEdge("edge","firstNode","endNode",12);
//TODO remove edge
}
@Test
public void testRemoveAllEdgesOfNode() throws Exception {
WeightedDirectedGraph<String> graph = new WeightedDirectedGraph<>();
//add 20 edges
for(int i = 0; i<20; i++){
graph.addEdge("edge","firstNode","endNode",i);
}
assertEquals(20, graph.getNumberOfNeighbours("firstNode"));
graph.removeAllEdgesOfNode("firstNode");
assertEquals(0, graph.getNumberOfNeighbours("firstNode"));
assertTrue(graph.isPresent("firstNode"));
assertTrue(graph.isPresent("endNode"));
}
@Test
public void testGetNeighbours() throws Exception {
WeightedDirectedGraph<String> graph = new WeightedDirectedGraph<>();
graph.addEdge("edge","firstNode","endNode",12);
assertEquals("endNode", graph.getNeighbours("firstNode").get(0));
assertEquals(0, graph.getNeighbours("endNode").size());
}
}
|
#This script is almost verbatim from https://github.com/tobania/VSTS.Extension.EntityFrameworkMigrations
[CmdletBinding()]
param(
)
$PackagesConfig = Get-VstsInput -Name "PackagesConfig" -Require
$PackagesFolder = Get-VstsInput -Name "PackagesFolder" -Require
$EFPackageName = Get-VstsInput -Name "EFPackageName"
$OutputDirectory = Get-VstsInput -Name "OutputDirectory"
$UseVerbose = Get-VstsInput -Name "UseVerbose"
if($VerbosePreference -eq "SilentlyContinue" -And $UseVerbose -eq "true") {
$VerbosePreference = "continue"
}
if([string]::IsNullOrWhiteSpace($EFPackageName)) {
$EFPackageName = "EntityFramework"
}
if([string]::IsNullOrWhiteSpace($OutputDirectory)) {
$OutputDirectory = "$(Build.ArtifactStagingDirectory)\Migrate"
}
# Check if packages folder exists
Write-Host "Checking if $PackagesFolder exists..."
if(-Not (Test-Path $PackagesFolder)) {
Write-Error "$PackagesFolder does not exist."
exit 1
}
# Check if packages.config exists
Write-Host "Checking if $PackagesConfig exists..."
if(-Not (Test-Path $PackagesConfig)) {
Write-Error "$PackagesConfig does not exist."
exit 2
}
# Check if output folder exists
Write-Host "Checking if $OutputDirectory exists..."
if(-Not (Test-Path $OutputDirectory)) {
# Create new directory which will hold all required DLLs, exe's and configurations.
Write-Host "Creating output directory $OutputDirectory"
New-Item -Force -Type Directory $OutputDirectory
}
Write-Host "Starting copy of migrate.exe to $OutputDirectory"
Write-Host "Using packages.config: $PackagesConfig"
# Load packages.config
[xml]$Cfg = Get-Content $PackagesConfig
# Find the version of entity framework currently installed
Write-Host "Attempting to find package $EFPackageName in $PackagesConfig"
$EF = $Cfg.packages.package | where { $_.id -eq $EFPackageName }
if($EF -eq $null){
Write-Error "Package $EFPackageName is not listed in $PackagesConfig"
exit 1;
}
Write-Host "Parsing installed Entity Framework version"
$EFVersion = [version]$EF.version
$EFTargetFramework = $EF.targetFramework
Write-Host "$EFPackageName is installed with version $EFVersion for framework $EFTargetFramework"
if($EFVersion -lt [version]"4.1.0"){
Write-Error "Code first migrations are only supported in Entity Framework version 4.1 or higher";
exit 3;
}
# Compose the directory in which the EF package tools are located (which contains the migrate.exe)
$EFTools = "$PackagesFolder\$EFPackageName.$EFVersion\tools\"
# Copy the migrate.exe to the working folder
Write-Host "$EFTools\migrate.exe to $OutputDirectory"
Copy-Item -Force "$EFTools\migrate.exe" -Destination "$OutputDirectory\migrate.exe"
# If .NET 4 is installed, we must copy the Redirect.config as migrate.exe.config
If ($EFTargetFramework -eq "net40")
{
Write-Host "Entity Framework is installed for .NET 4, copying configuration file for Migrate.exe"
If (Test-Path ($EFTools + "Redirect.config"))
{
Write-Host "Copying $EFTools\Redirect.config to $OutputDirectory\migrate.exe.config"
Copy-Item -Force "$EFTools\Redirect.config" -Destination "$OutputDirectory\migrate.exe.config"
}
}
Write-Host "Finished copying migrate.exe to $OutputDirectory"
|
__all__ = (
"object_property",
"bool_property",
"array_property",
"set_property",
"dict_property",
)
from objc import ivar, selector, _C_ID, _C_NSBOOL, _C_BOOL, NULL, _C_NSUInteger
from objc import lookUpClass
from copy import copy as copy_func
import sys
if sys.version_info[0] == 2:
import collections as collections_abc
else:
import collections.abc as collections_abc
NSSet = lookUpClass("NSSet")
NSObject = lookUpClass("NSObject")
if sys.version_info[0] == 2: # pragma: no 3.x cover
range = xrange
def _str(value):
return value
else: # pragma: no 2.x cover
long = int
def _str(value):
return value.decode("ascii")
def attrsetter(prop, name, copy):
if copy:
def func(self, value):
if isinstance(value, NSObject):
setattr(self, name, value.copy())
else:
setattr(self, name, copy_func(value))
else:
def func(self, value):
setattr(self, name, value)
return func
def attrgetter(name):
def func(self):
return getattr(self, name)
return func
def _return_value(value):
def func(self):
return value
return func
def _dynamic_getter(name):
def getter(object):
m = getattr(object.pyobjc_instanceMethods, name)
return m()
getter.__name__ = name
return getter
def _dynamic_setter(name):
def setter(object, value):
m = getattr(object.pyobjc_instanceMethods, name.replace(":", "_"))
return m(value)
setter.__name__ = name
return setter
class object_property(object):
def __init__(
self,
name=None,
read_only=False,
copy=False,
dynamic=False,
ivar=None,
typestr=_C_ID,
depends_on=None,
):
self.__created = False
self.__inherit = False
self._name = name
self._typestr = typestr
self._ro = read_only
self._copy = copy
self._dynamic = dynamic
self._ivar = ivar
self._getter = None
self._setter = None
self._validate = None
if depends_on is None:
self._depends_on = None
else:
self._depends_on = set(depends_on)
self.__getprop = None
self.__setprop = None
self.__parent = None
def _clone(self):
if self._depends_on is None:
depends = None
else:
depends = self._depends_on.copy()
v = type(self)(
name=self._name,
read_only=self._ro,
copy=self._copy,
dynamic=self._dynamic,
ivar=self._ivar,
typestr=self._typestr,
depends_on=depends,
)
v.__inherit = True
v.__getprop = self.__getprop
v.__setprop = self.__setprop
v.__parent = self
return v
def __pyobjc_class_setup__(self, name, class_dict, instance_methods, class_methods):
self.__created = True
if self._name is None:
self._name = name
if self._ivar is not NULL:
if self._ivar is None:
ivname = "_" + self._name
else:
ivname = self._ivar
if self.__parent is None:
ivar_ref = ivar(name=ivname, type=self._typestr)
class_dict[ivname] = ivar_ref
if self._ro:
self._setter = None
else:
setterName = (
b"set"
+ name[0].upper().encode("latin1")
+ name[1:].encode("latin1")
+ b":"
)
signature = b"v@:" + self._typestr
if self._setter is None:
if self.__inherit:
pass
elif self._dynamic:
dynSetterName = "set" + name[0].upper() + name[1:] + "_"
self.__setprop = _dynamic_setter(dynSetterName)
instance_methods.add(setterName)
else:
if self._ivar is NULL:
raise ValueError(
"Cannot create default setter for property " "without ivar"
)
setprop = selector(
attrsetter(self._name, ivname, self._copy),
selector=setterName,
signature=signature,
)
setprop.isHidden = True
instance_methods.add(setprop)
# Use dynamic setter to avoid problems when subclassing
self.__setprop = _dynamic_setter(_str(setterName))
else:
setprop = selector(self._setter, selector=setterName, signature=signature)
setprop.isHidden = True
instance_methods.add(setprop)
# Use dynamic setter to avoid problems when subclassing
self.__setprop = _dynamic_setter(_str(setterName))
if self._typestr in (_C_NSBOOL, _C_BOOL):
getterName = (
b"is" + name[0].upper().encode("latin1") + name[1:].encode("latin1")
)
else:
getterName = self._name.encode("latin1")
if self._getter is None:
if self.__inherit:
pass
elif self._dynamic:
if self._typestr in (_C_NSBOOL, _C_BOOL):
dynGetterName = "is" + name[0].upper() + name[1:]
else:
dynGetterName = self._name
self.__getprop = _dynamic_getter(dynGetterName)
instance_methods.add(getterName)
else:
if self._ivar is NULL:
raise ValueError(
"Cannot create default getter for property without ivar"
)
self.__getprop = selector(
attrgetter(ivname),
selector=getterName,
signature=self._typestr + b"@:",
)
self.__getprop.isHidden = True
instance_methods.add(self.__getprop)
else:
self.__getprop = getprop = selector(
self._getter, selector=getterName, signature=self._typestr + b"@:"
)
getprop.isHidden = True
instance_methods.add(getprop)
# self.__getprop = _dynamic_getter(getterName)
if self._validate is not None:
selName = (
b"validate"
+ self._name[0].upper().encode("latin")
+ self._name[1:].encode("latin")
+ b":error:"
)
signature = _C_NSBOOL + b"@:N^@o^@"
validate = selector(self._validate, selector=selName, signature=signature)
class_dict[validate.selector] = validate
instance_methods.add(validate)
if self._depends_on:
if self.__parent is not None:
if self.__parent._depends_on:
self._depends_on.update(self.__parent._depends_on.copy())
self._depends_on = self._depends_on
affecting = selector(
_return_value(NSSet.setWithArray_(list(self._depends_on))),
selector=b"keyPathsForValuesAffecting"
+ self._name[0].upper().encode("latin1")
+ self._name[1:].encode("latin1"),
signature=b"@@:",
isClassMethod=True,
)
class_dict[affecting.selector] = affecting
class_methods.add(affecting)
def __get__(self, object, owner):
if object is None:
return self
return self.__getprop(object)
def __set__(self, object, value):
if self.__setprop is None:
raise ValueError("setting read-only property " + self._name)
return self.__setprop(object, value)
def __delete__(self, object):
raise TypeError("cannot delete property " + self._name)
def depends_on(self, keypath):
if self._depends_on is None:
self._depends_on = set()
self._depends_on.add(keypath)
def getter(self, function):
if self.__created:
v = self._clone()
v._getter = function
return v
self._getter = function
return self
def setter(self, function):
if self.__created:
v = self._clone()
v._ro = False
v._setter = function
return v
if self._ro:
raise ValueError("Defining settter for read-only property")
self._setter = function
return self
def validate(self, function):
if self._ro:
raise ValueError("Defining validator for read-only property")
if self.__created:
v = self._clone()
v._validate = function
return v
self._validate = function
return self
class bool_property(object_property):
def __init__(
self,
name=None,
read_only=False,
copy=False,
dynamic=False,
ivar=None,
typestr=_C_NSBOOL,
):
super(bool_property, self).__init__(name, read_only, copy, dynamic, ivar, typestr)
NSIndexSet = lookUpClass("NSIndexSet")
NSMutableIndexSet = lookUpClass("NSMutableIndexSet")
NSKeyValueChangeSetting = 1
NSKeyValueChangeInsertion = 2
NSKeyValueChangeRemoval = 3
NSKeyValueChangeReplacement = 4
# Helper function for (not) pickling array_proxy instances
# NOTE: Don't remove this function, it can be referenced from
# pickle files.
def _id(value):
return value
# FIXME: split into two: array_proxy and mutable_array_proxy
class array_proxy(collections_abc.MutableSequence):
# XXX: The implemenation should be complete, but is currently not
# tested.
__slots__ = ("_name", "_parent", "__wrapped", "_ro")
def __init__(self, name, parent, wrapped, read_only):
self._name = name
self._parent = parent
self._ro = read_only
self.__wrapped = wrapped
@property
def _wrapped(self):
return self.__wrapped.__getvalue__(self._parent)
def __indexSetForIndex(self, index):
if isinstance(index, slice):
result = NSMutableIndexSet.alloc().init()
start, stop, step = index.indices(len(self._wrapped))
for i in range(start, stop, step):
result.addIndex_(i)
return result
elif isinstance(index, (int, long)):
if index < 0:
v = len(self) + index
if v < 0:
raise IndexError(index)
return NSIndexSet.alloc().initWithIndex_(v)
else:
return NSIndexSet.alloc().initWithIndex_(index)
else:
raise TypeError(index)
def __repr__(self):
return "<array proxy for property " + self._name + " " + repr(self._wrapped) + ">"
def __reduce__(self):
# Ensure that the proxy itself doesn't get stored
# in pickles.
return _id, (self._wrapped,)
def __getattr__(self, name):
# Default: just defer to wrapped list
return getattr(self._wrapped, name)
def __len__(self):
return self._wrapped.__len__()
def __getitem__(self, index):
return self._wrapped[index]
def __setitem__(self, index, value):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
indexes = self.__indexSetForIndex(index)
self._parent.willChange_valuesAtIndexes_forKey_(
NSKeyValueChangeSetting, indexes, self._name
)
try:
self._wrapped[index] = value
finally:
self._parent.didChange_valuesAtIndexes_forKey_(
NSKeyValueChangeReplacement, indexes, self._name
)
def __delitem__(self, index):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
indexes = self.__indexSetForIndex(index)
self._parent.willChange_valuesAtIndexes_forKey_(
NSKeyValueChangeRemoval, indexes, self._name
)
try:
del self._wrapped[index]
finally:
self._parent.didChange_valuesAtIndexes_forKey_(
NSKeyValueChangeRemoval, indexes, self._name
)
def append(self, value):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
index = len(self)
indexes = NSIndexSet.alloc().initWithIndex_(index)
self._parent.willChange_valuesAtIndexes_forKey_(
NSKeyValueChangeInsertion, indexes, self._name
)
try:
self._wrapped.append(value)
finally:
self._parent.didChange_valuesAtIndexes_forKey_(
NSKeyValueChangeInsertion, indexes, self._name
)
def insert(self, index, value):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
if isinstance(index, slice):
raise TypeError("insert argument 1 is a slice")
indexes = self.__indexSetForIndex(index)
self._parent.willChange_valuesAtIndexes_forKey_(
NSKeyValueChangeInsertion, indexes, self._name
)
try:
self._wrapped.insert(index, value)
finally:
self._parent.didChange_valuesAtIndexes_forKey_(
NSKeyValueChangeInsertion, indexes, self._name
)
def pop(self, index=-1):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
if isinstance(index, slice):
raise TypeError("insert argument 1 is a slice")
indexes = self.__indexSetForIndex(index)
self._parent.willChange_valuesAtIndexes_forKey_(
NSKeyValueChangeRemoval, indexes, self._name
)
try:
return self._wrapped.pop(index)
finally:
self._parent.didChange_valuesAtIndexes_forKey_(
NSKeyValueChangeRemoval, indexes, self._name
)
def extend(self, values):
# XXX: This is suboptimal but correct
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
values = list(values)
indexes = NSIndexSet.alloc().initWithIndexesInRange_((len(self), len(values)))
self._parent.willChange_valuesAtIndexes_forKey_(
NSKeyValueChangeInsertion, indexes, self._name
)
try:
self._wrapped.extend(values)
finally:
self._parent.didChange_valuesAtIndexes_forKey_(
NSKeyValueChangeInsertion, indexes, self._name
)
def __iadd__(self, values):
self.extend(values)
return self
def __add__(self, values):
return self._wrapped + values
def __mul__(self, count):
return self._wrapped * count
def __imul__(self, count):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
if not isinstance(count, (int, long)):
raise TypeError(count)
indexes = NSIndexSet.alloc().initWithIndexesInRange_(
(len(self), len(self) * (count - 1))
)
self._parent.willChange_valuesAtIndexes_forKey_(
NSKeyValueChangeInsertion, indexes, self._name
)
try:
self._wrapped.__imul__(count)
finally:
self._parent.didChange_valuesAtIndexes_forKey_(
NSKeyValueChangeInsertion, indexes, self._name
)
return self
def __eq__(self, other):
if isinstance(other, array_proxy):
return self._wrapped == other._wrapped
else:
return self._wrapped == other
def __ne__(self, other):
if isinstance(other, array_proxy):
return self._wrapped != other._wrapped
else:
return self._wrapped != other
def __lt__(self, other):
if isinstance(other, array_proxy):
return self._wrapped < other._wrapped
else:
return self._wrapped < other
def __le__(self, other):
if isinstance(other, array_proxy):
return self._wrapped <= other._wrapped
else:
return self._wrapped <= other
def __gt__(self, other):
if isinstance(other, array_proxy):
return self._wrapped > other._wrapped
else:
return self._wrapped > other
def __ge__(self, other):
if isinstance(other, array_proxy):
return self._wrapped >= other._wrapped
else:
return self._wrapped >= other
if sys.version_info[0] == 2: # pragma: no 3.x cover
def __cmp__(self, other):
if isinstance(other, array_proxy):
return cmp(self._wrapped, other._wrapped)
else:
return cmp(self._wrapped, other)
def sort(self, cmp=None, key=None, reverse=False):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
indexes = NSIndexSet.alloc().initWithIndexesInRange_((0, len(self._wrapped)))
self._parent.willChange_valuesAtIndexes_forKey_(
NSKeyValueChangeReplacement, indexes, self._name
)
try:
self._wrapped.sort(cmp=cmp, key=key, reverse=reverse)
finally:
self._parent.didChange_valuesAtIndexes_forKey_(
NSKeyValueChangeReplacement, indexes, self._name
)
else: # pragma: no 2.x cover
def sort(self, key=None, reverse=False):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
indexes = NSIndexSet.alloc().initWithIndexesInRange_((0, len(self._wrapped)))
self._parent.willChange_valuesAtIndexes_forKey_(
NSKeyValueChangeReplacement, indexes, self._name
)
try:
self._wrapped.sort(key=key, reverse=reverse)
finally:
self._parent.didChange_valuesAtIndexes_forKey_(
NSKeyValueChangeReplacement, indexes, self._name
)
def reverse(self):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
indexes = NSIndexSet.alloc().initWithIndexesInRange_((0, len(self._wrapped)))
self._parent.willChange_valuesAtIndexes_forKey_(
NSKeyValueChangeReplacement, indexes, self._name
)
try:
self._wrapped.reverse()
finally:
self._parent.didChange_valuesAtIndexes_forKey_(
NSKeyValueChangeReplacement, indexes, self._name
)
def makeArrayAccessors(name):
def countOf(self):
return len(getattr(self, name))
def objectIn(self, idx):
return getattr(self, name)[idx]
def insert(self, value, idx):
getattr(self, name).insert(idx, value)
def replace(self, idx, value):
getattr(self, name)[idx] = value
def remove(self, idx):
del getattr(self, name)[idx]
return countOf, objectIn, insert, remove, replace
class array_property(object_property):
def __init__(
self,
name=None,
read_only=False,
copy=True,
dynamic=False,
ivar=None,
depends_on=None,
):
super(array_property, self).__init__(
name,
read_only=read_only,
copy=copy,
dynamic=dynamic,
ivar=ivar,
depends_on=depends_on,
)
def __pyobjc_class_setup__(self, name, class_dict, instance_methods, class_methods):
super(array_property, self).__pyobjc_class_setup__(
name, class_dict, instance_methods, class_methods
)
# Insert (Mutable) Indexed Accessors
# FIXME: should only do the mutable bits when we're actually a mutable property
name = self._name
Name = name[0].upper() + name[1:]
countOf, objectIn, insert, remove, replace = makeArrayAccessors(self._name)
countOf = selector(
countOf,
selector=("countOf%s" % (Name,)).encode("latin1"),
signature=_C_NSUInteger + b"@:",
)
countOf.isHidden = True
instance_methods.add(countOf)
objectIn = selector(
objectIn,
selector=("objectIn%sAtIndex:" % (Name,)).encode("latin1"),
signature=b"@@:" + _C_NSUInteger,
)
objectIn.isHidden = True
instance_methods.add(objectIn)
insert = selector(
insert,
selector=("insertObject:in%sAtIndex:" % (Name,)).encode("latin1"),
signature=b"v@:@" + _C_NSUInteger,
)
insert.isHidden = True
instance_methods.add(insert)
remove = selector(
remove,
selector=("removeObjectFrom%sAtIndex:" % (Name,)).encode("latin1"),
signature=b"v@:" + _C_NSUInteger,
)
remove.isHidden = True
instance_methods.add(remove)
replace = selector(
replace,
selector=("replaceObjectIn%sAtIndex:withObject:" % (Name,)).encode("latin1"),
signature=b"v@:" + _C_NSUInteger + b"@",
)
replace.isHidden = True
instance_methods.add(replace)
def __set__(self, object, value):
if isinstance(value, array_proxy):
if value._name == self._name and value._parent is object:
# attr.prop = attr.prop
return
if isinstance(value, array_proxy):
value = list(value)
super(array_property, self).__set__(object, value)
def __get__(self, object, owner):
v = object_property.__get__(self, object, owner)
if v is None:
v = list()
object_property.__set__(self, object, v)
return array_proxy(self._name, object, self, self._ro)
def __getvalue__(self, object):
v = object_property.__get__(self, object, None)
if v is None:
v = list()
object_property.__set__(self, object, v)
return v
NSKeyValueUnionSetMutation = 1
NSKeyValueMinusSetMutation = 2
NSKeyValueIntersectSetMutation = 3
NSKeyValueSetSetMutation = 4
class set_proxy(collections_abc.MutableSet):
__slots__ = ("_name", "__wrapped", "_parent", "_ro")
def __init__(self, name, parent, wrapped, read_only):
self._name = name
self._parent = parent
self._ro = read_only
self.__wrapped = wrapped
def __repr__(self):
return "<set proxy for property " + self._name + " " + repr(self._wrapped) + ">"
@property
def _wrapped(self):
return self.__wrapped.__getvalue__(self._parent)
def __reduce__(self):
# Ensure that the proxy itself doesn't get stored
# in pickles.
return _id, (self._wrapped,)
def __getattr__(self, attr):
return getattr(self._wrapped, attr)
def __contains__(self, value):
return self._wrapped.__contains__(value)
def __iter__(self):
return self._wrapped.__iter__()
def __len__(self):
return self._wrapped.__len__()
def __eq__(self, other):
if isinstance(other, set_proxy):
return self._wrapped == other._wrapped
else:
return self._wrapped == other
def __ne__(self, other):
if isinstance(other, set_proxy):
return self._wrapped != other._wrapped
else:
return self._wrapped != other
def __lt__(self, other):
if isinstance(other, set_proxy):
return self._wrapped < other._wrapped
else:
return self._wrapped < other
def __le__(self, other):
if isinstance(other, set_proxy):
return self._wrapped <= other._wrapped
else:
return self._wrapped <= other
def __gt__(self, other):
if isinstance(other, set_proxy):
return self._wrapped > other._wrapped
else:
return self._wrapped > other
def __ge__(self, other):
if isinstance(other, set_proxy):
return self._wrapped >= other._wrapped
else:
return self._wrapped >= other
if sys.version_info[0] == 2: # pragma: no 3.x cover; pragma: no branch
def __cmp__(self, other):
raise TypeError("cannot compare sets using cmp()")
def add(self, item):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
self._parent.willChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueUnionSetMutation, set([item])
)
try:
self._wrapped.add(item)
finally:
self._parent.didChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueUnionSetMutation, set([item])
)
def clear(self):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
object = set(self._wrapped)
self._parent.willChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueMinusSetMutation, object
)
try:
self._wrapped.clear()
finally:
self._parent.didChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueMinusSetMutation, object
)
def difference_update(self, *others):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
s = set()
s.update(*others)
self._parent.willChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueMinusSetMutation, s
)
try:
self._wrapped.difference_update(s)
finally:
self._parent.didChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueMinusSetMutation, s
)
def discard(self, item):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
self._parent.willChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueMinusSetMutation, {item}
)
try:
self._wrapped.discard(item)
finally:
self._parent.didChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueMinusSetMutation, {item}
)
def intersection_update(self, other):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
other = set(other)
self._parent.willChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueIntersectSetMutation, other
)
try:
self._wrapped.intersection_update(other)
finally:
self._parent.didChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueIntersectSetMutation, other
)
def pop(self):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
try:
v = next(iter(self))
except StopIteration:
raise KeyError("Empty set")
self.remove(v)
return v
def remove(self, item):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
self._parent.willChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueMinusSetMutation, set([item])
)
try:
self._wrapped.remove(item)
finally:
self._parent.didChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueMinusSetMutation, set([item])
)
def symmetric_difference_update(self, other):
# NOTE: This method does not call the corresponding method
# of the wrapped set to ensure that we generate the right
# notifications.
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
other = set(other)
to_add = set()
to_remove = set()
for o in other:
if o in self:
to_remove.add(o)
else:
to_add.add(o)
self._parent.willChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueMinusSetMutation, to_remove
)
try:
self._wrapped.difference_update(to_remove)
finally:
self._parent.didChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueMinusSetMutation, to_remove
)
self._parent.willChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueUnionSetMutation, to_add
)
try:
self._wrapped.update(to_add)
finally:
self._parent.didChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueUnionSetMutation, to_add
)
def update(self, *others):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
s = set()
s.update(*others)
self._parent.willChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueUnionSetMutation, s
)
try:
self._wrapped.update(s)
finally:
self._parent.didChangeValueForKey_withSetMutation_usingObjects_(
self._name, NSKeyValueUnionSetMutation, s
)
def __or__(self, other):
return self._wrapped | other
def __and__(self, other):
return self._wrapped & other
def __xor__(self, other):
return self._wrapped ^ other
def __sub__(self, other):
return self._wrapped - other
def __ior__(self, other):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
self.update(other)
return self
def __isub__(self, other):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
self.difference_update(other)
return self
def __ixor__(self, other):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
self.symmetric_difference_update(other)
return self
def __iand__(self, other):
if self._ro:
raise ValueError("Property '%s' is read-only" % (self._name,))
self.intersection_update(other)
return self
def makeSetAccessors(name):
def countOf(self):
return len(getattr(self, name))
def enumeratorOf(self):
return iter(getattr(self, name))
def memberOf(self, value):
collection = getattr(self, name)
for item in collection:
if item == value:
return item
else:
return None
def add(self, value):
getattr(self, name).add(value)
def remove(self, value):
getattr(self, name).discard(value)
return countOf, enumeratorOf, memberOf, add, remove
class set_property(object_property):
def __init__(
self,
name=None,
read_only=False,
copy=True,
dynamic=False,
ivar=None,
depends_on=None,
):
super(set_property, self).__init__(
name,
read_only=read_only,
copy=copy,
dynamic=dynamic,
ivar=ivar,
depends_on=depends_on,
)
def __get__(self, object, owner):
v = object_property.__get__(self, object, owner)
if v is None:
v = set()
object_property.__set__(self, object, v)
return set_proxy(self._name, object, self, self._ro)
def __set__(self, object, value):
if isinstance(value, set_proxy):
if value._name == self._name and value._parent is object:
# attr.prop = attr.prop
return
if isinstance(value, set_proxy):
value = list(value)
super(set_property, self).__set__(object, value)
def __getvalue__(self, object):
v = object_property.__get__(self, object, None)
if v is None:
v = set()
object_property.__set__(self, object, v)
return v
def __pyobjc_class_setup__(self, name, class_dict, instance_methods, class_methods):
super(set_property, self).__pyobjc_class_setup__(
name, class_dict, instance_methods, class_methods
)
# (Mutable) Unordered Accessors
# FIXME: should only do the mutable bits when we're actually a mutable property
name = self._name
Name = name[0].upper() + name[1:]
countOf, enumeratorOf, memberOf, add, remove = makeSetAccessors(self._name)
countOf = selector(
countOf,
selector=("countOf%s" % (Name,)).encode("latin1"),
signature=_C_NSUInteger + b"@:",
)
countOf.isHidden = True
instance_methods.add(countOf)
enumeratorOf = selector(
enumeratorOf,
selector=("enumeratorOf%s" % (Name,)).encode("latin1"),
signature=b"@@:",
)
enumeratorOf.isHidden = True
instance_methods.add(enumeratorOf)
memberOf = selector(
memberOf,
selector=("memberOf%s:" % (Name,)).encode("latin"),
signature=b"@@:@",
)
memberOf.isHidden = True
instance_methods.add(memberOf)
add1 = selector(
add, selector=("add%s:" % (Name,)).encode("latin"), signature=b"v@:@"
)
add1.isHidden = True
instance_methods.add(add1)
add2 = selector(
add, selector=("add%sObject:" % (Name,)).encode("latin1"), signature=b"v@:@"
)
add2.isHidden = True
instance_methods.add(add2)
remove1 = selector(
remove, selector=("remove%s:" % (Name,)).encode("latin1"), signature=b"v@:@"
)
remove1.isHidden = True
instance_methods.add(remove1)
remove2 = selector(
remove,
selector=("remove%sObject:" % (Name,)).encode("latin"),
signature=b"v@:@",
)
remove2.isHidden = True
instance_methods.add(remove2)
NSMutableDictionary = lookUpClass("NSMutableDictionary")
class dict_property(object_property):
def __get__(self, object, owner):
v = object_property.__get__(self, object, owner)
if v is None:
v = NSMutableDictionary.alloc().init()
object_property.__set__(self, object, v)
return object_property.__get__(self, object, owner)
|
package com.serebit.diskord
import com.serebit.diskord.events.Event
import com.serebit.diskord.events.MessageCreatedEvent
object EventDispatcher {
private val eventListeners: MutableSet<(Event) -> Unit> = mutableSetOf({ evt ->
(evt as? MessageCreatedEvent)?.let {
if (it.message.author.id != 450109042220859392L) it.message.channel.send("my name jeff")
}
})
internal fun dispatch(event: Event) = eventListeners.forEach { it.invoke(event) }
}
|
var a00456 =
[
[ "KeyDesc", "a00456.html#a486dfb881bc360bbfbd36248bba80552", null ],
[ "KeySize", "a00456.html#a510104dbda460e78eb8d323502594ef2", null ],
[ "Root", "a00456.html#ab52e8a6004fc595de526dfa831c2e725", null ]
];
|
using System.Collections.Generic;
using System.Linq;
public class Kingdom : IKingdom
{
private King king;
private List<IKingGuard> kingGuards;
public Kingdom(King king)
{
this.KingGuards = new List<IKingGuard>();
this.King = king;
}
public List<IKingGuard> KingGuards { get => kingGuards; set => kingGuards = value; }
public King King { get => king; private set => king = value; }
public void AddGuards(IEnumerable<IKingGuard> guards)
{
foreach (IKingGuard guard in guards)
{
this.KingGuards.Add(guard);
guard.RespondToAttack(this.King);
}
}
public void AttackGuard(string guardName)
{
IKingGuard existingKingGuard = this.KingGuards.First(kg => kg.Name == guardName);
existingKingGuard.AttackGuard();
if (existingKingGuard.Health == 0)
{
this.KillGuard(existingKingGuard);
}
}
private void KillGuard(IKingGuard existingKingGuard)
{
existingKingGuard.NoLongerRespondToAttack(this.King);
this.KingGuards.Remove(existingKingGuard);
}
}
|
using System;
using System.Collections.Generic;
namespace TriviaGame
{
class Program
{
static void Main()
{
Answers a = new Answers();
Game g = new Game(a);
a.TextFileToDictionary();
g.GameFunc();
}
}
}
|
For kubernetes deployment we are using <b>ConfigMap</b> kubernetes entity to provide tb-nodes with logback configuration.
So in order to update <b>logback.xml</b> you need to do the following:
```bash
edit common/tb-node-configmap.yml
kubectl apply -f common/tb-node-configmap.yml
```
After 10 seconds the changes should be applied to logging configuration.
|
@testset "tagmap" begin
# Visit every entry in the map.
@testset "tag $t" for t in keys(PNML.tagmap)
@test haskey(PNML.tagmap,t)
@test !isempty(methods(PNML.tagmap[t], (EzXML.Node,))) ||
!isempty(methods(PNML.tagmap[t], (EzXML.Node, PnmlType)))
end
#TODO: Add non-trivial tests.
end
@testset "pnmltype" begin
#@test_call PNML.PnmlTypes.default_pntd_map()
@test_call PNML.pnmltype(PnmlCore())
@test_call pntd_symbol("foo")
@test_call PNML.pnmltype("pnmlcore")
@test_call PNML.pnmltype(:pnmlcore)
end
|
import { erpPostNew } from 'services/ajax';
export default {
namespace: 'targetCharge',
state: {
pannes: [{ title: '目标管理', content: null, key: '1', closable: false }],
activeKey: '1',
dataSource: [
{
key: '1',
group: 'A小组',
groupman: ['张大山', '刘晓吧', '黄校'],
station: 'Amazon-US',
store: 'A店铺',
prod_info1: 'Sony/索尼',
prod_info2: '(28-70)蚂蚁摄影',
prod_info3: 'SKU:abc123456',
prod_info4: 'Asin:87382747',
sellnum: 56,
rank_yesterday: 4500,
rank_today: 2500,
prod_stock: 1000,
starlevel: 5.0,
comment: 10025,
leavemsgrate: 0.25,
price: 9.9,
lastmonthtarget: 3500,
execution: 0.7,
suretarget_currentmonth: 4000,
suretarget_nextmonth: 5000,
},
{
key: '2',
group: 'A小组',
groupman: ['张大山', '刘晓吧', '黄校'],
station: 'Amazon-US',
store: 'A店铺',
prod_info1: 'Sony/索尼',
prod_info2: '(28-70)蚂蚁摄影',
prod_info3: 'SKU:abc123456',
prod_info4: 'Asin:87382747',
sellnum: 56,
rank_yesterday: 4500,
rank_today: 2500,
prod_stock: 1000,
starlevel: 5.0,
comment: 10025,
leavemsgrate: 0.25,
price: 9.9,
lastmonthtarget: 3500,
execution: 0.7,
suretarget_currentmonth: 4000,
suretarget_nextmonth: 5000,
},
],
},
effects: {
// 列表页数据
*fetchIndexList({ payload }, { call, put }) {
const data = yield call(async () => {}, payload);
if (data && Array.isArray(data)) {
data.map((item, index) => {
item.key = index;
item.selected = false;
return item;
});
}
yield put({
type: 'queryIndexList',
payload: Array.isArray(data) ? data : [],
});
},
},
reducers: {
// 列表数据
queryIndexList(state, action) {
return {
...state,
purchaseList: action.payload,
};
},
// 页签切换
pannesOnChange(state, action) {
return {
...state,
activeKey: action.payload,
};
},
},
};
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreatePcostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('pcosts', function(Blueprint $table) {
$table->increments('pcost_id');
$table->integer('sizeId');
$table->integer('capacity');
$table->string('f_employeeBenefit');
$table->string('f_fuelExp');
$table->string('f_waterElectict');
$table->string('f_packingExp');
$table->string('f_maintenanceExp');
$table->string('f_depreciationExp');
$table->string('f_otherExp');
$table->string('c_salary');
$table->string('c_employeeBenefit');
$table->string('c_carriageCharge');
$table->string('c_otherExp');
$table->string('c_mktOperational');
$table->string('c_salesIncentives');
$table->integer('periodeId');
$table->string('year');
$table->integer('userId');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('pcosts');
}
}
|
@include('Restaurante.recursos')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="container marg">
<div class="panel panel-default">
<div class="panel-heading"><h4>Agregar Alimento</h4></div>
<div class="container">
{{Form::open(array('url'=>'/restaurante/addA','files'=>'true'))}}
<div class="col-md-6" style="height:50%;">
<br>
<img id="blah" style="width:100%;" src="" />
<input type="file" name="imgFile" id="imgFile" value="">
</div>
<br>
<div class="col-md-3">
<label>Nombre</label>
<input type="text" name="nombre" value="">
<label>Descripcion</label>
<textarea name="descripcion" id="" rows="10"></textarea>
<label>Categoria </label>
<select name="categoria">
<option value="fria">Fria</option>
<option value="caliente">Caliente</option>
</select>
<br>
<label>Sabor </label>
<select name="sabor">
<option value="salado">Salado</option>
<option value="dulce">Dulce</option>
</select>
</div>
<div class="col-md-3">
<label >Precio</label>
<br>
<input name="precio" value="" type="text">
<br>
<label >Costo por transacción</label>
<br>
<input name="costo" type="text">
<br>
<label for="">Comisión</label>
<br>
<input name="comision" type="text">
<br>
<label for="">Precio final</label>
<br>
<input name="precio_final" value="" type="text">
<br>
<label for="">Horario</label> <input value="" name="horario" type="text">
<br>
<br>
<input type="hidden" name="id" value="">
{{Form::submit('Guardar cambios',array('class'=>'btn btn-primary'))}}
</div>
{{Form::close()}}
</div>
<div class="panel-footer clearfix">
@include('Restaurante.menu')
</div>
</div>
</div>
</body>
</html>
<script>
$('#imgFile').change(function(){
$('#blah')[0].src = window.URL.createObjectURL(this.files[0])
});
</script>
|
//unsigned int good;
unsigned int good=12;
int main ()
{
int a=14;
int b=21;
while (a != b)
{
if (a > b) a-= b;
else b -= a;
}
good = a;
return 0;
}
|
package common
import "container/list"
func MakeInfinite() (chan <-interface{}, <-chan interface{}) {
in := make(chan interface{})
out := make(chan interface{})
go func() {
inQueue := list.List{}
outCh := func() chan interface{} {
if inQueue.Len() == 0 {
return nil
}
return out
}
curVal := func() interface{} {
if inQueue.Len() == 0 {
return nil
}
return inQueue.Front().Value
}
for inQueue.Len() > 0 || in != nil {
select {
case v, ok := <-in:
if !ok {
in = nil
} else {
inQueue.PushBack(v)
}
case outCh() <- curVal():
inQueue.Remove(inQueue.Front())
}
}
close(out)
}()
return in, out
}
|
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
namespace CTFcolab.Entity
{
[Table("User")]
public class User : IEntity
{
public User() {
this.Teams = new HashSet<Team>();
}
[Key]
public int Id { get; set; }
[MaxLength(30)]
[MinLength(1)]
[Index(IsUnique = true)]
public string Name { get; set; }
[MaxLength(100)]
[Index(IsUnique = true)]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
[MaxLength(100)]
public string Password { get; set; }
[MaxLength(100)]
public string Role { get; set; }
public virtual ICollection<Team> Teams { get; set; }
public virtual ResetPasswordCode ResetPasswordCode { get; set; }
}
}
|
var dir_0416c842a0c2c99f7d945ea84c865809 =
[
[ "DrawFluence.C", "d1/dc1/DrawFluence_8C.html", "d1/dc1/DrawFluence_8C" ]
];
|
# Release History
## 1.0.0-beta.3 (Unreleased)
### Features Added
### Breaking Changes
### Bugs Fixed
### Other Changes
## 1.0.0-beta.2 (2021-12-06)
- Azure Resource Manager PolicyInsights client library for Java. This package contains Microsoft Azure SDK for PolicyInsights Management SDK. Package tag package-2021-10. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt).
### Breaking Changes
* `models.PolicyMetadataSlimProperties` was removed
* `models.PolicyMetadataProperties` was removed
### Features Added
* `models.RemediationPropertiesFailureThreshold` was added
#### `PolicyInsightsManager$Configurable` was modified
* `withScope(java.lang.String)` was added
#### `models.Remediation` was modified
* `statusMessage()` was added
* `failureThreshold()` was added
* `correlationId()` was added
* `resourceCount()` was added
* `listDeploymentsAtResourceGroup(java.lang.Integer,com.azure.core.util.Context)` was added
* `listDeploymentsAtResourceGroup()` was added
* `cancelAtResourceGroup()` was added
* `systemData()` was added
* `parallelDeployments()` was added
* `cancelAtResourceGroupWithResponse(com.azure.core.util.Context)` was added
#### `models.Remediation$Definition` was modified
* `withParallelDeployments(java.lang.Integer)` was added
* `withFailureThreshold(models.RemediationPropertiesFailureThreshold)` was added
* `withResourceCount(java.lang.Integer)` was added
#### `models.Remediation$Update` was modified
* `withParallelDeployments(java.lang.Integer)` was added
* `withFailureThreshold(models.RemediationPropertiesFailureThreshold)` was added
* `withResourceCount(java.lang.Integer)` was added
## 1.0.0-beta.1 (2021-04-22)
- Azure Resource Manager PolicyInsights client library for Java. This package contains Microsoft Azure SDK for PolicyInsights Management SDK. Package tag package-2021-01. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt).
|
using System;
using System.Linq;
using System.Management;
namespace SessionWatch.Service
{
internal class Machine
{
public String GetUsername()
{
try
{
var scope = new ManagementScope("\\\\.\\root\\cimv2");
scope.Connect();
var query = new ObjectQuery("SELECT * FROM Win32_ComputerSystem");
var searcher = new ManagementObjectSearcher(scope, query);
var results = searcher.Get()
.Cast<ManagementObject>()
.First();
var result = results["UserName"]
.ToString();
return result;
}
catch (Exception)
{
return null;
}
}
}
}
|
# Space Rocks
A simple space game made with Python and Pygame
## Installation
Requires Python 3.
```
pip install -r requirements.txt
python space_rocks
```
|
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:test/test.dart';
import 'package:stream_transform/stream_transform.dart';
void main() {
var streamTypes = {
'single subscription': () => StreamController(),
'broadcast': () => StreamController.broadcast()
};
for (var firstType in streamTypes.keys) {
for (var secondType in streamTypes.keys) {
group('followedBy [$firstType] with [$secondType]', () {
StreamController first;
StreamController second;
List emittedValues;
bool firstCanceled;
bool secondCanceled;
bool secondListened;
bool isDone;
List errors;
Stream transformed;
StreamSubscription subscription;
setUp(() async {
firstCanceled = false;
secondCanceled = false;
secondListened = false;
first = streamTypes[firstType]()
..onCancel = () {
firstCanceled = true;
};
second = streamTypes[secondType]()
..onCancel = () {
secondCanceled = true;
}
..onListen = () {
secondListened = true;
};
emittedValues = [];
errors = [];
isDone = false;
transformed = first.stream.transform(followedBy(second.stream));
subscription = transformed
.listen(emittedValues.add, onError: errors.add, onDone: () {
isDone = true;
});
});
test('adds all values from both streams', () async {
first..add(1)..add(2);
await first.close();
await Future(() {});
second..add(3)..add(4);
await Future(() {});
expect(emittedValues, [1, 2, 3, 4]);
});
test('Does not listen to second stream before first stream finishes',
() async {
expect(secondListened, false);
await first.close();
expect(secondListened, true);
});
test('closes stream after both inputs close', () async {
await first.close();
await second.close();
expect(isDone, true);
});
test('cancels any type of first stream on cancel', () async {
await subscription.cancel();
expect(firstCanceled, true);
});
if (firstType == 'single subscription') {
test(
'cancels any type of second stream on cancel if first is '
'broadcast', () async {
await first.close();
await subscription.cancel();
expect(secondCanceled, true);
});
if (secondType == 'broadcast') {
test('can pause and resume during second stream - dropping values',
() async {
await first.close();
subscription.pause();
second.add(1);
await Future(() {});
subscription.resume();
second.add(2);
await Future(() {});
expect(emittedValues, [2]);
});
} else {
test('can pause and resume during second stream - buffering values',
() async {
await first.close();
subscription.pause();
second.add(1);
await Future(() {});
subscription.resume();
second.add(2);
await Future(() {});
expect(emittedValues, [1, 2]);
});
}
}
if (firstType == 'broadcast') {
test('can cancel and relisten during first stream', () async {
await subscription.cancel();
first.add(1);
subscription = transformed.listen(emittedValues.add);
first.add(2);
await Future(() {});
expect(emittedValues, [2]);
});
test('can cancel and relisten during second stream', () async {
await first.close();
await subscription.cancel();
second.add(2);
await Future(() {});
subscription = transformed.listen(emittedValues.add);
second.add(3);
await Future(() {});
expect(emittedValues, [3]);
});
test('forwards values to multiple listeners', () async {
var otherValues = [];
transformed.listen(otherValues.add);
first.add(1);
await first.close();
second.add(2);
await Future(() {});
var thirdValues = [];
transformed.listen(thirdValues.add);
second.add(3);
await Future(() {});
expect(emittedValues, [1, 2, 3]);
expect(otherValues, [1, 2, 3]);
expect(thirdValues, [3]);
});
}
});
}
}
}
|
package com.cheise_proj.local.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.cheise_proj.local.mapper.user.UserLocalDataMapper
@Entity(tableName = "users")
data class UserLocal(
val email: String,
val avatarUrl: String,
@PrimaryKey(autoGenerate = false)
val userId: String,
val name: String,
var accessToken: String,
var refreshToken: String
) {
constructor() : this("", "", "", "", "", "")
companion object {
fun userMapper() = UserLocalDataMapper()
}
}
|
<?php
ini_set("display_errors", true);
ini_set("display_startup_errors", true);
error_reporting(E_ALL);
setlocale(LC_ALL, "", "pt_BR.utf8");
require_once __DIR__ . '/vendor/autoload.php';
$api = new Routes\Api();
$api->loadMap();
$api->setRequestAndDispatch();
|
#!/usr/bin/env bash
set -e
# -device ioh3420,bus=pci.0,addr=1c.0,multifunction=on,port=1,chassis=1,id=root.1
# -device vfio-pci,host=01:00.0,bus=root.1,addr=00.0,multifunction=on,x-vga=on
./build.sh
pushd ../efi-pcm-dxe
./build.sh
popd
pushd ../efi-pcm-test
./build.sh
popd
# pushd ../edk2-test
# ./build.sh
# popd
cp ./../efi-pcm-dxe/target/x86_64-unknown-uefi/debug/efi-pcm-dxe.efi hda
cp ./../efi-hda-dxe/target/x86_64-unknown-uefi/debug/efi-hda-dxe.efi hda
cp ./../efi-pcm-test/target/x86_64-unknown-uefi/debug/efi-pcm-test.efi hda
cp ~/edk2/Build/RustTestPkg/DEBUG_GCC5/X64/Launcher.efi hda
# -soundhw hda
# -device intel-hda
# -device intel-hda,debug=255
# -audiodev pa,id=hda,server=unix:/tmp/pulse-socket
# -device intel-hda,debug=255 \
# -device hda-micro,debug=255
# -audiodev pa,id=audiodev-0,timer-period=1000,in.buffer-length=3000,out.buffer-length=3000 \
qemu-system-x86_64 \
-machine q35 \
-m 1024 \
-vga std \
-hda fat:rw:hda \
-bios ovmf/OVMF.fd \
-global e1000.romfile="" \
-debugcon file:debug.log \
-global isa-debugcon.iobase=0x402 \
-s \
-serial file:serial.txt \
-serial stdio \
-device ich9-intel-hda,debug=255 \
-device hda-micro,debug=255
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.