repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
dkraczkowski/opyapi
tests/http/test_http_response.py
<gh_stars>1-10 import pytest from opyapi.http import Headers from opyapi.http import HttpResponse def test_can_instantiate(): instance = HttpResponse(200) assert isinstance(instance, HttpResponse) def test_can_write_and_read_body(): instance = HttpResponse(200) instance.write("Example text") assert str(instance) == "Example text" instance.body.seek(0) assert instance.body.read() == b"Example text" def test_can_close_body(): instance = HttpResponse(200) instance.write("Test") assert instance.writable instance.close() assert not instance.writable def test_headers(): instance = HttpResponse() with pytest.raises(AttributeError): instance.headers = None assert isinstance(instance.headers, Headers)
Enerccio/kclib
kclib/intinc/string.h
<reponame>Enerccio/kclib /* * string.h * * Created on: Dec 18, 2015 * Author: pvan */ #ifndef INTINC_STRING_H_ #define INTINC_STRING_H_ #ifdef __cplusplus extern "C" { #endif /** * Thread safe call to strtok */ char* __strtok_ts(char** token, char* restrict s1, const char* restrict s2) __attribute__((nonnull (1, 3))); /** * Same as memcpy, but stores true into flagged if flag_char is encountered * * - slower than memcpy */ void* __memcpy_cb(void* restrict s1, const void* restrict s2, size_t n, bool* flagged, char flag_char) __attribute__((nonnull (1, 2, 4))); /** * Same as memmove, but stores true into flagged if flag_char is encountered * * - slower than memmove */ void* __memmove_cb(void* s1, const void* s2, size_t n, bool* flagged, char flag_char) __attribute__((nonnull (1, 2, 4))); #ifdef __cplusplus } #endif #endif /* INTINC_STRING_H_ */
WPIMascotMQP/version0.1
behaviourtree/composite/Sequence.cpp
<filename>behaviourtree/composite/Sequence.cpp #include "Sequence.h" /** CONSTRUCTOR @param childr The children of this sequence object */ Sequence::Sequence(std::vector<Node*> childr) : Composite(childr) { currentChild = children.begin(); } /** DECONSTRUCTOR */ Sequence::~Sequence() { } /** Node execute as child function Calls all children in order @return The status */ Status* Sequence::executeC() { logger::log("Sequence Called As Child"); Node* node = *currentChild; node->setParent(this); logger::log("Call Sequence Child"); node->executeC(); currentChild++; status.setRunning(); return &status; } /** Node execute as parent function calls the next child or the parent node if done @param stat The status of the child executing this parent @return the status */ Status* Sequence::executeP(Status* stat) { logger::log("Sequence Called As Parent"); if (stat->getState() == failure) { reset(); return parent->executeP(stat); } if (currentChild >= children.end()) { reset(); status.setSuccess(); logger::log("Call Sequence Parent"); return parent->executeP(&status); } return executeC(); } /** Resets the sequence node to the beginning */ void Sequence::reset() { currentChild = children.begin(); }
cmri/BC-BSP
src/java/com/chinamobile/bcbsp/sync/WorkerSSControllerInterface.java
<reponame>cmri/BC-BSP /** * CopyRight by Chinamobile * * WorkerSSControllerInterface.java */ package com.chinamobile.bcbsp.sync; /** * WorkerSSControllerInterface * * WorkerSSControllerInterface for local synchronization and aggregation. This class is * connected to WorkerAgentForJob. * * @author * @version */ public interface WorkerSSControllerInterface { /** * Make sure that all staffs have completed the local computation and * message-receiving. * * @param superStepCounter * @param ssrc * @return */ public boolean firstStageSuperStepBarrier(int superStepCounter, SuperStepReportContainer ssrc); /** * Report the local information * * @param superStepCounter * @param ssrc * @return */ public boolean secondStageSuperStepBarrier(int superStepCounter, SuperStepReportContainer ssrc); /** * Make sure that all staffs have completed the checkpoint-write operation. * * @param superStepCounter * @param ssrc * @return */ public boolean checkPointStageSuperStepBarrier(int superStepCounter, SuperStepReportContainer ssrc); /** * Make sure that all staffs have saved the computation result and the job * finished successfully. * * @param superStepCounter * @param ssrc * @return */ public boolean saveResultStageSuperStepBarrier(int superStepCounter, SuperStepReportContainer ssrc); }
shashankcm/Full-Stack-Online-Shopping-Website
frontend/node_modules/apollo-client/index.js
<filename>frontend/node_modules/apollo-client/index.js export { print as printAST } from 'graphql/language/printer'; export { ObservableQuery, } from './core/ObservableQuery'; export { NetworkStatus } from './core/networkStatus'; export * from './core/types'; export { ApolloError } from './errors/ApolloError'; import ApolloClient from './ApolloClient'; export { ApolloClient }; export default ApolloClient; //# sourceMappingURL=index.js.map
horondi/horondi_client_fe
src/containers/currency/constants.js
export const HRYVNIA_UNICODE = '\u20b4'; export const DOLLAR_UNICODE = '\u0024';
flaviovdf/pyksc
src/pyksc/test/test_regression.py
<filename>src/pyksc/test/test_regression.py #-*- coding: utf8 '''Unit tests for the regression module''' from __future__ import division, print_function from numpy.testing import * from pyksc import regression from sklearn import linear_model from sklearn.grid_search import GridSearchCV import numpy as np import unittest class TestRSELinearRegression(unittest.TestCase): def test_rse(self): assert_equal(regression.mean_relative_square_error([1, 1, 1], [0, 0, 0]), 1) assert_almost_equal(regression.mean_relative_square_error([10, 10, 10],\ [1, 2, 3]), 0.6466, 3) assert_equal(regression.mean_relative_square_error([1, 0.5, 0.8], [1, 0.5, 0.8]), 0) def test_rse_fit_one_attr(self): X = [[1], [4]] X_conv = [[1], [2]] y = [1, 2] rse_lsq = regression.RSELinearRegression(fit_intercept=False) lsq = linear_model.LinearRegression(fit_intercept=False) model_rse = rse_lsq.fit(X, y) model_lsq = lsq.fit(X_conv, np.ones(len(y))) assert_array_equal(model_lsq.coef_, model_rse.coef_) assert_equal(model_lsq.intercept_, model_rse.intercept_) assert_array_almost_equal(model_rse.predict([[1], [4]]), model_lsq.predict([[1], [4]])) def test_rse_fit(self): X = [[1.0, 2], [4, 8]] X_conv = [[1.0, 2], [2, 4]] y = [1, 2] rse_lsq = regression.RSELinearRegression(fit_intercept=False) lsq = linear_model.LinearRegression(fit_intercept=False) model_rse = rse_lsq.fit(X, y) model_lsq = lsq.fit(X_conv, np.ones(len(y))) assert_array_equal(model_lsq.coef_, model_rse.coef_) assert_equal(model_lsq.intercept_, model_rse.intercept_) assert_array_almost_equal(model_rse.predict([[1, 2], [1, 2]]), model_lsq.predict([[1, 2], [1, 2]])) class TestMultiClassRegression(unittest.TestCase): def test_multiclass(self): X = [[1, 2], [1, 2], [4, 8], [4, 8], [200, 200], [199, 200.1], [200.2, 198]] y_clf = [0, 0, 0, 0, 1, 1, 1] y_regression = [1, 1, 2, 2, 100, 100, 100] regr_class = regression.RSELinearRegression(fit_intercept=False) clf_class = linear_model.LogisticRegression() multi_class = regression.MultiClassRegression(clf_class, regr_class) model = multi_class.fit(X, y_clf, y_regression) p = model.predict([[1, 2], [200, 200], [1, 2], [200, 200]]) assert_equal(p[0], p[2]) assert_equal(p[1], p[3]) self.assertTrue(p[0] != p[1]) def test_multiclass_parallel(self): X = [[1, 2], [1, 2], [4, 8], [4, 8], [200, 200], [199, 200.1], [200.2, 198]] y_clf = [0, 0, 0, 0, 1, 1, 1] y_regression = [1, 1, 2, 2, 100, 100, 100] regr_class = regression.RSELinearRegression(fit_intercept=False) clf_class = linear_model.LogisticRegression() multi_class = regression.MultiClassRegression(clf_class, regr_class, n_jobs=2) model = multi_class.fit(X, y_clf, y_regression) p = model.predict([[1, 2], [200, 200], [1, 2], [200, 200]]) assert_equal(p[0], p[2]) assert_equal(p[1], p[3]) self.assertTrue(p[0] != p[1]) def test_with_grid_search(self): X = [[1, 2], [1, 2], [4, 8], [4, 8], [200, 200], [199, 200.1], [200.2, 198]] y_clf = [0, 0, 0, 0, 1, 1, 1] y_regression = [1, 1, 2, 2, 100, 100, 100] regr_class = GridSearchCV(regression.RSELinearRegression(), {'normalize':[0,1]}) clf_class = GridSearchCV(linear_model.LogisticRegression(), {'C':[1,2]}) multi_class = regression.MultiClassRegression(clf_class, regr_class) model = multi_class.fit(X, y_clf, y_regression) p = model.predict([[1, 2], [200, 200], [1, 2], [200, 200]]) assert_equal(p[0], p[2]) assert_equal(p[1], p[3]) self.assertTrue(p[0] != p[1])
globalbus/karaf
util/src/test/java/org/apache/karaf/util/DeployerUtilsTest.java
<reponame>globalbus/karaf<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.karaf.util; import junit.framework.TestCase; import org.junit.Test; import static org.apache.karaf.util.DeployerUtils.extractNameVersionType; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class DeployerUtilsTest extends TestCase { @Test public void test() { assertThat( extractNameVersionType("foobarbaz-1.jar"), equalTo(new String[]{"foobarbaz", "1", "jar"}) ); assertThat( extractNameVersionType("foobarbaz-1.0.jar"), equalTo(new String[]{"foobarbaz", "1.0", "jar"}) ); assertThat( extractNameVersionType("foobarbaz-1.0.0.jar"), equalTo(new String[]{"foobarbaz", "1.0.0", "jar"}) ); assertThat( extractNameVersionType("foobarbaz-1-PR-4-SNAPSHOT.jar"), equalTo(new String[]{"foobarbaz", "1.0.0.PR-4-SNAPSHOT", "jar"}) ); assertThat( extractNameVersionType("foobarbaz-1.0-PR-4-SNAPSHOT.jar"), equalTo(new String[]{"foobarbaz", "1.0.0.PR-4-SNAPSHOT", "jar"}) ); assertThat( extractNameVersionType("foobarbaz-1.0.0-PR-4-SNAPSHOT.jar"), equalTo(new String[]{"foobarbaz", "1.0.0.PR-4-SNAPSHOT", "jar"}) ); } }
bstee615/ReVeal
code-slicer/joern/projects/extensions/jpanlib/src/main/java/ast/CodeLocation.java
<filename>code-slicer/joern/projects/extensions/jpanlib/src/main/java/ast/CodeLocation.java<gh_stars>10-100 package ast; public class CodeLocation { final public static int NOT_SET = -1; public int startLine = NOT_SET; public int endLine = NOT_SET; public int startPos = NOT_SET; public int startIndex = NOT_SET; public int stopIndex = NOT_SET; @Override public String toString() { return String.format("%d:%d:%d:%d", startLine, startPos, startIndex, stopIndex); } }
KonstantinosAng/CodeWars
Python/[6 kyu] consecutive count.py
# see https://www.codewars.com/kata/59c3e819d751df54e9000098/train/python from TestFunction import Test def get_consective_items(items, key): positions, max_count, count = [], 0, 0 for i, item in enumerate(str(items)): if item == str(key): positions.append(i) for i in range(len(positions)-1): if positions[i+1] - positions[i] == 1: count += 1 else: count = 0 if count > max_count: max_count = count if len(positions) == 0: return 0 return max_count + 1 test = Test(None) test.assert_equals(get_consective_items(90000, 0), 4) test.assert_equals(get_consective_items('ascasdaiiiasdacasdiiiiicasdasdiiiiiiiiiiisdasdasdiii', 'i'), 11)
Blaubot/Blaubot
blaubot-android/src/main/java/eu/hgross/blaubot/android/wifip2p/WifiP2PConnectionMetaDataDTO.java
<reponame>Blaubot/Blaubot<filename>blaubot-android/src/main/java/eu/hgross/blaubot/android/wifip2p/WifiP2PConnectionMetaDataDTO.java<gh_stars>10-100 package eu.hgross.blaubot.android.wifip2p; import eu.hgross.blaubot.core.acceptor.ConnectionMetaDataDTO; /** * Created by henna on 16.02.15. */ public class WifiP2PConnectionMetaDataDTO extends ConnectionMetaDataDTO { private static final String TYPE = "WifiP2PAcceptor_1.0"; public WifiP2PConnectionMetaDataDTO(String ipAddress, int acceptorPort) { super(); getMetaData().put(CONNECTION_TYPE_KEY, TYPE); } }
gspeedtech/Audacity
src/effects/Fade.cpp
<reponame>gspeedtech/Audacity /********************************************************************** Audacity: A Digital Audio Editor Fade.cpp <NAME> *******************************************************************//** \class EffectFadeIn \brief An EffectSimpleMono *//****************************************************************//** \class EffectFadeOut \brief An EffectSimpleMono *//*******************************************************************/ #include "../Audacity.h" #include "Fade.h" #include "../WaveTrack.h" #include <wx/generic/textdlgg.h> #include <math.h> bool EffectFadeIn::NewTrackSimpleMono() { mLen = (int)((mCurT1 - mCurT0) * mCurRate + 0.5); mSample = 0; return true; } bool EffectFadeIn::ProcessSimpleMono(float *buffer, sampleCount len) { for (sampleCount i = 0; i < len; i++) buffer[i] = (float) (buffer[i] * (float) (mSample + i) / (float) (mLen)); mSample += len; return true; } bool EffectFadeOut::NewTrackSimpleMono() { mLen = (int)((mCurT1 - mCurT0) * mCurRate + 0.5); mSample = 0; return true; } bool EffectFadeOut::ProcessSimpleMono(float *buffer, sampleCount len) { for (sampleCount i = 0; i < len; i++) buffer[i] = (float) (buffer[i] * (float) (mLen - 1 - (mSample + i)) / (float) (mLen)); mSample += len; return true; } // Indentation settings for Vim and Emacs and unique identifier for Arch, a // version control system. Please do not modify past this point. // // Local Variables: // c-basic-offset: 3 // indent-tabs-mode: nil // End: // // vim: et sts=3 sw=3 // arch-tag: cd703234-7ddd-4d78-b878-2847d0f014a4
yxlao/StanfordPCL
apps/src/dinast_grabber_example.cpp
#include <string> #include <string.h> #include <stdlib.h> #include <iostream> #include <cstdio> #include <Eigen/Core> #include <pcl/common/transforms.h> #include <pcl/common/time.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/visualization/image_viewer.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/io/dinast_grabber.h> #define FPS_CALC(_WHAT_) \ do { \ static unsigned count = 0; \ static double last = pcl::getTime(); \ double now = pcl::getTime(); \ ++count; \ if (now - last >= 1.0) { \ std::cout << "Average framerate(" << _WHAT_ \ << "): " << double(count) / double(now - last) << " Hz" \ << std::endl; \ count = 0; \ last = now; \ } \ } while (false) void savePGM(const unsigned char *image, const std::string &filename) { FILE *file = fopen(filename.c_str(), "w"); if (!file) { std::cerr << "Unable to open file '" << filename << "' for writing." << std::endl; return; } // PGM header fprintf(file, "P2\n%d %d\n255\n", IMAGE_WIDTH, IMAGE_HEIGHT); // Write data as ASCII for (int i = 0; i < IMAGE_HEIGHT; ++i) { for (int j = 0; j < IMAGE_WIDTH; ++j) { fprintf(file, "%3d ", (int)*image++); } fprintf(file, "\n"); } fclose(file); } void keyboardEventOccurred(const pcl::visualization::KeyboardEvent &event, void *data) { static int NUM_IMAGES = 0; if (event.getKeySym() == "s" && event.keyDown()) { char filename[16]; snprintf(filename, sizeof(filename), "image%.2d.pgm", NUM_IMAGES++); unsigned char *image = reinterpret_cast<unsigned char *>(data); savePGM(image, filename); printf("Wrote %s\n", filename); } } void convertImageToCloud(const unsigned char *image, pcl::PointCloud<pcl::PointXYZI> &cloud) { cloud.points.resize(IMAGE_WIDTH * IMAGE_HEIGHT); cloud.width = IMAGE_WIDTH; cloud.height = IMAGE_HEIGHT; cloud.is_dense = false; int depth_idx = 0; int pxl[9]; for (int x = 0; x < cloud.width; ++x) { for (int y = 0; y < cloud.height; ++y, ++depth_idx) { float xc = (float)(x - 160); float yc = (float)(y - 120); double r1 = sqrt(xc * xc + yc * yc); double r2 = r1 * r1; double r3 = r1 * r2; double A = -2e-5 * r3 + 0.004 * r2 + 0.1719 * r1 + 350.03; double B = -2e-9 * r3 + 3e-7 * r2 - 1e-5 * r1 - 0.01; // Low pass filtering /// @todo Try a bilateral filter to avoid blurring over depth /// boundaries int measure = 0; if ((y > 0) && (y < (IMAGE_HEIGHT - 1)) && (x > 0) && (x < (IMAGE_WIDTH - 1))) { int ipx = x + IMAGE_WIDTH * y; #if 1 pxl[0] = image[ipx]; pxl[1] = image[ipx - 1]; pxl[2] = image[ipx + 1]; pxl[3] = image[ipx - IMAGE_WIDTH]; pxl[4] = image[ipx - IMAGE_WIDTH - 1]; pxl[5] = image[ipx - IMAGE_WIDTH + 1]; pxl[6] = image[ipx + IMAGE_WIDTH]; pxl[7] = image[ipx + IMAGE_WIDTH - 1]; pxl[8] = image[ipx + IMAGE_WIDTH + 1]; for (int ii = 0; ii < 9; ii++) measure += pxl[ii]; measure /= 9; #else // No blurring measure = image[ipx]; #endif } if (measure > 255) measure = 255; // saturation for display unsigned char pixel = measure; // image[depth_idx]; if (pixel < 1) { cloud.points[depth_idx].x = std::numeric_limits<float>::quiet_NaN(); cloud.points[depth_idx].y = std::numeric_limits<float>::quiet_NaN(); cloud.points[depth_idx].z = std::numeric_limits<float>::quiet_NaN(); cloud.points[depth_idx].intensity = pixel; continue; } if (pixel > A) pixel = A; float dy = y * 0.1; double dist = (log((double)pixel / A) / B - dy) * (7E-07 * r3 - 0.0001 * r2 + 0.004 * r1 + 0.9985) * 1.5; double dist_2d = r1; static const double dist_max_2d = 1 / 160.0; /// @todo Why not 200? // static const double dist_max_2d = 1 / 200.0; static const double FOV = 64.0 * M_PI / 180.0; // diagonal FOV? double theta_colati = FOV * r1 * dist_max_2d; double c_theta = cos(theta_colati); double s_theta = sin(theta_colati); double c_ksai = ((double)(x - 160.)) / r1; double s_ksai = ((double)(y - 120.)) / r1; cloud.points[depth_idx].x = (dist * s_theta * c_ksai) / 500.0 + 0.5; // cartesian x cloud.points[depth_idx].y = (dist * s_theta * s_ksai) / 500.0 + 0.5; // cartesian y cloud.points[depth_idx].z = (dist * c_theta); // cartesian z /// @todo This looks weird, can it cause artifacts? if (cloud.points[depth_idx].z < 0.01) #if 1 cloud.points[depth_idx].z = 0.01; #else cloud.points[depth_idx].x = std::numeric_limits<float>::quiet_NaN(); cloud.points[depth_idx].y = std::numeric_limits<float>::quiet_NaN(); cloud.points[depth_idx].z = std::numeric_limits<float>::quiet_NaN(); cloud.points[depth_idx].intensity = pixel; continue; #endif cloud.points[depth_idx].z /= 500.0; cloud.points[depth_idx].intensity = pixel; } } } /* --[ */ int main(int argc, char **argv) { pcl::DinastGrabber grabber; grabber.findDevice(1); grabber.openDevice(); std::cerr << "Device version/revision number: " << grabber.getDeviceVersion() << std::endl; grabber.start(); pcl::visualization::ImageViewer vis_img("Dinast Image Viewer"); pcl::visualization::PCLVisualizer vis_cld(argc, argv, "Dinast Cloud Viewer"); unsigned char *img1 = (unsigned char *)malloc(IMAGE_SIZE); unsigned char *img2 = (unsigned char *)malloc(IMAGE_SIZE); pcl::PointCloud<pcl::PointXYZI>::Ptr cloud( new pcl::PointCloud<pcl::PointXYZI>); while (true) { if (grabber.readImage(img1, img2) == 0) continue; convertImageToCloud(img1, *cloud); FPS_CALC("grabber + visualization"); vis_img.showMonoImage(img1, IMAGE_WIDTH, IMAGE_HEIGHT); pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZI> handler(cloud, "intensity"); if (!vis_cld.updatePointCloud(cloud, handler, "DinastCloud")) { vis_cld.addPointCloud(cloud, handler, "DinastCloud"); vis_cld.resetCameraViewpoint("DinastCloud"); } vis_img.spinOnce(); vis_cld.spinOnce(); } grabber.stop(); grabber.closeDevice(); }
OpenChemistry/experimentaldataplatform
server/edp/server/models/postmortem.py
<gh_stars>1-10 from .base import Base class Postmortem(Base): def __init__(self): from girder.plugins.edp.models.project import Project from girder.plugins.edp.models.postmortemtest import PostmortemTest super(Postmortem, self).__init__( name='edp.postmortem', props=( { 'name': 'startDate', 'expose': True, 'create': True, 'mutable': True }, { 'name': 'title', 'expose': True, 'ensureIndex': True, 'create': True, 'mutable': True }, { 'name': 'comments', 'expose': True, 'ensureTextIndex': True, 'create': True, 'mutable': True }, { 'name':'public', 'mutable': True, 'create': True }, { 'name': 'projectId', 'create': True } ), parent_model=Project, child_model=PostmortemTest, url='postmortems' )
cardforcoin/shale-scala
logback-setup/build.sbt
name := "logback-setup" libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.0.0"
TakehideSoh/Scarab
org.sat4j.pb/src/main/java/org/sat4j/pb/IGroupPBSolver.java
package org.sat4j.pb; import java.math.BigInteger; import org.sat4j.specs.ContradictionException; import org.sat4j.specs.IConstr; import org.sat4j.specs.IGroupSolver; import org.sat4j.specs.IVec; import org.sat4j.specs.IVecInt; public interface IGroupPBSolver extends IGroupSolver, IPBSolver { IConstr addAtMost(IVecInt literals, int degree, int groupid) throws ContradictionException; IConstr addAtLeast(IVecInt literals, int degree, int groupid) throws ContradictionException; IConstr addExactly(IVecInt literals, int n, int groupid) throws ContradictionException; IConstr addAtMost(IVecInt literals, IVecInt coeffs, int degree) throws ContradictionException; IConstr addAtMost(IVecInt literals, IVec<BigInteger> coeffs, BigInteger degree, int groupdId) throws ContradictionException; IConstr addAtMost(IVecInt literals, IVecInt coeffs, int degree, int groupId) throws ContradictionException; IConstr addAtLeast(IVecInt literals, IVecInt coeffs, int degree, int groupId) throws ContradictionException; IConstr addAtLeast(IVecInt literals, IVec<BigInteger> coeffs, BigInteger degree, int groupId) throws ContradictionException; IConstr addExactly(IVecInt literals, IVecInt coeffs, int weight, int groupId) throws ContradictionException; IConstr addExactly(IVecInt literals, IVec<BigInteger> coeffs, BigInteger weight, int groupId) throws ContradictionException; }
sedurCode/nodOSC
firmware/newlib_nano/src/malloc.c
#include <stdlib.h> #include <string.h> #include <sys/config.h> #include <reent.h> #include <malloc.h> extern void *pvPortMalloc( size_t xWantedSize ); extern void vPortFree( void *pv ); extern size_t xPortGetFreeHeapSize( void ); extern size_t xPortGetMinimumEverFreeHeapSize( void ); extern size_t xPortGetHeapSize( void ); extern size_t xPortGetBlockSize( void* ptr ); extern void __malloc_lock(struct _reent *ptr); extern void __malloc_unlock(struct _reent *ptr); void* _malloc_r(struct _reent *r, size_t s) { (void)r; void* ptr = pvPortMalloc((size_t)s); return ptr; } void _free_r(struct _reent* r, void* ptr) { (void)r; vPortFree(ptr); } void _cfree_r(struct _reent* r, void* ptr) { _free_r(r, ptr); } void* _calloc_r(struct _reent* r, size_t n, size_t elem) { void* ptr = _malloc_r(r, (size_t)(n * elem)); if (ptr != NULL) { memset(ptr, 0, (size_t)(elem * n)); } return ptr; } void* _realloc_r(struct _reent* r, void *ptr, size_t newsize) { (void)r; if (newsize == 0) { vPortFree(ptr); return NULL; } void *p = pvPortMalloc(newsize); if (p) { if (ptr != NULL) { memcpy(p, ptr, newsize); vPortFree(ptr); } } return p; } static struct mallinfo current_mallinfo = {0}; struct mallinfo _mallinfo_r(struct _reent* r) { __malloc_lock(r); current_mallinfo.arena = xPortGetHeapSize(); current_mallinfo.fordblks = xPortGetFreeHeapSize(); current_mallinfo.uordblks = current_mallinfo.arena - current_mallinfo.fordblks; current_mallinfo.usmblks = current_mallinfo.arena - xPortGetMinimumEverFreeHeapSize(); __malloc_unlock(r); return current_mallinfo; } void _malloc_stats_r(struct _reent* r) { } size_t _malloc_usable_size_r(struct _reent* r, void* ptr) { (void)r; return xPortGetBlockSize(ptr); }
al1221/ghost-openshift
core/client/node_modules/ember-cli-babel/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/core-js/src/es6.object.prototype.js
!function(tmp){ // 19.1.3.6 Object.prototype.toString() tmp[SYMBOL_TAG] = DOT; if(cof(tmp) != DOT)hidden(ObjectProto, TO_STRING, function(){ return '[object ' + classof(this) + ']'; }); }({});
shapri/martian_robots
src/test/java/martian_robots/SpringIntegrationTest.java
package martian_robots; import martian_robots.config.Configuration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; @ActiveProfiles("test") @SpringBootTest @ContextConfiguration(classes = Configuration.class) public class SpringIntegrationTest { }
N-Silbernagel/discordbot
src/test/java/com/github/nsilbernagel/discordbot/audio/VolumeTaskTest.java
<gh_stars>0 package com.github.nsilbernagel.discordbot.audio; import com.github.nsilbernagel.discordbot.message.MessageTestUtil; import com.github.nsilbernagel.discordbot.message.MsgTaskRequest; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import discord4j.core.object.entity.Message; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.test.publisher.PublisherProbe; import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; @ExtendWith(MockitoExtension.class) public class VolumeTaskTest { @Mock private LavaPlayerAudioProvider lavaPlayerAudioProviderMock; @Mock private AudioPlayer audioPlayerMock; private VolumeTask volumeTask; @BeforeEach public void SetUp() { this.volumeTask = spy(new VolumeTask(this.lavaPlayerAudioProviderMock)); } @Test public void it_returns_the_current_volume_if_no_volume_param_was_specified(){ Integer fakeVolume = 50; MsgTaskRequest volumeTaskRequest = spy(MessageTestUtil.generateMsgTaskRequest()); String testCommand = volumeTaskRequest.getCommandToken() + "volume"; // current volume fake when(this.lavaPlayerAudioProviderMock.getPlayer()).thenReturn(this.audioPlayerMock); when(this.audioPlayerMock.getVolume()).thenReturn(fakeVolume); when(volumeTaskRequest.getMessage().getContent()).thenReturn(testCommand); ArgumentCaptor<String> volumeMessageResponseCaptor = ArgumentCaptor.forClass(String.class); PublisherProbe<Message> volumeMessageMono = PublisherProbe.empty(); doReturn(volumeMessageMono.mono()).when(volumeTaskRequest).respond(volumeMessageResponseCaptor.capture()); this.volumeTask.action(volumeTaskRequest); volumeMessageMono.assertWasSubscribed(); assertTrue(volumeMessageResponseCaptor.getValue().contains(fakeVolume.toString())); } }
Eve-ning/aleph0
scripts/f834.py
from math import pi import numpy as np from aleph.consts import * from reamber.osu.OsuBpm import OsuBpm, MIN_BPM, MAX_BPM from reamber.osu.OsuHit import OsuHit from reamber.osu.OsuMap import OsuMap from reamber.osu.lists.notes.OsuHitList import OsuHitList offsets = OsuHitList.readEditorString( "05:29:364 (" "329364|3,329484|3,329604|3,329724|3,329844|3,329964|3,330084|3,330204|3," "330324|3,330444|3,330564|3,330684|3,330804|3,330924|3,331044|3,331164|3," "332244|0,332364|0,332484|0,332604|0,332724|0,332844|0,332964|0,333084|0," "333204|0,333324|0,333444|0,333564|0,333684|0,333804|0,333924|0,334044|0," "334164|0,334284|0,334404|0,334524|0,334644|0,334764|0,334884|0,335004|0," "335124|0,335244|0,335364|0,335484|0,335604|0,335724|0,335844|0,335964|0," "337044|0,337164|0,337284|0,337404|0,337524|0,337644|0,337764|0,337884|0," "338004|0,338124|0,338244|0,338364|0,338484|0,338604|0,338724|0,338844|0," "339924|0,340044|0,340164|0,340284|0,340404|0,340524|0,340644|0,340764|0," "340884|0,341004|0,341124|0,341244|0,341364|0,341484|0,341604|0,341724|0," "341844|0,341964|0,342084|0,342204|0,342324|0,342444|0,342564|0,342684|0," "342804|0,342924|0,343044|0,343164|0,343284|0,343404|0,343524|0,343644|0," "345684|0,345804|0,345924|0,346044|0,346164|0,346284|0,346404|0,346524|0," "346644|0,346764|0,346884|0,347004|0,347124|0,347244|0,347364|0,347484|0," "348564|0,348684|0,348804|0,348924|0,349044|0,349164|0,349284|0,349404|0," "349524|0,349644|0,349764|0,349884|0,350004|0,350124|0,350244|0,350364|0," "350484|0,350604|0,350724|0,350844|0,350964|0,351084|0,351204|0,351324|0," "351444|0,351564|0,351684|0,351804|0,351924|0,352044|0,352164|0,352284|0," "353364|0,353484|0,353604|0,353724|0,353844|0,353964|0,354084|0,354204|0," "354324|0,354444|0,354564|0,354684|0,354804|0,354924|0,355044|0,355164|0," "356244|0,356364|0,356484|0,356604|0,356724|0,356844|0,356964|0,357084|0," "357204|0,357324|0,357444|0,357564|0,357684|0,357804|0,357924|0,358044|0," "358164|0,358284|0,358404|0,358524|0,358644|0,358764|0,358884|0,359004|0" ") - ").offsets() offsetsStart = OsuHitList.readEditorString("05:29:364 (329364|2,332244|2,337044|2,339924|2,345684|2,348564|2," "353364|2,356244|2) - ").offsets() offsetsEnd = OsuHitList.readEditorString("05:31:284 (331284|3,336084|2,338964|3,343764|2,347604|2,352404|2,355284|3," "359124|2) - ").offsets() def CHORD(offset: float, positions: list, m: OsuMap): positions_ = [p for p in positions if p >= 0] # Drop any negatives diffs = np.diff(sorted(positions_ + [0])) # print(positions, positions_) # print(diffs) # The larger the size, the larger the BPM used. for e, d in enumerate(diffs): # print( dict(offset=e + offset, bpm=max(d * REF_BPM * 450, MIN_BPM))) m.bpms.append(OsuBpm(offset=e + offset, bpm=max(d * REF_BPM * 450, MIN_BPM))) for e, p in enumerate(np.array(positions_).argsort()): # print( dict(offset=e + offset + 1, column=int(p))) m.notes.hits().append(OsuHit(offset=e + offset + 1, column=int(p))) m.bpms.append(OsuBpm(offset=offset + len(diffs), bpm=MAX_BPM)) m.bpms.append(OsuBpm(offset=offset + len(diffs) + 1, bpm=MIN_BPM)) def f834(m: OsuMap): CHORD_ = lambda os, ps, m=m: CHORD(offset=os, positions=ps, m=m) it = iter(offsets) for _ in np.linspace(0, 1, 8 * 2): CHORD_(os=next(it), ps=[np.random.rand() for _ in range(4)]) for x in np.linspace(0, 4, 8 * 4): CHORD_(os=next(it), ps=[np.sin(x * pi / 2 + 0 * pi / 2) / 2 * np.cos(x / 4 * pi / 2) + 0.5, np.sin(x * pi / 2 + 1 * pi / 2) / 2 * np.cos(x / 4 * pi / 2) + 0.5, np.sin(x * pi / 2 + 2 * pi / 2) / 2 * np.cos(x / 4 * pi / 2) + 0.5, np.sin(x * pi / 2 + 3 * pi / 2) / 2 * np.cos(x / 4 * pi / 2) + 0.5]) for _ in np.linspace(0, 1, 8 * 2): CHORD_(os=next(it), ps=[np.random.rand() for _ in range(4)]) for x in np.linspace(0, 12, 8 * 4): CHORD_(os=next(it), ps=[np.sin(x * pi / 4 + 0 * pi / 2) / 2 * np.cos(x / 12 * pi / 2) + 0.5, np.sin(x * pi / 3 + 1 * pi / 2) / 2 * np.cos(x / 12 * pi / 2) + 0.5, np.sin(x * pi / 2 + 2 * pi / 2) / 2 * np.cos(x / 12 * pi / 2) + 0.5, np.sin(x * pi / 1 + 3 * pi / 2) / 2 * np.cos(x / 12 * pi / 2) + 0.5]) for _ in np.linspace(0, 1, 8 * 2): CHORD_(os=next(it), ps=[np.random.rand() for _ in range(4)]) for e,x in enumerate(np.linspace(0, 1, 8 * 4)): CHORD_(os=next(it), ps=[(-1 if e % 2 else 1) * (- 0.5 ) * (np.sin((x + 1) * pi / 2) ** 1.5) + 0.5, (-1 if e % 2 else 1) * (- 0.33) * (np.sin((x + 1) * pi / 2) ** 1.5) + 0.5, (-1 if e % 2 else 1) * (+ 0.33) * (np.sin((x + 1) * pi / 2) ** 1.5) + 0.5, (-1 if e % 2 else 1) * (+ 0.5 ) * (np.sin((x + 1) * pi / 2) ** 1.5) + 0.5]) for _ in np.linspace(0, 1, 8 * 2): CHORD_(os=next(it), ps=[np.random.rand() for _ in range(4)]) for x in np.linspace(0, 1, 8 * 3): CHORD_(os=next(it), ps=[(np.random.rand() - 0.5) * np.cos(x * pi / 2) + 0.5 for _ in range(4)]) for o in offsetsStart: m.bpms.append(OsuBpm(offset=o - 1, bpm=MAX_BPM)) for o in offsetsEnd: m.bpms.append(OsuBpm(offset=o - 1, bpm=MAX_BPM)) m.bpms.append(OsuBpm(offset=o, bpm=REF_BPM / 4)) m.bpms.append(OsuBpm(offset=offsets[-1], bpm=250))
christopherwj/a_code_a_day
c++/generic_code/address_book/doc/html/search/functions_2.js
<reponame>christopherwj/a_code_a_day<filename>c++/generic_code/address_book/doc/html/search/functions_2.js var searchData= [ ['deletecontact_41',['deleteContact',['../class_address_book.html#a12d8f1663aa709e62369cc9dd1e466d9',1,'AddressBook']]] ];
gabrielrigon/trabalho_graduacao
app/models/comment.rb
<gh_stars>1-10 class Comment < ActiveRecord::Base # ---- relationships ---- belongs_to :user belongs_to :post # ---- delegates ---- delegate :name, to: :user, prefix: true, allow_nil: true # ---- validates ---- validates :content, presence: true end
praveen-garg/FogLAMP
python/foglamp/common/storage_client/__main__.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This module is for test purpose only! USE src/python/foglamp/storage/payload_builder.py This will go away when tests, payload_builder and actually STORAGE layer (FOGL-197) are in place """ import json from collections import OrderedDict from foglamp.common.storage_client.storage_client import StorageClient, ReadingsStorageClient from foglamp.common.storage_client.exceptions import * def insert_data(): print("StorageClient::insert_data :") data = dict() data['key'] = 'SENT_test' data['history_ts'] = 'now' data['value'] = 1 res = StorageClient().insert_into_tbl("statistics_history", json.dumps(data)) print(res) def update_data(): print("StorageClient::update_data :") condition = dict() condition['column'] = 'key' condition['condition'] = '=' condition['value'] = 'SENT_test' values = dict() values['value'] = 444 data = dict() data['condition'] = condition data['values'] = values res = StorageClient().update_tbl("statistics_history", json.dumps(data)) print(res) def delete_tbl_data(): print("StorageClient::delete_tbl_data :") # payload as per doc, # see: Plugin Common Delete del_cond = dict() del_cond['column'] = 'id' del_cond['condition'] = '=' del_cond['value'] = '13081' # join these AND/ OR conditions del_cond_2 = dict() del_cond_2['column'] = 'key' del_cond_2['condition'] = '=' del_cond_2['value'] = 'SENT_test' # same as where cond = dict() cond['where'] = del_cond ''' DELETE FROM statistics_history WHERE key = 'SENT_test' AND id='13084' ''' cond['and'] = del_cond_2 ''' DELETE FROM statistics_history WHERE key = 'SENT_test' OR id='13084' ''' cond['or'] = del_cond_2 res = StorageClient().delete_from_tbl("statistics_history", json.dumps(cond)) print(res) ''' DELETE FROM statistics_history ''' # res = StorageClient().delete_from_tbl("statistics_history") # print(res) def query_table(): print("StorageClient::query_table :") with StorageClient() as store: # commented code ''' query = dict() query['key'] = 'COAP_CONF' # ASK about approach query['blah'] = 'SENSORS' query_params = '?' for k, v in query.items(): if not query_params == "?": query_params += "&" query_params += '{}={}'.format(k, v) print("CHECK:", query_params) ''' ''' SELECT * FROM configuration WHERE key='COAP_CONF' ''' # TODO: check &limit=1 (and offset, order_by) will work here? q = 'key=COAP_CONF' res = store.query_tbl('configuration', q) print(res) ''' SELECT * FROM statistics ''' res = store.query_tbl('statistics') print(res) def query_table_with_payload(): print("StorageClient::query_table_with_payload :") # WHERE key = 'SENT_test'" where = OrderedDict() where['column'] = 'key' where['condition'] = '=' where['value'] = 'SENT_test' # verify AND / OR? where_2 = OrderedDict() where_2['column'] = 'value' where_2['condition'] = '>' where_2['value'] = '444' aggregate = OrderedDict() aggregate['operation'] = 'min' aggregate['column'] = 'value' query_payload = OrderedDict() query_payload['where'] = where_2 query_payload['and'] = where_2 # query_payload['or'] = where_2 # query_payload['aggregate'] = aggregate # query_payload['limit'] = 2 # query_payload['skip'] = 1 # check ? order_by = "" payload = json.dumps(query_payload) print(payload) with StorageClient() as store: res = store.query_tbl_with_payload('statistics_history', payload) print(res) def append_readings(): print("ReadingsStorageClient::append_readings :") import uuid import random readings = [] def map_reading(asset_code, reading, read_key=None, user_ts=None): read = dict() read['asset_code'] = asset_code print(read_key) read['read_key'] = read_key read['reading'] = dict() read['reading']['rate'] = reading read['user_ts'] = "2017-09-21 15:00:09.025655" # ingest 2017-01-02T01:02:03.23232Z-05:00 # asset, key, reading, timestamp # storage 2017-09-21 15:00:09.025655 # asset_code, read_key, reading, user_ts return read x = str(uuid.uuid4()) # to use duplicate read_key uuid (ON CONFLICT DO NOTHING) for _ in range(1, 2): readings.append(map_reading('MyAsset', random.uniform(1.0, 100.1), read_key=str(uuid.uuid4()))) payload = dict() payload['readings'] = readings print(json.dumps(payload)) res = ReadingsStorageClient().append(json.dumps(payload)) print(res) def fetch_readings(): print("ReadingsStorageClient::fetch_readings :") # tested, # works fine if records are less then count # also works fine if reading_id does not exist, {'rows': [], 'count': 0} res = ReadingsStorageClient().fetch(reading_id=1, count=2) print(res) def purge_readings(): print("ReadingsStorageClient::purge_readings :") res = ReadingsStorageClient().purge('24', '100071') # try many (type checking) res = ReadingsStorageClient().purge(24, '100071') # res = ReadingsStorageClient().purge(24, '100071', 'puRge') res = ReadingsStorageClient().purge(age=24, sent_id=100071, flag='RETAIN') try: # res = ReadingsStorageClient().purge('b', '100071', 'RETAIN') # res = ReadingsStorageClient().purge('1', 'v', 'RETAIN') res = ReadingsStorageClient().purge(24, '100071', 'xRETAIN') except ValueError: print("age or reading is not an integer value :/") except InvalidReadingsPurgeFlagParameters: print("AS expected, InvalidReadingsPurgeFlagParameters") print(res) def query_readings(): print("ReadingsStorageClient::query_readings :") cond1 = OrderedDict() cond1['column'] = 'asset_code' cond1['condition'] = '=' cond1['value'] = 'MyAsset' query_payload = OrderedDict() query_payload['where'] = cond1 query_payload['limit'] = 2 query_payload['skip'] = 1 print("query_readings payload: ", json.dumps(query_payload)) res = ReadingsStorageClient().query(json.dumps(query_payload)) print(res) # expected response '''{'count': 2, 'rows': [ {'read_key': 'cdbec41e-9c41-4144-8257-e2ab2242dc76', 'user_ts': '2017-09-21 15:00:09.025655+05:30', 'id': 22, 'reading': {'rate': 92.58901867128075}, 'asset_code': 'MyAsset', 'ts': '2017-09-28 20:18:43.809661+05:30'}, {'read_key': '<KEY>', 'user_ts': '2017-09-21 15:00:09.025655+05:30', 'id': 23, 'reading': {'rate': 24.350853712845392}, 'asset_code': 'MyAsset', 'ts': '2017-09-28 20:19:16.739619+05:30'} ] }''' try: # TODO: Move to tests :] ping_response = StorageClient().check_service_availibility() print("check_service_availibility res: ", ping_response) """ {'uptime': 1077, 'name': 'storage', 'statistics': {'commonInsert': 8, 'commonUpdate': 8, 'commonSimpleQuery': 16, 'commonDelete': 8, 'commonQuery': 8, 'readingQuery': 8, 'readingPurge': 13, 'readingFetch': 8, 'readingAppend': 8, } } """ query_table() insert_data() update_data() delete_tbl_data() query_table_with_payload() append_readings() # what happens on conflict? fetch_readings() # TODO: Shall these value be picked from purge config and passed to it? purge_readings() query_readings() # TODO: verify 1 error payload # shutdown_response = StorageClient().shutdown() # print("check_shutdown res: ", shutdown_response) """ {'message': 'Shutdown in progress'} """ except InvalidServiceInstance as ex: print(ex.code, ex.message) except StorageServiceUnavailable as ex: print(ex.code, ex.message)
fossabot/evemonk
spec/routing/api/eve/corporations_routing_spec.rb
<filename>spec/routing/api/eve/corporations_routing_spec.rb # frozen_string_literal: true require "rails_helper" describe Api::Eve::CorporationsController do describe "routing" do it "should route GET /api/eve/corporations to api/eve/corporations#index" do expect(get: "/api/eve/corporations").to route_to( controller: "api/eve/corporations", action: "index", format: "json" ) end it "should route GET /api/eve/corporations/98005120 to api/eve/corporations#show" do expect(get: "/api/eve/corporations/98005120").to route_to( controller: "api/eve/corporations", action: "show", id: "98005120", format: "json" ) end end end
JamesLoveCurry/bione_input
bione-plugin/src/main/java/com/yusys/bione/plugin/rptidx/entity/RptIdxSrcRelInfoPK.java
package com.yusys.bione.plugin.rptidx.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; /** * The primary key class for the RPT_IDX_SRC_REL_INFO database table. * */ @Embeddable public class RptIdxSrcRelInfoPK implements Serializable { //default serial version id, required for serializable classes. private static final long serialVersionUID = 1L; @Column(name="INDEX_NO") private String indexNo; @Column(name="INDEX_VER_ID") private long indexVerId; @Column(name="SRC_INDEX_NO") private String srcIndexNo; @Column(name="SRC_MEASURE_NO") private String srcMeasureNo; public RptIdxSrcRelInfoPK() { } public String getIndexNo() { return this.indexNo; } public void setIndexNo(String indexNo) { this.indexNo = indexNo; } public long getIndexVerId() { return this.indexVerId; } public void setIndexVerId(long indexVerId) { this.indexVerId = indexVerId; } public String getSrcIndexNo() { return this.srcIndexNo; } public void setSrcIndexNo(String srcIndexNo) { this.srcIndexNo = srcIndexNo; } public String getSrcMeasureNo() { return srcMeasureNo; } public void setSrcMeasureNo(String srcMeasureNo) { this.srcMeasureNo = srcMeasureNo; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RptIdxSrcRelInfoPK other = (RptIdxSrcRelInfoPK) obj; if (indexNo == null) { if (other.indexNo != null) return false; } else if (!indexNo.equals(other.indexNo)) return false; if (indexVerId != other.indexVerId) return false; if (srcIndexNo == null) { if (other.srcIndexNo != null) return false; } else if (!srcIndexNo.equals(other.srcIndexNo)) return false; if (srcMeasureNo == null) { if (other.srcMeasureNo != null) return false; } else if (!srcMeasureNo.equals(other.srcMeasureNo)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((indexNo == null) ? 0 : indexNo.hashCode()); result = prime * result + (int) (indexVerId ^ (indexVerId >>> 32)); result = prime * result + ((srcIndexNo == null) ? 0 : srcIndexNo.hashCode()); result = prime * result + ((srcMeasureNo == null) ? 0 : srcMeasureNo.hashCode()); return result; } }
Tollainmear/Nucleus
src/main/java/io/github/nucleuspowered/nucleus/modules/kit/commands/kit/KitRenameCommand.java
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.modules.kit.commands.kit; import io.github.nucleuspowered.nucleus.api.nucleusdata.Kit; import io.github.nucleuspowered.nucleus.internal.annotations.RunAsync; import io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers; import io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions; import io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand; import io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException; import io.github.nucleuspowered.nucleus.modules.kit.commands.KitFallbackBase; import io.github.nucleuspowered.nucleus.modules.kit.handlers.KitHandler; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.args.CommandElement; import org.spongepowered.api.command.args.GenericArguments; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.util.annotation.NonnullByDefault; @Permissions(prefix = "kit") @RegisterCommand(value = {"rename"}, subcommandOf = KitCommand.class) @RunAsync @NoModifiers @NonnullByDefault public class KitRenameCommand extends KitFallbackBase<CommandSource> { private final String name = "target name"; @Override protected CommandElement[] getArguments() { return new CommandElement[] { KitFallbackBase.KIT_PARAMETER_NO_PERM_CHECK, GenericArguments.onlyOne(GenericArguments.string(Text.of(this.name))) }; } @Override protected CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception { try { String name1 = args.<Kit>getOne(KitFallbackBase.KIT_PARAMETER_KEY).get().getName(); String name2 = args.<String>getOne(this.name).get(); getServiceUnchecked(KitHandler.class).renameKit(name1, name2); sendMessageTo(src, "command.kit.rename.renamed", name1, name2); return CommandResult.success(); } catch (IllegalArgumentException e) { throw new ReturnMessageException(Text.of(TextColors.RED, e.getMessage())); } } }
coheigea/tcommon-studio-se
main/plugins/org.talend.core.runtime/src/main/java/org/talend/core/service/IRemoteService.java
<filename>main/plugins/org.talend.core.runtime/src/main/java/org/talend/core/service/IRemoteService.java<gh_stars>10-100 // ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.core.service; import org.talend.commons.exception.LoginException; import org.talend.commons.exception.PersistenceException; import org.talend.core.IService; import org.talend.core.nexus.ArtifactRepositoryBean; import org.talend.utils.json.JSONException; import org.talend.utils.json.JSONObject; /** * DOC hywang class global comment. Detailled comment */ public interface IRemoteService extends IService { public JSONObject getLicenseKey(String user, String password, String url, String projectLabel) throws PersistenceException, LoginException; public ArtifactRepositoryBean getUpdateRepositoryUrl(String user, String password, String url) throws PersistenceException, LoginException; public ArtifactRepositoryBean getLibNexusServer(String user, String password, String url) throws PersistenceException, LoginException, JSONException; boolean isAuthorized(String value); }
tenpaiyomi/rodf
spec/tab_spec.rb
<gh_stars>0 # Copyright (c) 2010 <NAME> # # This file is part of rODF. # # rODF is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # rODF is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with rODF. If not, see <http://www.gnu.org/licenses/>. require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require 'rodf/paragraph' require 'rodf/tab' describe RODF::Tab do it "should be placed inside paragraphs" do output = RODF::Paragraph.create {|p| p << "Tab" p.tab p << "test" } output.should have_tag("//text:p/*", count: 3) output.should have_tag("//text:tab") end end
ethansaxenian/RosettaDecode
lang/Ruby/find-common-directory-path-3.rb
def common_directory_path(dirs, separator='/') dir1, dir2 = dirs.minmax.map{|dir| dir.split(separator)} dir1.zip(dir2).take_while{|dn1,dn2| dn1==dn2}.map(&:first).join(separator) end p common_directory_path(dirs) #=> "/home/user1/tmp"
zhouzy-creator/Tengine
source/device/vulkan/layer/packing_vulkan.hpp
<filename>source/device/vulkan/layer/packing_vulkan.hpp<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Parts of the following code in this file refs to * https://github.com/Tencent/ncnn/tree/master/src/layer/vulkan/ * Tencent is pleased to support the open source community by making ncnn * available. * * Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the * License at * * https://opensource.org/licenses/BSD-3-Clause */ /* * Copyright (c) 2020, Open AI Lab * Author: <EMAIL> */ #ifndef LAYER_PACKING_HPP #define LAYER_PACKING_HPP #include "../vulkan_layer.hpp" #include "../vulkan_command.hpp" namespace TEngine { class Packing_vulkan : public Layer { public: Packing_vulkan(); virtual int create_pipeline(const Option& opt); virtual int destroy_pipeline(const Option& opt); virtual int record_pipeline(const VkTensor& bottom_blob, VkTensor& top_blob, VkCompute& cmd, const Option& opt) const; public: int out_shape_packed_dims; int out_shape_packed_w; int out_shape_packed_h; int out_shape_packed_c; int out_shape_packed_cstep; int out_elempack; int use_padding; // element type // 0 = auto // 1 = fp32 // 2 = fp16p // 3 = fp16s int cast_type_from; int cast_type_to; // storage type // 0 = buffer // 1 = image int storage_type_from; int storage_type_to; Pipeline* pipeline_packing; Pipeline* pipeline_packing_pack4; Pipeline* pipeline_packing_pack8; Pipeline* pipeline_packing_pack1to4; Pipeline* pipeline_packing_pack4to1; Pipeline* pipeline_packing_pack1to8; Pipeline* pipeline_packing_pack4to8; Pipeline* pipeline_packing_pack8to4; Pipeline* pipeline_packing_pack8to1; }; } // namespace TEngine #endif
NicoleRobin/dovecot
dovecot-2.2.33.2/src/lib/aqueue.c
/* Copyright (c) 2003-2017 Dovecot authors, see the included COPYING file */ #include "lib.h" #include "array.h" #include "aqueue.h" struct aqueue *aqueue_init(struct array *array) { struct aqueue *aqueue; aqueue = i_new(struct aqueue, 1); aqueue->arr = array; aqueue->area_size = buffer_get_writable_size(aqueue->arr->buffer) / aqueue->arr->element_size; i_assert(aqueue->area_size > 0); return aqueue; } void aqueue_deinit(struct aqueue **_aqueue) { struct aqueue *aqueue = *_aqueue; *_aqueue = NULL; i_free(aqueue); } static void aqueue_grow(struct aqueue *aqueue) { unsigned int orig_area_size, count; i_assert(aqueue->full && aqueue->head == aqueue->tail); orig_area_size = aqueue->area_size; (void)array_append_space_i(aqueue->arr); aqueue->area_size = buffer_get_writable_size(aqueue->arr->buffer) / aqueue->arr->element_size; i_assert(orig_area_size < aqueue->area_size); count = I_MIN(aqueue->area_size - orig_area_size, aqueue->head); array_copy(aqueue->arr, orig_area_size, aqueue->arr, 0, count); if (count < aqueue->area_size - orig_area_size) aqueue->head = orig_area_size + count; else { array_copy(aqueue->arr, 0, aqueue->arr, count, aqueue->head - count); aqueue->head -= count; } i_assert(aqueue->head != aqueue->tail); aqueue->full = FALSE; } void aqueue_append(struct aqueue *aqueue, const void *data) { if (aqueue->full) { aqueue_grow(aqueue); i_assert(!aqueue->full); } array_idx_set_i(aqueue->arr, aqueue->head, data); aqueue->head = (aqueue->head + 1) % aqueue->area_size; aqueue->full = aqueue->head == aqueue->tail; } void aqueue_delete(struct aqueue *aqueue, unsigned int n) { unsigned int idx, count = aqueue_count(aqueue); i_assert(n < count); aqueue->full = FALSE; if (n == 0) { /* optimized deletion from tail */ aqueue->tail = (aqueue->tail + 1) % aqueue->area_size; return; } if (n == count-1) { /* optimized deletion from head */ aqueue->head = (aqueue->head + aqueue->area_size - 1) % aqueue->area_size; return; } idx = aqueue_idx(aqueue, n); if ((n < count/2 || idx > aqueue->head) && idx > aqueue->tail) { /* move tail forward. ..tail##idx##head.. or ##head..tail##idx## */ array_copy(aqueue->arr, aqueue->tail + 1, aqueue->arr, aqueue->tail, idx - aqueue->tail); aqueue->tail++; i_assert(aqueue->tail < aqueue->area_size); } else { /* move head backward. ..tail##idx##head.. or ##idx##head..tail## */ i_assert(idx < aqueue->head); array_copy(aqueue->arr, idx, aqueue->arr, idx + 1, aqueue->head - idx); aqueue->head = (aqueue->head + aqueue->area_size - 1) % aqueue->area_size; } i_assert(aqueue->head < aqueue->area_size && aqueue->head != aqueue->tail); } void aqueue_delete_tail(struct aqueue *aqueue) { aqueue_delete(aqueue, 0); } void aqueue_clear(struct aqueue *aqueue) { aqueue->head = aqueue->tail = 0; aqueue->full = FALSE; } unsigned int aqueue_count(const struct aqueue *aqueue) { unsigned int area_size = aqueue->area_size; return aqueue->full ? area_size : (area_size - aqueue->tail + aqueue->head) % area_size; }
wallywest/magnum
lib/magnum/error.rb
module Magnum class Error < StandardError end class PersistenceError < Error end class InvalidType < Error end end
eltonyeh/tp
src/main/java/seedu/address/logic/parser/CliSyntax.java
<gh_stars>0 package seedu.address.logic.parser; /** * Contains Command Line Interface (CLI) syntax definitions common to multiple commands */ public class CliSyntax { /* Umbrella command definitions */ public static final String PERSON_COMMAND = "student"; public static final String GROUP_COMMAND = "group"; /* Prefix definitions */ public static final Prefix PREFIX_NAME = new Prefix("n/"); public static final Prefix PREFIX_PHONE = new Prefix("p/"); public static final Prefix PREFIX_EMAIL = new Prefix("e/"); public static final Prefix PREFIX_ADDRESS = new Prefix("a/"); public static final Prefix PREFIX_TAG = new Prefix("t/"); public static final Prefix PREFIX_START_TIME = new Prefix("st/"); public static final Prefix PREFIX_END_TIME = new Prefix("et/"); public static final Prefix PREFIX_DAY = new Prefix("d/"); public static final Prefix PREFIX_SUBJECT = new Prefix("s/"); /* Prefixes for tasks */ public static final Prefix PREFIX_DESCRIPTION = new Prefix("n/"); public static final Prefix PREFIX_DEADLINE = new Prefix("d/"); public static final String MONDAY = "mon"; public static final String TUESDAY = "tue"; public static final String WEDNESDAY = "wed"; public static final String THURSDAY = "thu"; public static final String FRIDAY = "fri"; public static final String SATURDAY = "sat"; public static final String SUNDAY = "sun"; }
rgrr/smartmeshsdk
libs/SmartMeshSDK/protocols/oap/OAPNotif.py
import OAPMessage import OAPDefines import struct import datetime from array import array DIGITAL_IN_ADDRESS = 2 ANALOG_ADDRESS = 4 TEMP_ADDRESS = array('B', [5]) NOTIFTYPE_SAMPLE = 0 NOTIFTYPE_STATS = 1 NOTIFTYPE_DIG = 2 NOTIFTYPE_LOCATEME = 3 NOTIFTYPE_PKGEN = 4 TAG_ADDRESS = 0xff # TODO: turn parse_oap_notif into an OAP Notification Factory? def parse_oap_notif(data, index = 0): ''' Parse the OAP notification data and return a OAPNotif object. data: array of bytes from the OAP notification payload. OAP transport header and OAP command type should be stripped ''' # TODO: validate length result = None # notif type notif_type = data[index] index += 1 # payload if notif_type==NOTIFTYPE_SAMPLE: #===== parse # channel (TLV) (tag, l, channel) = OAPMessage.parse_tlv(data[index:]) if tag!=TAG_ADDRESS: raise ValueError('invalid notification data: expected address tag') index += 2 + l # timestamp (secs, usecs) = struct.unpack_from('!ql', data, index) index += 12 # rate rate = struct.unpack_from('!l', data, index)[0] index += 4 # numSamples num_samples = int(data[index]) index += 1 # sampleSize sample_size = int(data[index]) index += 1 #===== create result structure if len(channel)==2 and channel[0]==DIGITAL_IN_ADDRESS: result = OAPDigitalInSample() elif channel == TEMP_ADDRESS: result = OAPTempSample() elif len(channel)==2 and channel[0]==ANALOG_ADDRESS: result = OAPAnalogSample() else: raise SystemError("unknown OAP sample with channel={0}").format(channel) #===== populate result structure if channel[0]==ANALOG_ADDRESS or channel[0]==DIGITAL_IN_ADDRESS: result.input = channel[1] result.packet_timestamp = (secs, usecs) result.rate = rate result.num_samples = num_samples result.sample_size = sample_size for i in range(num_samples): if sample_size==8: temp = struct.unpack('!B', data[index:index+1])[0] index += 1 elif sample_size==16: temp = struct.unpack('!h', data[index:index+2])[0] index += 2 else: raise SystemError("unexpected sample_size of {0}".format(sample_size)) result.samples.append(temp) elif notif_type==NOTIFTYPE_STATS: #===== parse # channel (TLV) (tag, l, channel) = OAPMessage.parse_tlv(data[index:]) if tag!=TAG_ADDRESS: raise ValueError('invalid notification data: expected address tag') index += 2 + l # timestamp (secs, usecs) = struct.unpack_from('!ql', data, index) index += 12 # rate rate = struct.unpack_from('!l', data, index)[0] index += 4 # numSamples num_samples = int(data[index]) index += 1 # sampleSize sample_size = int(data[index]) index += 1 #===== create and populate result structure # TODO populate result = OAPAnalogStats() result.packet_timestamp = (secs, usecs) elif notif_type==NOTIFTYPE_DIG: #===== parse # channel (TLV) (tag, l, channel) = OAPMessage.parse_tlv(data[index:]) if tag!=TAG_ADDRESS: raise ValueError('invalid notification data: expected address tag') index += 2 + l # timestamp (secs, usecs) = struct.unpack_from('!ql', data, index) index += 12 # new value new_val = int(data[index]) index += 1 #===== create and populate result structure result = OAPDigitalIn() result.channel = channel result.packet_timestamp = (secs, usecs) result.new_val = new_val elif notif_type==NOTIFTYPE_LOCATEME: #===== parse raise NotImplementedError("parsing locateMe OAP notification") #===== create and populate result structure raise NotImplementedError("filling locateMe OAP result structure") elif notif_type == 4: # pkgen #===== parse # channel (TLV) (tag, l, channel) = OAPMessage.parse_tlv(data[index:]) if tag != 0xFF: raise ValueError('invalid notification data: expected address tag') index += 2 + l # pid pid = struct.unpack_from('!l', data, index)[0] index += 4 # startPid startPid = struct.unpack_from('!l', data, index)[0] index += 4 # numPackets numPackets = struct.unpack_from('!l', data, index)[0] index += 4 # payload payload = data[index:] #===== create and populate result structure result = OAPpkGenPacket() result.pid = pid result.startPid = startPid result.numPackets = numPackets result.payload = payload # set common notification attributes if result: result.raw_data = data result.channel = channel result.received_timestamp = datetime.datetime.now() return result #===== OAP notification base class class OAPNotif(object): ''' \brief Parent class for all OAP notification structures. ''' def __init__(self): self.channel = '' self.packet_timestamp = None self.received_timestamp = None def channel_str(self): returnVal = 'UNKNOWN' for (k,v) in OAPDefines.ADDRESS.items(): if list(v)==self.channel.tolist(): returnVal = k break return returnVal def _asdict(self): returnVal = { 'channel': self.channel.tolist(), 'channel_str': self.channel_str(), 'packet_timestamp': self.packet_timestamp, 'received_timestamp': str(self.received_timestamp), } return returnVal #===== OAP Sample/Report notification class OAPSample(OAPNotif): ''' \brief representation of a (e.g. sensor) sample notification. ''' def __str__(self): return 'C=[{0}] samples: {1}'.format( self.channel_str(), ', '.join([str(i) for i in self.samples]), ) class OAPDigitalInSample(OAPSample): ''' \brief representation of an digital_in sample notification. ''' def __init__(self): self.rate = 0 self.input = 0 self.num_samples = 0 self.sample_size = 0 self.samples = [] def __str__(self): return 'DIGITAL_IN input={0} state={1} V'.format( self.input, self.samples[0], ) def _asdict(self): returnVal = super(OAPDigitalInSample, self)._asdict() returnVal['rate'] = self.rate returnVal['input'] = self.input returnVal['num_samples'] = self.num_samples returnVal['sample_size'] = self.sample_size returnVal['samples'] = self.samples return returnVal class OAPTempSample(OAPSample): ''' \brief representation of a temperature sample notification. ''' def __init__(self): self.rate = 0 self.num_samples = 0 self.sample_size = 0 self.samples = [] def __str__(self): return 'TEMPERATURE {0:.2f} C'.format( float(self.samples[0])/100, ) def _asdict(self): returnVal = super(OAPTempSample, self)._asdict() returnVal['rate'] = self.rate returnVal['num_samples'] = self.num_samples returnVal['sample_size'] = self.sample_size returnVal['samples'] = self.samples return returnVal class OAPAnalogSample(OAPSample): ''' \brief representation of an analog sample notification. ''' def __init__(self): self.rate = 0 self.input = 0 self.num_samples = 0 self.sample_size = 0 self.samples = [] def __str__(self): return 'ANALOG input={0} voltage={1:.3f} V'.format( self.input, float(self.samples[0])/1000, ) def _asdict(self): returnVal = super(OAPAnalogSample, self)._asdict() returnVal['rate'] = self.rate returnVal['input'] = self.input returnVal['num_samples'] = self.num_samples returnVal['sample_size'] = self.sample_size returnVal['samples'] = self.samples return returnVal #===== OAP Stats report (min/max/ave) class OAPAnalogStats(OAPNotif): ''' \brief representation of a stats notification. ''' def __init__(self): self.rate = 0 self.num_samples = 0 self.sample_size = 0 self.min_value = 0 self.max_value = 0 self.ave_value = 0 def __str__(self): return 'C=[{0}] min_value={1} max_value={2} ave_value={3}'.format( self.channel_str(), self.min_value, self.max_value, self.ave_value, ) def _asdict(self): returnVal = super(OAPAnalogStats, self)._asdict() returnVal['rate'] = self.rate returnVal['num_samples'] = self.num_samples returnVal['sample_size'] = self.sample_size returnVal['min_value'] = self.min_value returnVal['max_value'] = self.max_value returnVal['ave_value'] = self.ave_value return returnVal #===== OAP Digital change notification class OAPDigitalIn(OAPNotif): ''' \brief representation of a digital input notification. ''' def __init__(self): self.new_val = 0 def __str__(self): return 'DIGITAL value={0}'.format( self.new_val, ) def _asdict(self): returnVal = super(OAPDigitalIn, self)._asdict() returnVal['new_val'] = self.new_val return returnVal #===== OAP PkGen notification class OAPpkGenPacket(OAPNotif): def __init__(self): self.pid = 0 self.startPid = 0 self.numPackets = 0 self.payload = [] def __str__(self): template = "{0}={1}" output = ['PKGEN'] output += [template.format("pid", self.pid)] output += [template.format("startPid", self.startPid)] output += [template.format("numPackets",self.numPackets)] return ' '.join(output) def _asdict(self): returnVal = super(OAPpkGenPacket, self)._asdict() returnVal['pid'] = self.pid returnVal['startPid'] = self.startPid returnVal['numPackets'] = self.numPackets returnVal['payload'] = self.payload return returnVal
RequestPrivacy/sparrow
src/main/java/com/sparrowwallet/sparrow/wallet/AdvancedDialog.java
<gh_stars>100-1000 package com.sparrowwallet.sparrow.wallet; import com.sparrowwallet.drongo.wallet.Wallet; import com.sparrowwallet.sparrow.AppServices; import com.sparrowwallet.sparrow.io.Storage; import javafx.fxml.FXMLLoader; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.DialogPane; import org.controlsfx.tools.Borders; import java.io.IOException; public class AdvancedDialog extends Dialog<Boolean> { public AdvancedDialog(WalletForm walletForm) { final DialogPane dialogPane = getDialogPane(); AppServices.setStageIcon(dialogPane.getScene().getWindow()); Wallet wallet = walletForm.getWallet(); try { FXMLLoader advancedLoader = new FXMLLoader(AppServices.class.getResource("wallet/advanced.fxml")); dialogPane.setContent(Borders.wrap(advancedLoader.load()).emptyBorder().buildAll()); AdvancedController settingsAdvancedController = advancedLoader.getController(); settingsAdvancedController.initializeView(wallet); boolean noPassword = Storage.NO_PASSWORD_KEY.equals(walletForm.getStorage().getEncryptionPubKey()); final ButtonType closeButtonType = new javafx.scene.control.ButtonType("Close", ButtonBar.ButtonData.CANCEL_CLOSE); final ButtonType passwordButtonType = new javafx.scene.control.ButtonType(noPassword ? "Add Password..." : "Change Password...", ButtonBar.ButtonData.LEFT); dialogPane.getButtonTypes().add(closeButtonType); if(wallet.isValid()) { dialogPane.getButtonTypes().add(passwordButtonType); } dialogPane.setPrefWidth(400); dialogPane.setPrefHeight(300); AppServices.moveToActiveWindowScreen(this); setResultConverter(dialogButton -> dialogButton == passwordButtonType); } catch(IOException e) { throw new RuntimeException(e); } } }
Hap-Hugh/quicksel
test/python/test_time_gaussian_3d.py
import sys sys.path.append('../../src/python') import pprint from quickSel import * import numpy as np query_dir = '../../test/python/queries/' data_file_name = query_dir + 'gaussian_3d.data' query_file_name = query_dir + 'gaussian_trans.query' # get data def get_data(): data_file = open(data_file_name) data = [] for line in data_file.readlines(): data.append([float(x) for x in line.split(',')]) data_file.close() return data # get queries def get_queries(): query_file = open(query_file_name) queries = [] for line in query_file.readlines(): [strll, strur, strfreq] = line.split(';') ll = [float(x) for x in strll.split(',')] ur = [float(x) for x in strur.split(',')] freq = float(strfreq) queries.append([{0: (ll[0], ur[0]), 1: (ll[1], ur[1]), 2: (ll[2], ur[2])}, freq]) return queries def count_tuple(data, boundary): assert(len(boundary) == 6) D = data D = [x for x in D if x[0] >= boundary[0] and x[0] <= boundary[3]] D = [x for x in D if x[1] >= boundary[1] and x[1] <= boundary[4]] D = [x for x in D if x[2] >= boundary[2] and x[2] <= boundary[5]] return len(D) # generate permanent assertions def generate_permanent_assertions(data): nx = 10 ny = 10 nz = 10 xstep = 1.0 / nx ystep = 1.0 / ny zstep = 1.0 / nz boundaries = [] for i in range(nx-1): xstart = xstep * i xend = xstep * (i + 1) boundaries.append([xstart, 0.0, 0.0, xend, 1.0, 1.0]) for i in range(ny-1): ystart = ystep * i yend = ystep * (i + 1) boundaries.append([0.0, ystart, 0.0, 1.0, yend, 1.0]) for i in range(nz-1): zstart = zstep * i zend = zstep * (i + 1) boundaries.append([0.0, 0.0, zstart, 1.0, 1.0, zend]) xstart = xstep * (nx-1) xend = xstep * nx boundaries.append([xstart, 0.0, 0.0, xend, 1.0, 1.0]) N = float(len(data)) freqs = map(lambda b: float(count_tuple(data, b)) / N, boundaries) assertions = [] for i in range(len(boundaries)): assertions.append(Assertion({0: (boundaries[i][0], boundaries[i][3]), 1: (boundaries[i][1], boundaries[i][4]), 2: (boundaries[i][2], boundaries[i][5])}, freqs[i])) return assertions # test quickSel def test_crumbs(data, queries): # testcases = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000] # testcases = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70] testcases = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200] test_queries = [x[0] for x in queries[1000:2000]] test_truth = [x[1] for x in queries[1000:2000]] perma_assertions = generate_permanent_assertions(data) for num_queries in testcases: print "Testing Crumbs with " + str(num_queries) + " new queries" new_assertions = [Assertion(query[0], query[1]) for query in queries[0:num_queries]] min_max = Hyperrectangle([[0, 1], [0, 1], [0, 1]]) start = time.time() quickSel = Crumbs(min_max) A, b, x = quickSel.assign_optimal_freq(perma_assertions + new_assertions) end = time.time() answers = map(lambda t: quickSel.answer(t), test_queries) err = [] rel_err = [] for i in range(len(answers)): err.append(abs(answers[i] - test_truth[i])) # rel_err.append(abs(answers[i] - test_queries[i][1]) / float(test_queries[i][1])) # avg_rel_err = sum(rel_err)/len(rel_err) avg_err = sum(err) / len(err) print "Avg err is " + str(avg_err) print "Time used: " + str(end - start) print "\n\n" # test isomer def test_isomer(data, queries): testcases = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70] # testcases = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200] # testcases = [30] test_queries = [x[0] for x in queries[1000:2000]] test_truth = [x[1] for x in queries[1000:2000]] perma_assertions = generate_permanent_assertions(data) for num_queries in testcases: print "Testing Crumbs with " + str(num_queries) + " new queries" new_assertions = [Assertion(query[0], query[1]) for query in queries[0:num_queries]] min_max = Hyperrectangle([[0, 1], [0, 1], [0, 1]]) start = time.time() isomer = Isomer(min_max) total_freq = count_tuple(data, [0, 0, 0, 1, 1, 1]) / float(len(data)) isomer.assign_optimal_freq(perma_assertions + new_assertions) end = time.time() print "Time used: " + str(end - start) # answers = map(lambda t: isomer.answer(t), test_queries) # err = [] # rel_err = [] # for i in range(len(answers)): # err.append(abs(answers[i] - test_truth[i])) # # rel_err.append(abs(answers[i] - test_queries[i][1]) / float(test_queries[i][1])) # # avg_rel_err = sum(rel_err)/len(rel_err) # avg_err = sum(err) / len(err) # print "Avg err is " + str(avg_err) print "\n\n" sys.stdout.flush() data = get_data() queries = get_queries() test_crumbs(data, queries) # test_isomer(data, queries)
Maksim2498/spe-game
src/static/scripts/ecs/entity/EntityManager.js
import ECSManager from "/scripts/ecs/ECSManager.js" import "/scripts/ext/Map.js" export default class EntityManager extends ECSManager { deleteAllWithComponents(...components) { let deleted = 0 for (const entity of this.entitiesWithComponents(...components)) deleted += this.delete(entity) return deleted } hasWithComponents(...components) { return !this.entitiesWithComponents(...components).next().done } getAllWithComponents(...components) { return [...this.entitiesWithComponents(...components)] } *idsWithComponents(...components) { for (const [id, ] of this.entriesWithComponents(...components)) yield id } countWithComponents(...components) { let count = 0 for (const _ of this.entriesWithComponents(...components)) ++count return count } *entitiesWithComponents(...components) { for (const [, entity] of this.entriesWithComponents(...components)) yield entity } entitiesWithTypes() { return targetsWithTypes() } entities() { return targets() } *entriesWithComponents(...components) { for (const [id, entity] of this.entries()) if (entity.components.hasAll(...components)) yield [id, entity] } }
knes1/high-performance-java-persistence
core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/identifier/StringSequenceIdentifierTest.java
<filename>core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/identifier/StringSequenceIdentifierTest.java package com.vladmihalcea.book.hpjp.hibernate.identifier; import com.vladmihalcea.book.hpjp.util.AbstractOracleXEIntegrationTest; import org.hibernate.annotations.GenericGenerator; import org.junit.Test; import javax.persistence.*; public class StringSequenceIdentifierTest extends AbstractOracleXEIntegrationTest { @Override protected Class<?>[] entities() { return new Class<?>[] { Post.class, Board.class }; } @Test public void test() { LOGGER.debug("test"); doInJPA(entityManager -> { entityManager.persist(new Post()); entityManager.persist(new Post("ABC")); entityManager.persist(new Post()); entityManager.persist(new Post("DEF")); entityManager.persist(new Post()); entityManager.persist(new Post()); }); } @Entity(name = "Post") @Table(name = "post") public static class Post implements Identifiable<String> { @Id @GenericGenerator( name = "assigned-sequence", strategy = "com.vladmihalcea.book.hpjp.hibernate.identifier.StringSequenceIdentifier", parameters = { @org.hibernate.annotations.Parameter( name = "sequence_name", value = "hibernate_sequence"), @org.hibernate.annotations.Parameter( name = "sequence_prefix", value = "CTC_"), } ) @GeneratedValue(generator = "assigned-sequence", strategy = GenerationType.SEQUENCE) private String id; @Version private Integer version; public Post() { } public Post(String id) { this.id = id; } @Override public String getId() { return id; } } @Entity(name = "Board") public static class Board { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; } }
will62794/tlaplus
org.lamport.tla.toolbox/src/org/lamport/tla/toolbox/ui/handler/DeleteModuleHandler.java
package org.lamport.tla.toolbox.ui.handler; import java.util.List; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.expressions.IEvaluationContext; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.lamport.tla.toolbox.Activator; import org.lamport.tla.toolbox.spec.Module; import org.lamport.tla.toolbox.spec.Spec; import org.lamport.tla.toolbox.spec.manager.WorkspaceSpecManager; import org.lamport.tla.toolbox.util.ToolboxJob; /** * If a module is selected and it is not the main module of the specification, facilitate its deletion. */ public class DeleteModuleHandler extends AbstractHandler { private boolean m_enabled = false; /** * {@inheritDoc} */ @Override public void setEnabled(final Object evaluationContext) { final Module m = getModuleFromContext((IEvaluationContext)evaluationContext); if (m != null) { final WorkspaceSpecManager specManager = Activator.getSpecManager(); final Spec loadedSpec = specManager.getSpecLoaded(); final String specName = loadedSpec.getName(); final String moduleName = m.getModuleName(); m_enabled = !specName.equals(moduleName); return; } m_enabled = false; } /** * {@inheritDoc} */ @Override public boolean isEnabled() { return m_enabled; } /** * {@inheritDoc} */ public Object execute(ExecutionEvent event) throws ExecutionException { final Module m = getModuleFromContext((IEvaluationContext)event.getApplicationContext()); final Job j = new ToolboxJob("Removing module...") { protected IStatus run(final IProgressMonitor monitor) { try { m.getResource().delete(IResource.NEVER_DELETE_PROJECT_CONTENT, monitor); return Status.OK_STATUS; } catch (Exception e) { return Status.CANCEL_STATUS; } } }; final IWorkbenchWindow iww = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); final IWorkbenchPage page = iww.getActivePage(); final IEditorReference[] refs = page.getEditorReferences(); final String tabName = m.getModuleName() + ".tla"; boolean removeModule = true; for (final IEditorReference ier : refs) { if (tabName.equals(ier.getName())) { final IEditorPart editor = ier.getEditor(false); if (editor != null) { // If dirty and they cancel the closing, this will return false removeModule = page.closeEditor(editor, true); } } } if (removeModule) { j.schedule(); } return null; } private Module getModuleFromContext(final IEvaluationContext context) { final Object defaultVariable = context.getDefaultVariable(); if (defaultVariable instanceof List) { final List<?> list = (List<?>)defaultVariable; if (list.size() == 1) { final Object o = list.get(0); if (o instanceof Module) { return (Module)o; } } } return null; } }
JonathanLehner/korali
examples/study.cases/covid19/src/tools/tools.py
#!/usr/bin/env python3 # Author: <NAME> # Date: 16/3/2020 # Email: <EMAIL> import os import sys import shutil import glob import pandas as pd import io import requests import json import os.path import numpy as np def print_params_to_infer(model, pairs=False): """Print the list of parameter identifiers for 'model' to stdout """ try: tags = model.params_to_infer except AttributeError: raise RuntimeError(f"Model {model} has no 'params_to_infer' attribute") try: pretty = model.params_to_infer_pretty except AttributeError: pretty = tags if pairs: print(' '.join([f'{x},{y}' for x,y in zip(tags,pretty)])) else: print(' '.join([x for x in tags])) def prepareFolder( dir, clean=True): if(clean==True): shutil.rmtree(dir, ignore_errors=True) if os.path.isdir(dir) == False: os.mkdir(dir) def get_last_generation( folder, pattern ): files = glob.glob(folder + pattern) return len(files), sorted(files)[-1] def check_parsed_arguments( args ): if(args.data and len(args.data)==0 ): sys.exit('Empty data list.') if( args.nThreads<1 ): sys.exit('Number of threads must be >= 1.') if( args.nSamples < 10 ): sys.exit('Number of samples must >= 10.') if( args.populationSize < 2): sys.exit('Population size must be > 1') if( args.nPoints < 1 ): sys.exit('Number of samples must >= 1.') if( args.futureDays < 0 ): sys.exit('Number of samples must > 0.') if( any( [ x<=0. or x>=1. for x in args.percentages ] ) ): sys.exit('Percentages must be between 0 and 1.') args.percentages.sort() def fileOutputDefaults( args, saveFolder): js = {} if(args.noSave): js['Enabled'] = False else: js['Enabled'] = True saveFolder = os.path.join(args.dataFolder, saveFolder) prepareFolder( saveFolder ) relativeSaveFolder = os.path.relpath(saveFolder, './') js['Path'] = relativeSaveFolder return js def moving_average(x, w): """ x: `numpy.ndarray`, (N) w: int Window half-width. Returns: xa: `numpy.ndarray`, (N) Array `x` averaged over window [-w,w]. """ s = np.zeros_like(x) q = np.zeros_like(x) for i in range(len(x)): for j in range(max(0, i - w), min(i + w + 1, len(x))): if np.isfinite(x[j]): s[i] += x[j] q[i] += 1 xa = s / q return xa def download_data( args ): if( args.data ): I = args.data else: url = 'https://hgis.uw.edu/virus/assets/virus.csv' print(f'Retrieve population data for {args.country} from: {url}') s = requests.get(url).content df = pd.read_csv(io.StringIO(s.decode('utf-8'))) if( not args.country in list( df.columns.values ) ): sys.exit('Country not in database.') d = df[[args.country]].dropna().values.tolist() I = [ float(l.split('-')[0]) for k in d for l in k ] Nv = args.validateData N = len(I)-Nv I = list(moving_average(I, args.moving_average)) Iv = I[-Nv:] if Nv>0 else [] I = I[:N] js={} js['Population Size'] = args.populationSize js['Time'] = [ i for i in range(N) ] js['Infected'] = I js['Infected Validation'] = Iv js['Time Validation'] = [ N+i for i in range(Nv) ] js['Country'] = args.country if( not args.noSave ): prepareFolder( args.dataFolder ) dataFile = args.dataFolder + 'population_data.json' print(f'Save population data in: {dataFile}') with open(dataFile, 'w') as f: json.dump( js, f, indent=2, sort_keys=True) return js
gameley-tc/bi-go
bimodels/equip_level.go
<reponame>gameley-tc/bi-go // Copyright 2018 The Gameley-TC Authors. All rights reserved. package bimodels import ( "strconv" "github.com/gameley-tc/bi-go" ) type LogEquipLevel struct { *LogReason // 装备类型 EquipType int // 装备ID EquipId int // 装备原来的等级 EquipOldLevel int // 装备新的等级 EquipNewLevel int // 本次变动的等级 非负数 EquipLevel int } func (l *LogEquipLevel) ToString() string { return bigo.BiJoin("log_equip_level", l.LogReason.ToString(), strconv.Itoa(l.EquipType), strconv.Itoa(l.EquipId), strconv.Itoa(l.EquipOldLevel), strconv.Itoa(l.EquipNewLevel), strconv.Itoa(l.EquipLevel)) } func NewLogEquipLevel(channelId int, uid string, equipType int, equipId int, equipOldLevel int, equipNewLevel int) *LogEquipLevel { return &LogEquipLevel{LogReason: NewLogReason(channelId, uid), EquipType: equipType, EquipId: equipId, EquipOldLevel: equipOldLevel, EquipNewLevel: equipNewLevel, EquipLevel: bigo.BiAbs(equipNewLevel - equipOldLevel)} }
SmallWhite-Jamie/sharp-sword
sharp-sword-core/src/main/java/com/jamie/framework/quartz/job/OpLogWriteQuartzJob.java
package com.jamie.framework.quartz.job; import com.jamie.framework.log.mapper.OpLogMapper; import com.jamie.framework.log.op.OpLog; import com.jamie.framework.log.op.OpLogWriteAspect; import com.jamie.framework.redis.RedisService; import com.jamie.framework.util.ApplicationContextUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.quartz.JobExecutionContext; import org.springframework.scheduling.quartz.QuartzJobBean; import java.util.List; import java.util.stream.Collectors; /** * @author jamie.li */ @Slf4j public class OpLogWriteQuartzJob extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext jobExecutionContext) { RedisService redisService = ApplicationContextUtil.getBean(RedisService.class); OpLogMapper mapper = ApplicationContextUtil.getBean(OpLogMapper.class); List<Object> list = redisService.getList(OpLogWriteAspect.REDIS_KEY); if (CollectionUtils.isNotEmpty(list)) { List<OpLog> opLogs = list.stream().map(item -> (OpLog) item).collect(Collectors.toList()); mapper.batchInsert(opLogs); redisService.delKey(OpLogWriteAspect.REDIS_KEY); log.debug("日志同步成功:{} 条", opLogs.size()); } } }
dedalusgs/sitae
sitae/src/main/java/es/novasoft/sitae/business/dao/interfaz/RelacionEdictosDAO.java
package es.novasoft.sitae.business.dao.interfaz; import java.util.List; import es.novasoft.comun.exceptions.DAOException; import es.novasoft.sitae.business.objects.RelacionEdictos; public interface RelacionEdictosDAO { public void save(RelacionEdictos transientInstance) throws DAOException; public void delete(RelacionEdictos persistentInstance) throws DAOException; public RelacionEdictos findById(Integer id) throws DAOException; public List findByExample(RelacionEdictos instance) throws DAOException; public List findByProperty(String propertyName, Object value) throws DAOException; public List findAll() throws DAOException; public RelacionEdictos merge(RelacionEdictos detachedInstance) throws DAOException; public void attachDirty(RelacionEdictos instance) throws DAOException; public void attachClean(RelacionEdictos instance) throws DAOException; public List findByEdicto(Integer idEdicto) throws DAOException; }
BeckerFrank/egradle
egradle-plugin-main/src/main/java/de/jcup/egradle/core/GradleExecutor.java
<reponame>BeckerFrank/egradle<filename>egradle-plugin-main/src/main/java/de/jcup/egradle/core/GradleExecutor.java /* * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions * and limitations under the License. * */ package de.jcup.egradle.core; import static org.apache.commons.lang3.Validate.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import de.jcup.egradle.core.config.GradleConfiguration; import de.jcup.egradle.core.domain.CancelStateProvider; import de.jcup.egradle.core.domain.GradleCommand; import de.jcup.egradle.core.domain.GradleContext; import de.jcup.egradle.core.process.EGradleShellType; import de.jcup.egradle.core.process.ProcessExecutor; /** * Simple executor mechansim for gradle command * * @author <NAME> * */ public class GradleExecutor { private ProcessExecutor processExecutor; public GradleExecutor(ProcessExecutor processExecutor) { notNull(processExecutor, "Process executor may not be null!"); this.processExecutor = processExecutor; } /** * Executes gradle * * @param context * @return result */ public ProcessExecutionResult execute(GradleContext context) { ProcessExecutionResult processExecutionResult = new ProcessExecutionResult(); String[] commandStrings = createExecutionCommand(context); /* execute process */ int processResult; try { processResult = processExecutor.execute(context.getConfiguration(), context, context, commandStrings); processExecutionResult.setCommands(context.getCommandString()); processExecutionResult.setProcessResult(processResult); } catch (IOException e) { processExecutionResult.setException(e); } CancelStateProvider cancelStateProvider = context.getCancelStateProvider(); if (cancelStateProvider.isCanceled()) { processExecutionResult.setCanceledByuser(true); } return processExecutionResult; } String[] createExecutionCommand(GradleContext context) { /* build command string */ int pos = 0; GradleCommand[] commands = context.getCommands(); int arraySize = commands.length + 1; /* expand arraysize for command arguments too */ for (GradleCommand c : commands) { arraySize += c.getCommandArguments().size(); } GradleConfiguration config = context.getConfiguration(); EGradleShellType shell = config.getShellType(); if (shell == null) { shell = EGradleShellType.NONE; } List<String> shellCommands = shell.createCommands(); arraySize += shellCommands.size();// we must call shell executor too String[] options = context.getOptions(); if (options == null) { options = new String[] {}; } /* be aware of empty content */ List<String> safeOptions = new ArrayList<>(); for (String opt : options) { if (StringUtils.isNotBlank(opt)) { safeOptions.add(opt); } } arraySize += safeOptions.size(); Map<String, String> gradleProperties = context.getGradleProperties(); Map<String, String> systemProperties = context.getSystemProperties(); arraySize += gradleProperties.size(); arraySize += systemProperties.size(); String[] commandStrings = new String[arraySize]; for (String shellCommand : shellCommands) { commandStrings[pos++] = shellCommand; } commandStrings[pos++] = config.getGradleCommandFullPath(); /* raw options */ for (String rawOption : safeOptions) { commandStrings[pos++] = rawOption; } /* gradle properties */ for (String key : gradleProperties.keySet()) { commandStrings[pos++] = "-P" + key + "=" + gradleProperties.get(key); } /* system properties */ for (String key : systemProperties.keySet()) { commandStrings[pos++] = "-D" + key + "=" + systemProperties.get(key); } /* commands */ for (int i = 0; i < commands.length; i++) { GradleCommand gradleCommand = commands[i]; commandStrings[pos++] = gradleCommand.getCommand(); List<String> commandArguments = gradleCommand.getCommandArguments(); if (commandArguments.size() > 1) { commandStrings[pos++] = commandArguments.get(0); commandStrings[pos++] = commandArguments.get(1); } } return commandStrings; } }
wpumacay/tiny_renderer
legacy/src/graphics/CShadowMap.cpp
#include <graphics/CShadowMap.h> namespace engine { std::string toString( const eShadowRangeType& rangeType ) { if ( rangeType == eShadowRangeType::AUTOFIX_CAMERA ) return "autofix_camera"; if ( rangeType == eShadowRangeType::FIXED_USER ) return "fixed_user"; ENGINE_CORE_ASSERT( false, "Invalid eShadowRangeType enum given" ); return "undefined"; } CShadowMap::CShadowMap( int32 width, int32 height ) { m_shadowMapWidth = width; m_shadowMapHeight = height; m_previousViewportX = -1; m_previousViewportY = -1; m_previousViewportWidth = -1; m_previousViewportHeight = -1; /* configure the framebuffer used to render the depth-map */ CAttachmentConfig _fbDepthConfig; _fbDepthConfig.name = "shadow_depth_attachment"; _fbDepthConfig.attachment = eFboAttachment::DEPTH; _fbDepthConfig.texInternalFormat = eTextureFormat::DEPTH; _fbDepthConfig.texFormat = eTextureFormat::DEPTH; _fbDepthConfig.texPixelDataType = ePixelDataType::FLOAT_32; _fbDepthConfig.texWrapU = eTextureWrap::CLAMP_TO_BORDER; _fbDepthConfig.texWrapV = eTextureWrap::CLAMP_TO_BORDER; _fbDepthConfig.texBorderColorU = { 1.0f, 1.0f, 1.0f, 1.0f }; _fbDepthConfig.texBorderColorV = { 1.0f, 1.0f, 1.0f, 1.0f }; /* create the framebuffer with an attachment given by the config. above */ m_frameBuffer = std::make_unique< CFrameBuffer >( m_shadowMapWidth, m_shadowMapHeight ); m_frameBuffer->addAttachment( _fbDepthConfig ); /* tell opengl we don't need a color attachment */ m_frameBuffer->bind(); glDrawBuffer( GL_NONE ); glReadBuffer( GL_NONE ); m_frameBuffer->unbind(); /* define the points in clip-space of the vertices of the view-frustum */ /* near plane */ m_frustumPointsClipSpace[0] = { -1.0f, -1.0f, -1.0f }; m_frustumPointsClipSpace[1] = { 1.0f, -1.0f, -1.0f }; m_frustumPointsClipSpace[2] = { 1.0f, 1.0f, -1.0f }; m_frustumPointsClipSpace[3] = { -1.0f, 1.0f, -1.0f }; /* far plane */ m_frustumPointsClipSpace[4] = { -1.0f, -1.0f, 1.0f }; m_frustumPointsClipSpace[5] = { 1.0f, -1.0f, 1.0f }; m_frustumPointsClipSpace[6] = { 1.0f, 1.0f, 1.0f }; m_frustumPointsClipSpace[7] = { -1.0f, 1.0f, 1.0f }; } CShadowMap::~CShadowMap() { // nothing to release explicitly } void CShadowMap::setup( const CShadowMapRangeConfig& config ) { // sanity check: if using autofix-camera, make sure we are given a camera if ( config.type == eShadowRangeType::AUTOFIX_CAMERA && !config.cameraPtr ) { ENGINE_CORE_ERROR( "Must provide a valid camera for AUTOFIX_CAMERA mode" ); return; } if ( config.dirLightPtr ) _setupDirectionalLight( config, config.dirLightPtr ); else if ( config.pointLightPtr ) _setupPointLight( config, config.pointLightPtr ); else if ( config.spotLightPtr ) _setupSpotLight( config, config.spotLightPtr ); else ENGINE_CORE_ERROR( "Didn't provide a light to configure shadow-map" ); } void CShadowMap::_setupDirectionalLight( const CShadowMapRangeConfig& config, CDirectionalLight* dirLightPtr ) { if ( config.type == eShadowRangeType::AUTOFIX_CAMERA ) { // Configure the clipping volume for shadow-mapping such that it // is an OOBB to the view camera's view frustum /* compute the vertices of the view frustum */ auto _invViewProjMatrix = tinymath::inverse( config.cameraPtr->mat_proj() * config.cameraPtr->mat_view() ); std::vector< CVec3 > _frustumPointsInWorld; for ( size_t q = 0; q < m_frustumPointsClipSpace.size(); q++ ) { CVec4 _frustumPointNormalized = _invViewProjMatrix * CVec4( m_frustumPointsClipSpace[q], 1.0f ); CVec3 _frustumPoint = CVec3( _frustumPointNormalized.x() / _frustumPointNormalized.w(), _frustumPointNormalized.y() / _frustumPointNormalized.w(), _frustumPointNormalized.z() / _frustumPointNormalized.w() ); _frustumPointsInWorld.push_back( _frustumPoint ); } /* construct a frame using the direction vector as front */ CVec3 _fvec, _rvec, _uvec; if ( dirLightPtr->direction == config.worldUp ) { _fvec = config.worldUp; _rvec = CVec3( config.worldUp.z(), config.worldUp.x(), config.worldUp.y() ); _uvec = CVec3( config.worldUp.y(), config.worldUp.z(), config.worldUp.x() ); } else if ( ( dirLightPtr->direction + config.worldUp ) == CVec3( 0.0f, 0.0f, 0.0f ) ) { _fvec = -config.worldUp; _rvec = CVec3( config.worldUp.z(), config.worldUp.x(), config.worldUp.y() ); _uvec = CVec3( config.worldUp.y(), config.worldUp.z(), config.worldUp.x() ); } else { _fvec = dirLightPtr->direction; _rvec = tinymath::cross( config.worldUp, _fvec ); _uvec = tinymath::cross( _fvec, _rvec ); } _fvec.normalize(); _rvec.normalize(); _uvec.normalize(); /* sort over f-vector */ auto _fPoints3d = _frustumPointsInWorld; // create a copy { m_comparatorDotDirection.direction = _fvec; std::sort( _fPoints3d.begin(), _fPoints3d.end(), m_comparatorDotDirection ); } /* sort over r-vector */ auto _rPoints3d = _frustumPointsInWorld; // create a copy { m_comparatorDotDirection.direction = _rvec; std::sort( _rPoints3d.begin(), _rPoints3d.end(), m_comparatorDotDirection ); } /* sort over u-vector */ auto _uPoints3d = _frustumPointsInWorld; // create a copy { m_comparatorDotDirection.direction = _uvec; std::sort( _uPoints3d.begin(), _uPoints3d.end(), m_comparatorDotDirection ); } /* compute the dimensions of the clipping volume */ float32 _df = std::abs( ( _fPoints3d.back() - _fPoints3d.front() ).dot( _fvec ) ); float32 _dr = std::abs( ( _rPoints3d.back() - _rPoints3d.front() ).dot( _rvec ) ); float32 _du = std::abs( ( _uPoints3d.back() - _uPoints3d.front() ).dot( _uvec ) ); /* compute the center of the clipping volume */ auto _center = ( 0.5f * ( _fPoints3d.front() + _fPoints3d.back() ) ).dot( _fvec ) * _fvec + ( 0.5f * ( _rPoints3d.front() + _rPoints3d.back() ) ).dot( _rvec ) * _rvec + ( 0.5f * ( _uPoints3d.front() + _uPoints3d.back() ) ).dot( _uvec ) * _uvec; /* construct view and proj matrices in light space */ auto _position = _center - ( 0.5f * _df ) * _fvec; auto _target = _position + dirLightPtr->direction; m_lightSpaceMatView = engine::lookAt( _position, _target, config.worldUp ); m_lightSpaceMatProj = engine::ortho( _dr + config.extraWidth, _du + config.extraHeight, -0.5f * config.extraDepth, _df + 0.5f * config.extraDepth ); } else if ( config.type == eShadowRangeType::FIXED_USER ) { // Configure the clipping volume for shadow mapping according to the // configuration parameters given by the user (focus on an area). // Setup adapted from DeepMimic shadow-pass setup to obtain similar results (his graphics look nice as well :D): // https://github.com/xbpeng/DeepMimic/blob/fbd77f66f7e0ee9d7cd2c863636f296f3af45e04/DeepMimicCore/scenes/DrawScene.cpp#L560 /* \ * /\ * / \ * / \ * / (*) position of clip-volume (znear) * (depth) / * / / * / / * / (*) focus-point * \/ / * \ / * \ / * (*) (zfar) */ /* compute the position of the clipping volume from the point we want to focus */ auto _position = config.focusPoint - 0.5f * config.clipSpaceDepth * dirLightPtr->direction; m_lightSpaceMatView = engine::lookAt( _position, config.focusPoint, config.worldUp ); m_lightSpaceMatProj = engine::ortho( config.clipSpaceWidth, config.clipSpaceHeight, 0.0f, config.clipSpaceDepth ); } else ENGINE_CORE_ERROR( "Invalid range-type parameter given while setting up shadowmap" ); } void CShadowMap::_setupPointLight( const CShadowMapRangeConfig& config, CPointLight* pointLightPtr ) { if ( config.type == eShadowRangeType::AUTOFIX_CAMERA ) { ENGINE_CORE_WARN( "Point-lights don't support autofix functionality yet :(. Use a directional light instead, or use FIXED_USER" ); } else if ( config.type == eShadowRangeType::FIXED_USER ) { m_lightSpaceMatView = engine::lookAt( pointLightPtr->position, config.focusPoint, config.worldUp ); m_lightSpaceMatProj = engine::perspective( config.clipSpaceFov, ((float)m_shadowMapWidth) / m_shadowMapHeight, config.clipSpaceZNear, config.clipSpaceZFar ); } } void CShadowMap::_setupSpotLight( const CShadowMapRangeConfig& config, CSpotLight* spotLightPtr ) { if ( config.type == eShadowRangeType::AUTOFIX_CAMERA ) { ENGINE_CORE_WARN( "Spot-lights don't support autofix functionality yet :(. Use a directional light instead, or use FIXED_USER" ); } else if ( config.type == eShadowRangeType::FIXED_USER ) { m_lightSpaceMatView = engine::lookAt( spotLightPtr->position, spotLightPtr->position + spotLightPtr->direction, config.worldUp ); m_lightSpaceMatProj = engine::perspective( config.clipSpaceFov, ((float)m_shadowMapWidth) / m_shadowMapHeight, config.clipSpaceZNear, config.clipSpaceZFar ); } } void CShadowMap::bind() { /* grab the previous viewport configuration (@TODO: might not be necessary if renderer handles it) */ int32 _currentViewport[4]; glGetIntegerv( GL_VIEWPORT, _currentViewport ); m_previousViewportX = _currentViewport[0]; m_previousViewportY = _currentViewport[1]; m_previousViewportWidth = _currentViewport[2]; m_previousViewportHeight = _currentViewport[3]; /* configure the viewport with the resolution of our depth-map */ glViewport( 0, 0, m_shadowMapWidth, m_shadowMapHeight ); /* bind the framebuffer for the depth-map and clear it before using it */ m_frameBuffer->bind(); glClear( GL_DEPTH_BUFFER_BIT ); } void CShadowMap::unbind() { /* unbind the framebuffer (go back to the default gl-framebuffer) */ m_frameBuffer->unbind(); /* restore the viewport configuration previous to using the shadowmap */ glViewport( m_previousViewportX, m_previousViewportY, m_previousViewportWidth, m_previousViewportHeight ); } }
0420syj/KOSM
test6/frontend/src/sign/login/forgot/ForgotPassword.js
import React, {useState} from 'react'; import './ForgotPassword.scss'; import { forgot } from '../../../util/APIUtils'; import { Button } from 'reactstrap'; const ForgotPassword = () => { const [data, setData] = useState({ email: '', originPassword: '', //기존 비밀번호 password: '', //새 비밀번호 confirmPassword: '', //비밀번호 확인 }) const confirm = (e) => { e.preventDefault(); const userinfo = { email:data.email} forgot(userinfo) .then(() => {alert('임시 비밀번호가 메일로 발송되었습니다.')}) .catch(e => { alert('임시 비밀번호 발송 실패')}) } const onChange = (e) => { setData({ ...data, [e.target.name] : e.target.value }) } return ( <div className='forgotContainer'> <div className='container2'> <div className='title'>Join KOSM</div> <div className='title2'>Forgot Password</div> <form type='submit'> <div className='contents'> <div className='in'> <div style={{marginBottom: '20px'}} className='inContents'> <div className='subTitle'>이메일</div> <div className='email'> <input type='email' name='email' value={data.email} onChange = {onChange} className='subInput'/> <Button style={{ background: '#3aada8', width: '80px', marginLeft: '10px', borderRadius: '10px', color: '#ffffff', fontWeight: '500', fontSize: '20px', }} onClick={confirm}>인증</Button> </div> </div> </div> </div> </form> </div> </div> ) } export default ForgotPassword;
msoharab/madmec
inh_manage.madmec.com/assets/js/drawing.js
function DrawingCtrl() { var CPO = {}; var listofrequi = {}; var listofdesin = {}; var requi = {}; this.__construct = function (cpoctrl) { CPO = cpoctrl; requi = CPO.cpo.require; list = CPO.list; $(CPO.msgDiv).html(''); /* Requirement */ // fetchRequirement(); fetchDesigner(); CPO.cpo.require.prjmid = 0; CPO.cpo.require.requi_id = 0; CPO.cpo.require.prjdesc_id = 0; CPO.cpo.require.ref_no = ''; CPO.cpo.require.quot_id = 0; CPO.cpo.require.po_id = 0; CPO.cpo.require.inv_id = 0; CPO.cpo.require.client_id = 0; CPO.cpo.require.ethno_id = 0; CPO.cpo.require.rep_id = 0; CPO.cpo.require.ethno = ''; CPO.cpo.require.rep = ''; CPO.cpo.require.doethno = ''; CPO.cpo.require.ind = 0; CPO.cpo.require.artype = ''; $(CPO.cpo.submit).click(function (evt) { evt.stopPropagation(); evt.preventDefault(); uploadCPO(); }); $(CPO.list.menuBut).click(function () { listDoc(); }); $(CPO.cpo.doi).datepicker({ dateFormat: 'yy-mm-dd', changeYear: true, changeMonth: true }); $(CPO.cpo.refno + ',' + CPO.cpo.doi + ',' + CPO.cpo.file).val(''); fetchPCCrement(); }; function fetchDesigner() { $(CPO.cpo.desin).html(LOADER_ONE); $.ajax({ type: 'POST', url: CPO.url, data: { autoloader: true, action: 'fetchDesigner' }, success: function (data, extStatus, xhr) { console.log(data); data = $.trim(data); switch (data) { case 'logout': logoutAdmin({}); break; case 'login': loginAdmin({}); break; default: listofdesig = $.parseJSON($.trim(data)); $(CPO.cpo.desin).html('<select class="form-control" id="' + CPO.cpo.des_type + '"><option value="">Select Designer/Employee</option>' + listofdesig + '</select><p class="help-block" id="' + CPO.cpo.des_msg + '">Enter / Select</p>'); break; } }, error: function () { $(CPO.outputDiv).html(INET_ERROR); }, complete: function (xhr, textStatus) { console.log(xhr.status); } }); } function fetchPCCrement() { var htm = ''; $.ajax({ type: 'POST', url: requi.url, data: { autoloader: true, action: 'fetchRequirement' }, success: function (data, extStatus, xhr) { data = $.trim(data); switch (data) { case 'logout': logoutAdmin({}); break; case 'login': loginAdmin({}); break; default: listofrequi = $.parseJSON($.trim(data)); if (listofrequi != null) { for (i = 0; i < listofrequi.length; i++) { htm += listofrequi[i]["html"]; } $(requi.TVQtype).html('<select class="form-control" id="' + requi.Qrequi_type + '"><option value="NULL" selected>Select Project</option>' + htm + '</select><p class="help-block" id="' + requi.QRT_msg + '">Enter / Select</p>'); $('#' + requi.Qrequi_type).change({para: CPO.cpo, requi: listofrequi, len: listofrequi.length }, function (evt) { var para = evt.data.para; var requi = evt.data.requi; var len = evt.data.len; for (i = 0; i < len; i++) { if (requi[i]["req_id"] == $(this).select().val()) { para.require.prjmid = requi[i]["id"]; para.require.requi_id = requi[i]["req_id"]; para.require.ref_no = requi[i]["ref_no"]; para.require.quot_id = requi[i]["quot_id"]; para.require.po_id = requi[i]["po_id"]; para.require.inv_id = requi[i]["inv_id"]; para.require.client_id = requi[i]["client_id"]; para.require.ethno_id = requi[i]["ethno_id"]; para.require.rep_id = requi[i]["rep_id"]; para.require.ethno = requi[i]["ethno"]; para.require.rep = requi[i]["rep"]; para.require.doethno = requi[i]["doethno"]; para.require.ind = i; para.require.artype = requi[i]["artype"]; para.require.prjdesc_id = requi[i]["task_descp"]["id"]; break; } } }); } break; } }, error: function () { $(CPO.outputDiv).html(INET_ERROR); }, complete: function (xhr, textStatus) { console.log(xhr.status); } }); } ; function uploadCPO() { var flag = false; /* Requirement */ if ($('#' + CPO.cpo.des_type).val() == "") { flag = false; $('#' + CPO.cpo.des_msg).html(INVALIDNOT); $('html, body').animate({scrollTop: Number($('#' + CPO.cpo.des_msg).offset().top) - 95}, 'slow'); $('#' + CPO.cpo.des_type).focus(); return; } else { flag = true; $('#' + CPO.cpo.des_msg).html(VALIDNOT); } if (CPO.cpo.require.prjmid != 0) { flag = true; $('#' + CPO.cpo.require.QRT_msg).html(VALIDNOT); } else { flag = false; $('#' + CPO.cpo.require.QRT_msg).html(INVALIDNOT); $('html, body').animate({scrollTop: Number($('#' + CPO.cpo.require.QRT_msg).offset().top) - 95}, 'slow'); $('#' + CPO.cpo.require.Qrequi_type).focus(); return; } if (CPO.cpo.require.ref_no != '' || CPO.cpo.require.ethno != '' || CPO.cpo.require.rep != '' || !$(CPO.cpo.require.doethno).val().match(/(\d{4})-(\d{2})-(\d{2})/) || CPO.cpo.require.artype != '') { flag = true; $('#' + CPO.cpo.require.QRT_msg).html(VALIDNOT); } else { flag = false; $('#' + CPO.cpo.require.QRT_msg).html(INVALIDNOT); $('html, body').animate({scrollTop: Number($('#' + CPO.cpo.require.QRT_msg).offset().top) - 95}, 'slow'); $('#' + CPO.cpo.require.Qrequi_type).focus(); return; } /* Drawing Name */ var draname = $.trim($(CPO.cpo.refno).val()); if (!draname == "") { flag = true; $(CPO.cpo.refnomsg).html(VALIDNOT); } else { flag = false; $(CPO.cpo.refnomsg).html(INVALIDNOT); $('html, body').animate({scrollTop: Number($(CPO.cpo.refnomsg).offset().top) - 95}, 'slow'); $(CPO.cpo.refno).focus(); return; } /* Date of Issue */ if ($(CPO.cpo.doi).val().match(/(\d{4})-(\d{2})-(\d{2})/)) { flag = true; $(CPO.cpo.doimsg).html(VALIDNOT); } else { flag = false; $(CPO.cpo.doimsg).html(INVALIDNOT); $('html, body').animate({scrollTop: Number($(CPO.cpo.doimsg).offset().top) - 95}, 'slow'); $(CPO.cpo.doi).focus(); return; } /* File selected */ if ($(CPO.cpo.file).val().length) { flag = true; $(CPO.cpo.filemsg).html(VALIDNOT); } else { flag = false; $(CPO.cpo.filemsg).html(INVALIDNOT); $('html, body').animate({scrollTop: Number($(CPO.cpo.filemsg).offset().top) - 95}, 'slow'); $(CPO.cpo.file).focus(); return; } if (flag) { var options = { url: CPO.cpo.url, type: 'POST', dataType: 'json', clearForm: true, resetForm: true, target: CPO.cpo.status, data: {autoloader: true, action: 'uploadDrawing', prjname: $.trim($('#' + CPO.cpo.require.Qrequi_type + ' option:selected').text()), prjmid: CPO.cpo.require.prjmid, requi_id: CPO.cpo.require.requi_id, designerid: $('#' + CPO.cpo.des_type).val(), quot_id: CPO.cpo.require.quot_id, po_id: CPO.cpo.require.po_id, inv_id: CPO.cpo.require.inv_id, client_id: CPO.cpo.require.client_id, ethno_id: CPO.cpo.require.ethno_id, ind: CPO.cpo.require.ind, rep_id: CPO.cpo.require.rep_id, ref_no: CPO.cpo.require.ref_no, ethno: CPO.cpo.require.ethno, rep: CPO.cpo.require.rep, doethn: $(CPO.cpo.require.doethno).val(), artype: CPO.cpo.require.artype, refno: $(CPO.cpo.refno).val(), doi: $(CPO.cpo.doi).val(), projdescid: CPO.cpo.require.prjdesc_id }, beforeSubmit: function () { $(CPO.cpo.status).empty(); $(CPO.cpo.bar).width(CPO.cpo.percentVal) $(CPO.cpo.percent).html(CPO.cpo.percentVal) }, uploadProgress: function (event, position, total, percentComplete) { CPO.cpo.percentVal = percentComplete + '%'; $(CPO.cpo.bar).width(CPO.cpo.percentVal) $(CPO.cpo.percent).html(CPO.cpo.percentVal); }, success: function (json, statusText, xhr, $form) { CPO.cpo.percentVal = '100%'; $(CPO.cpo.bar).width(CPO.cpo.percentVal) $(CPO.cpo.percent).html(CPO.cpo.percentVal); $(CPO.cpo.status).html(json.msg); }, complete: function (xhr) { var percentVal = '0%'; if (xhr.responseText.length == 0) { $(CPO.cpo.bar).width(percentVal); $(CPO.cpo.percent).html(percentVal); } }, error: function (xhr) { $(CPO.cpo.status).html(xhr.responseText); $(CPO.cpo.status).append('<br />Some thing went wrong'); } }; $(CPO.cpo.formid).ajaxSubmit(options); } } ; function listDoc() { $(list.listDiv).html(LOADER_FIV); var htm = ''; $.ajax({ url: list.url, type: 'POST', data: { autoloader: true, action: list.action, display: list.display, what: list.what }, success: function (data, textStatus, xhr) { data = $.trim(data); switch (data) { case 'logout': logoutAdmin({}); break; case 'login': loginAdmin({}); break; default: var lists = $.parseJSON(data); if (lists != null) { for (i = 0; i < lists.length; i++) { htm += lists[i].html; } } var header = '<div class="col-md-12">' + '<div class="panel panel-default">' + '<div class="panel-heading"> List of Drawings </div>' + '<div class="panel-body">' + '<table class="table table-striped table-bordered table-hover dataTable no-footer" id="list_what_' + list.what + '">' + '<thead><tr><th>#</th><th>Name</th><th>Date</th><th>Location</th></tr></thead>' + '<tbody>'; var footer = '</tbody></table></div></div></div>'; $(list.listDiv).html(header + htm + footer); window.setTimeout(function () { $('#list_what_' + list.what).dataTable(); }, 300); break; } }, error: function () { $(CPO.outputDiv).html(INET_ERROR); }, complete: function (xhr, textStatus) { console.log(xhr.status); } }); } }
dannyadkins/uwazi
app/api/settings/specs/settings.spec.js
<reponame>dannyadkins/uwazi<filename>app/api/settings/specs/settings.spec.js import { catchErrors } from 'api/utils/jasmineHelpers'; import db from 'api/utils/testing_db'; import translations from 'api/i18n/translations'; import settings from '../settings.js'; import fixtures from './fixtures.js'; describe('settings', () => { beforeEach((done) => { spyOn(translations, 'updateContext').and.returnValue(Promise.resolve('ok')); db.clearAllAndLoad(fixtures).then(done).catch(catchErrors(done)); }); afterAll((done) => { db.disconnect().then(done); }); describe('save()', () => { it('should save the settings', (done) => { const config = { site_name: 'My collection' }; settings.save(config) .then(() => settings.save({ custom: { customNested: 'data' } })) .then(() => settings.get()) .then((result) => { expect(result.site_name).toBe('My collection'); expect(result.custom.customNested).toBe('data'); done(); }) .catch(catchErrors(done)); }); it('should return the updated settings', (done) => { const config = { site_name: 'New settings' }; settings.save(config) .then((createdDocument) => { expect(createdDocument.site_name).toBe(config.site_name); expect(createdDocument.allowedPublicTemplates[0]).toBe('id1'); expect(createdDocument.allowedPublicTemplates[1]).toBe('id2'); done(); }) .catch(catchErrors(done)); }); describe('when there are Links', () => { let config; beforeEach(() => { config = { site_name: 'My collection', links: [{ title: 'Page one' }] }; }); it('should create a translation context for the passed links', (done) => { settings.save(config) .then(() => { expect(translations.updateContext).toHaveBeenCalledWith('Menu', 'Menu', {}, [], { 'Page one': 'Page one' }, 'Uwazi UI'); done(); }) .catch(catchErrors(done)); }); describe('updating the links', () => { it('should update the translation context for the links', (done) => { config.links.push({ title: 'Page two' }); settings.save(config) .then((savedConfig) => { config = { site_name: 'My collection', links: [{ title: 'Page 1', _id: savedConfig.links[0]._id }, { title: 'Page three' }] }; return settings.save(config); }) .then(() => { expect(translations.updateContext) .toHaveBeenCalledWith( 'Menu', 'Menu', { 'Page one': 'Page 1' }, ['Page two'], { 'Page 1': 'Page 1', 'Page three': 'Page three' }, 'Uwazi UI' ); done(); }) .catch(catchErrors(done)); }); }); }); describe('when there are filter groups', () => { it('should create translations for them', (done) => { const config = { site_name: 'My collection', filters: [{ id: 1, name: 'Judge' }, { id: 2, name: 'Documents', items: [{ id: 3, name: 'Cause' }] }] }; settings.save(config) .then(() => { expect(translations.updateContext).toHaveBeenCalledWith('Filters', 'Filters', {}, [], { Documents: 'Documents' }, 'Uwazi UI'); done(); }) .catch(catchErrors(done)); }); it('should update them', (done) => { let config = { site_name: 'My collection', filters: [{ id: '1', name: 'Judge' }, { id: '2', name: 'Documents', items: [] }, { id: '3', name: 'Files', items: [] }] }; settings.save(config) .then(() => { config = { site_name: 'My collection', filters: [{ id: '1', name: 'Judge' }, { id: '2', name: 'Important Documents', items: [] }] }; translations.updateContext.calls.reset(); return settings.save(config); }) .then(() => { expect(translations.updateContext) .toHaveBeenCalledWith( 'Filters', 'Filters', { Documents: 'Important Documents' }, ['Files'], { 'Important Documents': 'Important Documents' }, 'Uwazi UI' ); done(); }) .catch(catchErrors(done)); }); }); describe('when no links or filters are present', () => { it('should not update contexts translations', async () => { await settings.save({ css: 'something that does not have links' }); await translations.get(); expect(translations.updateContext).not.toHaveBeenCalled(); }); }); }); describe('get()', () => { describe('if there is no settings on the DB', () => { it('should return an empty object', (done) => { db.clear(['settings'], () => { settings.get() .then((result) => { expect(result).toEqual({}); done(); }) .catch(catchErrors(done)); }); }); }); it('should not return private values', async () => { const values = await settings.get(); expect(values.publicFormDestination).not.toBeDefined(); }); it('should return private values if asked for', async () => { const values = await settings.get(true); expect(values.publicFormDestination).toBeDefined(); }); }); describe('setDefaultLanguage()', () => { it('should save the settings with the new default language', (done) => { settings.setDefaultLanguage('en') .then(() => settings.get()) .then((result) => { expect(result.languages[1].key).toBe('en'); expect(result.languages[1].default).toBe(true); done(); }) .catch(catchErrors(done)); }); }); describe('addLanguage()', () => { it('should add a to settings list language', (done) => { settings.addLanguage({ key: 'fr', label: 'Frances' }) .then(() => settings.get()) .then((result) => { expect(result.languages.length).toBe(3); done(); }) .catch(catchErrors(done)); }); }); describe('deleteLanguage()', () => { it('should add a to settings list language', (done) => { settings.deleteLanguage('en') .then(() => settings.get()) .then((result) => { expect(result.languages.length).toBe(1); done(); }) .catch(catchErrors(done)); }); }); describe('removeTemplateFromFilters', () => { it('should remove the template from the filters', (done) => { const _settings = { filters: [ { id: '123' }, { id: 'axz', items: [{ id: '123' }] } ] }; spyOn(settings, 'get').and.returnValue(Promise.resolve(_settings)); spyOn(settings, 'save'); settings.removeTemplateFromFilters('123') .then(() => { expect(settings.save).toHaveBeenCalledWith({ filters: [{ id: 'axz', items: [] }] }); done(); }); }); }); describe('updateFilterName', () => { const _settings = { filters: [ { id: '123', name: 'Batman' }, ] }; it('should update a filter name', async () => { spyOn(settings, 'get').and.returnValue(Promise.resolve(_settings)); spyOn(settings, 'save').and.returnValue(Promise.resolve('updatedSettings')); const updatedFilter = await settings.updateFilterName('123', 'The dark knight'); expect(settings.save).toHaveBeenCalledWith({ filters: [{ id: '123', name: 'The dark knight' }] }); expect(updatedFilter).toEqual('updatedSettings'); }); it('should do nothing when filter does not exist', async () => { spyOn(settings, 'get').and.returnValue(Promise.resolve(_settings)); spyOn(settings, 'save').and.returnValue(Promise.resolve('updatedSettings')); const updatedFilter = await settings.updateFilterName('321', 'Filter not present'); expect(settings.save).not.toHaveBeenCalled(); expect(updatedFilter).toBeUndefined(); }); }); });
jkolokotronis/ds_mod_tools
pkg/Python27/Lib/site-packages/win32comext/axscript/client/framework.py
"""AXScript Client Framework This module provides a core framework for an ActiveX Scripting client. Derived classes actually implement the AX Client itself, including the scoping rules, etc. There are classes defined for the engine itself, and for ScriptItems """ import sys from win32com.axscript import axscript import win32com.server.util import win32com.client.connect # Need simple connection point support import win32api, winerror import pythoncom import types import re def RemoveCR(text): # No longer just "RemoveCR" - should be renamed to # FixNewlines, or something. Idea is to fix arbitary newlines into # something Python can compile... return re.sub('(\r\n)|\r|(\n\r)','\n',text) SCRIPTTEXT_FORCEEXECUTION = -2147483648 # 0x80000000 SCRIPTTEXT_ISEXPRESSION = 0x00000020 SCRIPTTEXT_ISPERSISTENT = 0x00000040 from win32com.server.exception import Exception, IsCOMServerException import error # ax.client.error state_map = { axscript.SCRIPTSTATE_UNINITIALIZED: "SCRIPTSTATE_UNINITIALIZED", axscript.SCRIPTSTATE_INITIALIZED: "SCRIPTSTATE_INITIALIZED", axscript.SCRIPTSTATE_STARTED: "SCRIPTSTATE_STARTED", axscript.SCRIPTSTATE_CONNECTED: "SCRIPTSTATE_CONNECTED", axscript.SCRIPTSTATE_DISCONNECTED: "SCRIPTSTATE_DISCONNECTED", axscript.SCRIPTSTATE_CLOSED: "SCRIPTSTATE_CLOSED", } def profile(fn, *args): import profile prof = profile.Profile() try: # roll on 1.6 :-) # return prof.runcall(fn, *args) return prof.runcall(*(fn,) + args) finally: import pstats # Damn - really want to send this to Excel! # width, list = pstats.Stats(prof).strip_dirs().get_print_list([]) pstats.Stats(prof).strip_dirs().sort_stats("time").print_stats() class SafeOutput: softspace=1 def __init__(self, redir=None): if redir is None: redir = sys.stdout self.redir=redir def write(self,message): try: self.redir.write(message) except: win32api.OutputDebugString(message.encode('mbcs')) def flush(self): pass def close(self): pass # Make sure we have a valid sys.stdout/stderr, otherwise out # print and trace statements may raise an exception def MakeValidSysOuts(): if not isinstance(sys.stdout, SafeOutput): sys.stdout = sys.stderr = SafeOutput() # and for the sake of working around something I can't understand... # prevent keyboard interrupts from killing IIS import signal def noOp(a,b): # it would be nice to get to the bottom of this, so a warning to # the debug console can't hurt. print "WARNING: Ignoring keyboard interrupt from ActiveScripting engine" # If someone else has already redirected, then assume they know what they are doing! if signal.getsignal(signal.SIGINT) == signal.default_int_handler: try: signal.signal(signal.SIGINT, noOp) except ValueError: # Not the main thread - can't do much. pass def trace(*args): """A function used instead of "print" for debugging output. """ for arg in args: print arg, print def RaiseAssert(scode, desc): """A debugging function that raises an exception considered an "Assertion". """ print "**************** ASSERTION FAILED *******************" print desc raise Exception(desc, scode) class AXScriptCodeBlock: """An object which represents a chunk of code in an AX Script """ def __init__(self, name, codeText, sourceContextCookie, startLineNumber, flags): self.name = name self.codeText = codeText self.codeObject = None self.sourceContextCookie = sourceContextCookie self.startLineNumber = startLineNumber self.flags = flags self.beenExecuted = 0 def GetFileName(self): # Gets the "file name" for Python - uses <...> so Python doesnt think # it is a real file. return "<%s>" % self.name def GetDisplayName(self): return self.name def GetLineNo(self, no): pos = -1 for i in range(no-1): pos = self.codeText.find('\n', pos+1) if pos==-1: pos=len(self.codeText) epos = self.codeText.find('\n', pos+1) if epos==-1: epos=len(self.codeText) return self.codeText[pos+1:epos].strip() class Event: """A single event for a ActiveX named object. """ def __init__(self): self.name = "<None>" def __repr__(self): return "<%s at %d: %s>" % (self.__class__.__name__, id(self), self.name) def Reset(self): pass def Close(self): pass def Build(self, typeinfo, funcdesc): self.dispid = funcdesc[0] self.name = typeinfo.GetNames(self.dispid)[0] # print "Event.Build() - Event Name is ", self.name class EventSink: """A set of events against an item. Note this is a COM client for connection points. """ _public_methods_ = [] def __init__(self, myItem, coDispatch): self.events = {} self.connection = None self.coDispatch = coDispatch self.myScriptItem = myItem self.myInvokeMethod = myItem.GetEngine().ProcessScriptItemEvent self.iid = None def Reset(self): self.Disconnect() def Close(self): self.iid = None self.myScriptItem = None self.myInvokeMethod = None self.coDispatch = None for event in self.events.itervalues(): event.Reset() self.events = {} self.Disconnect() # COM Connection point methods. def _query_interface_(self, iid): if iid==self.iid: return win32com.server.util.wrap(self) def _invoke_(self, dispid, lcid, wFlags, args): try: event = self.events[dispid] except: raise Exception(scode=winerror.DISP_E_MEMBERNOTFOUND) #print "Invoke for ", event, "on", self.myScriptItem, " - calling", self.myInvokeMethod return self.myInvokeMethod(self.myScriptItem, event, lcid, wFlags, args) def GetSourceTypeInfo(self, typeinfo): """Gets the typeinfo for the Source Events for the passed typeinfo""" attr = typeinfo.GetTypeAttr() cFuncs = attr[6] typeKind = attr[5] if typeKind not in [pythoncom.TKIND_COCLASS, pythoncom.TKIND_INTERFACE]: RaiseAssert(winerror.E_UNEXPECTED, "The typeKind of the object is unexpected") cImplType = attr[8] for i in xrange(cImplType): # Look for the [source, default] interface on the coclass # that isn't marked as restricted. flags = typeinfo.GetImplTypeFlags(i) flagsNeeded = pythoncom.IMPLTYPEFLAG_FDEFAULT | pythoncom.IMPLTYPEFLAG_FSOURCE if (flags & ( flagsNeeded | pythoncom.IMPLTYPEFLAG_FRESTRICTED))==(flagsNeeded): # Get the handle to the implemented interface. href = typeinfo.GetRefTypeOfImplType(i) return typeinfo.GetRefTypeInfo(href) def BuildEvents(self): # See if it is an extender object. try: mainTypeInfo = self.coDispatch.QueryInterface(axscript.IID_IProvideMultipleClassInfo) isMulti = 1 numTypeInfos = mainTypeInfo.GetMultiTypeInfoCount() except pythoncom.com_error: isMulti = 0 numTypeInfos = 1 try: mainTypeInfo = self.coDispatch.QueryInterface(pythoncom.IID_IProvideClassInfo) except pythoncom.com_error: numTypeInfos = 0 # Create an event handler for the item. for item in xrange(numTypeInfos): if isMulti: typeinfo, flags = mainTypeInfo.GetInfoOfIndex(item, axscript.MULTICLASSINFO_GETTYPEINFO) else: typeinfo = mainTypeInfo.GetClassInfo() sourceType = self.GetSourceTypeInfo(typeinfo) cFuncs = 0 if sourceType: attr = sourceType.GetTypeAttr() self.iid = attr[0] cFuncs = attr[6] for i in xrange(cFuncs): funcdesc = sourceType.GetFuncDesc(i) event = Event() event.Build(sourceType, funcdesc) self.events[event.dispid] = event def Connect(self): if self.connection is not None or self.iid is None: return # trace("Connect for sink item", self.myScriptItem.name, "with IID",str(self.iid)) self.connection = win32com.client.connect.SimpleConnection(self.coDispatch, self, self.iid) def Disconnect(self): if self.connection: try: self.connection.Disconnect() except pythoncom.com_error: pass # Ignore disconnection errors. self.connection = None class ScriptItem: """An item (or subitem) that is exposed to the ActiveX script """ def __init__(self, parentItem, name, dispatch, flags): self.parentItem = parentItem self.dispatch = dispatch self.name = name self.flags = flags self.eventSink = None self.subItems = {} self.createdConnections = 0 self.isRegistered = 0 # trace("Creating ScriptItem", name, "of parent", parentItem,"with dispatch", dispatch) def __repr__(self): flagsDesc="" if self.flags is not None and self.flags & axscript.SCRIPTITEM_GLOBALMEMBERS: flagsDesc = "/Global" return "<%s at %d: %s%s>" % (self.__class__.__name__, id(self), self.name,flagsDesc) def _dump_(self, level): flagDescs = [] if self.flags is not None and self.flags & axscript.SCRIPTITEM_GLOBALMEMBERS: flagDescs.append("GLOBAL!") if self.flags is None or self.flags & axscript.SCRIPTITEM_ISVISIBLE == 0: flagDescs.append("NOT VISIBLE") if self.flags is not None and self.flags & axscript.SCRIPTITEM_ISSOURCE: flagDescs.append("EVENT SINK") if self.flags is not None and self.flags & axscript.SCRIPTITEM_CODEONLY: flagDescs.append("CODE ONLY") print " " * level, "Name=", self.name, ", flags=", "/".join(flagDescs), self for subItem in self.subItems.itervalues(): subItem._dump_(level+1) def Reset(self): self.Disconnect() if self.eventSink: self.eventSink.Reset() self.isRegistered = 0 for subItem in self.subItems.itervalues(): subItem.Reset() def Close(self): self.Reset() self.dispatch = None self.parentItem = None if self.eventSink: self.eventSink.Close() self.eventSink = None for subItem in self.subItems.itervalues(): subItem.Close() self.subItems = [] self.createdConnections = 0 def Register(self): if self.isRegistered: return # Get the type info to use to build this item. # if not self.dispatch: # id = self.parentItem.dispatch.GetIDsOfNames(self.name) # print "DispID of me is", id # result = self.parentItem.dispatch.Invoke(id, 0, pythoncom.DISPATCH_PROPERTYGET,1) # if type(result)==pythoncom.TypeIIDs[pythoncom.IID_IDispatch]: # self.dispatch = result # else: # print "*** No dispatch" # return # print "**** Made dispatch" self.isRegistered = 1 # Register the sub-items. for item in self.subItems.itervalues(): if not item.isRegistered: item.Register() def IsGlobal(self): return self.flags & axscript.SCRIPTITEM_GLOBALMEMBERS def IsVisible(self): return (self.flags & (axscript.SCRIPTITEM_ISVISIBLE | axscript.SCRIPTITEM_ISSOURCE)) != 0 def GetEngine(self): item = self while item.parentItem.__class__==self.__class__: item = item.parentItem return item.parentItem def _GetFullItemName(self): ret = self.name if self.parentItem: try: ret = self.parentItem._GetFullItemName() + "." + ret except AttributeError: pass return ret def GetSubItemClass(self): return self.__class__ def GetSubItem(self, name): return self.subItems[name.lower()] def GetCreateSubItem(self, parentItem, name, dispatch, flags): keyName = name.lower() try: rc = self.subItems[keyName] # No changes allowed to existing flags. if not rc.flags is None and not flags is None and rc.flags != flags: raise Exception(scode=winerror.E_INVALIDARG) # Existing item must not have a dispatch. if not rc.dispatch is None and not dispatch is None: raise Exception(scode=winerror.E_INVALIDARG) rc.flags = flags # Setup the real flags. rc.dispatch = dispatch except KeyError: rc = self.subItems[keyName] = self.GetSubItemClass()(parentItem, name, dispatch, flags) return rc # if self.dispatch is None: # RaiseAssert(winerror.E_UNEXPECTED, "??") def CreateConnections(self): # Create (but do not connect to) the connection points. if self.createdConnections: return self.createdConnections = 1 # Nothing to do unless this is an event source # This flags means self, _and_ children, are connectable. if self.flags & axscript.SCRIPTITEM_ISSOURCE: self.BuildEvents() self.FindBuildSubItemEvents() def Connect(self): # Connect to the already created connection points. if self.eventSink: self.eventSink.Connect() for subItem in self.subItems.itervalues(): subItem.Connect() def Disconnect(self): # Disconnect from the connection points. if self.eventSink: self.eventSink.Disconnect() for subItem in self.subItems.itervalues(): subItem.Disconnect() def BuildEvents(self): if self.eventSink is not None or self.dispatch is None: RaiseAssert(winerror.E_UNEXPECTED, "Item already has built events, or no dispatch available?") # trace("BuildEvents for named item", self._GetFullItemName()) self.eventSink = EventSink(self, self.dispatch) self.eventSink.BuildEvents() def FindBuildSubItemEvents(self): # Called during connection to event source. Seeks out and connects to # all children. As per the AX spec, this is not recursive # (ie, children sub-items are not seeked) try: multiTypeInfo = self.dispatch.QueryInterface(axscript.IID_IProvideMultipleClassInfo) numTypeInfos = multiTypeInfo.GetMultiTypeInfoCount() except pythoncom.com_error: return for item in xrange(numTypeInfos): typeinfo, flags = multiTypeInfo.GetInfoOfIndex(item, axscript.MULTICLASSINFO_GETTYPEINFO) defaultType = self.GetDefaultSourceTypeInfo(typeinfo) index = 0 while 1: try: fdesc = defaultType.GetFuncDesc(index) except pythoncom.com_error: break # No more funcs index = index + 1 dispid = fdesc[0] funckind = fdesc[3] invkind = fdesc[4] elemdesc = fdesc[8] funcflags = fdesc[9] try: isSubObject = not (funcflags & pythoncom.FUNCFLAG_FRESTRICTED) and \ funckind == pythoncom.FUNC_DISPATCH and \ invkind == pythoncom.INVOKE_PROPERTYGET and \ elemdesc[0][0] == pythoncom.VT_PTR and \ elemdesc[0][1][0] == pythoncom.VT_USERDEFINED except: isSubObject = 0 if isSubObject: try: # We found a sub-object. names = typeinfo.GetNames(dispid); result = self.dispatch.Invoke(dispid, 0x0, pythoncom.DISPATCH_PROPERTYGET, 1) # IE has an interesting problem - there are lots of synonyms for the same object. Eg # in a simple form, "window.top", "window.window", "window.parent", "window.self" # all refer to the same object. Our event implementation code does not differentiate # eg, "window_onload" will fire for *all* objects named "window". Thus, # "window" and "window.window" will fire the same event handler :( # One option would be to check if the sub-object is indeed the # parent object - however, this would stop "top_onload" from firing, # as no event handler for "top" would work. # I think we simply need to connect to a *single* event handler. # As use in IE is deprecated, I am not solving this now. if type(result)==pythoncom.TypeIIDs[pythoncom.IID_IDispatch]: name = names[0] subObj = self.GetCreateSubItem(self, name, result, axscript.SCRIPTITEM_ISVISIBLE) #print "subobj", name, "flags are", subObj.flags, "mydisp=", self.dispatch, "result disp=", result, "compare=", self.dispatch==result subObj.BuildEvents() subObj.Register() except pythoncom.com_error: pass def GetDefaultSourceTypeInfo(self, typeinfo): """Gets the typeinfo for the Default Dispatch for the passed typeinfo""" attr = typeinfo.GetTypeAttr() cFuncs = attr[6] typeKind = attr[5] if typeKind not in [pythoncom.TKIND_COCLASS, pythoncom.TKIND_INTERFACE]: RaiseAssert(winerror.E_UNEXPECTED, "The typeKind of the object is unexpected") cImplType = attr[8] for i in xrange(cImplType): # Look for the [source, default] interface on the coclass # that isn't marked as restricted. flags = typeinfo.GetImplTypeFlags(i) if (flags & ( pythoncom.IMPLTYPEFLAG_FDEFAULT | pythoncom.IMPLTYPEFLAG_FSOURCE | pythoncom.IMPLTYPEFLAG_FRESTRICTED))==pythoncom.IMPLTYPEFLAG_FDEFAULT: # Get the handle to the implemented interface. href = typeinfo.GetRefTypeOfImplType(i) defTypeInfo = typeinfo.GetRefTypeInfo(href) attr = defTypeInfo.GetTypeAttr() typeKind = attr[5] typeFlags = attr[11] if typeKind == pythoncom.TKIND_INTERFACE and typeFlags & pythoncom.TYPEFLAG_FDUAL: # Get corresponding Disp interface # -1 is a special value which does this for us. href = typeinfo.GetRefTypeOfImplType(-1) return defTypeInfo.GetRefTypeInfo(href) else: return defTypeInfo IActiveScriptMethods = [ "SetScriptSite", "GetScriptSite", "SetScriptState", "GetScriptState", "Close", "AddNamedItem", "AddTypeLib", "GetScriptDispatch", "GetCurrentScriptThreadID", "GetScriptThreadID", "GetScriptThreadState", "InterruptScriptThread", "Clone" ] IActiveScriptParseMethods = [ "InitNew", "AddScriptlet", "ParseScriptText" ] IObjectSafetyMethods = [ "GetInterfaceSafetyOptions", "SetInterfaceSafetyOptions"] # ActiveScriptParseProcedure is a new interface with IIS4/IE4. IActiveScriptParseProcedureMethods = ['ParseProcedureText'] class COMScript: """An ActiveX Scripting engine base class. This class implements the required COM interfaces for ActiveX scripting. """ _public_methods_ = IActiveScriptMethods + IActiveScriptParseMethods + IObjectSafetyMethods + IActiveScriptParseProcedureMethods _com_interfaces_ = [axscript.IID_IActiveScript, axscript.IID_IActiveScriptParse, axscript.IID_IObjectSafety] #, axscript.IID_IActiveScriptParseProcedure] def __init__(self): # Make sure we can print/trace wihout an exception! MakeValidSysOuts() # trace("AXScriptEngine object created", self) self.baseThreadId = -1 self.debugManager = None self.threadState = axscript.SCRIPTTHREADSTATE_NOTINSCRIPT self.scriptState = axscript.SCRIPTSTATE_UNINITIALIZED self.scriptSite = None self.safetyOptions = 0 self.lcid = 0 self.subItems = {} self.scriptCodeBlocks = {} def _query_interface_(self, iid): if self.debugManager: return self.debugManager._query_interface_for_debugger_(iid) # trace("ScriptEngine QI - unknown IID", iid) return 0 # IActiveScriptParse def InitNew(self): if self.scriptSite is not None: self.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED) def AddScriptlet(self, defaultName, code, itemName, subItemName, eventName, delimiter, sourceContextCookie, startLineNumber): # trace ("AddScriptlet", defaultName, code, itemName, subItemName, eventName, delimiter, sourceContextCookie, startLineNumber) self.DoAddScriptlet(defaultName, code, itemName, subItemName, eventName, delimiter,sourceContextCookie, startLineNumber) def ParseScriptText(self, code, itemName, context, delimiter, sourceContextCookie, startLineNumber, flags, bWantResult): # trace ("ParseScriptText", code[:20],"...", itemName, context, delimiter, sourceContextCookie, startLineNumber, flags, bWantResult) if bWantResult or self.scriptState == axscript.SCRIPTSTATE_STARTED \ or self.scriptState == axscript.SCRIPTSTATE_CONNECTED \ or self.scriptState == axscript.SCRIPTSTATE_DISCONNECTED : flags = flags | SCRIPTTEXT_FORCEEXECUTION else: flags = flags & (~SCRIPTTEXT_FORCEEXECUTION) if flags & SCRIPTTEXT_FORCEEXECUTION: # About to execute the code. self.RegisterNewNamedItems() return self.DoParseScriptText(code, sourceContextCookie, startLineNumber, bWantResult, flags) # # IActiveScriptParseProcedure def ParseProcedureText( self, code, formalParams, procName, itemName, unkContext, delimiter, contextCookie, startingLineNumber, flags): trace("ParseProcedureText", code, formalParams, procName, itemName, unkContext, delimiter, contextCookie, startingLineNumber, flags) # NOTE - this is never called, as we have disabled this interface. # Problem is, once enabled all even code comes via here, rather than AddScriptlet. # However, the "procName" is always an empty string - ie, itemName is the object whose event we are handling, # but no idea what the specific event is!? # Problem is disabling this block is that AddScriptlet is _not_ passed # <SCRIPT for="whatever" event="onClick" language="Python"> # (but even for those blocks, the "onClick" information is still missing!?!?!?) # self.DoAddScriptlet(None, code, itemName, subItemName, eventName, delimiter,sourceContextCookie, startLineNumber) return None # # IActiveScript def SetScriptSite(self, site): # We should still work with an existing site (or so MSXML believes :) self.scriptSite = site if self.debugManager is not None: self.debugManager.Close() import traceback try: import win32com.axdebug.axdebug # see if the core exists. import debug self.debugManager = debug.DebugManager(self) except pythoncom.com_error: # COM errors will occur if the debugger interface has never been # seen on the target system trace("Debugging interfaces not available - debugging is disabled..") self.debugManager = None except ImportError: trace("Debugging extensions (axdebug) module does not exist - debugging is disabled..") self.debugManager = None except: traceback.print_exc() trace("*** Debugger Manager could not initialize - %s: %s" % (sys.exc_info()[0],sys.exc_info()[1])) self.debugManager = None try: self.lcid = site.GetLCID() except pythoncom.com_error: self.lcid = win32api.GetUserDefaultLCID() self.Reset() def GetScriptSite(self, iid): if self.scriptSite is None: raise Exception(scode=winerror.S_FALSE) return self.scriptSite.QueryInterface(iid) def SetScriptState(self, state): #print "SetScriptState with %s - currentstate = %s" % (state_map.get(state),state_map.get(self.scriptState)) if state == self.scriptState: return # If closed, allow no other state transitions if self.scriptState==axscript.SCRIPTSTATE_CLOSED: raise Exception(scode=winerror.E_INVALIDARG) if state==axscript.SCRIPTSTATE_INITIALIZED: # Re-initialize - shutdown then reset. if self.scriptState in [axscript.SCRIPTSTATE_CONNECTED, axscript.SCRIPTSTATE_STARTED]: self.Stop() elif state==axscript.SCRIPTSTATE_STARTED: if self.scriptState == axscript.SCRIPTSTATE_CONNECTED: self.Disconnect() if self.scriptState == axscript.SCRIPTSTATE_DISCONNECTED: self.Reset() self.Run() self.ChangeScriptState(axscript.SCRIPTSTATE_STARTED) elif state==axscript.SCRIPTSTATE_CONNECTED: if self.scriptState in [axscript.SCRIPTSTATE_UNINITIALIZED,axscript.SCRIPTSTATE_INITIALIZED]: self.ChangeScriptState(axscript.SCRIPTSTATE_STARTED) # report transition through started self.Run() if self.scriptState == axscript.SCRIPTSTATE_STARTED: self.Connect() self.ChangeScriptState(state) elif state==axscript.SCRIPTSTATE_DISCONNECTED: if self.scriptState == axscript.SCRIPTSTATE_CONNECTED: self.Disconnect() elif state==axscript.SCRIPTSTATE_CLOSED: self.Close() elif state==axscript.SCRIPTSTATE_UNINITIALIZED: if self.scriptState == axscript.SCRIPTSTATE_STARTED: self.Stop() if self.scriptState == axscript.SCRIPTSTATE_CONNECTED: self.Disconnect() if self.scriptState == axscript.SCRIPTSTATE_DISCONNECTED: self.Reset() self.ChangeScriptState(state) else: raise Exception(scode=winerror.E_INVALIDARG) def GetScriptState(self): return self.scriptState def Close(self): # trace("Close") if self.scriptState in [axscript.SCRIPTSTATE_CONNECTED, axscript.SCRIPTSTATE_DISCONNECTED]: self.Stop() if self.scriptState in [axscript.SCRIPTSTATE_CONNECTED, axscript.SCRIPTSTATE_DISCONNECTED, axscript.SCRIPTSTATE_INITIALIZED, axscript.SCRIPTSTATE_STARTED]: pass # engine.close?? if self.scriptState in [axscript.SCRIPTSTATE_UNINITIALIZED, axscript.SCRIPTSTATE_CONNECTED, axscript.SCRIPTSTATE_DISCONNECTED, axscript.SCRIPTSTATE_INITIALIZED, axscript.SCRIPTSTATE_STARTED]: self.ChangeScriptState(axscript.SCRIPTSTATE_CLOSED) # Completely reset all named items (including persistent) for item in self.subItems.itervalues(): item.Close() self.subItems = {} self.baseThreadId = -1 if self.debugManager: self.debugManager.Close() self.debugManager = None self.scriptSite = None self.scriptCodeBlocks = {} self.persistLoaded = 0 def AddNamedItem(self, name, flags): if self.scriptSite is None: raise Exception(scode=winerror.E_INVALIDARG) try: unknown = self.scriptSite.GetItemInfo(name, axscript.SCRIPTINFO_IUNKNOWN)[0] dispatch = unknown.QueryInterface(pythoncom.IID_IDispatch) except pythoncom.com_error: raise Exception(scode=winerror.E_NOINTERFACE, desc="Object has no dispatch interface available.") newItem = self.subItems[name] = self.GetNamedItemClass()(self, name, dispatch, flags) if newItem.IsGlobal(): newItem.CreateConnections() def GetScriptDispatch(self, name): # Base classes should override. raise Exception(scode=winerror.E_NOTIMPL) def GetCurrentScriptThreadID(self): return self.baseThreadId def GetScriptThreadID(self, win32ThreadId): if self.baseThreadId == -1: raise Exception(scode=winerror.E_UNEXPECTED) if self.baseThreadId != win32ThreadId: raise Exception(scode=winerror.E_INVALIDARG) return self.baseThreadId def GetScriptThreadState(self, scriptThreadId): if self.baseThreadId == -1: raise Exception(scode=winerror.E_UNEXPECTED) if scriptThreadId != self.baseThreadId: raise Exception(scode=winerror.E_INVALIDARG) return self.threadState def AddTypeLib(self, uuid, major, minor, flags): # Get the win32com gencache to register this library. from win32com.client import gencache gencache.EnsureModule(uuid, self.lcid, major, minor, bForDemand = 1) # This is never called by the C++ framework - it does magic. # See PyGActiveScript.cpp #def InterruptScriptThread(self, stidThread, exc_info, flags): # raise Exception("Not Implemented", scode=winerror.E_NOTIMPL) def Clone(self): raise Exception("Not Implemented", scode=winerror.E_NOTIMPL) # # IObjectSafety # Note that IE seems to insist we say we support all the flags, even tho # we dont accept them all. If unknown flags come in, they are ignored, and never # reflected in GetInterfaceSafetyOptions and the QIs obviously fail, but still IE # allows our engine to initialize. def SetInterfaceSafetyOptions(self, iid, optionsMask, enabledOptions): # trace ("SetInterfaceSafetyOptions", iid, optionsMask, enabledOptions) if optionsMask & enabledOptions == 0: return # See comments above. # if (optionsMask & enabledOptions & \ # ~(axscript.INTERFACESAFE_FOR_UNTRUSTED_DATA | axscript.INTERFACESAFE_FOR_UNTRUSTED_CALLER)): # # request for options we don't understand # RaiseAssert(scode=winerror.E_FAIL, desc="Unknown safety options") if iid in [pythoncom.IID_IPersist, pythoncom.IID_IPersistStream, pythoncom.IID_IPersistStreamInit, axscript.IID_IActiveScript, axscript.IID_IActiveScriptParse]: supported = self._GetSupportedInterfaceSafetyOptions() self.safetyOptions = supported & optionsMask & enabledOptions else: raise Exception(scode=winerror.E_NOINTERFACE) def _GetSupportedInterfaceSafetyOptions(self): return 0 def GetInterfaceSafetyOptions(self, iid): if iid in [pythoncom.IID_IPersist, pythoncom.IID_IPersistStream, pythoncom.IID_IPersistStreamInit, axscript.IID_IActiveScript, axscript.IID_IActiveScriptParse]: supported = self._GetSupportedInterfaceSafetyOptions() return supported, self.safetyOptions else: raise Exception(scode=winerror.E_NOINTERFACE) # # Other helpers. def ExecutePendingScripts(self): self.RegisterNewNamedItems() self.DoExecutePendingScripts() def ProcessScriptItemEvent(self, item, event, lcid, wFlags, args): # trace("ProcessScriptItemEvent", item, event, lcid, wFlags, args) self.RegisterNewNamedItems() return self.DoProcessScriptItemEvent(item, event, lcid, wFlags, args) def _DumpNamedItems_(self): for item in self.subItems.itervalues(): item._dump_(0) def ResetNamedItems(self): # Due to the way we work, we re-create persistent ones. existing = self.subItems self.subItems = {} for name, item in existing.iteritems(): item.Close() if item.flags & axscript.SCRIPTITEM_ISPERSISTENT: self.AddNamedItem(item.name, item.flags) def GetCurrentSafetyOptions(self): return self.safetyOptions def ProcessNewNamedItemsConnections(self): # Process all sub-items. for item in self.subItems.itervalues(): if not item.createdConnections: # Fast-track! item.CreateConnections() def RegisterNewNamedItems(self): # Register all sub-items. for item in self.subItems.itervalues(): if not item.isRegistered: # Fast-track! self.RegisterNamedItem(item) def RegisterNamedItem(self, item): item.Register() def CheckConnectedOrDisconnected(self): if self.scriptState in [axscript.SCRIPTSTATE_CONNECTED, axscript.SCRIPTSTATE_DISCONNECTED]: return RaiseAssert(winerror.E_UNEXPECTED, "Not connected or disconnected - %d" % self.scriptState) def Connect(self): self.ProcessNewNamedItemsConnections() self.RegisterNewNamedItems() self.ConnectEventHandlers() def Run(self): # trace("AXScript running...") if self.scriptState != axscript.SCRIPTSTATE_INITIALIZED and self.scriptState != axscript.SCRIPTSTATE_STARTED: raise Exception(scode=winerror.E_UNEXPECTED) # self._DumpNamedItems_() self.ExecutePendingScripts() self.DoRun() def Stop(self): # Stop all executing scripts, and disconnect. if self.scriptState == axscript.SCRIPTSTATE_CONNECTED: self.Disconnect() # Reset back to initialized. self.Reset() def Disconnect(self): self.CheckConnectedOrDisconnected() try: self.DisconnectEventHandlers() except pythoncom.com_error: # Ignore errors when disconnecting. pass self.ChangeScriptState(axscript.SCRIPTSTATE_DISCONNECTED) def ConnectEventHandlers(self): # trace ("Connecting to event handlers") for item in self.subItems.itervalues(): item.Connect() self.ChangeScriptState(axscript.SCRIPTSTATE_CONNECTED); def DisconnectEventHandlers(self): # trace ("Disconnecting from event handlers") for item in self.subItems.itervalues(): item.Disconnect() def Reset(self): # Keeping persistent engine state, reset back an initialized state self.ResetNamedItems() self.ChangeScriptState(axscript.SCRIPTSTATE_INITIALIZED) def ChangeScriptState(self, state): #print " ChangeScriptState with %s - currentstate = %s" % (state_map.get(state),state_map.get(self.scriptState)) self.DisableInterrupts() try: self.scriptState = state try: if self.scriptSite: self.scriptSite.OnStateChange(state) except pythoncom.com_error, (hr, desc, exc, arg): pass # Ignore all errors here - E_NOTIMPL likely from scriptlets. finally: self.EnableInterrupts() # This stack frame is debugged - therefore we do as little as possible in it. def _ApplyInScriptedSection(self, fn, args): if self.debugManager: self.debugManager.OnEnterScript() if self.debugManager.adb.appDebugger: return self.debugManager.adb.runcall(fn, *args) else: return fn(*args) else: return fn(*args) def ApplyInScriptedSection(self, codeBlock, fn, args): self.BeginScriptedSection() try: try: # print "ApplyInSS", codeBlock, fn, args return self._ApplyInScriptedSection(fn, args) finally: if self.debugManager: self.debugManager.OnLeaveScript() self.EndScriptedSection() except: self.HandleException(codeBlock) # This stack frame is debugged - therefore we do as little as possible in it. def _CompileInScriptedSection(self, code, name, type): if self.debugManager: self.debugManager.OnEnterScript() return compile(code, name, type) def CompileInScriptedSection(self, codeBlock, type, realCode = None): if codeBlock.codeObject is not None: # already compiled return 1 if realCode is None: code = codeBlock.codeText else: code = realCode name = codeBlock.GetFileName() self.BeginScriptedSection() try: try: codeObject = self._CompileInScriptedSection(RemoveCR(code), name, type) codeBlock.codeObject = codeObject return 1 finally: if self.debugManager: self.debugManager.OnLeaveScript() self.EndScriptedSection() except: self.HandleException(codeBlock) # This stack frame is debugged - therefore we do as little as possible in it. def _ExecInScriptedSection(self, codeObject, globals, locals = None): if self.debugManager: self.debugManager.OnEnterScript() if self.debugManager.adb.appDebugger: return self.debugManager.adb.run(codeObject, globals, locals) else: exec codeObject in globals, locals else: exec codeObject in globals, locals def ExecInScriptedSection(self, codeBlock, globals, locals = None): if locals is None: locals = globals assert not codeBlock.beenExecuted, "This code block should not have been executed" codeBlock.beenExecuted = 1 self.BeginScriptedSection() try: try: self._ExecInScriptedSection(codeBlock.codeObject, globals, locals) finally: if self.debugManager: self.debugManager.OnLeaveScript() self.EndScriptedSection() except: self.HandleException(codeBlock) def _EvalInScriptedSection(self, codeBlock, globals, locals = None): if self.debugManager: self.debugManager.OnEnterScript() if self.debugManager.adb.appDebugger: return self.debugManager.adb.runeval(codeBlock, globals, locals) else: return eval(codeBlock, globals, locals) else: return eval(codeBlock, globals, locals) def EvalInScriptedSection(self, codeBlock, globals, locals = None): if locals is None: locals = globals assert not codeBlock.beenExecuted, "This code block should not have been executed" codeBlock.beenExecuted = 1 self.BeginScriptedSection() try: try: return self._EvalInScriptedSection(codeBlock.codeObject, globals, locals) finally: if self.debugManager: self.debugManager.OnLeaveScript() self.EndScriptedSection() except: self.HandleException(codeBlock) def HandleException(self, codeBlock): # NOTE - Never returns - raises a ComException exc_type, exc_value, exc_traceback = sys.exc_info() # If a SERVER exception, re-raise it. If a client side COM error, it is # likely to have originated from the script code itself, and therefore # needs to be reported like any other exception. if IsCOMServerException(exc_type): # Ensure the traceback doesnt cause a cycle. exc_traceback = None raise # It could be an error by another script. if issubclass(pythoncom.com_error, exc_type) and exc_value[0]==axscript.SCRIPT_E_REPORTED: # Ensure the traceback doesnt cause a cycle. exc_traceback = None raise Exception(scode=exc_value[0]) exception = error.AXScriptException(self, \ codeBlock, exc_type, exc_value, exc_traceback) # Ensure the traceback doesnt cause a cycle. exc_traceback = None result_exception = error.ProcessAXScriptException(self.scriptSite, self.debugManager, exception) if result_exception is not None: try: self.scriptSite.OnScriptTerminate(None, result_exception) except pythoncom.com_error: pass # Ignore errors telling engine we stopped. # reset ourselves to 'connected' so further events continue to fire. self.SetScriptState(axscript.SCRIPTSTATE_CONNECTED) raise result_exception # I think that in some cases this should just return - but the code # that could return None above is disabled, so it never happens. RaiseAssert(winerror.E_UNEXPECTED, "Don't have an exception to raise to the caller!") def BeginScriptedSection(self): if self.scriptSite is None: raise Exception(scode=winerror.E_UNEXPECTED) self.scriptSite.OnEnterScript() def EndScriptedSection(self): if self.scriptSite is None: raise Exception(scode=winerror.E_UNEXPECTED) self.scriptSite.OnLeaveScript() def DisableInterrupts(self): pass def EnableInterrupts(self): pass def GetNamedItem(self, name): try: return self.subItems[name] except KeyError: raise Exception(scode=winerror.E_INVALIDARG) def GetNamedItemClass(self): return ScriptItem def _AddScriptCodeBlock(self, codeBlock): self.scriptCodeBlocks[codeBlock.GetFileName()] = codeBlock if self.debugManager: self.debugManager.AddScriptBlock(codeBlock) if __name__=='__main__': print "This is a framework class - please use pyscript.py etc" def dumptypeinfo(typeinfo): return attr = typeinfo.GetTypeAttr() # Loop over all methods print "Methods" for j in xrange(attr[6]): fdesc = list(typeinfo.GetFuncDesc(j)) id = fdesc[0] try: names = typeinfo.GetNames(id) except pythoncom.ole_error: names = None doc = typeinfo.GetDocumentation(id) print " ", names, "has attr", fdesc # Loop over all variables (ie, properties) print "Variables" for j in xrange(attr[7]): fdesc = list(typeinfo.GetVarDesc(j)) names = typeinfo.GetNames(id) print " ", names, "has attr", fdesc
aczapi/PingPong
game.hpp
#pragma once #include <SFML/Audio.hpp> #include <SFML/Graphics.hpp> #include <memory> #include "background.hpp" #include "ball.hpp" #include "entity.hpp" #include "gameStates.hpp" #include "headers.hpp" #include "leftPaddle.hpp" #include "rightPaddle.hpp" class Game : public State { public: void initialize(sf::RenderWindow* window); void update(sf::RenderWindow* window); void render(sf::RenderWindow* window); void destroy(sf::RenderWindow* window); private: std::shared_ptr<Background> background_; std::shared_ptr<Ball> ball_; std::shared_ptr<LeftPaddle> leftPaddle_; std::shared_ptr<RightPaddle> rightPaddle_; std::shared_ptr<Paddle> paddle_; std::shared_ptr<Score> scorePlayer1_; std::shared_ptr<Score> scorePlayer2_; sf::Font* font_; sf::Font* scoreFont_; sf::Text* pausedText_; sf::Font* pausedFont_; sf::Text* startDigits_; sf::Text* control_; sf::Clock startTimer_; sf::Time startElapsed_; bool paused_, enterKey_; };
ElianeBriand/ensmallen
include/ensmallen_bits/fw/atoms.hpp
<gh_stars>1-10 /** * @file atoms.hpp * @author <NAME> * * * ensmallen is free software; you may redistribute it and/or modify it under * the terms of the 3-clause BSD license. You should have received a copy of * the 3-clause BSD license along with ensmallen. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef ENSMALLEN_FW_ATOMS_HPP #define ENSMALLEN_FW_ATOMS_HPP #include "proximal/proximal.hpp" #include "func_sq.hpp" namespace ens { /** * Class to hold the information and operations of current atoms in the * soluton space. This is not fully templatized, and may cost some extra * operations for the conversion. */ class Atoms { public: Atoms(){ /* Nothing to do. */ } /** * Add atom into the solution space. * * @param v new atom to be added. * @param c coefficient of the new atom. */ void AddAtom(const arma::mat& v, FuncSq& function, const double c = 0) { if (currentAtoms.is_empty()) { CurrentAtoms() = v; CurrentCoeffs().set_size(1); CurrentCoeffs().fill(c); atomSqTerm.set_size(1); atomSqTerm(0) = std::pow(norm(function.MatrixA() * v, 2), 2); } else { currentAtoms.insert_cols(0, v); arma::vec cVec(1); cVec(0) = c; currentCoeffs.insert_rows(0, cVec); double tmp = std::pow(norm(function.MatrixA() * v, 2), 2); arma::vec tmpVec(1); tmpVec(0) = tmp; atomSqTerm.insert_rows(0, tmpVec); } } //! Recover the solution coordinate from the coefficients of current atoms. void RecoverVector(arma::mat& x) { x = currentAtoms * currentCoeffs; } /** * Prune the support, delete previous atoms if they don't contribute much. * See Algorithm 2 of paper: * @code * @article{RaoShaWri:2015Forward--backward, * Author = {<NAME> and <NAME> and <NAME>}, * Journal = {IEEE Transactions on Signal Processing}, * Number = {21}, * Pages = {5798--5811}, * Publisher = {IEEE}, * Title = {Forward--backward greedy algorithms for atomic norm regularization}, * Volume = {63}, * Year = {2015} * } * @endcode * * @param F thresholding number. * @param function function to be optimized. */ void PruneSupport(const double F, FuncSq& function) { arma::vec sqTerm = 0.5 * atomSqTerm % square(currentCoeffs); while (currentAtoms.n_cols > 1) { // Solve for current gradient. arma::mat x; RecoverVector(x); arma::mat gradient(arma::size(x)); function.Gradient(x, gradient); // Find possible atom to be deleted. arma::vec gap = sqTerm - currentCoeffs % trans(gradient.t() * currentAtoms); arma::uword ind; gap.min(ind); // Try deleting the atom. arma::mat newAtoms(currentAtoms.n_rows, currentAtoms.n_cols - 1); if (ind > 0) newAtoms.cols(0, ind - 1) = currentAtoms.cols(0, ind - 1); if (ind < (currentAtoms.n_cols - 1)) { newAtoms.cols(ind, newAtoms.n_cols - 1) = currentAtoms.cols(ind + 1, currentAtoms.n_cols - 1); } // Reoptimize the coefficients, we brute-forcely reoptimize in the span, // which would be used in UpdateSpan class. Alternatively, if you want to // add an atom norm constraint, you could use projected gradient method, // see the implementaton of ProjectedGradientEnhancement(). arma::vec newCoeffs = solve(function.MatrixA() * newAtoms, function.Vectorb(), arma::solve_opts::fast); // Evaluate the function again. double Fnew = function.Evaluate(newAtoms * newCoeffs); if (Fnew > F) // Should not delete the atom. break; else { // Delete the atom from current atoms. currentAtoms = newAtoms; currentCoeffs = newCoeffs; atomSqTerm.shed_row(ind); sqTerm.shed_row(ind); } // else } // while } /** * Enhance the solution in the convex hull of current atoms with atom norm * constraint tau. Used in UpdateFullCorrection class for update step. * * Minimize the function in the atom domain defined by current atoms, * where the solution still need to have atom norm (defined by current atoms) * less than or equal to tau. We use projected gradient method to solve it, * see the "Enhancement step" of the following paper: * @code * @article{RaoShaWri:2015Forward--backward, * Author = {<NAME> and <NAME> and <NAME>}, * Journal = {IEEE Transactions on Signal Processing}, * Number = {21}, * Pages = {5798--5811}, * Publisher = {IEEE}, * Title = {Forward--backward greedy algorithms for atomic norm regularization}, * Volume = {63}, * Year = {2015} * } * @endcode * * @param function function to be minimized. * @param tau atom norm constraint. * @param stepSize step size for projected gradient method. * @param maxIteration maximum iteration number. * @param tolerance tolerance for projected gradient method. */ void ProjectedGradientEnhancement(FuncSq& function, double tau, double stepSize, size_t maxIteration = 100, double tolerance = 1e-3) { arma::mat x; RecoverVector(x); double value = function.Evaluate(x); for (size_t iter = 1; iter<maxIteration; iter++) { // Update currentCoeffs with gradient descent method. arma::mat g; function.Gradient(x, g); g = currentAtoms.t() * g; currentCoeffs = currentCoeffs - stepSize * g; // Projection of currentCoeffs to satisfy the atom norm constraint. Proximal::ProjectToL1Ball(currentCoeffs, tau); RecoverVector(x); double valueNew = function.Evaluate(x); if ((value - valueNew) < tolerance) break; value = valueNew; } } //! Get the current atom coefficients. const arma::vec& CurrentCoeffs() const { return currentCoeffs; } //! Modify the current atom coefficients. arma::vec& CurrentCoeffs() { return currentCoeffs; } //! Get the current atoms. const arma::mat& CurrentAtoms() const { return currentAtoms; } //! Modify the current atoms. arma::mat& CurrentAtoms() { return currentAtoms; } private: //! Coefficients of current atoms. arma::vec currentCoeffs; //! Current atoms in the solution space. arma::mat currentAtoms; //! Atom square term: ||A * atom||^2, used in PruneSupport(). It is computed //! when an atom is added. arma::vec atomSqTerm; }; // class Atoms } // namespace ens #endif
panda-factory/showmaker
src/render/layer/clip_path_layer.h
// // Created by guozhenxiong on 2021-11-04. // #ifndef SHOWMAKER_CLIP_PATH_LAYER_H #define SHOWMAKER_CLIP_PATH_LAYER_H #include "render/layer/container_layer.h" #include "render/painting/canvas_path.h" #include "render/painting/clip.h" namespace sm { class ClipPathLayer : public ContainerLayer { public: void SetClipPath(const Path& path); ClipPathLayer(const Path& clip_path, const Clip& clip_behavior = Clip::ANTI_ALIAS); private: Path clip_path_; Clip clip_behavior_; }; } // namespace sm #endif //SHOWMAKER_CLIP_PATH_LAYER_H
danghica/mokapot
mokapot/src/main/java/xyz/acygn/mokapot/MigrationActionsMessage.java
package xyz.acygn.mokapot; import java.time.Duration; import xyz.acygn.mokapot.util.AutocloseableLockWrapper; /** * A distributed message that returns a set of migration actions for an object. * This should typically be sent to the system which currently stores the * object's data (otherwise, the message is likely to simply be forwarded on to * the system were the object's data is stored). * * @author <NAME> * @param <T> The actual type of the object for which migration actions are * being returned. */ class MigrationActionsMessage<T> extends SynchronousMessage<MigrationActions<T>> implements SynchronousMessage.BorrowOnly { /** * The object for which we're getting the migration actions. Because the * object is highly likely to already exist on the target system, there's no * real performance cost to using a long reference here (as opposed to a * reference value or object location), as this won't cause a new object to * be created on the target system. Meanwhile, using the general * serialisation mechanism rather than a custom, cut-down version will * handle garbage collection properties appropriately (by ensuring that the * object isn't deallocated until after the migration actions are created); * the BorrowOnly marker interface makes it clear that we aren't going to * hang onto the provided reference indefinitely (we only use it to find the * location manager, which must already exist). * <p> * The most efficient way to initially create this field is probably via use * of <code>RemoteOnlyStandin</code>. */ private final T getActionsFor; /** * Creates a migration actions message that gets actions for the given * object. The object in question can be an actual real object, or (more * likely, as this message is unlikely to be constructed on the same machine * as the object itself) a standin that's acting as a long reference to it. * * @param getActionsFor The object for which to get actions. This must * either be a <code>T</code> (actual class, not just declared class) or a * <code>Standin&lt;T&gt;</code>. */ MigrationActionsMessage(T getActionsFor) { this.getActionsFor = getActionsFor; } /** * Creates a migration actions message that gets actions for the object * managed by a given location manager. This is a shorthand for creating a * <code>RemoteOnlyStandin</code> and using it as a long reference to the * object (as, despite being simple, it is sufficiently powerful for the * recipient machine to be able to identify the object in question). * * @param lm The location manager of the object for which to get actions. */ @SuppressWarnings("unchecked") MigrationActionsMessage(LocationManager<T> lm) { /* Note: this is an utter abuse of type erasure, and relies on the fact that although a RemoteOnlyStandin<T> is not a T, it will turn into a T after being sent over the network, and Java will let us store an object of the wrong type in getActionsFor meanwhile. */ this((T) new RemoteOnlyStandin<T>(lm)); } @Override protected MigrationActions<T> calculateReply() { LocationManager<T> lm; try { lm = getCommunicator() .findLocationManagerForObject(getActionsFor); } catch (AutocloseableLockWrapper.CannotLockException ex) { /* It shouldn't be possible for this to fail; the object should be being held alive on the remote system, and it's obviously alive here, thus the location manager must already exist and thus we can't be past the point at which they can be created. */ throw new RuntimeException(ex); } return new MigrationActions<>(lm); } @Override public Duration periodic() { return null; } }
cquoss/jboss-4.2.3.GA-jdk8
testsuite/src/main/org/jboss/test/util/ServiceControllerUtil.java
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.util; import javax.management.MBeanServerConnection; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectName; import org.jboss.system.ServiceContext; import org.jboss.system.ServiceControllerMBean; /** * Utility class that can deal with the ServiceController to * start/stop/create/destroy a service * @author <a href="mailto:<EMAIL>"><NAME></a> * @version $Revision$ * @since Aug 23, 2006 */ public class ServiceControllerUtil { private ServiceControllerMBean scmb = null; public ServiceControllerUtil(MBeanServerConnection server) { ObjectName so = ServiceControllerMBean.OBJECT_NAME; scmb = (ServiceControllerMBean) MBeanServerInvocationHandler.newProxyInstance(server, so, ServiceControllerMBean.class, false); } public void createAService(ObjectName serviceOName) throws Exception { scmb.create(serviceOName); } public void startAService(ObjectName serviceName) throws Exception { scmb.start(serviceName); } public void stopAService(ObjectName serviceName) throws Exception { scmb.stop(serviceName); } public void destroyAService(ObjectName serviceName) throws Exception { scmb.destroy(serviceName); } public boolean isStarted(ObjectName serviceName) { ServiceContext sc = scmb.getServiceContext(serviceName); return sc.state == ServiceContext.RUNNING; } public boolean isCreated(ObjectName serviceName) { ServiceContext sc = scmb.getServiceContext(serviceName); return sc.state == ServiceContext.CREATED; } public boolean isStopped(ObjectName serviceName) { ServiceContext sc = scmb.getServiceContext(serviceName); return sc.state == ServiceContext.STOPPED; } public boolean isDestroyed(ObjectName serviceName) { ServiceContext sc = scmb.getServiceContext(serviceName); return sc.state == ServiceContext.DESTROYED; } public boolean isFailed(ObjectName serviceName) { ServiceContext sc = scmb.getServiceContext(serviceName); return sc.state == ServiceContext.FAILED; } }
tardeaux/SnapTools
app/src/pack/java/com/ljmu/andre/snaptools/ModulePack/MiscChanges.java
package com.ljmu.andre.snaptools.ModulePack; import android.content.ClipboardManager; import android.content.ComponentName; import android.content.Context; import android.content.pm.ComponentInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.Typeface; import android.text.InputFilter; import android.text.InputType; import android.view.ActionMode; import android.view.Menu; import android.view.MenuItem; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import com.ljmu.andre.snaptools.Dialogs.Content.TextInputBasic; import com.ljmu.andre.snaptools.Dialogs.DialogFactory; import com.ljmu.andre.snaptools.Dialogs.ThemedDialog; import com.ljmu.andre.snaptools.Dialogs.ThemedDialog.ThemedClickWrapper; import com.ljmu.andre.snaptools.Fragments.FragmentHelper; import com.ljmu.andre.snaptools.ModulePack.Fragments.KotlinViews.ColorPickerDialogExtension; import com.ljmu.andre.snaptools.ModulePack.Fragments.KotlinViews.FontPickerDialogExtension; import com.ljmu.andre.snaptools.ModulePack.Fragments.MiscChangesFragment; import com.ljmu.andre.snaptools.Utils.ContextHelper; import com.ljmu.andre.snaptools.Utils.ResourceMapper; import com.ljmu.andre.snaptools.Utils.ResourceUtils; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import timber.log.Timber; import static com.ljmu.andre.GsonPreferences.Preferences.getCreateDir; import static com.ljmu.andre.GsonPreferences.Preferences.getPref; import static com.ljmu.andre.GsonPreferences.Preferences.putPref; import static com.ljmu.andre.snaptools.ModulePack.HookDefinitions.HookClassDef.SNAPCHAT_CAPTION_VIEW_CLASS; import static com.ljmu.andre.snaptools.ModulePack.HookDefinitions.HookDef.CAPTION_CREATE_HOOK; import static com.ljmu.andre.snaptools.ModulePack.HookDefinitions.HookDef.FONT_HOOK; import static com.ljmu.andre.snaptools.ModulePack.HookDefinitions.HookVariableDef.SNAPCAPTIONVIEW_CONTEXT; import static com.ljmu.andre.snaptools.ModulePack.Utils.ModulePreferenceDef.COPY_BUTTON; import static com.ljmu.andre.snaptools.ModulePack.Utils.ModulePreferenceDef.CURRENT_FONT; import static com.ljmu.andre.snaptools.ModulePack.Utils.ModulePreferenceDef.CUT_BUTTON; import static com.ljmu.andre.snaptools.ModulePack.Utils.ModulePreferenceDef.FONTS_PATH; import static com.ljmu.andre.snaptools.ModulePack.Utils.ModulePreferenceDef.FORCE_MULTILINE; import static com.ljmu.andre.snaptools.ModulePack.Utils.ModulePreferenceDef.PASTE_BUTTON; /*import com.flask.colorpicker.ColorPickerView.WHEEL_TYPE; import com.flask.colorpicker.OnColorChangedListener; import com.flask.colorpicker.OnColorSelectedListener; import com.flask.colorpicker.builder.ColorPickerClickListener; import com.flask.colorpicker.builder.ColorPickerDialogBuilder;*/ /** * This class was created by <NAME> (SID: 701439) * It and its contents are free to use by all */ public class MiscChanges extends ModuleHelper { public static boolean isInternalFontCall; public MiscChanges(String name, boolean canBeDisabled) { super(name, canBeDisabled); } public static Typeface createTypefaceSafe(File fontFile) { isInternalFontCall = true; return Typeface.createFromFile(fontFile); } @Override public FragmentHelper[] getUIFragments() { return new FragmentHelper[]{new MiscChangesFragment()}; } public static boolean isComponentEnabled(PackageManager pm, String pkgName, String clsName) { ComponentName componentName = new ComponentName(pkgName, clsName); int componentEnabledSetting = pm.getComponentEnabledSetting(componentName); switch (componentEnabledSetting) { case PackageManager.COMPONENT_ENABLED_STATE_DISABLED: return false; case PackageManager.COMPONENT_ENABLED_STATE_ENABLED: return true; case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT: default: // We need to get the application info to get the component's default state try { PackageInfo packageInfo = pm.getPackageInfo(pkgName, PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS | PackageManager.GET_DISABLED_COMPONENTS); List<ComponentInfo> components = new ArrayList<>(); if (packageInfo.activities != null) Collections.addAll(components, packageInfo.activities); if (packageInfo.services != null) Collections.addAll(components, packageInfo.services); if (packageInfo.providers != null) Collections.addAll(components, packageInfo.providers); for (ComponentInfo componentInfo : components) { if (componentInfo.name.equals(clsName)) { return componentInfo.isEnabled(); } } // the component is not declared in the AndroidManifest return false; } catch (PackageManager.NameNotFoundException e) { // the package isn't installed on the device return false; } } } @Override public void loadHooks(ClassLoader snapClassLoader, Context snapContext) { String currentFontFile = getPref(CURRENT_FONT); if (!currentFontFile.equals("Default")) { hookMethod( FONT_HOOK, new HookWrapper((HookBefore) param -> { if (isInternalFontCall) { isInternalFontCall = false; return; } String fontFilename = (String) param.args[0]; File fontDir = getCreateDir(FONTS_PATH); File replacementFontFile = new File(fontDir, currentFontFile); if (replacementFontFile.exists()) { fontFilename = replacementFontFile.getAbsolutePath(); Timber.d("[FONT] Font handled by hook"); } param.args[0] = fontFilename; }) ); } hookMethod( CAPTION_CREATE_HOOK, new HookWrapper((HookBefore) param -> { Timber.d("Attempting to load custom menu"); /** * =========================================================================== * Recreate Snapchat's context menu * =========================================================================== */ ActionMode actionMode = (ActionMode) param.args[0]; Menu menu = (Menu) param.args[1]; menu.clear(); actionMode.getMenuInflater().inflate(ResourceMapper.getResId(ContextHelper.getActivity(), "caption_context_menu", "menu"), menu); EditText captionEditText = getObjectField(SNAPCAPTIONVIEW_CONTEXT, param.thisObject); int paste = ResourceUtils.getId(ContextHelper.getActivity(), "menu_item_paste"); int cut = ResourceUtils.getId(ContextHelper.getActivity(), "menu_item_cut"); int copy = ResourceUtils.getId(ContextHelper.getActivity(), "menu_item_copy"); if (getPref(COPY_BUTTON)) { menu.findItem(copy).setVisible(true); } if (getPref(CUT_BUTTON)) { menu.findItem(cut).setVisible(true); } //TODO: check if something is on the clipboard ClipboardManager clipboardManager = (ClipboardManager) ContextHelper.getActivity().getSystemService(Context.CLIPBOARD_SERVICE); if (getPref(PASTE_BUTTON)) { if (clipboardManager != null) { if (!clipboardManager.hasPrimaryClip()) { menu.findItem(paste).setVisible(false); } else { menu.findItem(paste).setVisible(true); } } else { menu.findItem(paste).setVisible(true); } } int bold = ResourceUtils.getId(ContextHelper.getActivity(), "menu_item_bold"); int italic = ResourceUtils.getId(ContextHelper.getActivity(), "menu_item_italic"); int underline = ResourceUtils.getId(ContextHelper.getActivity(), "menu_item_underline"); menu.findItem(bold).setVisible(true); menu.findItem(italic).setVisible(true); menu.findItem(underline).setVisible(true); // =========================================================================== /** * =========================================================================== * Add a BG Color Picker * =========================================================================== */ MenuItem bgColor = menu.add("BG Color"); bgColor.setOnMenuItemClickListener(item -> { Timber.d("Changing BG color"); new ThemedDialog(ContextHelper.getActivity()) .setTitle("Color Picker") .setExtension( new ColorPickerDialogExtension( ContextHelper.getActivity(), "primary", captionEditText::setBackgroundColor ) ).show(); return true; }); bgColor.setVisible(true); // =========================================================================== /** * =========================================================================== * Add a Font Picker * =========================================================================== */ MenuItem font = menu.add("Font"); font.setOnMenuItemClickListener(item -> { new ThemedDialog(ContextHelper.getActivity()) .setTitle("Choose Font") .setExtension( new FontPickerDialogExtension( ContextHelper.getActivity(), MiscChangesFragment.getInstalledFonts(), s -> { Timber.d("Selected font: " + s); putPref(CURRENT_FONT, s); captionEditText.setTypeface(MiscChangesFragment.getTypefaceSafe(s)); } ) ).show(); return true; }); font.setVisible(true); // =========================================================================== /** * =========================================================================== * Add a Size Picker * =========================================================================== */ MenuItem size = menu.add("Size"); size.setOnMenuItemClickListener(item -> { DialogFactory.createBasicTextInputDialog( ContextHelper.getActivity(), "Font Size", "What size should the text be set to?", null, null, InputType.TYPE_CLASS_NUMBER, new ThemedClickWrapper(themedDialog -> { String input = themedDialog.<TextInputBasic>getExtension() .getInputMessage(); try { Float f = Float.parseFloat(input); captionEditText.setTextSize(f); themedDialog.dismiss(); return; } catch (Exception ignored) { } themedDialog.dismiss(); })).show(); return true; }); size.setVisible(true); // =========================================================================== param.setResult(true); }) ); hookAllConstructors( SNAPCHAT_CAPTION_VIEW_CLASS, new HookWrapper((HookAfter) param -> { EditText text = (EditText) param.thisObject; if (getPref(FORCE_MULTILINE)) { text.setSingleLine(false); text.setMaxLines(500); text.setImeOptions(EditorInfo.IME_ACTION_NONE); text.setFilters(new InputFilter[0]); text.setOnLongClickListener(v -> { text.showContextMenu(); return false; }); } }) ); } }
chs6558/chs6558.github.io
node_modules/styled-icons/crypto/Btx/Btx.esm.js
export * from '@styled-icons/crypto/Btx';
codekoala/glujs
spec/Providers/extjs/validationSpec.js
<gh_stars>1-10 describe('validation specs', function () { describe('given a text field with a boolean validation function', function () { var vm, view, itemId; function standUp(initialStatus) { itemId = Ext.id(); testNs = { viewmodels:{ validationTest:{ status:initialStatus, statusIsValid:{ on:['statusChanged'], formula:function () { return this.get('status') == 'GOOD' || this.get('status') == 'BAD' } } } }, views:{ validationTest:{ items:[ { xtype:'textfield', id:itemId, name:'status', invalidText:'WRONG' } ] } } }; vm = glu.model({ ns:'testNs', mtype:'validationTest' }); view = glu.view(vm, 'testNs', 'validationTest'); } ; xdescribe('and the isValid property starts off as true (invalid)', function () { beforeEach(function () { standUp('WEIRD'); }); it('the button should begin disabled', function () { expect(Ext.getCmp(itemId).disabled).toEqual(true); }); describe('when the guard property becomes true', function () { beforeEach(function () { vm.set('status', true); }); it('The button should become enabled', function () { expect(Ext.getCmp(itemId).disabled).toEqual(false); }); }) }); describe('and the isValid property starts off as true (valid)', function () { beforeEach(function () { standUp('GOOD'); }); it('the field should begin valid', function () { expect(Ext.getCmp(itemId).activeError).toEqual(null); }); describe('when the valid property becomes false', function () { beforeEach(function () { vm.set('status', 'WEIRD'); }); it('The field should become invalid', function () { expect(Ext.getCmp(itemId).activeError).toContain('WRONG'); }); describe('then when it goes back again to valid', function () { beforeEach(function () { vm.set('status', 'BAD'); }); it('The field should become valid', function () { expect(Ext.getCmp(itemId).activeError).toEqual(null); }); }) }) }); }); });
ngageoint/mapcache-electron
src/lib/source/zip/ZipSource.js
<filename>src/lib/source/zip/ZipSource.js import Source from '../Source' import AdmZip from 'adm-zip' import ShapeFileSource from '../shapefile/ShapeFileSource' import KMZSource from '../kml/KMZSource' import XYZFileSource from '../xyz/XYZFileSource' import isNil from 'lodash/isNil' export default class ZipSource extends Source { async retrieveLayers (statusCallback) { statusCallback('Determining zip file contents', 0) await this.sleep(250) let shapeFileSource let kmzSource let xyzFileSource let layers = [] const zip = new AdmZip(this.filePath) const zipEntries = zip.getEntries() const zipFileNames = zipEntries.map(zipEntry => zipEntry.entryName) const shapeFile = zipFileNames.find(file => file.endsWith('.shp')) const kmlFile = zipFileNames.find(file => file.endsWith('.kml')) const xyzImageFile = zipFileNames.find(file => file.match('.*\\d\\/\\d\\/\\d.png') !== null) if (!isNil(kmlFile)) { try { kmzSource = new KMZSource(this.id, this.directory, this.filePath) layers = await kmzSource.retrieveLayers(statusCallback) // eslint-disable-next-line no-unused-vars } catch (e) { // eslint-disable-next-line no-console console.error('Failed to retrieve shape file layer.') } } else if (!isNil(shapeFile)) { try { shapeFileSource = new ShapeFileSource(this.id, this.directory, this.filePath) layers = await shapeFileSource.retrieveLayers(statusCallback) // eslint-disable-next-line no-unused-vars } catch (e) { // eslint-disable-next-line no-console console.error('Failed to retrieve shape file layer.') } } else if (!isNil(xyzImageFile)) { xyzFileSource = new XYZFileSource(this.id, this.directory, this.filePath) layers = await xyzFileSource.retrieveLayers(statusCallback) } return layers } }
cameroncooke/XcodeHeaders
Frameworks/IDEKit/IDENavigableItemPredicateFilter.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import <IDEKit/_IDENavigableItemPredicateFilter.h> @interface IDENavigableItemPredicateFilter : _IDENavigableItemPredicateFilter { } - (id)initWithPredicate:(id)arg1; @end
sun-996/safty
src/utils/index.js
import Vue from 'vue' import store from '@/store' /** * Parse the time to string * @param {(Object|string|number)} time * @param {string} cFormat * @returns {string | null} */ export function parseTime(time, cFormat) { if (arguments.length === 0) { return null } const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}' let date if (typeof time === 'object') { date = time } else { if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) { time = parseInt(time) } if ((typeof time === 'number') && (time.toString().length === 10)) { time = time * 1000 } date = new Date(time) } const formatObj = { y: date.getFullYear(), m: date.getMonth() + 1, d: date.getDate(), h: date.getHours(), i: date.getMinutes(), s: date.getSeconds(), a: date.getDay() } const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => { const value = formatObj[key] // Note: getDay() returns 0 on Sunday if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] } return value.toString().padStart(2, '0') }) return time_str } /** * @param {number} time * @param {string} option * @returns {string} */ export function formatTime(time, option) { if (('' + time).length === 10) { time = parseInt(time) * 1000 } else { time = +time } const d = new Date(time) const now = Date.now() const diff = (now - d) / 1000 if (diff < 30) { return '刚刚' } else if (diff < 3600) { // less 1 hour return Math.ceil(diff / 60) + '分钟前' } else if (diff < 3600 * 24) { return Math.ceil(diff / 3600) + '小时前' } else if (diff < 3600 * 24 * 2) { return '1天前' } if (option) { return parseTime(time, option) } else { return ( d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分' ) } } /** * @param {string} url * @returns {Object} */ export function param2Obj(url) { const search = url.split('?')[1] if (!search) { return {} } return JSON.parse( '{"' + decodeURIComponent(search) .replace(/"/g, '\\"') .replace(/&/g, '","') .replace(/=/g, '":"') .replace(/\+/g, ' ') + '"}' ) } /** * @param {Function} func * @param {number} wait * @param {boolean} immediate * @return {*} */ // 防抖 export function debounce(func, wait, immediate) { let timeout, args, context, timestamp, result const later = function() { // 据上一次触发时间间隔 const last = +new Date() - timestamp // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait if (last < wait && last > 0) { timeout = setTimeout(later, wait - last) } else { timeout = null // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用 if (!immediate) { result = func.apply(context, args) if (!timeout) context = args = null } } } return function(...args) { context = this timestamp = +new Date() const callNow = immediate && !timeout // 如果延时不存在,重新设定延时 if (!timeout) timeout = setTimeout(later, wait) if (callNow) { result = func.apply(context, args) context = args = null } return result } } /** * @param {Array} arr * @returns {Array} */ // 数组去重 export function uniqueArr(arr) { return Array.from(new Set(arr)) } /** * @param {Object} obj * @returns {Object} */ // 深拷贝方法 export function depClone(obj) { return JSON.parse(JSON.stringify(obj)) } // 模糊搜索(表格) dataArray搜索数据 search搜索的关键字 flag搜索的字段 export function fuzzySearch(dataArray, search, flag) { if (search) { return dataArray.filter(data => { return String(data[flag]).toLowerCase().includes(search.toLowerCase()) }) } return dataArray } // 文件下载方法 import { fileDownload } from '@/api/fileManagement/myFile' export function downloadClick(fileId, fileName) { console.log('下载的文件编号为:' + fileId) if (!fileId || fileId === 0) { return } fileDownload(fileId).then(res => { const url = window.URL.createObjectURL(new Blob([res.data])) const link = document.createElement('a') link.style.display = 'none' link.href = url link.setAttribute('download', fileName) document.body.appendChild(link) link.click() document.body.removeChild(link) // 下载完成移除元素 window.URL.revokeObjectURL(url) // 释放掉blob对象 }).catch(() => {}) } // 文件预览方法 export function filePreview(file) { const url = process.env.VUE_APP_BASE_API + file.url // const url = 'http://172.16.17.32:8084' + file.url window.open('http://47.99.113.105:8012/onlinePreview?url=' + encodeURIComponent(url)) console.log(url) // console.log('http://172.16.17.32:8012/onlinePreview?url=' + encodeURIComponent(url)) } // 照片预览方法 /** * @param {that} vue组件实例this * @param {Array} picList[图片数组] * @param {Object} option[配置] dialog是弹窗显示状态 list是图片列表 */ export function picsPreview(that, picList, options) { console.log(Vue) const option = Object.assign({}, { dailog: 'sunViewPics', list: 'sunPicList' }, options) picList = picList.map(item => { return { ...item, url: process.env.VUE_APP_BASE_API + item.url } }) that[option.dailog] = true that[option.list] = picList } // 通过 module和id 返回分类中文 export function transformClassify(module, id) { try { return store.getters.classify_options[module][id]['label'] } catch (e) { return '未知' } } // 通过 数组、module、id 返回改造数组 // 0是分类模块名 1是id的键名 2自定义的名字 // 会改变原数组 /** * @param {string} arr * @param {Array} transformArray[二维数组] 0是分类模块名 1是id的键名 2自定义的名字 * @returns {Array} */ export function zhClassify(arr, transformArray) { return arr.map((item) => { transformArray.forEach((transform) => { if (transform[2]) { item[transform[2]] = transformClassify(transform[0], item[transform[1]]) } else { item['zh-' + transform[1]] = transformClassify(transform[0], item[transform[1]]) } }) return item }) } // 处理弹框关闭清空表单 /** * @param {that} vue组件实例this * @param {String} formName[表单名称] * @param {Object} option[配置] upload是上传组件的ref值 btnLoading是表单提交按钮的loading */ export function dialogClosed(that, formName, options) { const option = Object.assign({}, { upload: 'UPLOAD', btnLoading: 'btnLoading' }, options) const temp = formName + 'Dialog' that[temp] = false that.$refs[formName].resetFields() for (const key in that.$refs) { // 判断是否包含上传组件的ref值 if (key.includes(option.upload)) { that.$refs[key].$refs.upload.abort() } } if (that[option.btnLoading]) { that[option.btnLoading] = false } } // 处理重置清空表单 /** * @param {that} vue组件实例this * @param {String} formName[表单名称] * @param {Object} option[配置] upload是上传组件的ref值 btnLoading是表单提交按钮的loading */ export function resetForm(that, formName, options) { const option = Object.assign({}, { upload: 'UPLOAD', btnLoading: 'btnLoading' }, options) that.$refs[formName].resetFields() for (const key in that.$refs) { // 判断是否包含上传组件的ref值 if (key.includes(option.upload)) { that.$refs[key].$refs.upload.abort() } } if (that[option.btnLoading]) { that[option.btnLoading] = false } }
ForFunPenguin/Mekanism
src/api/java/mekanism/api/SerializerHelper.java
<gh_stars>0 package mekanism.api; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import com.mojang.brigadier.exceptions.CommandSyntaxException; import javax.annotation.Nonnull; import mekanism.api.gas.Gas; import mekanism.api.gas.GasStack; import mekanism.api.infuse.InfuseType; import mekanism.api.infuse.InfusionStack; import net.minecraft.fluid.Fluid; import net.minecraft.fluid.Fluids; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.ShapedRecipe; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.JsonToNBT; import net.minecraft.util.JSONUtils; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.registries.ForgeRegistries; public class SerializerHelper { private static Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); public static ItemStack getItemStack(@Nonnull JsonObject json, @Nonnull String key) { if (!json.has(key)) { throw new JsonSyntaxException("Missing '" + key + "', expected to find an object"); } if (!json.get(key).isJsonObject()) { throw new JsonSyntaxException("Expected '" + key + "' to be an object"); } return ShapedRecipe.deserializeItem(JSONUtils.getJsonObject(json, key)); } public static GasStack getGasStack(@Nonnull JsonObject json, @Nonnull String key) { if (!json.has(key)) { throw new JsonSyntaxException("Missing '" + key + "', expected to find an object"); } if (!json.get(key).isJsonObject()) { throw new JsonSyntaxException("Expected '" + key + "' to be an object"); } return deserializeGas(JSONUtils.getJsonObject(json, key)); } public static FluidStack getFluidStack(@Nonnull JsonObject json, @Nonnull String key) { if (!json.has(key)) { throw new JsonSyntaxException("Missing '" + key + "', expected to find an object"); } if (!json.get(key).isJsonObject()) { throw new JsonSyntaxException("Expected '" + key + "' to be an object"); } return deserializeFluid(JSONUtils.getJsonObject(json, key)); } public static InfusionStack getInfusionStack(@Nonnull JsonObject json, @Nonnull String key) { if (!json.has(key)) { throw new JsonSyntaxException("Missing '" + key + "', expected to find an object"); } if (!json.get(key).isJsonObject()) { throw new JsonSyntaxException("Expected '" + key + "' to be an object"); } return deserializeInfuseType(JSONUtils.getJsonObject(json, key)); } public static GasStack deserializeGas(@Nonnull JsonObject json) { if (!json.has("amount")) { throw new JsonSyntaxException("Expected to receive a amount that is greater than zero"); } JsonElement count = json.get("amount"); if (!JSONUtils.isNumber(count)) { throw new JsonSyntaxException("Expected amount to be a number greater than zero."); } int amount = count.getAsJsonPrimitive().getAsInt(); if (amount < 1) { throw new JsonSyntaxException("Expected amount to be greater than zero."); } ResourceLocation resourceLocation = new ResourceLocation(JSONUtils.getString(json, "gas")); Gas gas = Gas.getFromRegistry(resourceLocation); if (gas.isEmptyType()) { throw new JsonSyntaxException("Invalid gas type '" + resourceLocation + "'"); } return new GasStack(gas, amount); } public static FluidStack deserializeFluid(@Nonnull JsonObject json) { if (!json.has("amount")) { throw new JsonSyntaxException("Expected to receive a amount that is greater than zero"); } JsonElement count = json.get("amount"); if (!JSONUtils.isNumber(count)) { throw new JsonSyntaxException("Expected amount to be a number greater than zero."); } int amount = count.getAsJsonPrimitive().getAsInt(); if (amount < 1) { throw new JsonSyntaxException("Expected amount to be greater than zero."); } ResourceLocation resourceLocation = new ResourceLocation(JSONUtils.getString(json, "fluid")); Fluid fluid = ForgeRegistries.FLUIDS.getValue(resourceLocation); if (fluid == null || fluid == Fluids.EMPTY) { throw new JsonSyntaxException("Invalid fluid type '" + resourceLocation + "'"); } CompoundNBT nbt = null; if (json.has("nbt")) { JsonElement jsonNBT = json.get("nbt"); try { if (jsonNBT.isJsonObject()) { nbt = JsonToNBT.getTagFromJson(GSON.toJson(jsonNBT)); } else { nbt = JsonToNBT.getTagFromJson(JSONUtils.getString(jsonNBT, "nbt")); } } catch (CommandSyntaxException e) { throw new JsonSyntaxException("Invalid NBT entry for fluid '" + resourceLocation + "'"); } } return new FluidStack(fluid, amount, nbt); } public static InfusionStack deserializeInfuseType(@Nonnull JsonObject json) { if (!json.has("amount")) { throw new JsonSyntaxException("Expected to receive a amount that is greater than zero"); } JsonElement count = json.get("amount"); if (!JSONUtils.isNumber(count)) { throw new JsonSyntaxException("Expected amount to be a number greater than zero."); } int amount = count.getAsJsonPrimitive().getAsInt(); if (amount < 1) { throw new JsonSyntaxException("Expected amount to be greater than zero."); } ResourceLocation resourceLocation = new ResourceLocation(JSONUtils.getString(json, "infuse_type")); InfuseType infuseType = InfuseType.getFromRegistry(resourceLocation); if (infuseType.isEmptyType()) { throw new JsonSyntaxException("Invalid infusion type '" + resourceLocation + "'"); } return new InfusionStack(infuseType, amount); } public static JsonElement serializeItemStack(@Nonnull ItemStack stack) { JsonObject json = new JsonObject(); json.addProperty("item", stack.getItem().getRegistryName().toString()); if (stack.getCount() > 1) { json.addProperty("count", stack.getCount()); } if (stack.hasTag()) { json.addProperty("nbt", stack.getTag().toString()); } return json; } public static JsonElement serializeGasStack(@Nonnull GasStack stack) { JsonObject json = new JsonObject(); json.addProperty("gas", stack.getType().getRegistryName().toString()); json.addProperty("amount", stack.getAmount()); return json; } public static JsonElement serializeFluidStack(@Nonnull FluidStack stack) { JsonObject json = new JsonObject(); json.addProperty("fluid", stack.getFluid().getRegistryName().toString()); json.addProperty("amount", stack.getAmount()); if (stack.hasTag()) { json.addProperty("nbt", stack.getTag().toString()); } return json; } public static JsonElement serializeInfusionStack(@Nonnull InfusionStack stack) { JsonObject json = new JsonObject(); json.addProperty("infuse_type", stack.getType().getRegistryName().toString()); json.addProperty("amount", stack.getAmount()); return json; } }
RMMJR/g3m
iOS/G3MiOSSDK/Commons/GEO/GEOSymbol.hpp
<filename>iOS/G3MiOSSDK/Commons/GEO/GEOSymbol.hpp // // GEOSymbol.hpp // G3MiOSSDK // // Created by <NAME> on 3/25/13. // // #ifndef __G3MiOSSDK__GEOSymbol__ #define __G3MiOSSDK__GEOSymbol__ #include <vector> class G3MRenderContext; class GEOSymbolizer; class MeshRenderer; class ShapesRenderer; class MarksRenderer; class GEOTileRasterizer; class GEOSymbol { public: virtual ~GEOSymbol() { } virtual bool symbolize(const G3MRenderContext* rc, const GEOSymbolizer* symbolizer, MeshRenderer* meshRenderer, ShapesRenderer* shapesRenderer, MarksRenderer* marksRenderer, GEOTileRasterizer* geoTileRasterizer) const = 0 ; }; #endif
terminux/jdk1.7.0_80
src/com/sun/corba/se/impl/util/PackagePrefixChecker.java
/* * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.corba.se.impl.util; import java.io.File; /** * PackagePrefixChecker provides static utility methods for getting package prefixes. * @author <NAME> */ public final class PackagePrefixChecker { private static final String PACKAGE_PREFIX = "org.omg.stub."; public static String packagePrefix(){ return PACKAGE_PREFIX;} public static String correctPackageName (String p){ if (p==null) return p; if ( hasOffendingPrefix(p)) { return PACKAGE_PREFIX+p; } return p; } public static boolean isOffendingPackage(String p){ return !(p==null) && ( false || hasOffendingPrefix(p) ); } public static boolean hasOffendingPrefix(String p){ return ( p.startsWith("java.") || p.equals("java") // || p.startsWith("com.sun.") || p.equals("com.sun") || p.startsWith("net.jini.") || p.equals("net.jini") || p.startsWith("jini.") || p.equals("jini") || p.startsWith("javax.") || p.equals("javax") ); } public static boolean hasBeenPrefixed(String p){ return p.startsWith(packagePrefix()); } public static String withoutPackagePrefix(String p){ if(hasBeenPrefixed(p)) return p.substring(packagePrefix().length()); else return p; } }
Vujovic/ihyht
src/components/contactCard.js
import React from 'react' import styled from 'styled-components' import ContactQR from './contactQR' import ContactIcon from './svg/contact' import PhoneIcon from './svg/phone' export default () => ( <ContactCard> <h2>联系方式</h2> <p className="contact email"> <ContactIcon /> <EMAIL> </p> <p className="contact phone"> <PhoneIcon /> +86 010 6477 6380 </p> <ContactQR /> </ContactCard> ) const ContactCard = styled.div` animation: 1s slideUp; background-color: #2e83e6; color: #fff; padding: 20px 30px; transform: translateX(100px); .contact { display: flex; align-items: center; justify-content: flex-start; margin-top: 45px; svg { fill: #fff; margin-right: 15px; width: 25px; } } .phone { svg { margin-left: 3px; width: 19px; } } @media screen and (max-width: 1280px) { animation: none; transform: none; } @media screen and (max-width: 768px) { text-align: center; width: 100%; p { display: inline-block; margin: 0 auto; } } @keyframes slideUp { 0% { transform: translate(100px, 50px); } 100% { transform: translate(100px, 0); } } `
jkloth/pyxml
test/dom/html/test_a.py
from util import testAttribute from util import testIntAttribute def test(): print 'testing source code syntax' from xml.dom.html import HTMLAnchorElement from xml.dom import implementation doc = implementation.createHTMLDocument('Title') a = doc.createElement('A') print 'testing get/set' testAttribute(a,'accessKey') testAttribute(a,'charset') testAttribute(a,'coords') testAttribute(a,'href') testAttribute(a,'hreflang') testAttribute(a,'rel') testAttribute(a,'rev') testIntAttribute(a,'tabIndex') testAttribute(a,'target') testAttribute(a,'type') a._set_shape('rect') rt = a._get_shape() if rt != 'Rect': error('get/set shape failed') print 'get/set works' if __name__ == '__main__': test()
tie/Valkyrien-Skies
src/main/java/org/valkyrienskies/mod/common/util/jackson/minecraft/ChunkPosSerialization.java
package org.valkyrienskies.mod.common.util.jackson.minecraft; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import net.minecraft.util.math.ChunkPos; import java.io.IOException; public class ChunkPosSerialization { public static class Deserializer extends StdDeserializer<ChunkPos> { public Deserializer() { this(null); } public Deserializer(Class<ChunkPos> vc) { super(vc); } @Override public ChunkPos deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); long chunkPos = node.get("chunkPos").longValue(); return new ChunkPos(getChunkX(chunkPos), getChunkZ(chunkPos)); } } public static class Serializer extends StdSerializer<ChunkPos> { public Serializer() { this(null); } public Serializer(Class<ChunkPos> vc) { super(vc); } @Override public void serialize(ChunkPos value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeStartObject();; gen.writeNumberField("chunkPos", ChunkPos.asLong(value.x, value.z)); gen.writeEndObject(); } } // Helper functions, not meant to be exposed outside of ChunkPosSerialization private static int getChunkX(long chunkPos) { return (int) (chunkPos & 4294967295L); } private static int getChunkZ(long chunkPos) { return (int) ((chunkPos >> 32) & 4294967295L); } }
nguyenduythuan/mock-project-reactjs
app/containers/GlobalLoading/actions.js
import * as type from './constants'; export function showLoading() { return { type: type.SHOW_LOADING, }; } export function hideLoading() { return { type: type.HIDE_LOADING, }; }
giranath/atelier
lib/gpu/opengl45/private/opengl45_gpu_device.cpp
<gh_stars>0 #include "opengl45_gpu_device.hpp" #include "opengl45_gpu_pipeline_state.hpp" #include "opengl45_gpu_buffer.hpp" #include "opengl45_gpu_texture.hpp" #include "opengl45_helpers.hpp" #include <cassert> namespace at { // TODO: Check if glad needs to be loaded inside this library // Needs to test on windows with a DLL build std::unique_ptr<gpu_buffer> opengl45_gpu_device::make_buffer(const gpu_buffer_description& description) { return opengl45_gpu_buffer::make_from_description(description); } void opengl45_gpu_device::bind_vertex_buffer(gpu_buffer& buffer, std::size_t offset) { opengl45_gpu_buffer& opengl_buffer = static_cast<opengl45_gpu_buffer&>(buffer); if(last_bound_pipeline_state_) { last_bound_pipeline_state_->bind_vertex_buffer(opengl_buffer.handle(), static_cast<GLintptr>(offset)); } } void opengl45_gpu_device::bind_index_buffer(gpu_buffer& buffer) { opengl45_gpu_buffer& opengl_buffer = static_cast<opengl45_gpu_buffer&>(buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, opengl_buffer.handle()); } std::unique_ptr<gpu_pipeline_state> opengl45_gpu_device::make_pipeline_state(const gpu_pipeline_state_description& description) { return opengl45_gpu_pipeline_state::make_from_description(description); } void opengl45_gpu_device::bind_pipeline_state(gpu_pipeline_state& state) { opengl45_gpu_pipeline_state& opengl_state = static_cast<opengl45_gpu_pipeline_state&>(state); opengl_state.bind(); last_bound_pipeline_state_ = &opengl_state; } std::unique_ptr<gpu_texture> opengl45_gpu_device::make_texture2d(const gpu_texture2d_description& description) { return opengl45_gpu_texture::make_from_description(description); } void opengl45_gpu_device::bind_texture(gpu_texture& texture, int binding) { opengl45_gpu_texture& opengl_texture = static_cast<opengl45_gpu_texture&>(texture); glActiveTexture(GL_TEXTURE0 + binding); glBindTexture(GL_TEXTURE_2D, opengl_texture.handle()); } void opengl45_gpu_device::clear_render_target(float r, float g, float b) { glClearColor(r, g, b, 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void opengl45_gpu_device::draw(const gpu_draw_description& description) { if(description.is_indexed) { const GLsizei index_type_size = gl_index_type_size(description.index_type); glDrawElements(gl_draw_topology(description.topology), description.count, gl_index_type(description.index_type), reinterpret_cast<GLvoid*>(index_type_size * description.offset)); } else { glDrawArrays(gl_draw_topology(description.topology), description.offset, description.count); } } }
idealeak/goserver
core/builtin/filter/connectionthrottle.go
<filename>core/builtin/filter/connectionthrottle.go<gh_stars>10-100 package filter import ( "net" "time" "github.com/idealeak/goserver/core/container" "github.com/idealeak/goserver/core/netlib" ) var ( DefaultAllowedInterval = 500 //ms ConnectionThrottleFilterName = "session-filter-connectionthrottle" ) type ConnectionThrottleFilter struct { clients *container.SynchronizedMap //need synchronize AllowedInterval int //ms } func (ctf *ConnectionThrottleFilter) GetName() string { return ConnectionThrottleFilterName } func (ctf *ConnectionThrottleFilter) GetInterestOps() uint { return 1 << netlib.InterestOps_Opened } func (ctf *ConnectionThrottleFilter) OnSessionOpened(s *netlib.Session) bool { if !ctf.isConnectionOk(s) { s.Close() return false } return true } func (ctf *ConnectionThrottleFilter) OnSessionClosed(s *netlib.Session) bool { return true } func (ctf *ConnectionThrottleFilter) OnSessionIdle(s *netlib.Session) bool { return true } func (ctf *ConnectionThrottleFilter) OnPacketReceived(s *netlib.Session, packetid int, logicNo uint32, packet interface{}) bool { return true } func (ctf *ConnectionThrottleFilter) OnPacketSent(s *netlib.Session, packetid int, logicNo uint32, data []byte) bool { return true } func (ctf *ConnectionThrottleFilter) isConnectionOk(s *netlib.Session) bool { host, _, err := net.SplitHostPort(s.RemoteAddr()) if err != nil { return false } tNow := time.Now() value := ctf.clients.Get(host) if value != nil { tLast := value.(time.Time) if tNow.Sub(tLast) < time.Duration(ctf.AllowedInterval)*time.Millisecond { ctf.clients.Set(host, tNow) return false } } ctf.clients.Set(host, tNow) return true } func init() { netlib.RegisteSessionFilterCreator(ConnectionThrottleFilterName, func() netlib.SessionFilter { return &ConnectionThrottleFilter{clients: container.NewSynchronizedMap(), AllowedInterval: DefaultAllowedInterval} }) }
vishalbelsare/chronos
org.chronos.chronodb/src/main/java/org/chronos/chronodb/internal/impl/query/parser/ast/DoubleWhereElement.java
<reponame>vishalbelsare/chronos package org.chronos.chronodb.internal.impl.query.parser.ast; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.query.NumberCondition; import org.chronos.chronodb.internal.api.query.searchspec.DoubleSearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; public class DoubleWhereElement extends WhereElement<Double, NumberCondition> { private final double equalityTolerance; public DoubleWhereElement(final String indexName, final NumberCondition condition, final double comparisonValue, final double equalityTolerance) { super(indexName, condition, comparisonValue); checkArgument(equalityTolerance >= 0, "Precondition violation - argument 'equalityTolerance' must not be negative!"); this.equalityTolerance = equalityTolerance; } public double getEqualityTolerance() { return this.equalityTolerance; } @Override public DoubleWhereElement negate() { return new DoubleWhereElement(this.getIndexName(), this.getCondition().negate(), this.getComparisonValue(), this.getEqualityTolerance()); } @Override public SearchSpecification<?> toSearchSpecification() { return DoubleSearchSpecification.create(this.getIndexName(), this.getCondition(), this.getComparisonValue(), this.getEqualityTolerance()); } }
wx930910/commons-jelly
jelly-tags/jaxme/src/main/java/org/apache/commons/jelly/tags/jaxme/MarshallTag.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.jelly.tags.jaxme; import java.io.File; import java.io.IOException; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.apache.commons.jelly.TagSupport; import org.apache.commons.jelly.XMLOutput; import org.apache.commons.jelly.MissingAttributeException; import org.apache.commons.jelly.JellyTagException; import org.xml.sax.SAXException; /** * <p>Marshalls a generated object generated by a JAXB implementation into xml.</p> * <p> * The result is placed into the processed content for further processing by enclosing * tags.</p> * * @author <a href="mailto:<EMAIL>"><NAME></a> * @author <a href="mailto:dev at commons.apache.org">Apache Commons Development Team</a> * @version $Revision$ */ public class MarshallTag extends TagSupport { private String packages; private Object object; public String getPackages() { return packages; } /** * Defines the generated objects which will be marshalled by specifying the package name. */ public void setPackages(String packages) { this.packages = packages; } public Object getObject() { return object; } /** * Defines the object to be unmarshalled into xml by specifying a jelly variable name. */ public void setObject(Object object) { this.object = object; } public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException { if (packages == null) { throw new MissingAttributeException( "packages" ); } if (object == null) { throw new MissingAttributeException( "object" ); } try { JAXBContext jaxbContext = JAXBContext.newInstance(packages); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.marshal(object, output); } catch (JAXBException ex) { throw new JellyTagException(ex); } } }
navin09/layerJS
test/e2e/slidelayout/fade_spec.js
var utilities = require('../helpers/utilities.js'); describe('fade', function() { utilities.resizeWindow(800, 600); describe('fade frame', function() { /* frame1(default-frame) fades out as frame2 fades in */ it('frame1 fades out as frame2 fades in', function() { browser.get('slidelayout/fade.html').then(function() { var f1 = element(by.id('frame1')); var f2 = element(by.id('frame2')); // frame1_display_before == block expect(f1.getCssValue('display')).toBe('block'); // frame2_display_before == none expect(f2.getCssValue('display')).toBe('none'); protractor.promise.all([utilities.setStyle('frame2', { width: '500px', height: '500px' }), utilities.setStyle('stage', { width: '500px', height: '500px' })]).then(function() { utilities.setAttributes('frame2', { 'lj-transition': 'fade' }).then(function() { utilities.wait(100); // time for the style changes to take effect utilities.listenDimensionsBeforeTransition('layer', 'frame1'); utilities.listenDimensionsBeforeTransition('layer', 'frame2'); utilities.transitionTo('layer', 'frame2', {duration: '0.3s'}).then(function() { protractor.promise.all([ utilities.getBoundingClientRect('stage'), utilities.getBoundingClientRect('frame1'), utilities.getBoundingClientRect('frame2'), utilities.getFromStore('frame1'), utilities.getFromStore('frame2') ]).then(function(data) { var stage_dimensions = data[0]; var frame1_dimensions_after = data[1]; var frame2_dimensions_after = data[2]; var frame1_dimensions_before = data[3]; var frame2_dimensions_before = data[4]; // frame1_display_after == none f1 = element(by.id('frame1')); expect(f1.getCssValue('display')).toBe('none'); // frame2_display_after == block expect(f2.getCssValue('display')).toBe('block'); // opacity expect(frame1_dimensions_before.opacity).toBe('1'); expect(frame2_dimensions_before.opacity).toBe('0'); expect(frame2_dimensions_after.opacity).toBe('1'); // expect(frame1_dimensions_after.opacity).toBe('0'); //result: Expected '1' to be '0'.- this is not fulfilled because of resetting opacity // z-index (shouldn't change by the transition) // expect(frame1_dimensions_before['z-index']).toBe('1'); // current code doesn't enforce z-index on current frame expect(frame2_dimensions_before['z-index']).toBe('-1'); expect(frame2_dimensions_after['z-index']).toBe('auto'); expect(frame1_dimensions_after['z-index']).toBe('auto'); // positioning and dimensions of frame1 and frame 2 expect(frame1_dimensions_after.width).toBe(stage_dimensions.width); expect(frame2_dimensions_after.width).toBe(stage_dimensions.width); expect(frame1_dimensions_after.height).toBe(stage_dimensions.height); expect(frame2_dimensions_after.height).toBe(stage_dimensions.height); delete frame1_dimensions_before.opacity; delete frame2_dimensions_before.opacity; delete frame1_dimensions_after.opacity; delete frame2_dimensions_after.opacity; delete frame1_dimensions_before['z-index']; delete frame1_dimensions_after['z-index']; delete frame2_dimensions_before['z-index']; delete frame2_dimensions_after['z-index']; expect(frame1_dimensions_before).toEqual(frame2_dimensions_before); expect(frame2_dimensions_before).toEqual(frame1_dimensions_after); expect(frame1_dimensions_before).toEqual(frame2_dimensions_after); }); }); }); }); }); }); }); });
foundations/onedev
server-core/src/main/java/io/onedev/server/model/support/pullrequest/changedata/PullRequestAssigneeRemoveData.java
<reponame>foundations/onedev<gh_stars>1-10 package io.onedev.server.model.support.pullrequest.changedata; import javax.annotation.Nullable; import io.onedev.server.OneDev; import io.onedev.server.entitymanager.UserManager; import io.onedev.server.model.User; public class PullRequestAssigneeRemoveData extends PullRequestChangeData { private static final long serialVersionUID = 1L; private final Long assigneeId; public PullRequestAssigneeRemoveData(User assignee) { this.assigneeId = assignee.getId(); } @Override public String getActivity() { User user = getUser(); if (user != null) return "removed assignee \"" + user.getDisplayName() + "\""; else return "removed assignee unknown"; } @Nullable public User getUser() { return OneDev.getInstance(UserManager.class).get(assigneeId); } }
silenc3502/MYSQL-Arch-Doc-Summary
mysql-server/plugin/x/src/session.cc
/* * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2.0, * as published by the Free Software Foundation. * * This program is also distributed with certain software (including * but not limited to OpenSSL) that is licensed under separate terms, * as designated in a particular file or component or in included license * documentation. The authors of MySQL hereby grant you an additional * permission to link the program and your derivative works with the * separately licensed software that they have included with MySQL. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License, version 2.0, for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "plugin/x/src/session.h" #include <stddef.h> #include <sys/types.h> #include <set> #include <string> #include "include/my_sys.h" #include "plugin/x/src/document_id_aggregator.h" #include "plugin/x/src/interface/authentication.h" #include "plugin/x/src/interface/client.h" #include "plugin/x/src/interface/protocol_encoder.h" #include "plugin/x/src/interface/protocol_monitor.h" #include "plugin/x/src/interface/server.h" #include "plugin/x/src/ngs/log.h" #include "plugin/x/src/ngs/protocol/protocol_protobuf.h" #include "plugin/x/src/ngs/scheduler.h" #include "plugin/x/src/notices.h" #include "plugin/x/src/sql_data_context.h" #include "plugin/x/src/xpl_dispatcher.h" #include "plugin/x/src/xpl_error.h" #include "plugin/x/src/xpl_log.h" // #undef ERROR // Needed to avoid conflict with ERROR in mysqlx.pb.h // #include "plugin/x/src/ngs/protocol/protocol_protobuf.h" namespace xpl { // Code below this line is executed from the network thread // ---------------------------------------------------------------------------- Session::Session(iface::Client *client, iface::Protocol_encoder *proto, const Session_id session_id) : m_client(client), // don't hold a real reference to the parent to avoid // circular reference m_encoder(proto), m_auth_handler(), m_state(State::k_authenticating), m_state_before_close(State::k_authenticating), m_id(session_id), m_thread_pending(0), m_thread_active(0), m_notice_output_queue(proto, &m_notice_configuration), m_was_authenticated(false), m_document_id_aggregator(&client->server().get_document_id_generator()) { log_debug("%s.%i: New session allocated by client", client->client_id(), session_id); #ifndef WIN32 mdbg_my_thread = pthread_self(); #endif } Session::~Session() { log_debug("%s: Delete session", m_client->client_id()); #ifndef WIN32 assert(mdbg_my_thread == pthread_self()); #endif m_sql.deinit(); DBUG_LOG("debug", "~Session(m_was_authenticated:" << m_was_authenticated << ", m_failed_auth_count: " << static_cast<int>(m_failed_auth_count) << ", m_state_before_close: " << static_cast<int>(state_before_close())); if (m_was_authenticated) --Global_status_variables::instance().m_sessions_count; if (m_failed_auth_count > 0 && !m_was_authenticated) ++Global_status_variables::instance().m_rejected_sessions_count; if (state_before_close() != iface::Session::State::k_authenticating) { ++Global_status_variables::instance().m_closed_sessions_count; } } void Session::on_close(const Session::Close_flags flags) { if (m_state != State::k_closing) { if (flags & Close_flags::k_update_old_state) m_state_before_close = m_state; m_state = State::k_closing; if (flags & Close_flags::k_force_close_client) m_client->on_session_close(this); } } void Session::set_proto(iface::Protocol_encoder *encoder) { m_encoder = encoder; m_notice_output_queue.set_encoder(encoder); } // Code below this line is executed from the worker thread // ---------------------------------------------------------------------------- // Return value means true if message was handled, false if not. // If message is handled, ownership of the object is passed on (and should be // deleted by the callee) bool Session::handle_message(const ngs::Message_request &command) { if (m_state == State::k_authenticating) { return handle_auth_message(command); } else if (m_state == State::k_ready) { // handle session commands return handle_ready_message(command); } // msg not handled return false; } void Session::stop_auth() { m_auth_handler.reset(); // request termination m_client->on_session_close(this); } bool Session::handle_auth_message(const ngs::Message_request &command) { iface::Authentication::Response r; int8_t type = command.get_message_type(); if (type == Mysqlx::ClientMessages::SESS_AUTHENTICATE_START && m_auth_handler.get() == nullptr) { const Mysqlx::Session::AuthenticateStart &authm = static_cast<const Mysqlx::Session::AuthenticateStart &>( *command.get_message()); log_debug("%s.%u: Login attempt: mechanism=%s auth_data=%s", m_client->client_id(), m_id, authm.mech_name().c_str(), authm.auth_data().c_str()); m_auth_handler = m_client->server().get_authentications().get_auth_handler( authm.mech_name(), this); if (!m_auth_handler.get()) { log_debug("%s.%u: Invalid authentication method %s", m_client->client_id(), m_id, authm.mech_name().c_str()); m_encoder->send_error(ngs::Fatal(ER_NOT_SUPPORTED_AUTH_MODE, "Invalid authentication method %s", authm.mech_name().c_str()), true); stop_auth(); return true; } else { r = m_auth_handler->handle_start(authm.mech_name(), authm.auth_data(), authm.initial_response()); } } else if (type == Mysqlx::ClientMessages::SESS_AUTHENTICATE_CONTINUE && m_auth_handler.get()) { const Mysqlx::Session::AuthenticateContinue &authm = static_cast<const Mysqlx::Session::AuthenticateContinue &>( *command.get_message()); r = m_auth_handler->handle_continue(authm.auth_data()); } else { m_encoder->get_protocol_monitor().on_error_unknown_msg_type(); log_debug( "%s: Unexpected message of type %i received during authentication", m_client->client_id(), type); m_encoder->send_error(ngs::Fatal(ER_X_BAD_MESSAGE, "Invalid message"), true); stop_auth(); return false; } switch (r.status) { case iface::Authentication::Status::k_succeeded: on_auth_success(r); break; case iface::Authentication::Status::k_failed: on_auth_failure(r); break; default: m_encoder->send_auth_continue(r.data); } return true; } void Session::on_auth_success(const iface::Authentication::Response &response) { proto().send_notice_client_id(m_client->client_id_num()); log_debug("%s.%u: Login succeeded", m_client->client_id(), m_id); m_auth_handler.reset(); m_state = State::k_ready; m_client->on_session_auth_success(this); m_encoder->send_auth_ok(response.data); // send it last, so that // on_auth_success() can send session // specific notices m_failed_auth_count = 0; ++Global_status_variables::instance().m_accepted_sessions_count; ++Global_status_variables::instance().m_sessions_count; m_was_authenticated = true; } void Session::on_auth_failure_impl( const iface::Authentication::Response &response) { log_debug("%s.%u: Unsuccessful authentication attempt", m_client->client_id(), m_id); m_failed_auth_count++; ngs::Error_code error_send_back_to_user = get_authentication_access_denied_error(); if (can_forward_error_code_to_client(response.error_code)) { error_send_back_to_user = ngs::Error(response.error_code, "%s", response.data.c_str()); } error_send_back_to_user.severity = can_authenticate_again() ? ngs::Error_code::ERROR : ngs::Error_code::FATAL; m_encoder->send_error(error_send_back_to_user, true); // It is possible to use different auth methods therefore we should not // stop authentication in such case. if (!can_authenticate_again()) { log_info(ER_XPLUGIN_MAX_AUTH_ATTEMPTS_REACHED, m_client->client_id(), m_id); stop_auth(); } m_auth_handler.reset(); } void Session::on_auth_failure(const iface::Authentication::Response &response) { if (response.error_code == ER_MUST_CHANGE_PASSWORD && !m_sql.password_expired()) { iface::Authentication::Response r{response.status, response.error_code, "Password for " MYSQLXSYS_ACCOUNT " account has been expired"}; on_auth_failure_impl(r); } else { on_auth_failure_impl(response); } } ngs::Error_code Session::get_authentication_access_denied_error() const { const auto authentication_info = m_auth_handler->get_authentication_info(); const char *is_using_password = authentication_info.m_was_using_password ? my_get_err_msg(ER_YES) : my_get_err_msg(ER_NO); std::string username = authentication_info.m_tried_account_name; std::string hostname = client().client_hostname_or_address(); auto result = ngs::SQLError(ER_ACCESS_DENIED_ERROR, username.c_str(), hostname.c_str(), is_using_password); if (can_authenticate_again()) log_debug("Try to authenticate again, got: %s", result.message.c_str()); return result; } bool Session::can_forward_error_code_to_client(const int error_code) { // Lets ignore ER_ACCESS_DENIED_ERROR it is used by the plugin to // return general authentication problem. It may have not too // accurate error message. static const std::set<int> allowed_error_codes{ ER_DBACCESS_DENIED_ERROR, ER_MUST_CHANGE_PASSWORD_LOGIN, ER_ACCOUNT_HAS_BEEN_LOCKED, ER_SECURE_TRANSPORT_REQUIRED, ER_SERVER_OFFLINE_MODE, ER_BAD_DB_ERROR, ER_AUDIT_API_ABORT}; return 0 < allowed_error_codes.count(error_code); } bool Session::can_authenticate_again() const { return m_failed_auth_count < k_max_auth_attempts; } // handle a message while in Ready state bool Session::handle_ready_message(const ngs::Message_request &command) { // check if the session got killed if (m_sql.is_killed()) { m_encoder->send_result(ngs::Error_code(ER_QUERY_INTERRUPTED, "Query execution was interrupted", "70100", ngs::Error_code::FATAL)); // close as fatal_error instead of killed. killed is for when the client // is idle on_close(); return true; } switch (command.get_message_type()) { case Mysqlx::ClientMessages::SESS_CLOSE: m_state = State::k_closing; m_client->on_session_reset(this); return true; case Mysqlx::ClientMessages::CON_CLOSE: m_encoder->send_ok("bye!"); on_close(Close_flags::k_force_close_client | Close_flags::k_update_old_state); return true; case Mysqlx::ClientMessages::SESS_RESET: { const auto &msg = static_cast<const Mysqlx::Session::Reset &>(*command.get_message()); if (msg.has_keep_open() && msg.keep_open()) { on_reset(); return true; } m_state = State::k_closing; m_client->on_session_reset(this); return true; } } try { const auto error = m_dispatcher.execute(command); switch (error.severity) { case ngs::Error_code::OK: return true; case ngs::Error_code::ERROR: return error.error != ER_UNKNOWN_COM_ERROR; case ngs::Error_code::FATAL: on_close(); return true; } } catch (ngs::Error_code &err) { m_encoder->send_result(err); on_close(); return true; } catch (std::exception &exc) { // not supposed to happen, but catch exceptions as a last defense.. log_error(ER_XPLUGIN_UNEXPECTED_EXCEPTION_DISPATCHING_CMD, m_client->client_id(), exc.what()); on_close(); return true; } return false; } ngs::Error_code Session::init() { const unsigned short port = m_client->client_port(); const Connection_type type = m_client->connection().get_type(); return m_sql.init(port, type); } void Session::on_kill() { DBUG_TRACE; if (!m_sql.is_killed()) { if (!m_sql.kill()) log_debug("%s: Could not interrupt client session", m_client->client_id()); } on_close(Close_flags::k_update_old_state); } void Session::on_reset() { ngs::Error_code error = m_sql.reset(); if (error) { m_encoder->send_result(error); return; } m_dispatcher.reset(); m_encoder->send_ok(); } void Session::mark_as_tls_session() { data_context().set_connection_type(Connection_tls); } /** Checks whether things owned by the given user are visible to this session. Returns true if we're SUPER or the same user as the given one. If user is NULL, then it's only visible for SUPER users. */ bool Session::can_see_user(const std::string &user) const { const std::string owner = m_sql.get_authenticated_user_name(); if (state() == iface::Session::State::k_ready && !owner.empty()) { if (m_sql.has_authenticated_user_a_super_priv() || (owner == user)) return true; } return false; } void Session::update_status(Common_status_variable variable) { ++(m_status_variables.*variable); ++(Global_status_variables::instance().*variable); } bool Session::get_prepared_statement_id(const uint32_t client_stmt_id, uint32_t *out_server_stmt_id) const { const auto &stmt_info = m_dispatcher.get_prepared_stmt_info(); const auto i = stmt_info.find(client_stmt_id); if (i == stmt_info.end()) return false; *out_server_stmt_id = i->second.m_server_stmt_id; return true; } } // namespace xpl
xkcoding/scaffold
scaffold-notification/src/main/java/com/xkcoding/scaffold/notification/model/dingtalk/Link.java
<reponame>xkcoding/scaffold<gh_stars>10-100 /* * Copyright 2019 Yangkai.Shen * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.xkcoding.scaffold.notification.model.dingtalk; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * <p> * link类型 * </p> * * @package: com.xkcoding.scaffold.notification.model.dingtalk * @description: link类型 * @author: yangkai.shen * @date: Created in 2019-03-18 14:06 * @copyright: Copyright (c) 2019 * @version: V1.0 * @modified: yangkai.shen */ @Data @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class Link extends BaseLink { /** * 消息内容。如果太长只会部分展示 */ private String text; /** * 点击消息跳转的URL */ private String messageUrl; /** * 图片URL */ private String picUrl; }
HelixOS/prebuilts-ndk
6/platforms/android-9/arch-x86/usr/include/linux/taskstats.h
/**************************************************************************** **************************************************************************** *** *** This header was automatically generated from a Linux kernel header *** of the same name, to make information necessary for userspace to *** call into the kernel available to libc. It contains only constants, *** structures, and macros generated from the original header, and thus, *** contains no copyrightable information. *** **************************************************************************** ****************************************************************************/ #ifndef _LINUX_TASKSTATS_H #define _LINUX_TASKSTATS_H #define TASKSTATS_VERSION 1 struct taskstats { __u16 version; __u16 padding[3]; __u64 cpu_count; __u64 cpu_delay_total; __u64 blkio_count; __u64 blkio_delay_total; __u64 swapin_count; __u64 swapin_delay_total; __u64 cpu_run_real_total; __u64 cpu_run_virtual_total; }; enum { TASKSTATS_CMD_UNSPEC = 0, TASKSTATS_CMD_GET, TASKSTATS_CMD_NEW, __TASKSTATS_CMD_MAX, }; #define TASKSTATS_CMD_MAX (__TASKSTATS_CMD_MAX - 1) enum { TASKSTATS_TYPE_UNSPEC = 0, TASKSTATS_TYPE_PID, TASKSTATS_TYPE_TGID, TASKSTATS_TYPE_STATS, TASKSTATS_TYPE_AGGR_PID, TASKSTATS_TYPE_AGGR_TGID, __TASKSTATS_TYPE_MAX, }; #define TASKSTATS_TYPE_MAX (__TASKSTATS_TYPE_MAX - 1) enum { TASKSTATS_CMD_ATTR_UNSPEC = 0, TASKSTATS_CMD_ATTR_PID, TASKSTATS_CMD_ATTR_TGID, TASKSTATS_CMD_ATTR_REGISTER_CPUMASK, TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK, __TASKSTATS_CMD_ATTR_MAX, }; #define TASKSTATS_CMD_ATTR_MAX (__TASKSTATS_CMD_ATTR_MAX - 1) #define TASKSTATS_GENL_NAME "TASKSTATS" #define TASKSTATS_GENL_VERSION 0x1 #endif
cyjake/material
icons/AccountGroupIcon.js
import React from 'react' const DEFAULT_SIZE = 24 export default ({ fill = 'currentColor', width = DEFAULT_SIZE, height = DEFAULT_SIZE, style = {}, ...props }) => ( <svg viewBox={ `0 0 ${ DEFAULT_SIZE } ${ DEFAULT_SIZE }` } style={{ fill, width, height, ...style }} { ...props } > <path d="M12,6C10.34,6 9,7.34 9,9C9,10.66 10.34,12 12,12C13.66,12 15,10.66 15,9C15,7.34 13.66,6 12,6M6,8.17C4.62,8.17 3.5,9.29 3.5,10.67C3.5,12.05 4.62,13.17 6,13.17C6.88,13.17 7.65,12.71 8.09,12.03C7.42,11.18 7,10.15 7,9C7,8.8 7,8.6 7.04,8.4C6.72,8.25 6.37,8.17 6,8.17M18,8.17C17.63,8.17 17.28,8.25 16.96,8.4C17,8.6 17,8.8 17,9C17,10.15 16.58,11.18 15.91,12.03C16.35,12.71 17.12,13.17 18,13.17C19.38,13.17 20.5,12.05 20.5,10.67C20.5,9.29 19.38,8.17 18,8.17M12,14C10,14 6,15 6,17V19H18V17C18,15 14,14 12,14M4.67,14.97C3,15.26 1,16.04 1,17.33V19H4V17C4,16.22 4.29,15.53 4.67,14.97M19.33,14.97C19.71,15.53 20,16.22 20,17V19H23V17.33C23,16.04 21,15.26 19.33,14.97Z" /> </svg> )
bobmcwhirter/drools
drools-eclipse/drools-eclipse-plugin/src/main/java/org/drools/eclipse/flow/ruleflow/view/property/ProcessNameSection.java
package org.drools.eclipse.flow.ruleflow.view.property; import org.drools.eclipse.flow.common.editor.core.ProcessWrapper; import org.drools.eclipse.flow.common.editor.editpart.ProcessEditPart; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.views.properties.tabbed.AbstractPropertySection; import org.eclipse.ui.views.properties.tabbed.ITabbedPropertyConstants; import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage; public class ProcessNameSection extends AbstractPropertySection implements ModifyListener { private Text nameText; private ProcessWrapper processWrapper; public void createControls(Composite parent, TabbedPropertySheetPage aTabbedPropertySheetPage) { super.createControls(parent, aTabbedPropertySheetPage); Composite composite = getWidgetFactory().createFlatFormComposite(parent); nameText = getWidgetFactory().createText(composite, ""); FormData data = new FormData(); data.left = new FormAttachment(0, STANDARD_LABEL_WIDTH); data.right = new FormAttachment(100, 0); data.top = new FormAttachment(0, ITabbedPropertyConstants.VSPACE); nameText.setLayoutData(data); nameText.addModifyListener(this); CLabel labelLabel = getWidgetFactory().createCLabel(composite, "Name:"); data = new FormData(); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(nameText, -ITabbedPropertyConstants.HSPACE); data.top = new FormAttachment(nameText, 0, SWT.CENTER); labelLabel.setLayoutData(data); } public void setInput(IWorkbenchPart part, ISelection selection) { super.setInput(part, selection); if (selection instanceof IStructuredSelection) { Object input = ((IStructuredSelection) selection).getFirstElement(); if (input instanceof ProcessEditPart) { input = ((ProcessEditPart) input).getModel(); } if (input instanceof ProcessWrapper) { this.processWrapper = (ProcessWrapper) input; } } } public void refresh() { if (processWrapper != null) { nameText.removeModifyListener(this); nameText.setText(processWrapper.getName()); nameText.addModifyListener(this); } } public void modifyText(ModifyEvent arg0) { if (processWrapper != null) { processWrapper.setName(nameText.getText()); } } }
5cs/spdk
module/event/subsystems/scheduler/scheduler.c
/*- * BSD LICENSE * * Copyright (c) Intel Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "spdk/stdinc.h" #include "spdk/env.h" #include "spdk/scheduler.h" #include "spdk_internal/event.h" #include "spdk_internal/init.h" static void scheduler_subsystem_init(void) { int rc = 0; /* Set the defaults */ if (spdk_scheduler_get() == NULL) { rc = spdk_scheduler_set("static"); } if (spdk_scheduler_get_period() == 0) { spdk_scheduler_set_period(SPDK_SEC_TO_USEC); } spdk_subsystem_init_next(rc); } static void scheduler_subsystem_fini(void) { spdk_scheduler_set_period(0); spdk_scheduler_set(NULL); spdk_subsystem_fini_next(); } static void scheduler_write_config_json(struct spdk_json_write_ctx *w) { struct spdk_scheduler *scheduler; uint64_t scheduler_period; assert(w != NULL); scheduler = spdk_scheduler_get(); if (scheduler == NULL) { SPDK_ERRLOG("Unable to get scheduler info\n"); return; } scheduler_period = spdk_scheduler_get_period(); spdk_json_write_array_begin(w); spdk_json_write_object_begin(w); spdk_json_write_named_string(w, "method", "framework_set_scheduler"); spdk_json_write_named_object_begin(w, "params"); spdk_json_write_named_string(w, "name", scheduler->name); if (scheduler_period != 0) { spdk_json_write_named_uint32(w, "period", scheduler_period); } spdk_json_write_object_end(w); spdk_json_write_object_end(w); spdk_json_write_array_end(w); } static struct spdk_subsystem g_spdk_subsystem_scheduler = { .name = "scheduler", .init = scheduler_subsystem_init, .fini = scheduler_subsystem_fini, .write_config_json = scheduler_write_config_json, }; SPDK_SUBSYSTEM_REGISTER(g_spdk_subsystem_scheduler);
Jakgn/gem5_test
build/ARM/python/m5/internal/Clock_vector.i_init.cc
#include "sim/init.hh" extern "C" { void init_Clock_vector(); } EmbeddedSwig embed_swig_Clock_vector(init_Clock_vector, "m5.internal._Clock_vector");
GV-KrishnaTeja/Node-JS
arr2.js
<reponame>GV-KrishnaTeja/Node-JS<filename>arr2.js //copywithin 1 const array1 = ['a', 'b', 'c', 'd', 'e']; console.log(array1.copyWithin(0, 3)); //copywithin2 const array2 = [1, 2, 3, 4, 5] console.log(array2.copyWithin(-2, -3, -1)); //entries1 const array3 = ['a', 'b', 'c']; const iterator1 = array3.entries(); console.log(iterator1.next().value); //entries2 const a = ['a', 'b', 'c']; for (const[index, element] of a.entries()) console.log(index, element); //every1 const isBelowThreshold = (currentValue) => currentValue < 40; const array4 = [1, 30, 39, 29, 10, 13]; console.log(array4.every(isBelowThreshold)); //every2 var sampleArray = [ 1, 2, 3, 4, 5 ]; var sampleArray2 = [ 0, -1, -30, 5]; function tester(number){ return number > 0; } console.log(sampleArray.every(tester));
jmittert/cpp-docs
docs/mfc/reference/codesnippet/CPP/cfiledialog-class_4.cpp
<reponame>jmittert/cpp-docs // Get the interface pointer IFileDialogCustomize * customDlgPtr = m_myFileDialogPtr->GetIFileDialogCustomize(); // Make sure that it is not null if ( customDlgPtr != NULL ) { // // Perform any interface functionality here // // Release the pointer customDlgPtr->Release(); }
PalgamingHD/Prehistoric
src/main/java/net/prehistoric/items/Fossil.java
package net.prehistoric.items; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.block.Block; import net.minecraft.block.Material; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.sound.BlockSoundGroup; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.TypedActionResult; import net.minecraft.world.World; import net.prehistoric.Prehistoric; public class Fossil extends Item { public Fossil(Settings settings) { super(settings); } }
Rich2/openstrat
Tiling/Exs/testSrc/gOne/OneScen2Test.scala
<reponame>Rich2/openstrat /* Copyright 2018-21 <NAME>. Licensed under Apache Licence version 2.0. */ package ostrat; package gOne import utest._ object OneScen2Test extends TestSuite { val g = OneScen2.grid val tests = Tests { "test1" - { g.bottomCenRow ==> 2 g.topCenRow ==> 10 g.leftCenCol ==> 4 g.rightCenCol ==> 8 g.numRow0s ==> 2 g.bottomRem2Row ==> 2 g.topRem2Row ==> 10 g.numRow2s ==> 3 g.numTileRows ==> 5 g.row2sStart ==> 6 g.row0sStart ==> 4 // g. cRowStart(2) ==> 2 // g.cRowLen(2) ==> 3 // g.cRowEnd(2) ==> 10 // g.cRowLen(4) ==> 2 // g.cRowLen(6) ==> 1 // g.cRowEnd(6) ==> 6 // g.cRowLen(8) ==> 2 // g.cRowEnd(8) ==> 8 // g.numOfTiles ==> 8 } "Sides" - { //g.sideRoords.elemsLen ==> 36 } } }
jayrulez/NazaraEngine
include/Nazara/Graphics/UberShader.inl
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (<EMAIL>) // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/UberShader.hpp> #include <Nazara/Graphics/Debug.hpp> namespace Nz { inline ShaderStageTypeFlags UberShader::GetSupportedStages() const { return m_shaderStages; } inline bool UberShader::HasOption(const std::string& optionName, Pointer<const Option>* option) const { auto it = m_optionIndexByName.find(optionName); if (it == m_optionIndexByName.end()) return false; if (option) *option = &it->second; return true; } inline void UberShader::UpdateConfig(Config& config, const std::vector<RenderPipelineInfo::VertexBufferData>& vertexBuffers) { if (m_configCallback) m_configCallback(config, vertexBuffers); } inline void UberShader::UpdateConfigCallback(ConfigCallback callback) { m_configCallback = std::move(callback); } inline bool UberShader::ConfigEqual::operator()(const Config& lhs, const Config& rhs) const { return lhs.optionValues == rhs.optionValues; } inline std::size_t UberShader::ConfigHasher::operator()(const Config& config) const { std::size_t hash = 0; for (auto&& [key, value] : config.optionValues) { HashCombine(hash, key); HashCombine(hash, value); } return hash; } } #include <Nazara/Graphics/DebugOff.hpp>
rajadilipkolli/POC
poc-spring-boot-rest/poc-spring-boot-rest-webmvc/src/main/java/com/example/poc/webmvc/exception/LowerCaseClassNameResolver.java
<reponame>rajadilipkolli/POC package com.example.poc.webmvc.exception; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase; import java.util.Locale; class LowerCaseClassNameResolver extends TypeIdResolverBase { /** {@inheritDoc} */ @Override public String idFromValue(Object value) { return value.getClass().getSimpleName().toLowerCase(Locale.getDefault()); } /** {@inheritDoc} */ @Override public String idFromValueAndType(Object value, Class<?> suggestedType) { return idFromValue(value); } /** {@inheritDoc} */ @Override public JsonTypeInfo.Id getMechanism() { return JsonTypeInfo.Id.CUSTOM; } }
dubdabasoduba/estatio
estatioapp/integtests/src/test/java/org/estatio/integtests/agreement/AgreementRoleTypeRepositoryTest.java
package org.estatio.integtests.agreement; import java.util.List; import javax.inject.Inject; import org.junit.Before; import org.junit.Test; import org.apache.isis.applib.fixturescripts.FixtureScript; import org.estatio.dom.agreement.Agreement; import org.estatio.dom.agreement.AgreementRoleType; import org.estatio.dom.agreement.AgreementRoleTypeRepository; import org.estatio.dom.agreement.AgreementType; import org.estatio.dom.agreement.AgreementTypeRepository; import org.estatio.dom.agreement.AgreementRepository; import org.estatio.dom.lease.LeaseConstants; import org.estatio.dom.party.Parties; import org.estatio.dom.party.Party; import org.estatio.fixture.EstatioBaseLineFixture; import org.estatio.fixture.lease.LeaseForOxfTopModel001Gb; import org.estatio.integtests.EstatioIntegrationTest; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; public class AgreementRoleTypeRepositoryTest extends EstatioIntegrationTest { @Inject Parties parties; @Inject AgreementRepository agreementRepository; @Inject AgreementTypeRepository agreementTypeRepository; @Inject AgreementRoleTypeRepository agreementRoleTypeRepository; Party party; Agreement agreement; AgreementType agreementType; AgreementRoleType agreementRoleType; @Before public void setupData() { runFixtureScript(new FixtureScript() { @Override protected void execute(ExecutionContext executionContext) { executionContext.executeChild(this, new EstatioBaseLineFixture()); executionContext.executeChild(this, new LeaseForOxfTopModel001Gb()); } }); } @Before public void setUp() throws Exception { party = parties.findPartyByReference(LeaseForOxfTopModel001Gb.PARTY_REF_TENANT); agreement = agreementRepository.findAgreementByReference(LeaseForOxfTopModel001Gb.REF); agreementType = agreementTypeRepository.find(LeaseConstants.AT_LEASE); agreementRoleType = agreementRoleTypeRepository.findByAgreementTypeAndTitle(agreementType, LeaseConstants.ART_TENANT); } public static class FindByTitle extends AgreementRoleTypeRepositoryTest { @Test public void findByTitle() throws Exception { AgreementRoleType result = agreementRoleTypeRepository.findByTitle(LeaseConstants.ART_TENANT); assertThat(result, is(agreementRoleType)); } } public static class FindApplicableTo extends AgreementRoleTypeRepositoryTest { @Test public void findApplicableTo() throws Exception { List<AgreementRoleType> result = agreementRoleTypeRepository.findApplicableTo(agreementType); assertThat(result.size(), is(agreementType.getRoleTypesApplicableTo().size())); assertThat(result, is(agreementType.getRoleTypesApplicableTo())); } } public static class FindByAgreementTypeAndTitle extends AgreementRoleTypeRepositoryTest { @Test public void findByAgreementTypeAndTitle() throws Exception { AgreementRoleType result = agreementRoleTypeRepository.findByAgreementTypeAndTitle(agreementType, LeaseConstants.ART_TENANT); assertNotNull(result); } } }
qianbinbin/leetcode
cpp/src/MinimumWindowSubstring.cpp
#include "MinimumWindowSubstring.h" #include <array> #include <limits> using namespace lcpp; #define UC(Ch) (static_cast<unsigned char>(Ch)) std::string Solution76_1::minWindow(std::string s, std::string t) { const auto &Size1 = s.size(), &Size2 = t.size(); if (Size1 < Size2) return ""; typedef std::string::size_type SizeType; std::array<int, 256> Expected{}; for (auto Ch : t) ++Expected[UC(Ch)]; SizeType MinFirst = 0, Max = std::numeric_limits<SizeType>::max(), MinSize = Max; for (SizeType First = 0, Last = 0, ExpectedCount = 0; Last != Size1;) { if (Expected[UC(s[Last++])]-- > 0) ++ExpectedCount; while (ExpectedCount == Size2) { if (Last - First < MinSize) MinSize = Last - (MinFirst = First); if (++Expected[UC(s[First++])] > 0) --ExpectedCount; } } if (MinSize == Max) return ""; return s.substr(MinFirst, MinSize); }
vlehtola/questmud
lib/wizards/jenny/mehta/mosut/spider.c
<gh_stars>0 inherit "obj/monster"; reset(arg) { ::reset(arg); if (arg) { return; } set_level(6+random(7)); set_race("spider"); set_name("spider"); set_alias("animal"); set_short("A small woolly spider"); set_long("A small woolly spider is hanging from the ceiling. It\n" "is weaving a cobweb, but the net looks very fragile.\n"+ "The arachnid doesn't look very dangerous, but it might\n"+ "be poisonous.\n"); set_al(-3); set_animal(1); set_aggressive(1); }
Schwarz-Hexe/YAMMS
skse/GameData.h
<reponame>Schwarz-Hexe/YAMMS #pragma once #include "GameTypes.h" #include "GameForms.h" #include "GameObjects.h" #include "GameReferences.h" #include "GameResources.h" class BSFile; struct FormRecordData { UInt8 typeID; // corresponds to kFormType_XXX UInt32 typeCode; // i.e. 'GMST', 'FACT' UInt32 unk08; // only seen zero }; struct ChunkHeader { UInt32 type : 4; // i.e. 'XGRD', 'DATA' UInt16 size : 2; }; struct ModInfo // referred to by game as TESFile { ModInfo(); ~ModInfo(); // 18 info about currently loading form struct FormInfo { UInt32 recordType; // 00 i.e. 'FACT', 'GMST' UInt32 unk04; // 04 looks like size of entire record UInt32 formFlags; // 08 copied to TESForm->flags UInt32 formID; // 0C UInt32 unk10; // 10 UInt16 unk14; // 14 always initialized to 0F on SaveForm. UInt16 unk16; }; tList<UInt32> unkList; // 000 UInt32 /*NiTPointerMap<TESFile*>*/ * pointerMap; // 008 UInt32 unk00C; // 00C BSFile* unkFile; // 010 UInt32 unk014; // 014 void * unk018; // 018 seen all zeroes. size unknown void * unk01C; // 01C as above char name[0x104]; // 020 char filepath[0x104]; // 124 UInt32 unk228; // 228 UInt32 unk22C; // init'd to dword_F469CC (0x2800) same val as BSFile+10? UInt32 unk230; // 230 UInt32 unk234; // 234 UInt32 unk238; // 238 UInt32 unk23C; // 23C FormInfo formInfo; // 240 ChunkHeader subRecord; // 258 UInt32 unk260; // 260 UInt32 fileOffset; // 264 UInt32 dataOffset; // 268 index into dataBuf UInt32 subrecordBytesRead; // 26C generates error on Read if != expected length UInt32 unk268[(0x298-0x270) >> 2]; // 270 UInt8 unk298; // 298 UInt8 bIsBigEndian; // 299 UInt8 unk29A; // 29A UInt8 pad29B; WIN32_FIND_DATA fileData; // 29C float unk3DC; // 3DC init'd to 0.94 UInt32 unk3E0; // 3E0 UInt32 flags; // 3E4 init'd to 0x00000800. 4000 and 40000 do stuff UInt8 unk3E8; // 3E8 UInt8 pad3E9[3]; UInt32 unk3EC; // 3EC UInt32 unk3F0; // 3F0 UInt32 unk3F4; // 3F4 UInt32 unk3F8; // 3F8 UInt32 numRefMods; // 3FC related to modindex; see 4472D0 // formIDs in mod are as saved in GECK, must fix up at runtime ModInfo ** refModInfo; // 400 used to look up modInfo based on fixed mod index, double-check UInt32 unk404; // 404 UInt32 unk408; // 408 UInt8 modIndex; // 40C init to 0xFF UInt8 pad40D[3]; BSString author; // 410 BSString description; // 418 void * dataBuf; // 420 UInt32 unk424; // 424 looks like size of entire record UInt8 unk428; // 428 UInt8 pad429[3]; bool IsLoaded() const { return true; } }; struct ModList { tList<ModInfo> modInfoList; UInt32 loadedModCount; ModInfo* loadedMods[0xFF]; }; // E8 class TES { public: virtual ~TES(); UInt32 unk04; UInt32 unk08; UInt32 unk0C; UInt32 unk10; UInt32 unk14; UInt32 unk18; UInt32 unk1C; UInt32 unk20; UInt32 unk24; UInt32 unk28; UInt32 unk2C; UInt32 unk30; UInt32 unk34; UInt32 unk38; UInt32 unk3C; UInt32 gridCellArray; //40 GridCellArray 0x24 NiNode * objectLODRoot; // 44 NiNode * landLOD; // 48 NiNode * waterLOD; // 4C UInt32 tempNodeManager;//BSTempNodeManager UInt32 unk54; UInt32 unk58; UInt32 unk5C; // 7FFFFFFF UInt32 unk60; // 7FFFFFFF UInt32 unk64; // 7FFFFFFF UInt32 unk68; // 7FFFFFFF TESObjectCELL * currentCell; TESObjectCELL ** interiorCellBuffer; // idk, visited cells perhaps? UInt32 unk74; UInt32 unk78; // 0 UInt32 unk7C; // 0 UInt32 unk80; // 7FFFFFFF UInt32 unk84; // 7FFFFFFF UInt32 unk88; UInt32 unk8C; UInt32 unk90; UInt32 sky; // Sky UInt32 imageSpaceModifier; // ImageSpaceModifierInstanceForm UInt32 unk9C; // ImageSpaceModifierInstanceDOF ** ?? UInt32 unkA0; UInt32 unkA4; UInt8 unkA8; UInt8 unkA9; UInt8 unkAA; UInt8 unkAB; UInt8 unkAC; UInt8 unkAD; UInt8 unkAE; UInt8 unkAF; UInt8 unkB0; UInt8 padB1[3]; UInt32 unkB4; // 4579A000 UInt32 unkB8; // 457D2000 UInt32 worldSpace; // TESWorldSpace UInt32 npcs; // TESNPC ** ?? UInt32 unkC4; // TESNPC next? UInt32 queuedFile; // QueuedFile NiSourceTexture* someTexture; UInt32 queuedFile1; // QueuedFile UInt32 queuedFile2; UInt32 unkD8; // BSFadeNode ** ?? UInt32 unkDC; UInt32 navMeshInfoMap; // NavMeshInfoMap LoadedAreaBound * loadedAreaBound; }; STATIC_ASSERT(sizeof(TES) == 0xE8); STATIC_ASSERT(offsetof(TES, loadedAreaBound) == 0xE4); extern TES ** g_TES; class DataHandler { public: static DataHandler* GetSingleton(); // loads of tArrays of object types, at least a good number in formType order UInt32 unk000; UInt32 unk004; UnkFormArray unk008; UnkFormArray unk014; UnkFormArray unk020; UnkFormArray unk02C; tArray<BGSKeyword*> keywords; tArray<BGSLocationRefType*> locRefTypes; tArray<BGSAction*> actions; tArray<BGSTextureSet*> textureSets; tArray<BGSMenuIcon*> menuIcons; tArray<TESGlobal*> globals; tArray<TESClass*> classes; tArray<TESFaction*> factions; tArray<BGSHeadPart*> headParts; tArray<TESEyes*> eyes; tArray<TESRace*> races; tArray<TESSound*> sounds; tArray<BGSAcousticSpace*> acousticSpaces; UnkFormArray unkSkills; tArray<EffectSetting*> magicEffects; tArray<Script*> scripts; tArray<TESLandTexture*> landTextures; tArray<EnchantmentItem*> enchantments; tArray<SpellItem*> spellItems; tArray<ScrollItem*> scrolls; tArray<TESObjectACTI*> activators; tArray<BGSTalkingActivator*> talkingActivators; tArray<TESObjectARMO*> armors; tArray<TESObjectBOOK*> books; tArray<TESObjectCONT*> containers; tArray<TESObjectDOOR*> doors; tArray<IngredientItem*> ingredients; tArray<TESObjectLIGH*> lights; tArray<TESObjectMISC*> miscObjects; tArray<BGSApparatus*> apparatuses; tArray<TESObjectSTAT*> statics; tArray<BGSStaticCollection*> staticCollections; tArray<BGSMovableStatic*> movableStatics; tArray<TESGrass*> grasses; tArray<TESObjectTREE*> trees; tArray<TESFlora*> flora; tArray<TESFurniture*> furniture; tArray<TESObjectWEAP*> weapons; tArray<TESAmmo*> ammo; tArray<TESNPC*> npcs; tArray<TESLevCharacter*> levCharacters; tArray<TESKey*> keys; tArray<AlchemyItem*> potions; tArray<BGSIdleMarker*> idleMarkers; tArray<BGSNote*> notes; tArray<BGSConstructibleObject*> constructibles; tArray<BGSProjectile*> projectiles; tArray<BGSHazard*> bgsHazards; tArray<TESSoulGem*> soulGems; tArray<TESLevItem*> levItems; tArray<TESWeather*> weather; tArray<TESClimate*> climates; tArray<BGSShaderParticleGeometryData*> shaderParticleGeometryData; tArray<BGSReferenceEffect*> referenceEffects; tArray<TESRegion*> regions; tArray<NavMeshInfoMap*> navMeshInfoMaps; tArray<TESObjectCELL*> cells; tArray<TESObjectREFR*> refs; // could be actors tArray<Character*> characters; tArray<MissileProjectile*> missleProjs; tArray<ArrowProjectile*> arrowProjs; tArray<GrenadeProjectile*> grenadeProjs; tArray<BeamProjectile*> beamProjs; tArray<FlameProjectile*> flameProjs; tArray<ConeProjectile*> coneProjs; tArray<BarrierProjectile*> barrierProjs; tArray<Hazard*> hazards; tArray<TESWorldSpace*> worldSpaces; tArray<TESObjectLAND*> lands; tArray<NavMesh*> navMeshes; UnkFormArray unkTLOD; tArray<TESTopic*> topics; tArray<TESTopicInfo*> topicInfos; tArray<TESQuest*> quests; tArray<TESIdleForm*> idleForms; tArray<TESPackage*> packages; tArray<TESCombatStyle*> combatStyles; tArray<TESLoadScreen*> loadScreens; tArray<TESLevSpell*> levSpells; tArray<TESObjectANIO*> anios; tArray<TESWaterForm*> waterForms; tArray<TESEffectShader*> effectShaders; UnkFormArray unkTOFTs; tArray<BGSExplosion*> explosions; tArray<BGSDebris*> debris; tArray<TESImageSpace*> imageSpaces; tArray<TESImageSpaceModifier*> imageSpaceModifiers; tArray<BGSListForm*> listForms; tArray<BGSPerk*> perks; tArray<BGSBodyPartData*> bodyPartData; tArray<BGSAddonNode*> addonNodes; tArray<ActorValueInfo*> actorValueInfos; tArray<BGSCameraShot*> cameraShots; tArray<BGSCameraPath*> cameraPaths; tArray<BGSVoiceType*> voiceTypes; tArray<BGSMaterialType*> materialTypes; tArray<BGSImpactData*> impactData; tArray<BGSImpactDataSet*> impactDataSets; tArray<TESObjectARMA*> armorAddons; tArray<BGSEncounterZone*> encounterZones; tArray<BGSLocation*> locations; tArray<BGSMessage*> messages; tArray<BGSRagdoll*> ragdolls; UnkFormArray unkDOBJs; tArray<BGSLightingTemplate*> lightingTemplates; tArray<BGSMusicType*> musicTypes; tArray<BGSFootstep*> footsteps; tArray<BGSFootstepSet*> footstepSets; tArray<BGSStoryManagerBranchNode*> branchNodes; tArray<BGSStoryManagerQuestNode*> questNodes; tArray<BGSStoryManagerEventNode*> eventNodes; tArray<BGSDialogueBranch*> dialogBranches; tArray<BGSMusicTrackFormWrapper*> musicTrackFormWrappers; UnkFormArray unkDLVWs; tArray<TESWordOfPower*> wordOfPowers; tArray<TESShout*> shouts; tArray<BGSEquipSlot*> equipSlots; tArray<BGSRelationship*> relationships; tArray<BGSScene*> scenes; tArray<BGSAssociationType*> associationTypes; tArray<BGSOutfit*> outfits; tArray<BGSArtObject*> artObjects; tArray<BGSMaterialObject*> materialObjects; tArray<BGSMovementType*> movementTypes; tArray<BGSSoundDescriptorForm*> soundDescriptors; tArray<BGSDualCastData*> dualCastData; tArray<BGSSoundCategory*> soundCategories; tArray<BGSSoundOutput*> soundOutputs; tArray<BGSCollisionLayer*> collisonLayers; tArray<BGSColorForm*> colors; tArray<BGSReverbParameters*> reverbParams; UInt32 unks[0x0E]; // 03 Cell** 06 TESGlobal** ModList modList; UInt32 moreunks[100]; const ModInfo* LookupModByName(const char* modName); UInt8 GetModIndex(const char* modName); }; // 58 class BGSSaveLoadManager { public: enum { kEvent_Autosave = 1 << 0, kEvent_Save = 1 << 1, kEvent_Unk02 = 1 << 2, kEvent_Unk03 = 1 << 3, kEvent_Unk04 = 1 << 4, kEvent_Unk07 = 1 << 7, }; static BGSSaveLoadManager * GetSingleton(void); void Save(const char * name); void Load(const char * name); // used by Hooks_SaveLoad void SaveGame_Hook(const char * saveName); bool LoadGame_Hook(const char * saveName, bool unk1); void ProcessEvents_Hook(void); // use these when calling from a papyrus thread void RequestSave(const char * name); void RequestLoad(const char * name); MEMBER_FN_PREFIX(BGSSaveLoadManager); tList<const char*> * saveList; // 00 UInt32 unk04; // 04 UInt32 unk08; // 08 UInt32 unk0C; // 0C UInt8 unk10; // 10 UInt8 unk11; // 11 UInt8 pad12[2]; // 12 UInt32 pendingEvents; // 14 UInt32 unk18; // 18 UInt32 startTickCount; // 1C - GetTickCount when constructed UInt8 unk20; // 20 - init'd to 0x01 UInt8 pad21[3]; // 21 UInt32 unk24; // 24 UInt32 unk28; // 28 - init'd to 0xFFFFFFFF bool unk2C; // 2C UInt8 pad2E[3]; // 2E void * unk30; // 30 UInt8 unk34; // 34 - init'd to 0x01 UInt8 unk35; // 35 UInt8 pad36[2]; // 36 UInt32 unk38; // 38 UInt32 unk3C; // 3C UInt32 unk40; // 40 UInt32 unk44; // 44 UInt32 unk48; // 48 UInt32 unk4C; // 4C UInt32 unk50; // 50 void * unk54; // 54 private: DEFINE_MEMBER_FN(Save_Internal, bool, 0x006814D0, const char * name, int unk1, UInt32 unk2); DEFINE_MEMBER_FN(Load_Internal, bool, 0x006821C0, const char * name, int unk1, UInt32 unk2, UInt32 unk3); DEFINE_MEMBER_FN(SaveGame_HookTarget, void, 0x00679200, const char * fileName); DEFINE_MEMBER_FN(LoadGame_HookTarget, bool, 0x0067B720, const char * fileName, bool unk0); DEFINE_MEMBER_FN(ProcessEvents_Internal, void, 0x00682400); }; STATIC_ASSERT(sizeof(BGSSaveLoadManager) == 0x58); class MiscStatManager { public: static MiscStatManager * GetSingleton(void); // 14 struct MiscStat { const char * name; // 00 const char * unk04; // 04 UInt32 value; // 08 UInt32 unk0C; // 0C UInt8 unk10; // 10 UInt8 pad11[3]; // 11 }; class Visitor { public: virtual void Visit(MiscStat * stat, void * stat_unk04, UInt32 stat_unk0C, UInt32 value, UInt32 stat_unk10) = 0; }; MEMBER_FN_PREFIX(MiscStatManager); DEFINE_MEMBER_FN(Visit, void, 0x00488120, Visitor ** visitor); MiscStat * m_stats; // 00 UInt32 unk04; // 04 UInt32 m_numStats; // 08 MiscStat * Get(const char * name); }; class EquipManager { public: virtual ~EquipManager(); static EquipManager * GetSingleton(void); MEMBER_FN_PREFIX(EquipManager); DEFINE_MEMBER_FN(EquipItem, void, 0x006EF3E0, Actor * actor, TESForm * item, BaseExtraList * extraData, SInt32 count, BGSEquipSlot * equipSlot, bool withEquipSound, bool preventUnequip, bool showMsg, void * unk); DEFINE_MEMBER_FN(UnequipItem, bool, 0x006EE560, Actor * actor, TESForm * item, BaseExtraList * extraData, SInt32 count, BGSEquipSlot * equipSlot, bool unkFlag1 , bool preventEquip, bool unkFlag2, bool unkFlag3, void * unk); }; typedef BGSEquipSlot * (* _GetEitherHandSlot)(); extern const _GetEitherHandSlot GetEitherHandSlot; typedef BGSEquipSlot * (* _GetRightHandSlot)(); extern const _GetRightHandSlot GetRightHandSlot; typedef BGSEquipSlot * (* _GetLeftHandSlot)(); extern const _GetLeftHandSlot GetLeftHandSlot; typedef UInt32 (* _LookupActorValueByName)(const char * name); extern const _LookupActorValueByName LookupActorValueByName; class ActorValueList { public: enum { kNumActorValues = 164 }; static ActorValueList * GetSingleton(void); ActorValueInfo * GetActorValue(UInt32 id); static UInt32 ResolveActorValueByName(const char * name); private: UInt32 unk04; ActorValueInfo * actorValues[kNumActorValues]; }; class DefaultObjectList { public: enum { kNumDefaultObjects = 0x15A }; struct DefaultObject { const char * description; // 00 UInt32 unk04; // 04 UInt32 key; // 08 UInt32 unk0C; // 0C }; static DefaultObjectList * GetSingleton(void); DefaultObject objects[kNumDefaultObjects]; }; class FaceMorphList { public: enum { kNumMorphs = 19 }; enum { kMorph_NoseShortLong = 0, kMorph_NoseDownUp, kMorph_JawUpDown, kMorph_JawNarrowWide, kMorph_JawBackForward, kMorph_CheeksDownUp, kMorph_CheeksInOut, kMorph_EyesMoveDownUp, kMorph_EyesMoveInOut, kMorph_BrowDownUp, kMorph_BrowInOut, kMorph_BrowBackForward, kMorph_LipMoveDownUp, kMorph_LipMoveInOut, kMorph_ChinThinWide, kMorph_ChinMoveUpDown, kMorph_OverbiteUnderbite, kMorph_EyesBackForward, kMorph_Vampire }; static FaceMorphList * GetSingleton(void); struct Morph { UInt32 type; const char * lowerName; const char * upperName; }; Morph morphs[kNumMorphs]; }; class FacePresetData { public: virtual ~FacePresetData(); UInt32 unk08; // Always 10? const char * gameSettingName; }; class FacePresetList { public: enum { kNumPresets = 4 }; enum { kPreset_NoseType, kPreset_BrowType, kPreset_EyesType, kPreset_LipType }; static FacePresetList * GetSingleton(void); struct Preset { const char * presetName; FacePresetData * data; }; Preset presets[kNumPresets]; }; // 0x00882290 RaceMenu ctor // 0x0087F6E0 Morph Callback Handler // 0x005A4870 Apply Morph? // 0x005610F0 GetMorphName by Index and value // 0x00561180 SetMorph? class FaceGen { public: static FaceGen * GetSingleton(void); struct Action { BSFixedString name; UInt32 unk04; float delta; }; class MorphDatabase { public: MEMBER_FN_PREFIX(MorphDatabase); DEFINE_MEMBER_FN(GetFaceGenModelMapEntry, bool, 0x005A6230, const char * meshPath, BSFaceGenModelMap ** entry); DEFINE_MEMBER_FN(SetFaceGenModelMapEntry, void, 0x005A6540, const char * meshPath, BSFaceGenModel * model); UInt32 unk00; // 00 - Doesn't seem to be anything here? }; UInt32 unk00; // 00 UInt32 unk04; // 04 UInt32 unk08; // 08 UInt32 unk0C; // 0C MorphDatabase morphDatabase; // 10 UInt32 unk14[(0x3C - 0x14) >> 2]; // 14 UInt8 isReset; // 3C UInt8 pad3D[3]; // 3D MEMBER_FN_PREFIX(FaceGen); DEFINE_MEMBER_FN(RegenerateHead, void, 0x005A4B80, BSFaceGenNiNode * headNode, BGSHeadPart * head, TESNPC * npc); DEFINE_MEMBER_FN(ApplyMorph, void, 0x005A4070, BSFaceGenNiNode * faceGenNode, BGSHeadPart * headPart, BSFixedString * morphName, float relative); }; STATIC_ASSERT(offsetof(FaceGen, isReset) == 0x3C); // Changes one HeadPart to another typedef void (* _ChangeActorHeadPart)(Actor*, BGSHeadPart* oldPart, BGSHeadPart* newPart); extern const _ChangeActorHeadPart ChangeActorHeadPart; // Regenerates dynamic tints typedef UInt32 (* _UpdatePlayerTints)(); extern const _UpdatePlayerTints UpdatePlayerTints; typedef BGSHeadPart ** (* _GetActorBaseOverlays)(TESNPC * npc); extern const _GetActorBaseOverlays GetActorBaseOverlays; typedef UInt32 (* _GetNumActorBaseOverlays)(TESNPC * npc); extern const _GetNumActorBaseOverlays GetNumActorBaseOverlays; typedef bool (* _ApplyMasksToRenderTarget)(tArray<TintMask*> * tintMask, BSRenderTargetGroup ** renderTarget); extern const _ApplyMasksToRenderTarget ApplyMasksToRenderTarget; typedef UInt32 (* _UpdateModelSkin)(NiNode*, NiColorA**); extern const _UpdateModelSkin UpdateModelSkin; typedef UInt32 (* _UpdateModelHair)(NiNode*, NiColorA**); extern const _UpdateModelHair UpdateModelHair; typedef UInt32 (* _UpdateModelFace)(NiNode*); extern const _UpdateModelFace UpdateModelFace; // Loads a TRI file into the FaceGenDB, parameters are unknown ptrs // unk1 seems to be inited to zero before calling however // unk2 is a numeric value from some other object it seems // making it zero seems to cache anyway typedef bool (* _CacheTRIFile)(const char * filePath, BSFaceGenDB::TRI::DBTraits::MorphSet ** morphSet, UInt32 * unk1); extern const _CacheTRIFile CacheTRIFile; // 20 class MagicFavorites { // void ** _vtbl; // 00 UInt32 unk004; // 04 UnkFormArray spells; // 08 UnkFormArray hotkeys; // 14 public: virtual ~MagicFavorites(); void SetHotkey(TESForm * form, SInt8 idx); void ClearHotkey(SInt8 idx); TESForm * GetSpell(SInt8 idx); bool IsFavorited(TESForm * form); static MagicFavorites * GetSingleton(void) { return *((MagicFavorites **)0x01B2E39C); } }; // 84? class PersistentFormManager { public: struct EnchantData { EnchantmentItem * enchantment; // 00 volatile SInt32 refCount; // 04 }; UInt32 unk00; // 00 tArray<EnchantData> weaponEnchants; // 04 tArray<EnchantData> armorEnchants; // 10 UInt32 unk1C; // 1C UInt32 unk20; // 20 UInt32 unk24[(0x80 - 0x24) >> 2]; // 24 static PersistentFormManager * GetSingleton(void) { return *((PersistentFormManager **)0x012E3300); } void IncRefEnchantment(EnchantmentItem * enchantment) { if(enchantment && enchantment->formID >= 0xFF000000) { for(UInt32 i = 0; i < weaponEnchants.count; i++) { EnchantData foundData; weaponEnchants.GetNthItem(i, foundData); if(foundData.enchantment == enchantment) { InterlockedIncrement(&weaponEnchants[i].refCount); break; } } for(UInt32 i = 0; i < armorEnchants.count; i++) { EnchantData foundData; armorEnchants.GetNthItem(i, foundData); if(foundData.enchantment == enchantment) { InterlockedIncrement(&armorEnchants[i].refCount); break; } } } } // The game doesn't bother to dec ref or even delete custom enchants // when they are no longer used, maybe we can fix this? void DecRefEnchantment(EnchantmentItem * enchantment) { if(enchantment && enchantment->formID >= 0xFF000000) { for(UInt32 i = 0; i < weaponEnchants.count; i++) { EnchantData foundData; weaponEnchants.GetNthItem(i, foundData); if(foundData.enchantment == enchantment) { if(!InterlockedDecrement(&weaponEnchants[i].refCount)) CALL_MEMBER_FN(this, ScheduleForDeletion)(enchantment); break; } } for(UInt32 i = 0; i < armorEnchants.count; i++) { EnchantData foundData; armorEnchants.GetNthItem(i, foundData); if(foundData.enchantment == enchantment) { if(!InterlockedDecrement(&armorEnchants[i].refCount)) CALL_MEMBER_FN(this, ScheduleForDeletion)(enchantment); break; } } } } MEMBER_FN_PREFIX(PersistentFormManager); DEFINE_MEMBER_FN(CreateOffensiveEnchantment, EnchantmentItem *, 0x00689D30, tArray<MagicItem::EffectItem> * effectArray); DEFINE_MEMBER_FN(CreateDefensiveEnchantment, EnchantmentItem *, 0x00689D80, tArray<MagicItem::EffectItem> * effectArray); DEFINE_MEMBER_FN(CreatePotion, void, 0x0068ACB0, AlchemyItem ** potion, tArray<MagicItem::EffectItem> * effectArray); //DEFINE_MEMBER_FN(AddPersistentForm, void, 0x0068A0F0, TESForm *); DEFINE_MEMBER_FN(ScheduleForDeletion, void, 0x0068A1B0, TESForm *); }; class AnimationSpeedData { public: virtual ~AnimationSpeedData(); class SpeedData { public: UInt32 unk00; UInt32 unk04; // 8? UInt32 unk08; // 5? UInt32 unk0C; // 8? void * unk10; // DEADBEEF UInt32 unk14; UInt32 unk18; }; UInt32 unk04; UInt32 unk08; SpeedData unk0C; UInt32 unk28; UInt32 unk2C; }; class GarbageCollector { public: virtual ~GarbageCollector(); static GarbageCollector * GetSingleton(void); MEMBER_FN_PREFIX(GarbageCollector); DEFINE_MEMBER_FN(AddNiAVObject, UInt32, 0x0068FCF0, NiAVObject * object); }; class MenuTopicManager { public: virtual ~MenuTopicManager(); virtual void Unk_01(void); TESObjectREFR * GetDialogueTarget(); static MenuTopicManager * GetSingleton(void); BSTEventSink<void> playerPositionEvent; // 04 UInt32 unk08[(0x38 - 0x08) >> 2]; // 08 UInt32 talkingHandle; // 38 UInt32 handle2; // 3C UInt32 unk40[(0x60 - 0x40) >> 2]; // 40 UInt8 unk60; UInt8 unk61; UInt8 unk62; UInt8 unk63; UInt8 unk64; UInt8 unk65; UInt8 unk66; UInt8 unk67; UInt8 unk68; UInt8 unk69; UInt8 unk6A; UInt8 unk6B; }; STATIC_ASSERT(offsetof(MenuTopicManager, talkingHandle) == 0x38); // 04 class SkyObject { public: virtual ~SkyObject(); virtual void Unk_01(void); virtual void Unk_02(void); virtual void Unk_03(void); UInt32 m_refCount; // 04 }; // 1C class Atmosphere : public SkyObject { public: virtual ~Atmosphere(); virtual void Unk_04(void); UInt32 unk08; // 08 UInt32 unk0C; // 0C UInt32 unk10; // 10 UInt32 unk14; // 14 UInt32 unk18; // 18 }; // 10 class Stars : public SkyObject { public: virtual ~Stars(); UInt32 unk08; // 08 UInt32 unk0C; // 0C }; // 30 class Sun : public SkyObject { public: virtual ~Sun(); UInt32 unk08; // 08 UInt32 unk0C; // 0C UInt32 unk10; // 10 UInt32 unk14; // 14 UInt32 unk18; // 18 UInt32 unk1C; // 1C UInt32 unk20; // 20 UInt32 unk24; // 24 UInt8 unk28; // 28 UInt8 pad29[3]; // 29 UInt32 unk2C; // 2C - BSShaderAccumulator }; // 38C class Clouds : public SkyObject { public: virtual ~Clouds(); UInt32 unk08[(0x38C - 0x08) >> 2]; // 08 }; STATIC_ASSERT(sizeof(Clouds) == 0x38C); // 7C class Moon : public SkyObject { public: virtual ~Moon(); UInt32 unk08; // 08 - NiNode? UInt32 unk0C; // 0C - NiNode? UInt32 unk10; // 10 - NiNode? UInt32 unk14; // 14 - NiNode? char * unk18; // 18 - Data/Textures/Sky/%s_full.dds UInt32 unk1C; // 1C char * unk20; // 20 - Data/Textures/Sky/%s_three_wan.dds UInt32 unk24; // 24 char * unk28; // 28 - Data/Textures/Sky/%s_half_wan.dds UInt32 unk2C; // 3C char * unk30; // 30 - Data/Textures/Sky/%s_one_wan.dds UInt32 unk34; // 34 UInt32 unk38; // 38 UInt32 unk3C; // 3C char * unk40; // 40 - Data/Textures/Sky/%s_one_wax.dds UInt32 unk44; // 44 char * unk48; // 48 - Data/Textures/Sky/%s_half_wax.dds UInt32 unk4C; // 4C char * unk50; // 50 - Data/Textures/Sky/%s_three_wax.dds UInt32 unk54; // 54 UInt32 unk58; // 58 UInt32 unk7C[(0x7C - 0x58) >> 2]; // 08 }; // 1C class Precipitation : public SkyObject { public: virtual ~Precipitation(); UInt32 unk08; // 08 float unk0C; // 0C float unk10; // 10 float unk14; // 14 float unk18; // 18 }; STATIC_ASSERT(sizeof(Precipitation) == 0x1C); // 238 class Sky { public: virtual ~Sky(); void * unk04; // 04 - BSMultiBoundNode NiNode * unk08; // 08 UInt32 unk0C; // 0C UInt32 unk10; // 10 UInt32 unk14; // 14 UInt32 unk18; // 18 UInt32 unk1C; // 1C UInt32 unk20; // 20 UInt32 unk24; // 24 TESClimate * climate; // 28 TESWeather * weather; // 2C UInt32 unk30; // 30 UInt32 unk34; // 34 UInt32 unk38; // 38 TESRegion * region; // 3C Atmosphere * atmosphere; // 40 Stars * stars; // 44 Sun * sun; // 48 Clouds * clouds; // 4C Moon * masser; // 50 Moon * secunda; // 54 Precipitation * precipitation; // 58 float unk5C[6]; // 5C UInt32 unk74[3]; // 74 float unk80[6]; // 80 UInt32 unk98[6]; // 98 float unkB0[9]; // B0 UInt32 unkD4[6]; // D4 float unkEC[9]; // EC UInt32 unk110[9]; // 110 float unk134[7]; // 134 UInt32 unk150[3]; // 150 float unk15C[5]; // 15C UInt32 unk170; // 170 void * unk174; // 174 UInt32 unk178[3]; // 178 float unk184; // 184 UInt32 unk188[6]; // 188 float unk1A0[(0x210 - 0x1A0) >> 2]; // 1A0 void * skyEffectController; // 210 UInt32 unk214[(0x238 - 0x214) >> 2]; // 214 MEMBER_FN_PREFIX(Sky); DEFINE_MEMBER_FN(IsSnowing, bool, 0x00504350); }; STATIC_ASSERT(sizeof(Sky) == 0x238); typedef Sky * (* _GetSky)(); extern const _GetSky GetSky; typedef bool (* _HasLOS)(Actor* source, TESObjectREFR* target, UInt8 * unk1); extern const _HasLOS HasLOS; class PerkEntryPoints { public: static PerkEntryPoints * GetSingleton(void); enum { kEntryPoint_Calculate_Weapon_Damage, kEntryPoint_Calculate_My_Critical_Hit_Chance, kEntryPoint_Calculate_My_Critical_Hit_Damage, kEntryPoint_Calculate_Mine_Explode_Chance, kEntryPoint_Adjust_Limb_Damage, kEntryPoint_Adjust_Book_Skill_Points, kEntryPoint_Modify_Recovered_Health, kEntryPoint_Get_Should_Attack, kEntryPoint_Modify_Buy_Prices, kEntryPoint_Add_Leveled_List_On_Death, kEntryPoint_Get_Max_Carry_Weight, kEntryPoint_Modify_Addiction_Chance, kEntryPoint_Modify_Addiction_Duration, kEntryPoint_Modify_Positive_Chem_Duration, kEntryPoint_Activate, kEntryPoint_Ignore_Running_During_Detection, kEntryPoint_Ignore_Broken_Lock, kEntryPoint_Modify_Enemy_Critical_Hit_Chance, kEntryPoint_Modify_Sneak_Attack_Mult, kEntryPoint_Modify_Max_Placeable_Mines, kEntryPoint_Modify_Bow_Zoom, kEntryPoint_Modify_Recover_Arrow_Chance, kEntryPoint_Modify_Skill_Use, kEntryPoint_Modify_Telekinesis_Distance, kEntryPoint_Modify_Telekinesis_Damage_Mult, kEntryPoint_Modify_Telekinesis_Damage, kEntryPoint_Mod_Bashing_Damage, kEntryPoint_Mod_Power_Attack_Stamina, kEntryPoint_Mod_Power_Attack_Damage, kEntryPoint_Mod_Spell_Magnitude, kEntryPoint_Mod_Spell_Duration, kEntryPoint_Mod_Secondary_Value_Weight, kEntryPoint_Mod_Armor_Weight, kEntryPoint_Mod_Incoming_Stagger, kEntryPoint_Mod_Target_Stagger, kEntryPoint_Mod_Attack_Damage, kEntryPoint_Mod_Incoming_Damage, kEntryPoint_Mod_Target_Damage_Resistance, kEntryPoint_Mod_Spell_Cost, kEntryPoint_Mod_Percent_Blocked, kEntryPoint_Mod_Shield_Deflect_Arrow_Chance, kEntryPoint_Mod_Incoming_Spell_Magnitude, kEntryPoint_Mod_Incoming_Spell_Duration, kEntryPoint_Mod_Player_Intimidation, kEntryPoint_Mod_Player_Reputation, kEntryPoint_Mod_Favor_Points, kEntryPoint_Mod_Bribe_Amount, kEntryPoint_Mod_Detection_Light, kEntryPoint_Mod_Detection_Movement, kEntryPoint_Mod_Soul_Gem_Recharge, kEntryPoint_Set_Sweep_Attack, kEntryPoint_Apply_Combat_Hit_Spell, kEntryPoint_Apply_Bashing_Spell, kEntryPoint_Apply_Reanimate_Spell, kEntryPoint_Set_Boolean_Graph_Variable, kEntryPoint_Mod_Spell_Casting_Sound_Event, kEntryPoint_Modify_Pickpocket_Chance, kEntryPoint_Modify_Detection_Sneak_Skill, kEntryPoint_Modify_Falling_Damage, kEntryPoint_Modify_Lockpick_Sweet_Spot, kEntryPoint_Modify_Sell_Prices, kEntryPoint_Can_Pickpocket_Equipped_Item, kEntryPoint_Modify_Lockpick_level_allowed, kEntryPoint_Set_Lockpick_Starting_Arc, kEntryPoint_Set_Progression_Picking, kEntryPoint_Make_lockpicks_unbreakable_, kEntryPoint_Modify_Alchemy_Effectiveness, kEntryPoint_Apply_Weapon_Swing_Spell, kEntryPoint_Modify_Commanded_Actor_Limit, kEntryPoint_Apply_Sneaking_Spell, kEntryPoint_Modify_Player_Magic_Slowdown, kEntryPoint_Modify_Ward_Magicka_Absorption_Pct, kEntryPoint_Modify_Initial_Ingredient_Effects_Learned, kEntryPoint_Purify_Alchemy_Ingredients, kEntryPoint_Filter_Activation, kEntryPoint_Can_dual_cast_spell, kEntryPoint_Modify_Tempering_Health, kEntryPoint_Modify_Enchantment_Power, kEntryPoint_Modify_Soul_Pct_Captured_to_Weapon, kEntryPoint_Mod_Soul_Gem_Enchanting, kEntryPoint_Mod_applied_enchantments_allowed, kEntryPoint_Set_Activate_Label, kEntryPoint_Mod_Shout_OK, kEntryPoint_Mod_Poison_Dose_Count, kEntryPoint_Should_Apply_Placed_Item, kEntryPoint_Modify_Armor_Rating, kEntryPoint_Modify_lockpicking_crime_chance, kEntryPoint_Modify_ingredients_harvested, kEntryPoint_Modify_Spell_Range_Target_Loc, kEntryPoint_Modify_Potions_Created, kEntryPoint_Modify_lockpicking_key_reward_chance, kEntryPoint_Allow_Mount_Actor, kNumPerkEntryPoints }; struct Data { const char * name; // 00 UInt32 unk04; // 04 UInt32 unk08; // 08 UInt32 unk0C; // 0C }; Data entryPoints[kNumPerkEntryPoints]; }; typedef bool (* _CalculatePerkData)(UInt32 entryPointType, TESObjectREFR* source, ...); extern const _CalculatePerkData CalculatePerkData;
Ronald-Fi/Spring-Cloud
Netty/src/main/java/com/example/io/bio/tomcat_netty/http/NServlet.java
package com.example.io.bio.tomcat_netty.http; public abstract class NServlet { public void service(NRequest request, NResponse response) throws Exception { //由service方法来决定,是调用doGet或者调用doPost if ("GET".equalsIgnoreCase(request.getMethod())) { doGet(request, response); } else { doPost(request, response); } } public abstract void doGet(NRequest request, NResponse response) throws Exception; public abstract void doPost(NRequest request, NResponse response) throws Exception; }
cookingcodewithme/kafka
metadata/src/main/java/org/apache/kafka/metadata/BrokerHeartbeatReply.java
<gh_stars>10-100 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.metadata; import java.util.Objects; public class BrokerHeartbeatReply { /** * True if the heartbeat reply should tell the broker that it has caught up. */ private final boolean isCaughtUp; /** * True if the heartbeat reply should tell the broker that it is fenced. */ private final boolean isFenced; /** * True if the broker is currently in a controlled shutdown state. */ private final boolean inControlledShutdown; /** * True if the heartbeat reply should tell the broker that it should shut down. */ private final boolean shouldShutDown; public BrokerHeartbeatReply(boolean isCaughtUp, boolean isFenced, boolean inControlledShutdown, boolean shouldShutDown) { this.isCaughtUp = isCaughtUp; this.isFenced = isFenced; this.inControlledShutdown = inControlledShutdown; this.shouldShutDown = shouldShutDown; } public boolean isCaughtUp() { return isCaughtUp; } public boolean isFenced() { return isFenced; } public boolean inControlledShutdown() { return inControlledShutdown; } public boolean shouldShutDown() { return shouldShutDown; } @Override public int hashCode() { return Objects.hash(isCaughtUp, isFenced, inControlledShutdown, shouldShutDown); } @Override public boolean equals(Object o) { if (!(o instanceof BrokerHeartbeatReply)) return false; BrokerHeartbeatReply other = (BrokerHeartbeatReply) o; return other.isCaughtUp == isCaughtUp && other.isFenced == isFenced && other.inControlledShutdown == inControlledShutdown && other.shouldShutDown == shouldShutDown; } @Override public String toString() { return "BrokerHeartbeatReply(isCaughtUp=" + isCaughtUp + ", isFenced=" + isFenced + ", inControlledShutdown=" + inControlledShutdown + ", shouldShutDown = " + shouldShutDown + ")"; } }
JonyFang/MTHawkeye
MTHawkeye/UISkeleton/Toast/MTHToast.h
<gh_stars>1000+ // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 13/06/2018 // Created by: Huni // #import <Foundation/Foundation.h> #import "MTHToastBtnHandler.h" typedef NS_ENUM(NSInteger, MTHToastStyle) { MTHToastStyleSimple = 0, MTHToastStyleDetail }; @interface MTHToast : NSObject + (instancetype)shared; /** 显示短消息的弹框 @param message 信息 @param handler 点击弹框时间,默认为收起弹框 */ - (void)showToastWithMessage:(NSString *)message handler:(void (^)(void))handler; /** 显示 Toast 弹框 @param style 弹框类型 @param title 弹框标题 @param content 弹框内容 @param detailContent 弹框展开后内容 @param duration 弹框持续时间 @param handler 点击弹框事件 @param buttonHandlers 弹框展开后添加的按钮 @param hidden 弹框被遮挡后是否要被忽略 */ - (void)showToastWithStyle:(MTHToastStyle)style title:(NSString *)title content:(NSString *)content detailContent:(NSString *)detailContent duration:(NSTimeInterval)duration handler:(void (^)(void))handler buttonHandlers:(NSArray<MTHToastBtnHandler *> *)buttonHandlers autoHiddenBeOccluded:(BOOL)hidden; @end
ssb-ngi-pointer/manyverse-with-index-feeds
tools/echo-android-changelog.js
#!/usr/bin/env node // SPDX-FileCopyrightText: 2021 The Manyverse Authors // // SPDX-License-Identifier: CC0-1.0 const addStream = require('add-stream'); const intoStream = require('into-stream'); const generateChangelog = require('./generate-changelog'); intoStream('--------------BEGIN GOOGLE PLAY--------------\n') .pipe(addStream(generateChangelog(1, 'and'))) .pipe( addStream(intoStream('----------------END GOOGLE PLAY---------------\n')), ) .pipe(process.stdout);
koitoer/j2ee-components
src/main/java/webservices/chapter5/base64attach/server/SkiImagePublisherBase64.java
package webservices.chapter5.base64attach.server; import javax.xml.ws.Endpoint; import com.koitoer.webservices.chapter5.base64attach.server.SkiImageService; public class SkiImagePublisherBase64 { public static void main(String[] args){ System.out.println("URL: http://localhost:9876/ski"); Endpoint.publish("http://localhost:9876/ski", new SkiImageService()); } }
tgodzik/intellij-community
java/java-psi-impl/src/com/intellij/psi/impl/source/PsiPackageAccessibilityStatementImpl.java
<filename>java/java-psi-impl/src/com/intellij/psi/impl/source/PsiPackageAccessibilityStatementImpl.java // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.impl.source; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.impl.java.stubs.JavaPackageAccessibilityStatementElementType; import com.intellij.psi.impl.java.stubs.PsiPackageAccessibilityStatementStub; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import static com.intellij.psi.SyntaxTraverser.psiTraverser; public class PsiPackageAccessibilityStatementImpl extends JavaStubPsiElement<PsiPackageAccessibilityStatementStub> implements PsiPackageAccessibilityStatement { public PsiPackageAccessibilityStatementImpl(@NotNull PsiPackageAccessibilityStatementStub stub) { super(stub, stub.getStubType()); } public PsiPackageAccessibilityStatementImpl(@NotNull ASTNode node) { super(node); } @NotNull @Override public Role getRole() { return JavaPackageAccessibilityStatementElementType.typeToRole(getElementType()); } @Nullable @Override public PsiJavaCodeReferenceElement getPackageReference() { return PsiTreeUtil.getChildOfType(this, PsiJavaCodeReferenceElement.class); } @Nullable @Override public String getPackageName() { PsiPackageAccessibilityStatementStub stub = getGreenStub(); if (stub != null) { return StringUtil.nullize(stub.getPackageName()); } else { PsiJavaCodeReferenceElement ref = getPackageReference(); return ref != null ? PsiNameHelper.getQualifiedClassName(ref.getText(), true) : null; } } @NotNull @Override public Iterable<PsiJavaModuleReferenceElement> getModuleReferences() { return psiTraverser().children(this).filter(PsiJavaModuleReferenceElement.class); } @NotNull @Override public List<String> getModuleNames() { PsiPackageAccessibilityStatementStub stub = getGreenStub(); if (stub != null) { return stub.getTargets(); } else { List<String> targets = new SmartList<>(); for (PsiJavaModuleReferenceElement refElement : getModuleReferences()) targets.add(refElement.getReferenceText()); return targets; } } @Override public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof JavaElementVisitor) { ((JavaElementVisitor)visitor).visitPackageAccessibilityStatement(this); } else { visitor.visitElement(this); } } @Override public String toString() { return "PsiPackageAccessibilityStatement"; } }
shi00/foundation
plugins/log4j2/desensitization/src/main/java/com/silong/foundation/plugins/log4j2/desensitization/process/ChainSensitiveRecognizer.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.silong.foundation.plugins.log4j2.desensitization.process; import java.util.Arrays; import java.util.List; import java.util.Objects; /** * 链式敏感信息识别器,可以组合多个识别器按顺序进行敏感信息识别 * * @author <NAME> * @version 1.0.0 * @since 2022-03-01 08:01 */ public class ChainSensitiveRecognizer implements SensitiveRecognizer { private final List<SensitiveRecognizer> recognizers; /** * 构造方法 * * @param recognizers 识别器列表 */ public ChainSensitiveRecognizer(SensitiveRecognizer... recognizers) { this.recognizers = Arrays.stream(Objects.requireNonNull(recognizers, "recognizers must not be null.")) .toList(); } @Override public String replace(String text) { for (SensitiveRecognizer recognizer : recognizers) { text = recognizer.replace(text); } return text; } }
zer0infinity/CuteForCoast
coast/wdbase/Test/TestLib/TestRenderer.cpp
/* * Copyright (c) 2005, <NAME> and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #include "TestRenderer.h" RegisterRenderer(TestRenderer); TestRenderer::TestRenderer(const char *name) : Renderer(name) { } TestRenderer::~TestRenderer() { } void TestRenderer::RenderAll(std::ostream &reply, Context &ctx, const ROAnything &config) { StartTrace(TestRenderer.RenderAll); reply << "output from TestRenderer"; }
Brent-rb/University
bachelor/imperative-programming-2/ZSO7/student.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <math.h> struct student { char naam[32]; char voornaam[32]; int studentnr; double punten[5]; int jaar; }; #define aantalStudenten 3 void readIn(struct student*); void sortNr(struct student[]); void printStudent(struct student*); void addPoint(struct student[], int, double); int main(void) { struct student studenten[aantalStudenten]; int i; for(i = 0; i < aantalStudenten; i++) { readIn(&studenten[i]); } for(i = 0; i < aantalStudenten; i++) { printStudent(&studenten[i]); } sortNr(studenten); for(i = 0; i <aantalStudenten; i++){ printStudent(&studenten[i]); } for(i = 0; i < aantalStudenten; i++) { printStudent(&studenten[i]);) } return 0; } void readIn(struct student* st) { int i; printf("Geef de voornaam en naam van de student(voornaam naam): "); scanf("%s %s", st->voornaam, st->naam); printf("Geef de studentennummer: "); scanf("%d", &st->studentnr); printf("Geef het jaar: "); scanf("%d", &st->jaar); for (i = 0; i < st->jaar; ++i) { printf("Geef het punten van het %d jaar: ", i); scanf("%lf", &st->punten[i]); } } void printStudent(struct student* st) { int i; printf("\nDe voornaam en naam van de student(voornaam naam): %s %s\n", st->voornaam, st->naam); printf("De studentennummer: %d\n", st->studentnr); printf("Het jaar: %d\n", st->jaar); for (i = 0; i < st->jaar; ++i) { printf("De punten van het %d jaar: %lf\n", i, st->punten[i]); } } void sortNr(struct student st[]) { int i, j, lowest; struct student temp; for(i = 0; i < aantalStudenten; i++) { temp = st[i]; lowest = i; for(j = i; j < aantalStudenten; j++) { if(temp.studentnr > st[j].studentnr) { temp = st[j]; lowest = j; } } st[lowest] = st[i]; st[i] = temp; } } void addPoint(struct student studenten[], int studentNummer, double punt) { int realStudent = -1; int i; for(i = 0; i < aantalStudenten; i++) { if(studenten[i].studentnr == studentNummer) realStudent = i; } if(realStudent == -1) { printf("Ongeldigge stundentennummer ingegeven. \n"); } else { if(studenten[realStudent].jaar >= 5) { printf("De student is al afgestudeerd.\n"); } else { studenten[realStudent].punten[studenten[realStudent].jaar] = punt; studenten[realStudent].jaar++; } } }