text
stringlengths
1
1.05M
<filename>module_account/src/main/java/arouter/dawn/zju/edu/module_account/ui/modify_pickname/ModifyPicknameActivity.java package arouter.dawn.zju.edu.module_account.ui.modify_pickname; import android.view.MenuItem; import com.alibaba.android.arouter.facade.annotation.Route; import arouter.dawn.zju.edu.module_account.R; import arouter.dawn.zju.edu.module_account.databinding.ActivityModifyPicknameBinding; import baselib.base2.BaseActivity; import baselib.constants.RouteConstants; /** * @Auther: Dawn * @Date: 2018/11/22 22:01 * @Description: * 用户更改昵称页面 */ @Route(path = RouteConstants.AROUTER_ACCOUNT_MODIFY_PICKNAME) public class ModifyPicknameActivity extends BaseActivity<ActivityModifyPicknameBinding, ModifyPickNameViewModel> { @Override protected void init() { setSupportActionBar(binding.toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } viewModel.picknameData.observe(getLifecycleOwner(), s -> { if (s.length() >= 5 && s.length() <= 24) { binding.modifyPicknameConfirmModify.setClickable(true); binding.modifyPicknameConfirmModify.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); } else { binding.modifyPicknameConfirmModify.setClickable(false); binding.modifyPicknameConfirmModify.setBackgroundColor(getResources().getColor(R.color.lightgrey)); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return true; } }
using System; public class Citizen { private string _demCitizenValue; public string DemCitizenValue { get { return _demCitizenValue; } set { if (string.Equals(value, "yes", StringComparison.OrdinalIgnoreCase) || string.Equals(value, "no", StringComparison.OrdinalIgnoreCase)) { _demCitizenValue = value; } else { throw new ArgumentException("DemCitizenValue can only be 'yes' or 'no'."); } } } }
module.exports = { images: { domains: ['images.dog.ceo'], }, };
<reponame>googleapis/googleapis-gen<gh_stars>1-10 # frozen_string_literal: true # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! module Google module Ads module GoogleAds module V7 module Errors # Container for enum describing possible media file errors. class MediaFileErrorEnum include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # Enum describing possible media file errors. module MediaFileError # Enum unspecified. UNSPECIFIED = 0 # The received error code is not known in this version. UNKNOWN = 1 # Cannot create a standard icon type. CANNOT_CREATE_STANDARD_ICON = 2 # May only select Standard Icons alone. CANNOT_SELECT_STANDARD_ICON_WITH_OTHER_TYPES = 3 # Image contains both a media file ID and data. CANNOT_SPECIFY_MEDIA_FILE_ID_AND_DATA = 4 # A media file with given type and reference ID already exists. DUPLICATE_MEDIA = 5 # A required field was not specified or is an empty string. EMPTY_FIELD = 6 # A media file may only be modified once per call. RESOURCE_REFERENCED_IN_MULTIPLE_OPS = 7 # Field is not supported for the media sub type. FIELD_NOT_SUPPORTED_FOR_MEDIA_SUB_TYPE = 8 # The media file ID is invalid. INVALID_MEDIA_FILE_ID = 9 # The media subtype is invalid. INVALID_MEDIA_SUB_TYPE = 10 # The media file type is invalid. INVALID_MEDIA_FILE_TYPE = 11 # The mimetype is invalid. INVALID_MIME_TYPE = 12 # The media reference ID is invalid. INVALID_REFERENCE_ID = 13 # The YouTube video ID is invalid. INVALID_YOU_TUBE_ID = 14 # Media file has failed transcoding MEDIA_FILE_FAILED_TRANSCODING = 15 # Media file has not been transcoded. MEDIA_NOT_TRANSCODED = 16 # The media type does not match the actual media file's type. MEDIA_TYPE_DOES_NOT_MATCH_MEDIA_FILE_TYPE = 17 # None of the fields have been specified. NO_FIELDS_SPECIFIED = 18 # One of reference ID or media file ID must be specified. NULL_REFERENCE_ID_AND_MEDIA_ID = 19 # The string has too many characters. TOO_LONG = 20 # The specified type is not supported. UNSUPPORTED_TYPE = 21 # YouTube is unavailable for requesting video data. YOU_TUBE_SERVICE_UNAVAILABLE = 22 # The YouTube video has a non positive duration. YOU_TUBE_VIDEO_HAS_NON_POSITIVE_DURATION = 23 # The YouTube video ID is syntactically valid but the video was not found. YOU_TUBE_VIDEO_NOT_FOUND = 24 end end end end end end end
import dialogflow import os from google.api_core.exceptions import InvalidArgument # Set up DialogFlow session and credentials DIALOGFLOW_PROJECT_ID = "[PROJECT_ID]" DIALOGFLOW_LANGUAGE_CODE = 'en-US' os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "[CREDENTIALS]" SESSION_ID = "[SESSION_ID]" def detect_intents_texts(text): session_client = dialogflow.SessionsClient() session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID) text_input = dialogflow.types.TextInput(text=text, language_code=DIALOGFLOW_LANGUAGE_CODE) query_input = dialogflow.types.QueryInput(text=text_input) try: response = session_client.detect_intent(session=session, query_input=query_input) except InvalidArgument: raise return response.query_result.fulfillment_text # User query while(True): query = input('You: ') response = detect_intents_texts(query) print('Bot: {}'.format(response))
<reponame>deyihu/maptalks-echarts-gl /** * Provide WebGL layer to zrender. Which is rendered on top of qtek. * * * Relationship between zrender, LayerGL(renderer) and ViewGL(Scene, Camera, Viewport) * zrender * / \ * LayerGL LayerGL * (renderer) (renderer) * / \ * ViewGL ViewGL * * @module echarts-gl/core/LayerGL * @author <NAME>(http://github.com/pissang) */ import echarts from 'echarts/lib/echarts'; import Renderer from 'qtek/src/Renderer'; import RayPicking from 'qtek/src/picking/RayPicking'; import Texture from 'qtek/src/Texture'; // PENDING, qtek notifier is same with zrender Eventful import notifier from 'qtek/src/core/mixin/notifier'; import requestAnimationFrame from 'zrender/lib/animation/requestAnimationFrame'; // configs for Auto GC for GPU resources // PENDING var MAX_SHADER_COUNT = 60; var MAX_GEOMETRY_COUNT = 20; var MAX_TEXTURE_COUNT = 20; /** * @constructor * @alias module:echarts-gl/core/LayerGL * @param {string} id Layer ID * @param {module:zrender/ZRender} zr */ var LayerGL = function (id, zr) { /** * Layer ID * @type {string} */ this.id = id; /** * @type {module:zrender/ZRender} */ this.zr = zr; /** * @type {qtek.Renderer} */ try { this.renderer = new Renderer({ clearBit: 0, devicePixelRatio: zr.painter.dpr, preserveDrawingBuffer: true, // PENDING premultipliedAlpha: true }); this.renderer.resize(zr.painter.getWidth(), zr.painter.getHeight()); } catch (e) { this.renderer = null; this.dom = document.createElement('div'); this.dom.style.cssText = 'position:absolute; left: 0; top: 0; right: 0; bottom: 0;'; this.dom.className = 'ecgl-nowebgl'; this.dom.innerHTML = 'Sorry, your browser does support WebGL'; console.error(e); return; } this.onglobalout = this.onglobalout.bind(this); zr.on('globalout', this.onglobalout); /** * Canvas dom for webgl rendering * @type {HTMLCanvasElement} */ this.dom = this.renderer.canvas; var style = this.dom.style; style.position = 'absolute'; style.left = '0'; style.top = '0'; /** * @type {Array.<qtek.Scene>} */ this.views = []; this._picking = new RayPicking({ renderer: this.renderer }); this._viewsToDispose = []; /** * Current accumulating id. */ this._accumulatingId = 0; this._zrEventProxy = new echarts.graphic.Rect({ shape: {x: -1, y: -1, width: 2, height: 2}, // FIXME Better solution. __isGLToZRProxy: true }); }; /** * @param {module:echarts-gl/core/ViewGL} view */ LayerGL.prototype.addView = function (view) { if (view.layer === this) { return; } // If needs to dispose in this layer. unmark it. var idx = this._viewsToDispose.indexOf(view); if (idx >= 0) { this._viewsToDispose.splice(idx, 1); } this.views.push(view); view.layer = this; var zr = this.zr; view.scene.traverse(function (node) { node.__zr = zr; if (node.addAnimatorsToZr) { node.addAnimatorsToZr(zr); } }); }; function removeFromZr(node) { var zr = node.__zr; node.__zr = null; if (zr && node.removeAnimatorsFromZr) { node.removeAnimatorsFromZr(zr); } } /** * @param {module:echarts-gl/core/ViewGL} view */ LayerGL.prototype.removeView = function (view) { if (view.layer !== this) { return; } var idx = this.views.indexOf(view); if (idx >= 0) { this.views.splice(idx, 1); view.scene.traverse(removeFromZr, this); view.layer = null; // Mark to dispose in this layer. this._viewsToDispose.push(view); } }; /** * Remove all views */ LayerGL.prototype.removeViewsAll = function () { this.views.forEach(function (view) { view.scene.traverse(removeFromZr, this); view.layer = null; // Mark to dispose in this layer. this._viewsToDispose.push(view); }, this); this.views.length = 0; }; /** * Resize the canvas and viewport, will be invoked by zrender * @param {number} width * @param {number} height */ LayerGL.prototype.resize = function (width, height) { var renderer = this.renderer; renderer.resize(width, height); }; /** * Clear color and depth * @return {[type]} [description] */ LayerGL.prototype.clear = function () { var gl = this.renderer.gl; gl.clearColor(0, 0, 0, 0); gl.depthMask(true); gl.colorMask(true, true, true, true); gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT); }; /** * Clear depth */ LayerGL.prototype.clearDepth = function () { var gl = this.renderer.gl; gl.clear(gl.DEPTH_BUFFER_BIT); }; /** * Clear color */ LayerGL.prototype.clearColor = function () { var gl = this.renderer.gl; gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); }; /** * Mark layer to refresh next tick */ LayerGL.prototype.needsRefresh = function () { this.zr.refresh(); }; /** * Refresh the layer, will be invoked by zrender */ LayerGL.prototype.refresh = function () { for (var i = 0; i < this.views.length; i++) { this.views[i].prepareRender(); } this._doRender(false); // Auto dispose unused resources on GPU, like program(shader), texture, geometry(buffers) this._trackAndClean(); // Dispose trashed views for (var i = 0; i < this._viewsToDispose.length; i++) { this._viewsToDispose[i].dispose(this.renderer); } this._viewsToDispose.length = 0; this._startAccumulating(); }; LayerGL.prototype.renderToCanvas = function (ctx) { // PENDING will block the page this._startAccumulating(true); ctx.drawImage(this.dom, 0, 0, ctx.canvas.width, ctx.canvas.height); }; LayerGL.prototype._doRender = function (accumulating) { this.clear(); this.renderer.saveViewport(); for (var i = 0; i < this.views.length; i++) { this.views[i].render(this.renderer, accumulating); } this.renderer.restoreViewport(); }; /** * Stop accumulating */ LayerGL.prototype._stopAccumulating = function () { this._accumulatingId = 0; clearTimeout(this._accumulatingTimeout); }; var accumulatingId = 1; /** * Start accumulating all the views. * Accumulating is for antialising and have more sampling in SSAO * @private */ LayerGL.prototype._startAccumulating = function (immediate) { var self = this; this._stopAccumulating(); var needsAccumulate = false; for (var i = 0; i < this.views.length; i++) { needsAccumulate = this.views[i].needsAccumulate() || needsAccumulate; } if (!needsAccumulate) { return; } function accumulate(id) { if (!self._accumulatingId || id !== self._accumulatingId) { return; } var isFinished = true; for (var i = 0; i < self.views.length; i++) { isFinished = self.views[i].isAccumulateFinished() && needsAccumulate; } if (!isFinished) { self._doRender(true); if (immediate) { accumulate(id); } else { requestAnimationFrame(function () { accumulate(id); }); } } } this._accumulatingId = accumulatingId++; if (immediate) { accumulate(self._accumulatingId); } else { this._accumulatingTimeout = setTimeout(function () { accumulate(self._accumulatingId); }, 50); } }; function getId(resource) { return resource.__GUID__; } function checkAndDispose(renderer, resourceMap, maxCount) { var count = 0; // FIXME not allocate array. var unused = []; for (var id in resourceMap) { if (!resourceMap[id].count) { unused.push(resourceMap[id].target); } else { count++; } } for (var i = 0; i < Math.min(count - maxCount, unused.length); i++) { unused[i].dispose(renderer); } } function addToMap(map, target) { var id = getId(target); map[id] = map[id] || { count: 0, target: target }; map[id].count++; } LayerGL.prototype._trackAndClean = function () { var shadersMap = this._shadersMap = this._shadersMap || {}; var texturesMap = this._texturesMap = this._texturesMap || {}; var geometriesMap = this._geometriesMap = this._geometriesMap || {}; for (var id in shadersMap) { shadersMap[id].count = 0; } for (var id in texturesMap) { texturesMap[id].count = 0; } for (var id in geometriesMap) { geometriesMap[id].count = 0; } function trackQueue(queue) { for (var i = 0; i < queue.length; i++) { var renderable = queue[i]; var geometry = renderable.geometry; var material = renderable.material; var shader = material.shader; addToMap(geometriesMap, geometry); addToMap(shadersMap, shader); for (var name in material.uniforms) { var val = material.uniforms[name].value; if (val instanceof Texture) { addToMap(texturesMap, val); } else if (val instanceof Array) { for (var k = 0; k < val.length; k++) { if (val[k] instanceof Texture) { addToMap(texturesMap, val[k]); } } } } } } for (var i = 0; i < this.views.length; i++) { var viewGL = this.views[i]; var scene = viewGL.scene; trackQueue(scene.opaqueQueue); trackQueue(scene.transparentQueue); for (var k = 0; k < scene.lights.length; k++) { // Track AmbientCubemap if (scene.lights[k].cubemap) { addToMap(texturesMap, scene.lights[k].cubemap); } } } // Dispose those unsed resources checkAndDispose(this.renderer, shadersMap, MAX_SHADER_COUNT); checkAndDispose(this.renderer, texturesMap, MAX_TEXTURE_COUNT); checkAndDispose(this.renderer, geometriesMap, MAX_GEOMETRY_COUNT); }; /** * Dispose the layer */ LayerGL.prototype.dispose = function () { this._stopAccumulating(); this.renderer.disposeScene(this.scene); this.zr.off('globalout', this.onglobalout); }; // Event handlers LayerGL.prototype.onmousedown = function (e) { if (e.target && e.target.__isGLToZRProxy) { return; } e = e.event; var obj = this.pickObject(e.offsetX, e.offsetY); if (obj) { this._dispatchEvent('mousedown', e, obj); this._dispatchDataEvent('mousedown', e, obj); } this._downX = e.offsetX; this._downY = e.offsetY; }; LayerGL.prototype.onmousemove = function (e) { if (e.target && e.target.__isGLToZRProxy) { return; } e = e.event; var obj = this.pickObject(e.offsetX, e.offsetY); var target = obj && obj.target; var lastHovered = this._hovered; this._hovered = obj; if (lastHovered && target !== lastHovered.target) { lastHovered.relatedTarget = target; this._dispatchEvent('mouseout', e, lastHovered); // this._dispatchDataEvent('mouseout', e, lastHovered); this.zr.setCursorStyle('default'); } this._dispatchEvent('mousemove', e, obj); if (obj) { this.zr.setCursorStyle('pointer'); if (!lastHovered || (target !== lastHovered.target)) { this._dispatchEvent('mouseover', e, obj); // this._dispatchDataEvent('mouseover', e, obj); } } this._dispatchDataEvent('mousemove', e, obj); }; LayerGL.prototype.onmouseup = function (e) { if (e.target && e.target.__isGLToZRProxy) { return; } e = e.event; var obj = this.pickObject(e.offsetX, e.offsetY); if (obj) { this._dispatchEvent('mouseup', e, obj); this._dispatchDataEvent('mouseup', e, obj); } this._upX = e.offsetX; this._upY = e.offsetY; }; LayerGL.prototype.onclick = LayerGL.prototype.dblclick = function (e) { if (e.target && e.target.__isGLToZRProxy) { return; } // Ignore click event if mouse moved var dx = this._upX - this._downX; var dy = this._upY - this._downY; if (Math.sqrt(dx * dx + dy * dy) > 20) { return; } e = e.event; var obj = this.pickObject(e.offsetX, e.offsetY); if (obj) { this._dispatchEvent(e.type, e, obj); this._dispatchDataEvent(e.type, e, obj); } // Try set depth of field onclick var result = this._clickToSetFocusPoint(e); if (result) { var success = result.view.setDOFFocusOnPoint(result.distance); if (success) { this.zr.refresh(); } } }; LayerGL.prototype._clickToSetFocusPoint = function (e) { var renderer = this.renderer; var oldViewport = renderer.viewport; for (var i = this.views.length - 1; i >= 0; i--) { var viewGL = this.views[i]; if (viewGL.hasDOF() && viewGL.containPoint(e.offsetX, e.offsetY)) { this._picking.scene = viewGL.scene; this._picking.camera = viewGL.camera; // Only used for picking, renderer.setViewport will also invoke gl.viewport. // Set directly, PENDING. renderer.viewport = viewGL.viewport; var result = this._picking.pick(e.offsetX, e.offsetY, true); if (result) { result.view = viewGL; return result; } } } renderer.viewport = oldViewport; }; LayerGL.prototype.onglobalout = function (e) { var lastHovered = this._hovered; if (lastHovered) { this._dispatchEvent('mouseout', e, { target: lastHovered.target }); } }; LayerGL.prototype.pickObject = function (x, y) { var output = []; var renderer = this.renderer; var oldViewport = renderer.viewport; for (var i = 0; i < this.views.length; i++) { var viewGL = this.views[i]; if (viewGL.containPoint(x, y)) { this._picking.scene = viewGL.scene; this._picking.camera = viewGL.camera; // Only used for picking, renderer.setViewport will also invoke gl.viewport. // Set directly, PENDING. renderer.viewport = viewGL.viewport; this._picking.pickAll(x, y, output); } } renderer.viewport = oldViewport; output.sort(function (a, b) { return a.distance - b.distance; }); return output[0]; }; LayerGL.prototype._dispatchEvent = function (eveName, originalEvent, newEvent) { if (!newEvent) { newEvent = {}; } var current = newEvent.target; newEvent.cancelBubble = false; newEvent.event = originalEvent; newEvent.type = eveName; newEvent.offsetX = originalEvent.offsetX; newEvent.offsetY = originalEvent.offsetY; while (current) { current.trigger(eveName, newEvent); current = current.getParent(); if (newEvent.cancelBubble) { break; } } this._dispatchToView(eveName, newEvent); }; LayerGL.prototype._dispatchDataEvent = function (eveName, originalEvent, newEvent) { var mesh = newEvent && newEvent.target; var dataIndex = mesh && mesh.dataIndex; var seriesIndex = mesh && mesh.seriesIndex; // Custom event data var eventData = mesh && mesh.eventData; var elChangedInMouseMove = false; var eventProxy = this._zrEventProxy; eventProxy.position = [originalEvent.offsetX, originalEvent.offsetY]; eventProxy.update(); var targetInfo = { target: eventProxy }; if (eveName === 'mousemove') { if (dataIndex != null) { if (dataIndex !== this._lastDataIndex) { if (parseInt(this._lastDataIndex, 10) >= 0) { eventProxy.dataIndex = this._lastDataIndex; eventProxy.seriesIndex = this._lastSeriesIndex; // FIXME May cause double events. this.zr.handler.dispatchToElement(targetInfo, 'mouseout', originalEvent); } elChangedInMouseMove = true; } } else if (eventData != null) { if (eventData !== this._lastEventData) { if (this._lastEventData != null) { eventProxy.eventData = this._lastEventData; // FIXME May cause double events. this.zr.handler.dispatchToElement(targetInfo, 'mouseout', originalEvent); } elChangedInMouseMove = true; } } this._lastEventData = eventData; this._lastDataIndex = dataIndex; this._lastSeriesIndex = seriesIndex; } eventProxy.eventData = eventData; eventProxy.dataIndex = dataIndex; eventProxy.seriesIndex = seriesIndex; if (eventData != null || parseInt(dataIndex, 10) >= 0) { this.zr.handler.dispatchToElement(targetInfo, eveName, originalEvent); if (elChangedInMouseMove) { this.zr.handler.dispatchToElement(targetInfo, 'mouseover', originalEvent); } } }; LayerGL.prototype._dispatchToView = function (eventName, e) { for (var i = 0; i < this.views.length; i++) { if (this.views[i].containPoint(e.offsetX, e.offsetY)) { this.views[i].trigger(eventName, e); } } }; echarts.util.extend(LayerGL.prototype, notifier); export default LayerGL;
// AgoraHookingDlg.h : header file // #include "AGButton.h" #pragma once class CAssistantBox; class CExtendAudioFrameObserver; #include "CHookPlayerInstance.h" // CAgoraHookingDlg dialog class CAgoraHookingDlg : public CDialogEx { // Construction public: CAgoraHookingDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data enum { IDD = IDD_AGORAHOOKING_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: HICON m_hIcon; // Generated message map functions virtual BOOL OnInitDialog(); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnShowWindow(BOOL bShow, UINT nStatus); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnTimer(UINT_PTR nIDEvent); DECLARE_MESSAGE_MAP() virtual BOOL PreTranslateMessage(MSG* pMsg); void onButtonCloseClicked(); void onButtonMinClicked(); //EventHandle LRESULT OnJoinChannelSuccess(WPARAM wParam, LPARAM lParam); LRESULT OnRejoinChannelSuccess(WPARAM wParam, LPARAM lParam); LRESULT OnWarning(WPARAM wParam, LPARAM lParam); LRESULT OnError(WPARAM wParam, LPARAM lParam); LRESULT OnAudioQuality(WPARAM wParam, LPARAM lParam); LRESULT OnAudioVolumeIndication(WPARAM wParam, LPARAM lParam); LRESULT OnLeaveChannel(WPARAM wParam, LPARAM lParam); LRESULT OnRtcStats(WPARAM wParam, LPARAM lParam); LRESULT OnMediaEngineEvent(WPARAM wParam, LPARAM lParam); LRESULT OnAudioDeviceStateChanged(WPARAM wParam, LPARAM lParam); LRESULT OnVideoDeviceStateChanged(WPARAM wParam, LPARAM lParam); LRESULT OnRequestChannelKey(WPARAM wParam, LPARAM lParam); LRESULT OnLastmileQuality(WPARAM wParam, LPARAM lParam); LRESULT OnFirstLocalVideoFrame(WPARAM wParam, LPARAM lParam); LRESULT OnFirstRemoteVideoDecoded(WPARAM wParam, LPARAM lParam); LRESULT OnFirstRemoteVideoFrame(WPARAM wParam, LPARAM lParam); LRESULT OnUserJoined(WPARAM wParam, LPARAM lParam); LRESULT OnUserOffline(WPARAM wParam, LPARAM lParam); LRESULT OnUserMuteAudio(WPARAM wParam, LPARAM lParam); LRESULT OnUserMuteVideo(WPARAM wParam, LPARAM lParam); LRESULT OnApiCallExecuted(WPARAM wParam, LPARAM lParam); LRESULT OnLocalVideoStats(WPARAM wParam, LPARAM lParam); LRESULT OnRemoteVideoStats(WPARAM wParam, LPARAM lParam); LRESULT OnCameraReady(WPARAM wParam, LPARAM lParam); LRESULT OnVideoStopped(WPARAM wParam, LPARAM lParam); LRESULT OnConnectionLost(WPARAM wParam, LPARAM lParam); LRESULT OnConnectionInterrupted(WPARAM wParam, LPARAM lParam); LRESULT OnUserEnableVideo(WPARAM wParam, LPARAM lParam); LRESULT OnStartRecordingService(WPARAM wParam, LPARAM lParam); LRESULT OnStopRecordingService(WPARAM wParam, LPARAM lParam); LRESULT OnRefreshRecordingServiceStatus(WPARAM wParam, LPARAM lParam); LRESULT OnInviterJoinChannel(WPARAM wParam,LPARAM lParam); protected: inline void initCtrl(); inline void uninitCtrl(); inline void initResource(); inline void uninitResource(); inline void getRectClient(RECT &rt); inline void getRectClientLeft(RECT &rt); inline void getRectClientRight(RECT &rt); protected: HWND m_hWndLeftRemote; HWND m_hWndRightSelf; HWND m_hWndTitle; CAGButton m_AgBtnMin; CAGButton m_AgBtnClose; CAssistantBox* m_pAssistantBox; BOOL m_bIsCapture; std::string m_strAppId; std::string m_strAppcertificateId; std::string m_strChannel; UINT m_uLoginUid; std::string m_strCameraName; std::string m_strInstance; UINT m_uInviter; CAgoraObject* m_lpAgoraObject; IRtcEngine* m_lpRtcEngine; CExtendAudioFrameObserver* m_lpExtendAudioFrame; CHookPlayerInstance* m_lpHookPlayerInstance; const int const KNSampelRate = 44100; const int const KNChannel = 2; const int const KNSampelPerCall = 44100 * 2 / 100; };
#include <stdio.h> int main() { int i; for (i=1; i<200; i++) { if (i % 7 == 0) printf( "%d ", i ); } return 0; }
#!/usr/bin/env bash # Copyright 2019 curoky(cccuroky@gmail.com). # # 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. # os: debian:10,debian:11 set -xeuo pipefail cd "$(dirname $0)" || exit 1 OS=${1:-'debian:10'} OS_SHORT=${OS/:/} tag=curoky/box:${OS_SHORT} docker buildx build . --network=host --file Dockerfile "${@:2}" \ --build-arg OS=${OS} \ --build-arg OS_SHORT=${OS_SHORT} \ --cache-to=type=inline \ --cache-from=type=registry,ref=$tag \ --tag $tag
import sqlite3 def update_student(id): conn = sqlite3.connect('students.db') cur = conn.cursor() cur.execute("UPDATE students SET name='John Doe' WHERE id=?", (id, )) conn.commit() conn.close() update_student(1)
<reponame>archiloque/Tumblr-Machine require 'sequel/extensions/pg_array' require 'sequel/extensions/pg_array_ops' Sequel.extension :core_extensions Sequel.extension :pg_array_ops class TumblrMachine DATABASE.extension :pg_array class Tag < Sequel::Model end class Tumblr < Sequel::Model one_to_many :posts end class Post < Sequel::Model many_to_one :tumblr def before_destroy super remove_all_tags end attr_accessor :loaded_tags attr_accessor :loaded_tumblr end class Meta < Sequel::Model end end
class Timezone { constructor(zoneName) { this.zoneName = zoneName; } getCurrentTime() { // Get the current time based on the time zone } setTimezone(timezoneName) { // Set the time zone to the passed in name this.zoneName = timezoneName; } }
<filename>doc_test.go package numtow import ( "fmt" "github.com/gammban/numtow/lang" "github.com/gammban/numtow/lang/en" "github.com/gammban/numtow/lang/ru" "github.com/gammban/numtow/lang/ru/gender" ) func ExampleMustString_default() { fmt.Println(MustString("8691705", lang.EN, en.FormatDefault)) // Output: eight million, six hundred and ninety-one thousand, seven hundred and five } func ExampleMustString_without_and() { fmt.Println(MustString("8691705", lang.EN, en.FormatWithoutAnd)) // Output: eight million six hundred ninety-one thousand seven hundred five } func ExampleMustFloat64_default() { fmt.Println(MustFloat64(1, lang.RU)) // Output: одна } func ExampleMustFloat64_female() { fmt.Println(MustFloat64(2, lang.RU)) // Output: две } func ExampleMustFloat64_male() { fmt.Println(MustFloat64(2, lang.RU, ru.WithFmtGender(gender.Male))) // Output: два }
<gh_stars>0 export default () => ` <div class="profile-card-aligner"> <div class="profile-card"> <section class="upperProfileContainer"> <div class="upper-left"> <img id="user-photo" src="" alt="profile picture"> </div> <div class="upper-right"> <button id="otherBack"><i class="fas fa-chevron-left"></i></button> <img id="otherSlide" src="" alt="hobby pictures"> <button id="otherForward"><i class="fas fa-chevron-right"></i></button> </div> </section> <section class="lowerProfileContainer"> <div class="leftProfileContainer"> <div class="name-location-container"> <h3 id="user-name">Name</h3> <h4 id="user-location">Location</h4> </div> <div class="links"> <div> <a href="" target="_blank" id="instagram"><i class="fab fa-instagram-square"></i></a> <a href="" target="_blank" id="youtube"><i class="fab fa-youtube"></i></a> </div> <div> <a href="" target="_blank" id="pintrest"><i class="fab fa-pinterest"></i></a> <a href="" target="_blank" id="facebook"><i class="fab fa-facebook"></i></a> </div> <a href="" target="_blank" id="blog-website">Blog/Website</a> </div> <div class="edit-profile-container"> <a href="Profile" data-navigo><i class="fas fa-user"></i></a> </div> </div> <div class="lower-middle-container"> <div class="hobby-container"> <h3 class="right-profile-headers">Hobbies</h3> <p id="user-hobbies">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </div> <div class="interests-container"> <h3 class="right-profile-headers">What Hobbies Interest Me</h3> <p id="user-wants">Stuff</p> </div> </div> <div class="view-container"> <h3 id="hobbitat-next-header">Next</h3> <div id="hobbitat-controls"> <a href="" id="next"><i class="far fa-arrow-alt-circle-right"></i></a> <a href="Chatlog" data-navigo id="chat"><i class="fas fa-people-arrows"></i></a> </div> <h3 id="hobbitat-exchange-header">Exchange</h3> </div> </section> </div> </div> `;
class MaterialProperties: def __init__(self): self.properties = {} def set_property(self, name, value): self.properties[name] = value def get_property(self, name): return self.properties.get(name, None) def property_exists(self, name): return name in self.properties # Example usage material = MaterialProperties() material.set_property('Anisotropic Rotation', 0.5) material.set_property('Sheen', 0.8) print(material.get_property('Anisotropic Rotation')) # Output: 0.5 print(material.property_exists('Clearcoat')) # Output: False material.set_property('Clearcoat', 0.6) print(material.property_exists('Clearcoat')) # Output: True print(material.get_property('Transmission')) # Output: None
class UserInput: def __init__(self, input): self.input = input def process(self): output = "" if self.input == 42: output = "The answer to the Ultimate Question of Life, the Universe and Everything!" else: output = "Error. Unknown input." return output user_input = UserInput(42) print(user_input.process())
<reponame>chenggangpro/alibaba-rsocket-broker package com.alibaba.rsocket.listen.impl; import com.alibaba.rsocket.RSocketAppContext; import com.alibaba.rsocket.listen.RSocketListener; import com.alibaba.rsocket.observability.RsocketErrorCode; import io.netty.handler.ssl.OpenSsl; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import io.rsocket.SocketAcceptor; import io.rsocket.core.RSocketServer; import io.rsocket.plugins.DuplexConnectionInterceptor; import io.rsocket.plugins.RSocketInterceptor; import io.rsocket.plugins.SocketAcceptorInterceptor; import io.rsocket.transport.ServerTransport; import io.rsocket.transport.local.LocalServerTransport; import io.rsocket.transport.netty.server.TcpServerTransport; import io.rsocket.transport.netty.server.WebsocketServerTransport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.Disposable; import reactor.netty.http.server.HttpServer; import reactor.netty.tcp.TcpServer; import java.security.PrivateKey; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.*; import java.util.stream.Collectors; /** * RSocket listener implementation * * @author leijuan */ public class RSocketListenerImpl implements RSocketListener { private Logger log = LoggerFactory.getLogger(RSocketListenerImpl.class); private Map<Integer, String> schemas = new HashMap<>(); private String host = "0.0.0.0"; private static final String[] protocols = new String[]{"TLSv1.3", "TLSv.1.2"}; private Certificate certificate; private PrivateKey privateKey; private SocketAcceptor acceptor; private List<RSocketInterceptor> responderInterceptors = new ArrayList<>(); private List<SocketAcceptorInterceptor> acceptorInterceptors = new ArrayList<>(); private List<DuplexConnectionInterceptor> connectionInterceptors = new ArrayList<>(); private Integer status = -1; private List<Disposable> responders = new ArrayList<>(); public void host(String host) { this.host = host; } public void listen(String schema, int port) { this.schemas.put(port, schema); } public void setCertificate(Certificate certificate) { this.certificate = certificate; } public void setPrivateKey(PrivateKey privateKey) { this.privateKey = privateKey; } public void setAcceptor(SocketAcceptor acceptor) { this.acceptor = acceptor; } public void addResponderInterceptor(RSocketInterceptor interceptor) { this.responderInterceptors.add(interceptor); } public void addSocketAcceptorInterceptor(SocketAcceptorInterceptor interceptor) { this.acceptorInterceptors.add(interceptor); } public void addConnectionInterceptor(DuplexConnectionInterceptor interceptor) { this.connectionInterceptors.add(interceptor); } @Override public Collection<String> serverUris() { return schemas.entrySet().stream() .map(entry -> entry.getValue() + "://0.0.0.0:" + entry.getKey()) .collect(Collectors.toSet()); } @Override public void start() throws Exception { if (status != 1) { for (Map.Entry<Integer, String> entry : schemas.entrySet()) { String schema = entry.getValue(); int port = entry.getKey(); ServerTransport<?> transport; if (schema.equals("local")) { transport = LocalServerTransport.create("unittest"); } else if (schema.equals("tcp")) { transport = TcpServerTransport.create(host, port); } else if (schema.equals("tcps")) { TcpServer tcpServer = TcpServer.create() .host(host) .port(port) .secure(ssl -> ssl.sslContext( SslContextBuilder.forServer(privateKey, (X509Certificate) certificate) .protocols(protocols) .sslProvider(getSslProvider()) )); transport = TcpServerTransport.create(tcpServer); } else if (schema.equals("ws")) { transport = WebsocketServerTransport.create(host, port); } else if (schema.equals("wss")) { HttpServer httpServer = HttpServer.create() .host(host) .port(port) .secure(ssl -> ssl.sslContext( SslContextBuilder.forServer(privateKey, (X509Certificate) certificate) .protocols(protocols) .sslProvider(getSslProvider()) )); transport = WebsocketServerTransport.create(httpServer); } else { transport = TcpServerTransport.create(host, port); } RSocketServer rsocketServer = RSocketServer.create(); //acceptor interceptor for (SocketAcceptorInterceptor acceptorInterceptor : acceptorInterceptors) { rsocketServer.interceptors(interceptorRegistry -> { interceptorRegistry.forSocketAcceptor(acceptorInterceptor); }); } //connection interceptor for (DuplexConnectionInterceptor connectionInterceptor : connectionInterceptors) { rsocketServer.interceptors(interceptorRegistry -> { interceptorRegistry.forConnection(connectionInterceptor); }); } //responder interceptor for (RSocketInterceptor responderInterceptor : responderInterceptors) { rsocketServer.interceptors(interceptorRegistry -> { interceptorRegistry.forResponder(responderInterceptor); }); } Disposable disposable = rsocketServer .acceptor(acceptor) .bind(transport) .onTerminateDetach() .subscribe(); responders.add(disposable); log.info(RsocketErrorCode.message("RST-100001", schema + "://" + host + ":" + port)); } status = 1; RSocketAppContext.rsocketPorts = schemas; } } @Override public void stop() throws Exception { for (Disposable responder : responders) { responder.dispose(); } status = -1; } @Override public Integer getStatus() { return status; } private SslProvider getSslProvider() { if (OpenSsl.isAvailable()) { return SslProvider.OPENSSL_REFCNT; } else { return SslProvider.JDK; } } }
def fibonacci(n): if n<0: print("Incorrect input") # First Fibonacci number is 0 elif n==0: return 0 # Second Fibonacci number is 1 elif n==1: return 1 else: return fibonacci(n-1)+fibonacci(n-2)
import {Destination} from "./Destination"; import {Operator} from "./Operator"; export interface Leg { origin: Destination; destination: Destination; departure: Date; arrival: Date; hint: null; operator: Operator; mode: string; public: boolean; }
#!/bin/sh # Nagios plugin - simpler ping that doesn't leave zombie processes # This exists only because in December 2020, after upgrading the OS # distro, nagios, its plugins and *everything else*, the check_ping # command started leaving 1000+ zombies daily. This shell script doesn't. STATE_OK=0 STATE_WARNING=1 STATE_CRITICAL=2 STATE_UNKNOWN=3 warn=100,10% crit=500,50% packets=5 pingcmd=ping interface=br0 usage="Usage: $0 [-H host] [-w warn] [-c crit] [-p packets] -H, --hostname=<host> Hostname or IP address -c, --critical=<n>,<%> Crit threshold [$crit] -w, --warning=<n>,<%> Warn threshold [$warn] -I, --interface=<int> Interface (for ipv6) [$interface] -p, --packets=n Number of packets [$packets] -4, --use-ipv4 Use IPv4 -6, --use-ipv6 Use IPv6 (ping6) warn/crit expressed as <ms timeout>,<% dropped>" while test -n "$1"; do case "$1" in --critical|-c) crit=$2 ;; --warning|-w) warn=$2 ;; --hostname|-H) host=$2 ;; --packets|-p) packets=$2 ;; --use-ipv4|-4) pingcmd=ping ; shift 1 ; continue ;; --use-ipv6|-6) pingcmd=ping6; shift 1 ; continue ;; --help|-h) echo "$usage" exit $STATE_UNKNOWN ;; *) echo "Unknown argument: $1" echo "$usage" exit $STATE_UNKNOWN ;; esac shift 2 done thresh_parse() { ms=$(echo $1 | cut -d, -f 1) pct=$(echo $1 | cut -d, -f 2 | cut -d% -f 1) } thresh_parse $crit crit_sec=$(( $(printf %.0f $ms) / 1000 )) crit_ms=$ms crit_pct=$(printf %.0f $pct) thresh_parse $warn warn_sec=$(( $(printf %.0f $ms) / 1000 )) warn_ms=$ms warn_pct=$(printf %.0f $pct) [ $crit_sec -lt $packets ] && crit_sec=$packets [ $pingcmd = ping6 ] && pingcmd="$pingcmd -I $interface" output=$(mktemp) /bin/$pingcmd -c $packets -w $crit_sec $host > $output ret=$? status=$(egrep 'transmitted|round-trip|rtt' $output) rta=$(egrep 'round-trip|rtt' $output |cut -d= -f 2|cut -d / -f 2) loss=$(echo $status | grep -oP '[0-9]{1,3}%'|cut -d% -f 1) rm $output if [ $ret != 0 ]; then echo "CRIT: $status" exit $STATE_CRITICAL fi if [ "$loss" = "" ]; then echo "UNKNOWN: no loss % found: $status" exit $STATE_UNKNOWN elif [ $loss -ge $crit_pct ]; then echo "CRIT: loss ($loss%): $status" exit $STATE_CRITICAL elif [ $loss -ge $warn_pct ]; then echo "WARN: loss ($loss%): $status" exit $STATE_WARNING fi if [ "$rta" = "" ]; then echo "UNKNOWN: no rta found: $status" exit $STATE_UNKNOWN elif echo $crit_ms - $rta | bc | grep -q "-"; then echo "CRIT: rtt avg ($rta): $status" exit $STATE_CRITICAL elif echo $warn_ms - $rta | bc | grep -q "-"; then echo "WARN: rtt avg ($rta): $status" exit $STATE_WARNING fi echo "OK: $status" exit $STATE_OK
package com.breakersoft.plow.test.dao; import static org.junit.Assert.*; import javax.annotation.Resource; import org.junit.Test; import com.breakersoft.plow.Folder; import com.breakersoft.plow.dao.FolderDao; import com.breakersoft.plow.dao.ProjectDao; import com.breakersoft.plow.test.AbstractTest; public class FolderDaoTests extends AbstractTest { @Resource FolderDao folderDao; @Resource ProjectDao projectDao; @Test public void testCreate() { Folder folder1 = folderDao.createFolder(TEST_PROJECT, "foo"); Folder folder2 = folderDao.get(folder1.getFolderId()); assertEquals(folder1, folder2); } @Test public void testGetDefaultFolder() { Folder folder1 = folderDao.createFolder(TEST_PROJECT, "test"); projectDao.setDefaultFolder(TEST_PROJECT, folder1); Folder folder2 = folderDao.getDefaultFolder(TEST_PROJECT); assertEquals(folder1, folder2); } @Test public void testSetMinCores() { Folder folder1 = folderDao.createFolder(TEST_PROJECT, "foo"); folderDao.setMinCores(folder1, 101); int value = jdbc().queryForInt( "SELECT int_cores_min FROM plow.folder_dsp WHERE pk_folder=?", folder1.getFolderId()); assertEquals(101, value); } @Test public void testSetMaxCores() { Folder folder1 = folderDao.createFolder(TEST_PROJECT, "foo"); folderDao.setMaxCores(folder1, 101); int value = jdbc().queryForInt( "SELECT int_cores_max FROM plow.folder_dsp WHERE pk_folder=?", folder1.getFolderId()); assertEquals(101, value); } @Test public void testSetName() { Folder folder1 = folderDao.createFolder(TEST_PROJECT, "foo"); folderDao.setName(folder1, "bar"); String name = jdbc().queryForObject( "SELECT str_name FROM plow.folder WHERE pk_folder=?", String.class, folder1.getFolderId()); assertEquals("bar", name); } @Test public void testSet() { Folder folder1 = folderDao.createFolder(TEST_PROJECT, "foo"); Folder folder2 = folderDao.get(folder1.getFolderId()); assertEquals(folder1, folder2); } }
#!/usr/bin/env bash . lib.sh # https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-info.html execute_get_request _nodes
<reponame>rsuite/rsuite-icons // Generated by script, don't edit it please. import createSvgIcon from '../createSvgIcon'; import ProjectSvg from '@rsuite/icon-font/lib/file/Project'; const Project = createSvgIcon({ as: ProjectSvg, ariaLabel: 'project', category: 'file', displayName: 'Project' }); export default Project;
<gh_stars>0 import Listr from 'listr'; import buildApiReference from './api-reference'; import buildSearchIndex from './search-index'; const tasks = new Listr( [buildApiReference, buildSearchIndex] // { renderer: 'verbose' } ); export default tasks; if (!module.parent) { tasks.run().catch(err => { console.error(err); process.exit(1); }); }
def find_mode(list): max_count = 0 mode = list[0] count = {} for item in list: if (item in count): count[item] += 1 else: count[item] = 1 if (count[item] > max_count): max_count = count[item] mode = item return mode
#!/bin/sh find . -name "*~" -type f | xargs rm -f find . -name ".#*" -type f | xargs rm -f find . -name "*.rej" -type f | xargs rm -f find . -name "*.orig" -type f | xargs rm -f find . -name "DEADJOE" -type f | xargs rm -f find . -type f | grep -v ".psp" | grep -v ".gif" | grep -v ".jpg" | grep -v ".png" | grep -v ".tgz" | grep -v ".ico" | grep -v "druplicon" | xargs perl -wi -pe 's/\s+$/\n/' find . -type f | grep -v ".psp" | grep -v ".gif" | grep -v ".jpg" | grep -v ".png" | grep -v ".tgz" | grep -v ".ico" | grep -v "druplicon" | xargs perl -wi -pe 's/\t/ /g'
require "test_helper" class Houston::Slack::SlackControllerTest < ActionController::TestCase def setup @routes = Houston::Slack::Engine.routes end context "When Slack posts a slash command event, it" do setup do @calls = 0 Houston::Slack.config.slash("test") { @calls += 1 } stub(Houston::Slack.connection).find_channel("C0D1UMW7Q").returns({}) stub(Houston::Slack.connection).find_user("U0D1QH53N").returns({}) end teardown do Houston::Slack.config.instance_variable_get(:@slash_commands).clear end should "respond with success" do post :command, params: slash_command_payload assert_response :success end should "invoke the registered Slash command" do post :command, params: slash_command_payload assert_equal 1, @calls end should "look up the channel where the command was triggered" do mock(Houston::Slack.connection).find_channel("C0D1UMW7Q") post :command, params: slash_command_payload end should "look up the user that issued the command" do mock(Houston::Slack.connection).find_user("U0D1QH53N") post :command, params: slash_command_payload end end context "When Slack posts a message button event, it" do setup do @calls = 0 Houston::Slack.config.action("test:merge") { @calls += 1 } stub(Houston::Slack.connection).find_channel("C0D1UMW7Q").returns({}) stub(Houston::Slack.connection).find_user("U0D1QH53N").returns({}) end teardown do Houston::Slack.config.instance_variable_get(:@actions).clear end should "respond with success" do post :message, params: message_button_payload assert_response :success end should "invoke the registered action" do post :message, params: message_button_payload assert_equal 1, @calls end should "look up the channel where the command was triggered" do mock(Houston::Slack.connection).find_channel("C0D1UMW7Q") post :message, params: message_button_payload end should "look up the user that issued the command" do mock(Houston::Slack.connection).find_user("U0D1QH53N") post :message, params: message_button_payload end end private def slash_command_payload(params={}) { "token"=>"this token is sent by Slack so you can verify the command", "team_id"=>"T0D1SUB2S", "team_domain"=>"houston-sandbox", "channel_id"=>"C0D1UMW7Q", "channel_name"=>"alerts", "user_id"=>"U0D1QH53N", "user_name"=>"boblail", "command"=>"/test", "text"=>"", "response_url"=>"https://hooks.slack.com/commands/T0D1SUB2S/something" }.merge(params) end def message_button_payload(params={}) { payload: <<-JSON } { "actions": [{ "name": "merge", "value": "merge" }], "callback_id": "test", "team": { "id": "T0D1SUB2S", "domain": "houston-sandbox" }, "channel": { "id": "C0D1UMW7Q", "name": "alertrs" }, "user": { "id": "U0D1QH53N", "name": "boblail" }, "action_ts": "1484873847.542306", "message_ts": "1484873252.000005", "attachment_id": "1", "token": "this token is sent by Slack so you can verify the command", "original_message": { "type": "message", "user": "U3TV84KH9", "text": "hi", "bot_id": "B3U4EA7GD", "attachments": [{ "callback_id": "test", "fallback": "A certain pull request is ready to merge", "text": "A certain pull request is ready to merge", "id": 1, "color": "3AA3E3", "actions": [{ "id": "1", "name": "merge", "text": "Merge", "type": "button", "value": "merge" }] }], "ts": "1484873252.000005" }, "response_url": "https://hooks.slack.com/actions/T0D1SUB2S/129387369393/oAybdq3DbNlj8cvEJEK7AOmc" } JSON end end
<reponame>quintel/etengine # Presents information about the capacity and costs of producers. class ProductionParametersSerializer # Creates a new production parameters serializer. # # scenario - The Scenario whose node details are to be presented. # # Returns an ProductionParametersSerializer. def initialize(scenario) @graph = scenario.gql.future.graph end # Public: Formats the nodes for the scenario as a CSV file # containing the data. # # Returns a String. def as_csv(*) CSV.generate do |csv| csv << %w[ key number_of_units electricity_output_capacity\ (MW) heat_output_capacity\ (MW) full_load_hours total_initial_investment_per_plant\ (Euros) fixed_operation_and_maintenance_costs_per_year\ (Euros) variable_operation_and_maintenance_costs_per_full_load_hour\ (Euros) wacc\ (factor) technical_lifetime\ (years) total_investment_over_lifetime_per_node\ (Euros) ] nodes.each do |node| csv << node_row(node) end end end private def nodes ( @graph.group_nodes(:heat_production) + @graph.group_nodes(:electricity_production) + @graph.group_nodes(:cost_hydrogen_production) + @graph.group_nodes(:cost_hydrogen_infrastructure) + @graph.group_nodes(:cost_flexibility) + @graph.group_nodes(:cost_other) ).uniq.sort_by(&:key) end # Internal: Creates an array/CSV row representing the node and its # demands. def node_row(node) [ node.key, number_of_units(node), node.query.electricity_output_capacity, node.query.heat_output_capacity, node.query.full_load_hours, node.query.total_initial_investment_per(:plant), node.query.fixed_operation_and_maintenance_costs_per_year, node.query.variable_operation_and_maintenance_costs_per_full_load_hour, node.query.wacc, node.query.technical_lifetime, begin node.query.total_investment_over_lifetime_per(:node) rescue StandardError nil end ] end # Internal: Gets the node number of units. Guards against failure for # nodes where it cannot be calculated. def number_of_units(node) node.query.number_of_units rescue '' end end
def common_string(list): count = {} common = list[0] max_count = 1 for i in range(len(list)): element = list[i] if element in count: count[element] += 1 if element not in count: count[element] = 1 if max_count < count[element]: max_count = count[element] common = element return common print(common_string(['abc','abc','xyz','pqr','abc']))
#!/bin/bash # Copyright 2017 Istio Authors # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ####################################### # # # e2e-suite # # # ####################################### KUBE_USER="${KUBE_USER:-istio-prow-test-job@istio-testing.iam.gserviceaccount.com}" SETUP_CLUSTERREG="${SETUP_CLUSTERREG:-False}" USE_GKE="${USE_GKE:-True}" CLUSTER_NAME= SA_NAMESPACE="istio-system-multi" function gen_kubeconf_from_sa () { local service_account=$1 local filename=$2 NAMESPACE="${SA_NAMESPACE:-istio-system}" SERVER=$(kubectl config view --minify=true -o "jsonpath={.clusters[].cluster.server}") SECRET_NAME=$(kubectl get sa ${service_account} -n ${NAMESPACE} -o jsonpath='{.secrets[].name}') CA_DATA=$(kubectl get secret ${SECRET_NAME} -n ${NAMESPACE} -o "jsonpath={.data['ca\.crt']}") TOKEN=$(kubectl get secret ${SECRET_NAME} -n ${NAMESPACE} -o "jsonpath={.data['token']}" | base64 --decode) cat <<EOF > ${filename} apiVersion: v1 clusters: - cluster: certificate-authority-data: ${CA_DATA} server: ${SERVER} name: ${CLUSTER_NAME} contexts: - context: cluster: ${CLUSTER_NAME} user: ${CLUSTER_NAME} name: ${CLUSTER_NAME} current-context: ${CLUSTER_NAME} kind: Config preferences: {} users: - name: ${CLUSTER_NAME} user: token: ${TOKEN} EOF } function setup_clusterreg () { # setup cluster-registries dir setup by mason CLUSTERREG_DIR="${CLUSTERREG_DIR:-$(mktemp -d /tmp/clusterregXXX)}" SERVICE_ACCOUNT="istio-multi-test" # mason dumps all the kubeconfigs into the same file but we need to use per cluster # files for the clusterregsitry config. Create the separate files. # -- if PILOT_CLUSTER not set, assume pilot install to be in the first cluster PILOT_CLUSTER="${PILOT_CLUSTER:-$(kubectl config current-context)}" unset IFS k_contexts=$(kubectl config get-contexts -o name) for context in ${k_contexts}; do if [[ "${PILOT_CLUSTER}" != "${context}" ]]; then kubectl config use-context ${context} kubectl create ns ${SA_NAMESPACE} kubectl create sa ${SERVICE_ACCOUNT} -n ${SA_NAMESPACE} kubectl create clusterrolebinding istio-multi-test --clusterrole=cluster-admin --serviceaccount=${SA_NAMESPACE}:${SERVICE_ACCOUNT} CLUSTER_NAME=$(kubectl config view --minify=true -o "jsonpath={.clusters[].name}") if [[ "${CLUSTER_NAME}" =~ .*"_".* ]]; then # if clustername has '_' set value to stuff after the last '_' due to k8s secret data name limitation CLUSTER_NAME="${CLUSTER_NAME##*_}" fi KUBECFG_FILE="${CLUSTERREG_DIR}/${CLUSTER_NAME}" gen_kubeconf_from_sa ${SERVICE_ACCOUNT} ${KUBECFG_FILE} fi done kubectl config use-context ${PILOT_CLUSTER} } function join_by { local IFS="$1"; shift; echo "$*"; } function setup_cluster() { # use current-context if pilot_cluster not set PILOT_CLUSTER="${PILOT_CLUSTER:-$(kubectl config current-context)}" unset IFS k_contexts=$(kubectl config get-contexts -o name) for context in ${k_contexts}; do kubectl config use-context ${context} kubectl create clusterrolebinding prow-cluster-admin-binding\ --clusterrole=cluster-admin\ --user="${KUBE_USER}" done if [[ "${SETUP_CLUSTERREG}" == "True" ]]; then setup_clusterreg fi kubectl config use-context ${PILOT_CLUSTER} if [[ "${USE_GKE}" == "True" && "${SETUP_CLUSTERREG}" == "True" ]]; then ALL_CLUSTER_CIDRS=$(gcloud container clusters list --format='value(clusterIpv4Cidr)' | sort | uniq) ALL_CLUSTER_CIDRS=$(join_by , ${ALL_CLUSTER_CIDRS}) ALL_CLUSTER_NETTAGS=$(gcloud compute instances list --format='value(tags.items.[0])' | sort | uniq) ALL_CLUSTER_NETTAGS=$(join_by , ${ALL_CLUSTER_NETTAGS}) gcloud compute firewall-rules create istio-multicluster-test-pods \ --allow=tcp,udp,icmp,esp,ah,sctp \ --direction=INGRESS \ --priority=900 \ --source-ranges="${ALL_CLUSTER_CIDRS}" \ --target-tags="${ALL_CLUSTER_NETTAGS}" --quiet fi } function unsetup_clusters() { # use current-context if pilot_cluster not set PILOT_CLUSTER="${PILOT_CLUSTER:-$(kubectl config current-context)}" unset IFS k_contexts=$(kubectl config get-contexts -o name) for context in ${k_contexts}; do kubectl config use-context ${context} kubectl delete clusterrolebinding prow-cluster-admin-binding 2>/dev/null if [[ "${SETUP_CLUSTERREG}" == "True" && "${PILOT_CLUSTER}" != "$context" ]]; then kubectl delete clusterrolebinding istio-multi-test 2>/dev/null kubectl delete ns ${SA_NAMESPACE} 2>/dev/null fi done kubectl config use-context ${PILOT_CLUSTER} if [[ "${USE_GKE}" == "True" && "${SETUP_CLUSTERREG}" == "True" ]]; then gcloud compute firewall-rules delete istio-multicluster-test-pods --quiet fi }
import express from 'express'; const route = express.Router(); import cheerio from 'cheerio'; import dayjs from 'dayjs'; dayjs.locale('ko'); import getHTML from '../functions/getHTML.js'; function getDayCount(user){ return new Promise((resolve, reject) => { getHTML(req.params.user) .then((html) => { const $ = cheerio.load(html.data); let daycount = 0; $(`rect[data-date="${dayjs().format('YYYY-MM-DD')}"].ContributionCalendar-day`) .each(function(){ daycount += Number($(this).attr("data-count")) }) resolve(daycount); }) }) } route.get("/:user/daycount", async function(req, res){ const daycount = await getDayCount(req.params.user); res.json(daycount); }) export default route;
package pir import ( "math" "math/rand" "testing" "time" "github.com/ncw/gmp" "github.com/sachaservan/paillier" ) func setup() { rand.Seed(time.Now().Unix()) } // run with 'go test -v -run TestSharedQuery' to see log outputs. func TestSharedQuery(t *testing.T) { setup() db := GenerateRandomDB(TestDBSize, SlotBytes) for groupSize := MinGroupSize; groupSize < MaxGroupSize; groupSize++ { dimWidth := groupSize dimHeight := int(math.Ceil(float64(TestDBSize / dimWidth))) for i := 0; i < NumQueries; i++ { qIndex := rand.Intn(dimHeight) shares := db.NewIndexQueryShares(qIndex, groupSize, 2) resA, err := db.PrivateSecretSharedQuery(shares[0], NumProcsForQuery) if err != nil { t.Fatalf("%v", err) } resB, err := db.PrivateSecretSharedQuery(shares[1], NumProcsForQuery) if err != nil { t.Fatalf("%v", err) } resultShares := [...]*SecretSharedQueryResult{resA, resB} res := Recover(resultShares[:]) for j := 0; j < dimWidth; j++ { index := int(qIndex)*dimWidth + j if index >= db.DBSize { break } if !db.Slots[index].Equal(res[j]) { t.Fatalf( "Query result is incorrect. %v != %v\n", db.Slots[index], res[j], ) } t.Logf("Slot %v, is %v\n", j, res[j]) } } } } // run with 'go test -v -run TestEncryptedQuery' to see log outputs. func TestEncryptedQuery(t *testing.T) { setup() sk, pk := paillier.KeyGen(128) for slotBytes := 1; slotBytes < SlotBytes; slotBytes += SlotBytesStep { db := GenerateRandomDB(TestDBSize, SlotBytes) for groupSize := MinGroupSize; groupSize < MaxGroupSize; groupSize++ { dimWidth, dimHeight := db.GetDimentionsForDatabase(TestDBHeight, groupSize) for i := 0; i < NumQueries; i++ { qIndex := rand.Intn(dimHeight) query := db.NewEncryptedQuery(pk, groupSize, qIndex) response, err := db.PrivateEncryptedQuery(query, NumProcsForQuery) if err != nil { t.Fatalf("%v", err) } res := RecoverEncrypted(response, sk) if len(res)%groupSize != 0 { t.Fatalf("Response size is not a multiple of DBGroupSize") } for j := 0; j < dimWidth; j++ { index := qIndex*dimWidth + j if index >= db.DBSize { break } if !db.Slots[index].Equal(res[j]) { t.Fatalf( "Query result is incorrect. %v != %v\n", db.Slots[index], res[j], ) } } } } } } func TestEncryptedNullQuery(t *testing.T) { setup() sk, pk := paillier.KeyGen(128) for slotBytes := 1; slotBytes < SlotBytes; slotBytes += SlotBytesStep { db := GenerateRandomDB(TestDBSize, SlotBytes) for groupSize := MinGroupSize; groupSize < MaxGroupSize; groupSize++ { dimWidth, _ := db.GetDimentionsForDatabase(TestDBHeight, groupSize) for i := 0; i < NumQueries; i++ { qIndex := -1 query := db.NewEncryptedQuery(pk, groupSize, qIndex) response, err := db.PrivateEncryptedQuery(query, NumProcsForQuery) if err != nil { t.Fatalf("%v", err) } res := RecoverEncrypted(response, sk) if len(res)%groupSize != 0 { t.Fatalf("Response size is not a multiple of DBGroupSize") } emptySlot := NewEmptySlot(len(res[0].Data)) for j := 0; j < dimWidth; j++ { if !emptySlot.Equal(res[j]) { t.Fatalf( "Null query incorrect for group size %v. %v != %v\n", groupSize, emptySlot, res[j], ) } } } } } } func TestDoublyEncryptedNullQuery(t *testing.T) { setup() sk, pk := paillier.KeyGen(126) for slotBytes := 1; slotBytes < SlotBytes; slotBytes += SlotBytesStep { db := GenerateRandomDB(TestDBSize, SlotBytes) for groupSize := MinGroupSize; groupSize < MaxGroupSize; groupSize++ { for i := 0; i < NumQueries; i++ { query := db.NewDoublyEncryptedNullQuery(pk, groupSize) response, err := db.PrivateDoublyEncryptedQuery(query, NumProcsForQuery) if err != nil { t.Fatalf("%v", err) } res := RecoverDoublyEncrypted(response, sk) emptySlot := NewEmptySlot(len(res[0].Data)) for col := 0; col < groupSize; col++ { if !emptySlot.Equal(res[col]) { t.Fatalf( "Null query incorrect. %v != %v\n", emptySlot, res[col], ) } } } } } } // run with 'go test -v -run TestDoublyEncryptedQuery' to see log outputs. func TestDoublyEncryptedQuery(t *testing.T) { setup() sk, pk := paillier.KeyGen(128) for slotBytes := 1; slotBytes < SlotBytes; slotBytes += SlotBytesStep { db := GenerateRandomDB(TestDBSize, SlotBytes) for groupSize := MinGroupSize; groupSize < MaxGroupSize; groupSize++ { dimWidth, dimHeight := db.GetDimentionsForDatabase(TestDBHeight, groupSize) // make sure the database width and height are not ridiculous // (allow for up to 1 extra row) if dimWidth*dimHeight > db.DBSize+dimWidth { t.Fatalf( "Dimensions are incorrect. width = %v heigh = %v group size = %v (%v > %v)\n", dimWidth, dimHeight, groupSize, dimWidth*dimHeight, db.DBSize, ) } for i := 0; i < NumQueries; i++ { // select a random group qIndex := int(rand.Intn(dimWidth*dimHeight) / groupSize) query := db.NewDoublyEncryptedQuery(pk, groupSize, qIndex) if len(query.Col.EBits) > (dimWidth / groupSize) { t.Fatalf( "Query consists of %v encrypted bits for a db width of %v\n", len(query.Col.EBits), (query.Col.DBWidth / groupSize), ) } response, err := db.PrivateDoublyEncryptedQuery(query, NumProcsForQuery) if err != nil { t.Fatalf("%v", err) } res := RecoverDoublyEncrypted(response, sk) rowIndex, colIndex := db.IndexToCoordinates(qIndex, dimWidth, dimHeight) colIndex = int(colIndex / groupSize) for j := 0; j < groupSize; j++ { index := rowIndex*dimWidth + colIndex*groupSize + j if index >= db.DBSize { break } if !db.Slots[index].Equal(res[j]) { t.Fatalf( "Query result is incorrect. %v != %v\n", db.Slots[index], res[j], ) } } } } } } func BenchmarkBuildDB(b *testing.B) { setup() // benchmark index build time for i := 0; i < b.N; i++ { GenerateRandomDB(BenchmarkDBSize, SlotBytes) } } func BenchmarkQuerySecretShares(b *testing.B) { setup() db := GenerateRandomDB(BenchmarkDBSize, SlotBytes) queryA := db.NewIndexQueryShares(0, 1, 2)[0] b.ResetTimer() // benchmark index build time for i := 0; i < b.N; i++ { _, err := db.PrivateSecretSharedQuery(queryA, NumProcsForQuery) if err != nil { panic(err) } } } func BenchmarkQuerySecretSharesSingleThread(b *testing.B) { setup() db := GenerateEmptyDB(BenchmarkDBSize, SlotBytes) queryA := db.NewIndexQueryShares(0, 1, 2)[0] b.ResetTimer() // benchmark index build time for i := 0; i < b.N; i++ { _, err := db.PrivateSecretSharedQuery(queryA, 1) if err != nil { panic(err) } } } func BenchmarkQuerySecretSharesSingle8Thread(b *testing.B) { setup() db := GenerateEmptyDB(BenchmarkDBSize, SlotBytes) queryA := db.NewIndexQueryShares(0, 1, 2)[0] b.ResetTimer() // benchmark index build time for i := 0; i < b.N; i++ { _, err := db.PrivateSecretSharedQuery(queryA, 8) if err != nil { panic(err) } } } func BenchmarkGenEncryptedQuery(b *testing.B) { setup() _, pk := paillier.KeyGen(1024) db := GenerateRandomDB(BenchmarkDBSize, SlotBytes) b.ResetTimer() // benchmark index build time for i := 0; i < b.N; i++ { db.NewEncryptedQuery(pk, 1, 0) } } func BenchmarkGenDoublyEncryptedQuery(b *testing.B) { setup() _, pk := paillier.KeyGen(1024) db := GenerateRandomDB(BenchmarkDBSize, SlotBytes) b.ResetTimer() // benchmark index build time for i := 0; i < b.N; i++ { db.NewDoublyEncryptedNullQuery(pk, 1) } } func BenchmarkEncryptedQueryAHESingleThread(b *testing.B) { setup() _, pk := paillier.KeyGen(1024) db := GenerateEmptyDB(BenchmarkDBSize, SlotBytes) query := db.NewEncryptedQuery(pk, 1, 0) b.ResetTimer() for i := 0; i < b.N; i++ { _, err := db.PrivateEncryptedQuery(query, 1) if err != nil { panic(err) } } } func BenchmarkEncryptedQueryAHE8Thread(b *testing.B) { setup() _, pk := paillier.KeyGen(1024) db := GenerateEmptyDB(BenchmarkDBSize, SlotBytes) query := db.NewEncryptedQuery(pk, 1, 0) b.ResetTimer() for i := 0; i < b.N; i++ { _, err := db.PrivateEncryptedQuery(query, 8) if err != nil { panic(err) } } } func BenchmarkRecursiveEncryptedQueryAHESingleThread(b *testing.B) { setup() _, pk := paillier.KeyGen(1024) db := GenerateRandomDB(BenchmarkDBSize, SlotBytes) query := fakeDoublyEncryptedQuery(pk, db.DBSize) b.ResetTimer() for i := 0; i < b.N; i++ { _, err := db.PrivateDoublyEncryptedQuery(query, 1) if err != nil { panic(err) } } } func BenchmarkRecursiveEncryptedQueryAHE8Thread(b *testing.B) { setup() _, pk := paillier.KeyGen(1024) db := GenerateEmptyDB(BenchmarkDBSize, SlotBytes) query := fakeDoublyEncryptedQuery(pk, db.DBSize) b.ResetTimer() for i := 0; i < b.N; i++ { _, err := db.PrivateDoublyEncryptedQuery(query, 2) if err != nil { panic(err) } } } // generates a "fake" PIR query to avoid costly randomness computation (useful for benchmarking query processing) func fakeDoublyEncryptedQuery(pk *paillier.PublicKey, dbSize int) *DoublyEncryptedQuery { zero := gmp.NewInt(0) one := gmp.NewInt(1) rand := pk.EncryptZero().C // hack to get random number // compute sqrt dimentions height := int(math.Ceil(math.Sqrt(float64(dbSize)))) width := height rowIndex := 0 colIndex := 0 row := make([]*paillier.Ciphertext, height) for i := 0; i < height; i++ { if i == rowIndex { row[i] = pk.EncryptWithR(one, rand) } else { row[i] = pk.EncryptWithR(zero, rand) } } col := make([]*paillier.Ciphertext, width) for i := 0; i < width; i++ { if i == colIndex { col[i] = pk.EncryptWithRAtLevel(one, rand, paillier.EncLevelTwo) } else { col[i] = pk.EncryptWithRAtLevel(zero, rand, paillier.EncLevelTwo) } } rowQuery := &EncryptedQuery{ Pk: pk, EBits: row, GroupSize: 1, DBWidth: width * 1, DBHeight: height, } colQuery := &EncryptedQuery{ Pk: pk, EBits: col, GroupSize: 1, DBWidth: width, DBHeight: height, } return &DoublyEncryptedQuery{ Row: rowQuery, Col: colQuery, } }
package com.watayouxiang.mediaplayer.core; public enum Orientation { /** * 竖屏 */ Portrait, /** * 竖屏反向 */ Portrait_Reverse, /** * 横屏 */ Landscape, /** * 横屏反向 */ Landscape_Reverse }
#!/bin/bash source "./helpers.bash" set -e TEST_NET="cilium" function cleanup { gather_files 01-ct ${TEST_SUITE} docker rm -f server client httpd1 httpd2 curl curl2 2> /dev/null || true monitor_stop } trap cleanup EXIT cleanup monitor_start logs_clear docker network inspect $TEST_NET 2> /dev/null || { docker network create --ipv6 --subnet ::1/112 --ipam-driver cilium --driver cilium $TEST_NET } docker run -dt --net=$TEST_NET --name server -l id.server tgraf/netperf docker run -dt --net=$TEST_NET --name httpd1 -l id.httpd httpd docker run -dt --net=$TEST_NET --name httpd2 -l id.httpd_deny httpd docker run -dt --net=$TEST_NET --name client -l id.client tgraf/netperf docker run -dt --net=$TEST_NET --name curl -l id.curl tgraf/netperf docker run -dt --net=$TEST_NET --name curl2 -l id.curl tgraf/netperf wait_for_endpoints 6 CLIENT_IP=$(docker inspect --format '{{ .NetworkSettings.Networks.cilium.GlobalIPv6Address }}' client) CLIENT_IP4=$(docker inspect --format '{{ .NetworkSettings.Networks.cilium.IPAddress }}' client) CLIENT_ID=$(cilium endpoint list | grep id.client | awk '{ print $1}') SERVER_IP=$(docker inspect --format '{{ .NetworkSettings.Networks.cilium.GlobalIPv6Address }}' server) SERVER_IP4=$(docker inspect --format '{{ .NetworkSettings.Networks.cilium.IPAddress }}' server) SERVER_ID=$(cilium endpoint list | grep id.server | awk '{ print $1}') HTTPD1_IP=$(docker inspect --format '{{ .NetworkSettings.Networks.cilium.GlobalIPv6Address }}' httpd1) HTTPD1_IP4=$(docker inspect --format '{{ .NetworkSettings.Networks.cilium.IPAddress }}' httpd1) HTTPD2_IP=$(docker inspect --format '{{ .NetworkSettings.Networks.cilium.GlobalIPv6Address }}' httpd2) HTTPD2_IP4=$(docker inspect --format '{{ .NetworkSettings.Networks.cilium.IPAddress }}' httpd2) set -x cilium endpoint list cat <<EOF | policy_import_and_wait - [{ "endpointSelector": {"matchLabels":{"id.curl":""}}, "egress": [{ "toPorts": [{ "ports": [{"port": "80", "protocol": "tcp"}] }] }], "labels": ["id=curl"] },{ "endpointSelector": {"matchLabels":{"id.server":""}}, "ingress": [{ "fromEndpoints": [ {"matchLabels":{"reserved:host":""}}, {"matchLabels":{"id.client":""}} ] }], "labels": ["id=server"] },{ "endpointSelector": {"matchLabels":{"id.httpd":""}}, "ingress": [{ "fromEndpoints": [ {"matchLabels":{"id.curl":""}} ], "toPorts": [ {"ports": [{"port": "80", "protocol": "tcp"}]} ] }], "labels": ["id=httpd"] },{ "endpointSelector": {"matchLabels":{"id.httpd":""}}, "ingress": [{ "fromEndpoints": [ {"matchLabels":{"id.curl2":""}} ], "toPorts": [ {"ports": [{"port": "8080", "protocol": "tcp"}]} ] }], "labels": ["id=httpd"] },{ "endpointSelector": {"matchLabels":{"id.httpd_deny":""}}, "ingress": [{ "fromEndpoints": [ {"matchLabels":{"id.curl":""}} ], "toPorts": [ {"ports": [{"port": "9090", "protocol": "tcp"}]} ] }], "labels": ["id=httpd_deny"] }] EOF wait_for_endpoints 6 function connectivity_test() { monitor_clear docker exec -i curl bash -c "curl --connect-timeout 5 -XGET http://[$HTTPD1_IP]:80" || { abort "Error: Could not reach httpd1 on port 80" } monitor_clear docker exec -i curl bash -c "curl --connect-timeout 5 -XGET http://$HTTPD1_IP4:80" || { abort "Error: Could not reach httpd1 on port 80" } # FIXME(amre): Change following two expectations to the opposite when Issue #789 is fixed monitor_clear docker exec -i curl2 bash -c "curl --connect-timeout 5 -XGET http://[$HTTPD1_IP]:80" || { abort "Error: Could not reach httpd1 on port 80" } monitor_clear docker exec -i curl2 bash -c "curl --connect-timeout 5 -XGET http://$HTTPD1_IP4:80" || { abort "Error: Could not reach httpd1 on port 80" } monitor_clear docker exec -i curl bash -c "curl --connect-timeout 5 -XGET http://[$HTTPD2_IP]:80" && { abort "Error: Unexpected success reaching httpd2 on port 80" } monitor_clear docker exec -i curl bash -c "curl --connect-timeout 5 -XGET http://$HTTPD2_IP4:80" && { abort "Error: Unexpected success reaching httpd2 on port 80" } # ICMPv6 echo request client => server should succeed monitor_clear docker exec -i client ping6 -c 5 $SERVER_IP || { abort "Error: Could not ping server container from client" } if [ $SERVER_IP4 ]; then # ICMPv4 echo request client => server should succeed monitor_clear docker exec -i client ping -c 5 $SERVER_IP4 || { abort "Error: Could not ping server container from client" } fi # ICMPv6 echo request host => server should succeed monitor_clear ping6 -c 5 $SERVER_IP || { abort "Error: Could not ping server container from host" } if [ $SERVER_IP4 ]; then # ICMPv4 echo request host => server should succeed monitor_clear ping -c 5 $SERVER_IP4 || { abort "Error: Could not ping server container from host" } fi # FIXME: IPv4 host connectivity not working yet if [ $BIDIRECTIONAL = 1 ]; then # ICMPv6 echo request server => client should not succeed monitor_clear docker exec -i server ping6 -c 2 $CLIENT_IP && { abort "Error: Unexpected success of ICMPv6 echo request" } if [ $CLIENT_IP4 ]; then # ICMPv4 echo request server => client should not succeed monitor_clear docker exec -i server ping -c 2 $CLIENT_IP4 && { abort "Error: Unexpected success of ICMPv4 echo request" } fi fi # TCP request to closed port should fail monitor_clear docker exec -i client nc -w 5 $SERVER_IP 777 && { abort "Error: Unexpected success of TCP IPv6 session to port 777" } if [ $SERVER_IP4 ]; then # TCP request to closed port should fail monitor_clear docker exec -i client nc -w 5 $SERVER_IP4 777 && { abort "Error: Unexpected success of TCP IPv4 session to port 777" } fi # TCP client=>server should succeed monitor_clear docker exec -i client netperf -l 3 -t TCP_RR -H $SERVER_IP || { abort "Error: Unable to reach netperf TCP IPv6 endpoint" } if [ $SERVER_IP4 ]; then # TCP client=>server should succeed monitor_clear docker exec -i client netperf -l 3 -t TCP_RR -H $SERVER_IP4 || { abort "Error: Unable to reach netperf TCP IPv4 endpoint" } fi # FIXME: Need shorter timeout # TCP server=>client should not succeed #docker exec -i server netperf -l 3 -t TCP_RR -H $CLIENT_IP && { # abort "Error: Unexpected success of TCP netperf session" #} # UDP client=server should succeed monitor_clear docker exec -i client netperf -l 3 -t UDP_RR -H $SERVER_IP || { abort "Error: Unable to reach netperf TCP IPv6 endpoint" } if [ $SERVER_IP4 ]; then # UDP client=server should succeed monitor_clear docker exec -i client netperf -l 3 -t UDP_RR -H $SERVER_IP4 || { abort "Error: Unable to reach netperf TCP IPv4 endpoint" } fi # FIXME: Need shorter timeout # TCP server=>client should not succeed #docker exec -i server netperf -l 3 -t UDP_RR -H $CLIENT_IP && { # abort "Error: Unexpected success of UDP netperf session" #} } BIDIRECTIONAL=1 connectivity_test cilium endpoint config $SERVER_ID ConntrackLocal=true || { abort "Error: Unable to change config for $SERVER_ID" } cilium endpoint config $CLIENT_ID ConntrackLocal=true || { abort "Error: Unable to change config for $CLIENT_ID" } connectivity_test cilium endpoint config $SERVER_ID ConntrackLocal=false || { abort "Error: Unable to change config for $SERVER_ID" } cilium endpoint config $CLIENT_ID ConntrackLocal=false || { abort "Error: Unable to change config for $CLIENT_ID" } connectivity_test cilium endpoint config $SERVER_ID Conntrack=false || { abort "Error: Unable to change config for $SERVER_ID" } cilium endpoint config $CLIENT_ID Conntrack=false || { abort "Error: Unable to change config for $CLIENT_ID" } wait_for_endpoints 6 BIDIRECTIONAL=0 connectivity_test entriesBefore=$(sudo cilium bpf ct list global | wc -l) policy_delete_and_wait id=httpd # FIXME: Disabled for now, need a reliable way to know when this happened as it occurs async #entriesAfter=$(sudo cilium bpf ct list global | wc -l) #if [ "${entriesAfter}" -eq 0 ]; then # abort "CT map should not be empty" #elif [ "${entriesBefore}" -le "${entriesAfter}" ]; then # abort "some of the CT entries should have been removed after policy change" #fi cilium policy delete --all
<reponame>andrewvo89/tempnote<filename>firebase/functions/src/scheduled-functions/index.ts<gh_stars>1-10 import Firebase from '../utils/firebase'; import Firestore from '../utils/firestore'; import Note from '../models/note'; import Statistic from '../models/statistic'; import functions = require('firebase-functions'); /** At 11:55pm GMT time every day create a new record for the next day's statistic document */ export const createStatisticsDocument = functions .runWith(Firebase.getRuntimeOptions()) .pubsub.schedule('every day 23:55') .onRun(async () => { const statistic = new Statistic(); await statistic.create(); }); /** At second :00, at minute :00, every hour starting at 00am, of every day */ export const deleteExpiredNotes = functions .runWith(Firebase.getRuntimeOptions()) .pubsub.schedule('every 1 hours from 00:00 to 23:59') .onRun(async () => { // Get any note with expiry date prior to now const notes = await Note.getExpired(); const promises = []; // Start a new firestore batch let batch = Firestore.getBatch(); let count = 0; // Loop through all expired notes and add each one to batch for (const note of notes) { batch.delete(note.getDocRef()); count++; if (count === 500) { promises.push(batch.commit()); batch = Firestore.getBatch(); count = 0; } } promises.push(batch.commit()); // Perform all batch commits in parrallel await Promise.all(promises); });
<gh_stars>0 /* * Jira Ticket: * Created Date: Wed, 9th Dec 2020, 08:09:21 am * Author: <NAME> * Email: <EMAIL> * Copyright (c) 2020 The Distance */ import React, {useState} from 'react'; import {View, Platform, Text, ActivityIndicator} from 'react-native'; import {ScaleHook} from 'react-native-design-to-component'; import {useNavigation} from '@react-navigation/native'; import {useRoute} from '@react-navigation/core'; import useTheme from '../../hooks/theme/UseTheme'; import {TDAddPhoto} from 'the-core-ui-module-tdslideshow'; import useDictionary from '../../hooks/localisation/useDictionary'; import CustomCountdown from '../../components/Buttons/CustomCountdown'; import Header from '../../components/Headers/Header'; import {request, PERMISSIONS, RESULTS} from 'react-native-permissions'; import ImagePicker from 'react-native-image-crop-picker'; import {useMutation} from '@apollo/client'; import UploadProgressImage from '../../apollo/mutations/UploadProgressImage'; import ConfirmUploadProgressImage from '../../apollo/mutations/ConfirmUploadProgressImage'; import RNFetchBlob from 'rn-fetch-blob'; import useProgressData from '../../hooks/data/useProgressData'; import displayAlert from '../../utils/DisplayAlert'; import useInterval from '../../utils/useInterval'; import format from 'date-fns/format'; import * as R from 'ramda'; const cameraButton = require('../../../assets/icons/cameraButton.png'); const cameraFadedButton = require('../../../assets/images/cameraFadedButton.png'); const overlay = require('../../../assets/images/cameraPerson.png'); const countdown0 = require('../../../assets/images/countdown0s.png'); const countdown5 = require('../../../assets/images/countdown5s.png'); const countdown10 = require('../../../assets/images/countdown10s.png'); export default function TransformationScreen() { // ** ** ** ** ** SETUP ** ** ** ** ** const {getHeight, fontSize} = ScaleHook(); const {colors, textStyles} = useTheme(); const [loading, setLoading] = useState(false); const {dictionary} = useDictionary(); const {ProgressDict} = dictionary; const {getImages, addProgressImage} = useProgressData(); const navigation = useNavigation(); const { params: {alreadyExists = false}, } = useRoute(); navigation.setOptions({ header: () => ( <Header title={ProgressDict.Upload} goBack right="photoSelectIcon" rightAction={loading ? () => {} : handleSelectPhoto} /> ), }); const [requestUploadUrl] = useMutation(UploadProgressImage); const [confirmUpload] = useMutation(ConfirmUploadProgressImage); const [time, setTime] = useState(0); // ** ** ** ** ** STYLES ** ** ** ** ** const styles = { container: { height: '100%', width: '100%', backgroundColor: colors.backgroundWhite100, }, overlay: { height: '100%', width: '100%', top: getHeight(-50), resizeMode: 'cover', }, countDownStyle: { ...textStyles.bold30_white100, fontSize: fontSize(55), lineHeight: fontSize(60), }, }; // ** ** ** ** ** FUNCTIONS ** ** ** ** ** async function handlePhoto(path, contentType) { setLoading(true); const newPath = Platform.OS === 'android' ? path : path.replace('file://', 'private'); // Check file size const validSize = await RNFetchBlob.fs .stat(newPath) .then((stats) => { const {size} = stats; if (size) { console.log('Image size in MB: ', size / 1000000); const limit = 1000000 * 20; // 20MB in bytes return size <= limit; } }) .catch((err) => { console.log(err, '<---requestUrl err'); displayAlert({text: ProgressDict.UploadFailed}); setLoading(false); return false; }); if (!validSize) { console.log('Image size exceeds limit'); displayAlert({text: ProgressDict.TooLargeSizeImage}); setLoading(false); return; } // Request upload url const requestInput = { contentType: contentType, takenOn: format(new Date().setHours(0, 0, 0, 0), 'yyyy-MM-dd'), }; const uploadUrlRes = await requestUploadUrl({ variables: { input: requestInput, }, }).catch((err) => { console.log(err, '<---requestUrl err'); displayAlert({text: ProgressDict.UploadFailed}); setLoading(false); return; }); if ( !uploadUrlRes || !uploadUrlRes.data || !uploadUrlRes.data.uploadProgressImage ) { return; } const {uploadUrl, token} = uploadUrlRes.data.uploadProgressImage; // Initialize upload RNFetchBlob.fetch( 'PUT', uploadUrl, {'Content-Type': contentType}, RNFetchBlob.wrap(newPath), ) .uploadProgress((written, total) => { console.log('uploaded', written / total); }) .then(async (res) => { let {status} = res.info(); if (status === 200 || status === 204) { console.log('Upload done --- SUCCESS'); confirmUpload({ variables: { input: { token: token, }, }, }) .then(async (confirmRes) => { console.log('confirmUpload', confirmRes); const {success, progressImage} = R.path( ['data', 'confirmUploadProgressImage'], confirmRes, ); if (success) { await addProgressImage(progressImage, alreadyExists); navigation.goBack(); setLoading(false); } else { handleAddPhotoError(); } }) .catch((err) => { handleAddPhotoError(); }); } else { console.log('Upload failed', res); handleAddPhotoError(); } }) .catch((err) => { console.log(err, '<---fetch blob err'); handleAddPhotoError(); }); } async function handleAddPhotoError() { displayAlert({text: ProgressDict.UploadFailed}); setLoading(false); } function handleSelectPhoto() { setLoading(true); request( Platform.select({ ios: PERMISSIONS.IOS.PHOTO_LIBRARY, android: PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE, }), ) .then((result) => { if (result !== RESULTS.GRANTED) { setLoading(false); } if (result === RESULTS.UNAVAILABLE) { displayAlert({text: ProgressDict.FunctionNotAvailable}); } if (result === RESULTS.BLOCKED) { displayAlert({text: ProgressDict.NoCamera}); } if (result === RESULTS.GRANTED) { // compression rates tested: // Android 0.92 compressed 12.6MB --> 8.8MB about 70% // IOS 0.99 compressed 7.7MB -> 3.6MB about 46% ImagePicker.openPicker({ mediaType: 'photo', compressImageQuality: Platform.OS === 'android' ? 0.92 : 0.99, forceJpg: true, }) .then((cameraPhoto) => { const {path, mime} = cameraPhoto; handlePhoto(path, mime); }) .catch(() => { displayAlert({text: ProgressDict.UploadFailed}); setLoading(false); }); } }) .catch((err) => { console.log(err); setLoading(false); }); } const LoadingView = () => ( <View style={{ width: 50, height: 50, alignSelf: 'center', position: 'absolute', top: '40%', }}> <ActivityIndicator size={'large'} color={colors.blueGreen100} /> </View> ); // ** ** ** ** ** RENDER ** ** ** ** ** return ( <> <View style={styles.container}> <TDAddPhoto setPhoto={handlePhoto} overlayImage={overlay} overlayStyles={styles.overlay} CustomCountdown={() => <CustomCountdown time={time} />} CountdownTime={time} cameraButtonImage={cameraButton} cameraFadedButton={cameraFadedButton} backgroundColor={colors.backgroundWhite100} countdown0={countdown0} countdown5={countdown5} countdown10={countdown10} setTime={setTime} setLoading={setLoading} cameraEnabled={!loading} countDownStyle={styles.countDownStyle} CountDownView={() => ( <CountDownView time={time > 0 ? time / 1000 : 0} countDownStyle={styles.countDownStyle} /> )} /> {loading && LoadingView()} </View> </> ); } function CountDownView({time, countDownStyle}) { const [seconds, setSeconds] = useState(time); useInterval(() => { if (seconds > 0) { setSeconds(seconds - 1); } }, 1000); return ( <> {seconds > 0 && ( <View style={{ height: '100%', position: 'absolute', alignSelf: 'center', justifyContent: 'center', }}> <Text style={countDownStyle}>{seconds}</Text> </View> )} </> ); }
import { Injectable } from '@angular/core'; import { DataLayerRule, DataLayerConfig, DataLayerObserver, LogEvent, LogAppender, OperatorOptions, DataLayerTarget } from '@fullstory/data-layer-observer'; import { Subject } from 'rxjs'; import { DataLayerService } from './datalayer.service'; class ComposerAppender implements LogAppender { constructor(private subject: Subject<LogEvent>) { } log(event: LogEvent): void { this.subject.next(event); } } @Injectable({ providedIn: 'root' }) export class ObserverService { log$ = new Subject<LogEvent>(); output$ = new Subject<any[]>(); registered$ = new Subject<DataLayerRule>(); config: DataLayerConfig = { appender: new ComposerAppender(this.log$), // beforeDestination: { name: 'suffix' }, // @ts-ignore previewDestination: (...data: any[]) => { this.output$.next(data); }, previewMode: false, readOnLoad: true, rules: [], validateRules: true }; private observer: DataLayerObserver; constructor() { this.observer = new DataLayerObserver(this.config); } test(target: DataLayerTarget, options: OperatorOptions[], cb: (data: any) => void, debug?: boolean) { const handler = this.observer.registerTarget(target, options, cb, true, false, debug); this.observer.removeHandler(handler); } registerRule(rule: DataLayerRule) { const count = this.observer.handlers.length; this.observer.registerRule(rule); if (this.observer.handlers.length > count) { this.registered$.next(rule); } } fireEvents() { this.observer.handlers.forEach(handler => { handler.fireEvent(''); }); } }
$.ajaxSetup({ headers:{ 'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content') } }); function RemoveRow(id, url){ if(confirm('Xoa cai nay??')){ $.ajax({ type: 'DELETE', datatype: 'JSON', data: {id}, url:url, success: function(result){ if(result.error === false){ alert(result.message); location.reload(); }else{ alert('Delete Errorrrrr'); } } }); } } function ChangeCate(id, url){ $.ajax({ type: 'POST', datatype: 'JSON', data: {id}, url: url, success: function(result){ if(result.error == false){ location.reload(); }else{ alert('We got error when load by Cate sirrr...'); } } }); } function AddCart(id){ $.ajax({ type: 'GET', url: '/shopping/cart/add/' + id, success: function(response){ $("#changeable-list-cart").empty(); $("#changeable-list-cart").html(response); console.log('Success'); location.reload(); }, fail: function(){ console.log('failed'); } }); } function ClearCart(){ $.ajax({ type: 'GET', url: '/shopping/cart/clear', success: function(response){ $("#changeable-list-cart").empty(); $("#changeable-list-cart").html(response); console.log('Success'); location.reload(); }, fail: function(){ console.log('failed'); } }); } $("#changeable-list-cart").on("click", ".si-close i", function(){ $.ajax({ type: 'GET', url: '/shopping/cart/delete/' + $(this).data("id"), success: function(response){ $("#changeable-list-cart").empty(); $("#changeable-list-cart").html(response); console.log('Success'); location.reload(); },fail: function(){ console.log('failed'); } }); });
<filename>src/main/java/pe/com/optical/middleware/crm/repository/TipoRepository.java package pe.com.optical.middleware.crm.repository; import java.util.List; import pe.com.optical.middleware.crm.domain.TipoBE; public interface TipoRepository extends BaseRepository<TipoBE, Long> { List<TipoBE> obtenerTiposPorConcepto(String codigoConcepto); List<TipoBE> obtenerTipoMotivosAnulacionTareaPostVenta(); TipoBE obtenerTipoMotivoAnulacionTareaPostVenta(String codigoEstado); List<TipoBE> obtenerTipoMotivosCerradoPerdido(); TipoBE obtenerTipoMotivoCerradoPerdido(String codigoEstado); List<TipoBE> obtenerEstadosTareaPostVenta(); TipoBE obtenerEstadoTareaPostVenta(String codigoEstado); List<TipoBE> obtenerEstadosOportunidades(); TipoBE obtenerEstadoOportunidad(String codigoEstado); List<TipoBE> obtenerTipoPeriodos(); TipoBE obtenerTipoPeriodo(String codigoPeriodo); List<TipoBE> obtenerEstadosComerciales(); TipoBE obtenerEstadoComercial(String codigoEstado); List<TipoBE> obtenerEstadosOperativos(); TipoBE obtenerEstadoOperativo(String codigoEstado); List<TipoBE> obtenerEstadosServiciosVentas(); TipoBE obtenerEstadoServicioVenta(String codigoEstado); List<TipoBE> obtenerEstadosDocumentos(); TipoBE obtenerEstadoDocumento(String codigoEstado); }
#!/usr/bin/env bash RED=`tput setaf 1` GREEN=`tput setaf 2` YELLOW=`tput setaf 3` NOCOLOR=`tput sgr0` BASEDIR=$(dirname "$0") module_name=$1 module_package_name=$2 SOURCE=./$BASEDIR/template DEST=./$BASEDIR/../../${module_name} cp -r ${SOURCE} ${DEST} find $DEST -name '*.*' -exec sed -i -e "s/#module_name/$module_name/g" {} \; find $DEST -name '*.*' -exec sed -i -e "s/#module_package_name/$module_package_name/g" {} \; find $DEST -name '*-e' -exec rm {} + module_package_name=${module_package_name//./\/} mkdir -p $DEST/src/main/java/$module_package_name echo ${GREEN}${module_name}${NOCOLOR} with package name of ${GREEN}${module_package_name}${NOCOLOR} created successfully printf ", '${module_name}'" >> $DEST/../settings.gradle
#!/bin/bash cd weboob source env/bin/activate args=`while read x ; do echo $x ; done` python py/operations.py << EOF $args EOF
def parse_words(article): article_words = [] words = article.split() for word in words: if word not in article_words: article_words.append(word) return article_words article_words = parse_words(article) print(article_words)
arr = [2, 3, 2, 4, 5, 6, 2, 6] # Function to remove all duplicates def remove_duplicates(arr): unique_arr = [] for item in arr: if item not in unique_arr: unique_arr.append(item) return unique_arr unique_arr = remove_duplicates(arr) print("Array with all the duplicates removed is:",unique_arr)
#!/bin/bash # # Check the workstation configuration. # Autostart script for Text Workstation application consumes the exit code # from this script and launches (exit code 0) or does not launch # (exit code 1) the application. # # This is a temporary solution - when all the sites are off XTs this # script needs to be removed and the autostart simplified. # # Exit Code: # # 0 - if the workstation is an XT # - if the workstation is a new LX without a coupled XT # # 1 - if the workstation is an old LX # - if the workstation is a new LX with a coupled XT # - if the workstation is neither an LX nor a XT # if [ $(hostname | cut -c 1-2) = "xt" ]; then exit 0 fi if [ $(hostname | cut -c 1-2) = "lx" ]; then lxtype=$(dmesg | grep "^DMI:" | cut -d " " -f "4") ping -c 1 xt`hostname | cut -c 3-3` > /dev/null 2>&1 && hasxt=0 || hasxt=2 if [ $lxtype = "Z600" ]; then exit 1 elif [ $lxtype = "Z620" ] || [ $lxtype = "Z640" ]; then if [ $hasxt == 0 ]; then exit 1 else exit 0 fi fi else exit 1 fi
import LoadingBarClass from './loading-bar-instance'; interface IloadingBarConfig { color?: string, failedColor?: string, height?: number } class LoadingBar { private loadingBarInstance; private color: string = 'primary'; private failedColor: string = 'error'; private height: number = 2; private timer: any; constructor() { this.loadingBarInstance = LoadingBarClass.getInstance({ color: this.color, failedColor: this.failedColor, height: this.height }); } private clearTimer(): void { if (this.timer) { clearInterval(this.timer); this.timer = null; } } private hide(): void { setTimeout(() => { this.loadingBarInstance.update({ show: false }); setTimeout(() => { this.loadingBarInstance.update({ percent: 0 }); }, 200); }, 800); } public start(): void { if (this.timer) { return; } let percent = 0; this.loadingBarInstance.update({ percent, status: 'success', show: true }); this.timer = setInterval(() => { percent += Math.floor(Math.random () * 3 + 1); if (percent > 95) { this.clearTimer(); } this.loadingBarInstance.update({ percent, status: 'success', show: true }); }, 200); } public update(percent: number): void { this.clearTimer(); this.loadingBarInstance.update({ percent, status: 'success', show: true }); } public finish(): void { this.clearTimer(); this.loadingBarInstance.update({ percent: 100, }); this.hide(); } public error(): void { this.clearTimer(); this.loadingBarInstance.update({ percent: 100, status: 'error', show: true }); this.hide(); } public config(options: IloadingBarConfig): void { if (options.color) { this.color = options.color; } if (options.failedColor) { this.failedColor = options.failedColor; } if (options.height) { this.height = options.height; } this.destroy(); this.loadingBarInstance = LoadingBarClass.getInstance({ color: this.color, failedColor: this.failedColor, height: this.height }); } public destroy(): void { this.clearTimer(); this.loadingBarInstance.destroy(); this.loadingBarInstance = null; } } export default new LoadingBar();
SELECT COUNT(DISTINCT product_name) FROM products;
/* * Copyright 2016 <NAME> (<EMAIL>) * * 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.difference.historybook.proxy; import java.util.function.Predicate; /** * An abstract interface to a web proxy service */ public interface Proxy { /** * Start the web proxy service * * @throws Exception */ public void start() throws Exception; /** * Stop the web proxy service * * @throws Exception */ public void stop() throws Exception; /** * Specify the port to run the proxy server on. May not take affect until next start. * @param port port to run the proxy server on * @return this for method chaining */ public Proxy setPort(int port); /** * Specify a @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response * @param factory the @ProxyFilterFactory to use in creating @ProxyFilter instances for each proxy request/response * @return this for method call chaining */ public Proxy setFilterFactory(ProxyFilterFactory factory); /** * Specify a @Predicate to use to determine whether a @ProxyResponse will be required. * This is done early in the streaming of a response by peeking at the headers to determine * whether the content will need to be buffered and decompressed for use. * * @param selector a @Predicate that, given a @ProxyResponseInfo, determines whether a response should be buffered, decompressed, and passed to the filter for processing. * @return this for method call chaining */ public Proxy setResponseFilterSelector(Predicate<ProxyTransactionInfo> selector); }
<filename>test/fixtures/apps/rpc-server/config/config.default.js<gh_stars>1-10 'use strict'; exports.keys = 'rpc-server_1538293372835_2550'; exports.rpc = { server: { namespace: 'org.eggjs.dubbo', group: 'HSF', }, };
from typing import List def countDistinctIslands(grid: List[List[int]]) -> int: def dfs(grid, i, j, path, direction): if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] == 0: return '0' grid[i][j] = 0 path += direction path = dfs(grid, i+1, j, path, 'D') path = dfs(grid, i-1, j, path, 'U') path = dfs(grid, i, j+1, path, 'R') path = dfs(grid, i, j-1, path, 'L') return path + '0' distinct_islands = set() for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: island_shape = dfs(grid, i, j, '', 'X') distinct_islands.add(island_shape) return len(distinct_islands)
#!/usr/bin/env sh # # Copyright 2008 Amazon Technologies, Inc. # # Licensed under the Amazon Software License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://aws.amazon.com/asl # # This file 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. MTURK_CMD_HOME=${MTURK_CMD_HOME:-$(dirname "$0")/..} export MTURK_CMD_HOME exec "$MTURK_CMD_HOME"/bin/invoke.sh UpdateQualificationType "$@"
package org.tungsten.service.hastelloy.model; public class SpaceCraft { private String name; public SpaceCraft() { } public SpaceCraft(String name) { this.name = name; } public String getName() { return name; } }
<gh_stars>1-10 import { IWidget, IBalanceSettings, IBalanceFormSettings } from 'shared/types/models'; import { balanceSettingsFormEntry } from '../../../redux/reduxFormEntries'; import Settings from './Settings/Settings'; import { default as Content } from './Content/Content'; const widget: IWidget<IBalanceSettings, IBalanceFormSettings> = { Content, headerLeftPart: { kind: 'with-title' }, settingsForm: { Component: Settings, name: balanceSettingsFormEntry.name }, removable: true, titleI18nKey: 'WIDGETS:BALANCE-WIDGET-NAME', }; export default widget;
#!/bin/bash set -e RED="\033[0;31m" GREEN="\033[32m" NOCOLOR="\033[0m" genome_build=hg38 deploy_dir=${PWD}/temp log_file=${PWD}/INSTALL.log threads=1 setup_tabix_tools() { echo -e "${GREEN}=> Setup bgzip and tabix${NOCOLOR}" start_dir=${PWD} { cd ${deploy_dir} \ && wget https://github.com/samtools/htslib/releases/download/1.7/htslib-1.7.tar.bz2 \ && tar -xjvf htslib-1.7.tar.bz2 \ && cd htslib-1.7 \ && ./configure --prefix=${PWD} \ && make \ && make install; } >> ${log_file} 2>&1 if [ ! $? == 0 ]; then echo "Error occured! See ${log_file} for more details." exit 1 fi tabix=${PWD}/bin/tabix bgzip=${PWD}/bin/bgzip cd ${start_dir} } setup_ensembl_api() { echo -e "${GREEN}=> Setup BioPerl and Ensembl API${NOCOLOR}" start_dir=${PWD} { cd ${deploy_dir} \ && wget ftp://ftp.ensembl.org/pub/ensembl-api.tar.gz \ && wget https://cpan.metacpan.org/authors/id/C/CJ/CJFIELDS/BioPerl-1.6.1.tar.gz \ && tar -zxf ensembl-api.tar.gz \ && tar -zxf BioPerl-1.6.1.tar.gz; } >> ${log_file} 2>&1 if [ ! $? == 0 ]; then echo "Error occured! See ${log_file} for more details." exit 1 fi PERL5LIB=${PERL5LIB}:${PWD}/BioPerl-1.6.1 PERL5LIB=${PERL5LIB}:${PWD}/ensembl/modules PERL5LIB=${PERL5LIB}:${PWD}/ensembl-compara/modules PERL5LIB=${PERL5LIB}:${PWD}/ensembl-variation/modules PERL5LIB=${PERL5LIB}:${PWD}/ensembl-funcgen/modules export PERL5LIB cd ${start_dir} } download_GENCODE() { start_dir=${PWD} if [ "$genome_build" == "hg38" ]; then echo -e "${GREEN}=> Downloading GENCODE 27 for human genome version ${genome_build}${NOCOLOR}" url=ftp://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_human/release_27/gencode.v27.annotation.gtf.gz elif [ "$genome_build" == "hg19" ]; then echo -e "${GREEN}=> Downloading GENCODE 27 for human genome version ${genome_build}${NOCOLOR}" url=ftp://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_human/release_27/GRCh37_mapping/gencode.v27lift37.annotation.gtf.gz fi { cd ${deploy_dir} \ && wget -O gencode.gtf.gz ${url}; } >> ${log_file} 2>&1 if [ ! $? == 0 ]; then echo "Error occured! See ${log_file} for more details." exit 1 fi gencode_file=${PWD}/gencode.gtf.gz cd ${start_dir} } download_genenames() { echo -e "${GREEN}=> Downloading gene names from HGNC${NOCOLOR}" start_dir=${PWD} { cd ${deploy_dir} \ && wget -O hgnc.txt ftp://ftp.ebi.ac.uk/pub/databases/genenames/new/tsv/hgnc_complete_set.txt \ && gzip hgnc.txt; } >> ${log_file} 2>&1 if [ ! $? == 0 ]; then echo "Error occured! See ${log_file} for more details." exit 1 fi hgnc_file=${PWD}/hgnc.txt.gz cd ${start_dir} } download_OMIM() { dbversion=`curl -s "http://useast.ensembl.org/biomart/martservice?type=registry" | grep ENSEMBL_MART_ENSEMBL | grep -oP 'displayName="\K[^"]*'` echo -e "${GREEN}=> Downloading OMIM descriptions from BioMart ${dbversion}${NOCOLOR}" start_dir=${PWD} { cd ${deploy_dir} \ && wget -O omim.txt 'http://www.ensembl.org/biomart/martservice?query=<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE Query><Query virtualSchemaName="default" formatter="TSV" header="1" uniqueRows="0" count="" datasetConfigVersion="0.6"><Dataset name="hsapiens_gene_ensembl" interface="default"><Attribute name="ensembl_gene_id"/><Attribute name="ensembl_transcript_id"/><Attribute name="mim_gene_accession"/><Attribute name="mim_gene_description"/></Dataset></Query>' \ && gzip omim.txt; } >> ${log_file} 2>&1 if [ ! $? == 0 ]; then echo "Error occured! See ${log_file} for more details." exit 1 fi omim_file=${PWD}/omim.txt.gz cd ${start_dir} } download_dbSNP() { start_dir=${PWD} if [ "$genome_build" == "hg38" ]; then echo -e "${GREEN}=> Downloading dbSNP 150 for human genome version ${genome_build}${NOCOLOR}" url="ftp://ftp.ncbi.nlm.nih.gov/snp//organisms/human_9606_b150_GRCh38p7/database/data/organism_data/b150_SNPChrPosOnRef_108.bcp.gz" elif [ "$genome_build" == "hg19" ]; then echo -e "${GREEN}=> Downloading dbSNP 150 for human genome version ${genome_build}${NOCOLOR}" url="ftp://ftp.ncbi.nlm.nih.gov/snp//organisms/human_9606_b150_GRCh37p13/database/data/organism_data/b150_SNPChrPosOnRef_105.bcp.gz" fi { cd ${deploy_dir} \ && wget -O dbsnp.bcp.gz ${url} \ && gzip -dc dbsnp.bcp.gz | awk '{OFS = "\t"; if ($3 != "") { print $1,$2,$3 }}' | sort -k2,2 -k3,3n | ${bgzip} -c > dbsnp.tsv.gz \ && ${tabix} -s 2 -b 3 -e 3 dbsnp.tsv.gz \ && rm dbsnp.bcp.gz; } >> ${log_file} 2>&1 if [ ! $? == 0 ]; then echo "Error occured! See ${log_file} for more details." exit 1 fi dbsnp_file=${PWD}/dbsnp.tsv.gz cd ${start_dir} } download_canonical_transcripts() { # we should not worry about human genome build version here, because we don't need genomic coordinates # we want just a specific version of Ensembl dbversion="homo_sapiens_core_91_38" echo -e "${GREEN}=> Downloading canonical transcripts from Ensembl 91${NOCOLOR}" start_dir=${PWD} { cd ${deploy_dir} \ && perl ${start_dir}/download_canonical_transcripts.pl homo_sapiens_core_91_38 | gzip -c > canonical_transcripts.txt.gz; } >> ${log_file} 2>&1 if [ ! $? == 0 ]; then echo "Error occured! See ${log_file} for more details." exit 1 fi canonical_transcripts_file=${PWD}/canonical_transcripts.txt.gz cd ${start_dir} } while getopts ":hb:d:t:c:" opt; do case $opt in h) echo "This script will setup Bravo." echo "" echo "./INSTALL.sh" echo -e "\t-h Displays this help message." echo -e "\t-b build Human genome build version: hg38 (default), hg19." echo -e "\t-d directory Working directory for temporary deployment files and scripts. Default is ./temp." echo -e "\t-t threads Number of parallel threads. Default is 1." echo "" exit 0 ;; b) genome_build=$OPTARG ;; d) working_dir=$OPTARG ;; t) threads=$OPTARG ;; \?) echo "Invalid option: -$OPTARG" exit 1 ;; :) echo "Option -$OPTARG requires and argument." exit 1 ;; esac done if [ "$genome_build" != "hg38" ] && [ "$genome_build" != "hg19" ]; then echo "Genome build $genome_build is not supported." exit 1 fi if [ -d "${deploy_dir}" ]; then echo "Temporary deployment directory ${deploy_dir} already exists. Please remove it or provide an alternative." exit 1 fi mkdir ${deploy_dir} echo "Setting up Bravo for human genome version ${genome_build}." echo "Writing temporary deployment files to ${deploy_dir}." echo "Writing log information to ${log_file}." echo -n "" > ${log_file} echo -e "${RED}DOWNLOADING REQUIRED TOOLS/LIBRARIES${NOCOLOR}" command -v tabix > /dev/null && command -v bgzip > /dev/null if [ ! $? == 0 ]; then setup_tabix_tools else tabix=`command -v tabix` bgzip=`command -v bgzip` fi setup_ensembl_api echo -e "${RED}DOWNLOADING EXTERNAL DATA${NOCOLOR}" download_GENCODE download_genenames download_OMIM download_dbSNP download_canonical_transcripts echo -e "${RED}LOADING EXTERNAL DATA TO DATABASE${NOCOLOR}" python ../manage.py genes -t ${canonical_transcripts_file} -m ${omim_file} -f ${hgnc_file} -g ${gencode_file} python ../manage.py dbsnp -d ${dbsnp_file} -t ${threads} rm -rf ${deploy_dir} echo -e "${RED}DONE${NOCOLOR}"
#!/bin/bash #SBATCH --time=0:30:00 #SBATCH -N 2 #SBATCH --ntasks-per-node=28 #SBATCH --job-name=ondemand/sys/myjobs/basic_comsol_parallel #SBATCH --no-requeue #SBATCH --licenses=comsolscript@osc # A Basic COMSOL Parallel Job for the OSC Owens Cluster # https://www.osc.edu/resources/available_software/software_list/comsol # # The following lines set up the COMSOL environment # module load comsol # # Move to the directory where the job was submitted # cd ${SLURM_SUBMIT_DIR} echo "--- Copy Input Files to TMPDIR and Change Disk to TMPDIR" cp /usr/local/comsol/comsol52a/demo/api/beammodel/BeamModel.mph $TMPDIR cd $TMPDIR np=28 echo "--- Running on ${np} processes (cores) on the following nodes:" scontrol show hostnames $SLURM_JOB_NODELIST | uniq > hostfile # # Run COMSOL # echo "--- COMSOL run" comsol -nn 2 -np ${np} batch -f hostfile -mpirsh ssh -inputfile BeamModel.mph -outputfile output.mph # # Now, copy data (or move) back once the simulation has completed # echo "--- Copy files back" cp output.mph output.mph.status ${SLURM_SUBMIT_DIR} echo "---Job finished at: 'date'" echo "---------------------------------------------"
def insert_sorted(data): sorted_list = [] for i in range(len(data)): # Find the appropriate location for the number for j in range(len(sorted_list)): if data[i] < sorted_list[j]: sorted_list.insert(j,data[i]) break else: sorted_list.append(data[i]) return sorted_list
#!/bin/bash # # exit on any error: set -beEu -o pipefail # switching to beta for version 286 export branch="beta" # to use the top of the source tree, uncomment this branch=HEAD statment # and comment out the one above. This is sometimes useful when there # are new fixes in the source tree in between beta releases. # Note, the top of the source tree could be broken at any time, it is on # a 10-minute update cycle with live work taking place. # export branch="HEAD" # script to fetch extra source to use with the kent build, # and then selectively parts of the kent source tree, enough to # build just the user utilities # the combined samtabix source for the SAM/BAM/TABIX functions: rm -fr samtabix echo "fetch samtabix" 1>&2 git clone http://genome-source.cse.ucsc.edu/samtabix.git samtabix \ > /dev/null 2>&1 # These selective git archive commands only work up to a certain size # of fetched source (number of arguments), hence the multiple set of # individual fetches to get all the parts rm -f part1Src.zip part2Src.zip part3Src.zip part4Src.zip part5Src.zip export partNumber=1 export ofN="of 5" # this util changed from being in a directory to being a script # the extract can't overwrite the directory with a file rm -fr kent/src/utils/uniprotLift echo "fetch kent source part ${partNumber} ${ofN}" 1>&2 git archive --format=zip -9 --remote=git://genome-source.cse.ucsc.edu/kent.git \ --prefix=kent/ ${branch} \ src/machTest.sh \ src/checkUmask.sh \ src/ameme \ src/aladdin \ src/blat \ src/dnaDust \ src/fuse \ src/gfClient \ src/gfServer \ src/index \ src/makefile \ src/meta \ src/parasol \ src/primeMate \ src/product \ src/protDust \ src/weblet \ src/inc \ src/utils \ src/jkOwnLib \ src/lib \ src/hg/affyTransciptome \ src/hg/agpAllToFaFile \ src/hg/agpCloneCheck \ src/hg/agpCloneList \ src/hg/agpToFa \ src/hg/agpToGl \ src/hg/altSplice \ src/hg/autoDtd \ src/hg/autoSql \ src/hg/autoXml \ src/hg/bedIntersect \ src/hg/bedItemOverlapCount \ src/hg/bedOrBlocks \ src/hg/bedSort \ src/hg/bedSplitOnChrom \ src/hg/bedToGenePred \ src/hg/blastToPsl \ src/hg/borfBig \ src/hg/checkCoverageGaps \ src/hg/checkHgFindSpec \ src/hg/checkTableCoords \ src/hg/ctgFaToFa \ src/hg/ctgToChromFa \ src/hg/dbTrash \ src/hg/embossToPsl \ src/hg/estOrient \ src/hg/encode/validateFiles \ src/hg/fakeFinContigs \ src/hg/fakeOut \ src/hg/featureBits \ src/hg/ffaToFa \ src/hg/fishClones \ src/hg/fqToQa \ src/hg/fqToQac \ src/hg/fragPart \ src/hg/gbGetEntries \ src/hg/gbOneAcc > part${partNumber}Src.zip unzip -o -q part${partNumber}Src.zip ((partNumber++)) echo "fetch kent source part ${partNumber} ${ofN}" 1>&2 git archive --format=zip -9 --remote=git://genome-source.cse.ucsc.edu/kent.git \ --prefix=kent/ ${branch} \ src/hg/gbToFaRa \ src/hg/geneBounds \ src/hg/genePredHisto \ src/hg/genePredSingleCover \ src/hg/genePredToBed \ src/hg/genePredToFakePsl \ src/hg/genePredToGtf \ src/hg/genePredToMafFrames \ src/hg/getFeatDna \ src/hg/getRna \ src/hg/getRnaPred \ src/hg/gpStats \ src/hg/gpToGtf \ src/hg/gpcrParser \ src/hg/gsBig \ src/hg/hgChroms \ src/hg/hgGetAnn \ src/hg/hgKnownGeneList \ src/hg/hgSelect \ src/hg/hgSpeciesRna \ src/hg/hgTablesTest \ src/hg/hgsql \ src/hg/hgsqlSwapTables \ src/hg/hgsqlTableDate \ src/hg/hgsqladmin \ src/hg/hgsqldump \ src/hg/hgsqlimport \ src/hg/inc \ src/hg/intronEnds \ src/hg/lib \ src/hg/lfsOverlap \ src/hg/liftAcross \ src/hg/liftAgp \ src/hg/liftFrags \ src/hg/liftUp \ src/hg/liftOver \ src/hg/makefile \ src/hg/makeDb/hgLoadWiggle \ src/hg/makeDb/hgGcPercent \ src/hg/utils \ src/hg/maskOutFa \ src/hg/mdToNcbiLift \ src/hg/mrnaToGene \ src/hg/orthoMap \ src/hg/patCount \ src/hg/perf \ src/hg/pslCat \ src/hg/pslCheck \ src/hg/pslCoverage \ src/hg/pslCDnaFilter \ src/hg/pslPretty \ src/hg/pslReps \ src/hg/pslSort \ src/hg/pslDropOverlap > part${partNumber}Src.zip unzip -o -q part${partNumber}Src.zip ((partNumber++)) echo "fetch kent source part ${partNumber} ${ofN}" 1>&2 git archive --format=zip -9 --remote=git://genome-source.cse.ucsc.edu/kent.git \ --prefix=kent/ ${branch} \ src/hg/pslFilter \ src/hg/pslFilterPrimers \ src/hg/pslGlue \ src/hg/pslHisto \ src/hg/pslHitPercent \ src/hg/pslIntronsOnly \ src/hg/pslPairs \ src/hg/pslPartition \ src/hg/pslQuickFilter \ src/hg/pslRecalcMatch \ src/hg/pslSelect \ src/hg/pslSimp \ src/hg/pslSortAcc \ src/hg/pslSplitOnTarget \ src/hg/pslStats \ src/hg/pslSwap \ src/hg/pslToBed \ src/hg/pslUnpile \ src/hg/pslxToFa \ src/hg/qa \ src/hg/qaToQac \ src/hg/qacAgpLift \ src/hg/qacToQa \ src/hg/qacToWig \ src/hg/recycleDb \ src/hg/relPairs \ src/hg/reviewSanity \ src/hg/rnaStructure \ src/hg/scanRa \ src/hg/semiNorm \ src/hg/sim4big \ src/hg/snp \ src/hg/snpException \ src/hg/spideyToPsl \ src/hg/encode3 \ src/hg/splitFa \ src/hg/splitFaIntoContigs \ src/hg/sqlEnvTest.sh \ src/hg/sqlToXml \ src/hg/test \ src/hg/trfBig \ src/hg/txCds \ src/hg/txGene \ src/hg/txGraph \ src/hg/uniqSize \ src/hg/updateStsInfo \ src/hg/xmlCat \ src/hg/xmlToSql \ src/hg/hgTables \ src/hg/near \ src/hg/pslDiff \ src/hg/sage \ src/hg/gigAssembler/checkAgpAndFa \ src/hg/genePredCheck > part${partNumber}Src.zip unzip -o -q part${partNumber}Src.zip ((partNumber++)) echo "fetch kent source part ${partNumber} ${ofN}" 1>&2 git archive --format=zip -9 --remote=git://genome-source.cse.ucsc.edu/kent.git \ --prefix=kent/ ${branch} \ src/hg/makeDb/makefile \ src/hg/makeDb/hgAar \ src/hg/makeDb/hgAddLiftOverChain \ src/hg/makeDb/hgBbiDbLink \ src/hg/makeDb/hgClonePos \ src/hg/makeDb/hgCountAlign \ src/hg/makeDb/hgCtgPos \ src/hg/makeDb/hgDeleteChrom \ src/hg/makeDb/hgExperiment \ src/hg/makeDb/hgExtFileCheck \ src/hg/makeDb/hgFakeAgp \ src/hg/makeDb/hgFindSpec \ src/hg/makeDb/hgGeneBands \ src/hg/makeDb/hgGenericMicroarray \ src/hg/makeDb/hgPar \ src/hg/makeDb/hgGoldGapGl \ src/hg/makeDb/hgKgGetText \ src/hg/makeDb/hgKgMrna \ src/hg/makeDb/hgKnownMore \ src/hg/makeDb/hgKnownMore.oo21 \ src/hg/makeDb/hgLoadBed \ src/hg/makeDb/hgLoadBlastTab \ src/hg/makeDb/hgLoadChain \ src/hg/makeDb/hgLoadChromGraph \ src/hg/makeDb/hgLoadGenePred \ src/hg/makeDb/hgLoadItemAttr \ src/hg/makeDb/hgLoadMaf \ src/hg/makeDb/hgLoadMafFrames \ src/hg/makeDb/hgLoadNet \ src/hg/makeDb/hgLoadOut \ src/hg/makeDb/hgLoadOutJoined \ src/hg/makeDb/hgLoadPsl \ src/hg/makeDb/hgLoadSeq \ src/hg/makeDb/hgLoadSample \ src/hg/makeDb/hgLoadSqlTab \ src/hg/makeDb/hgMapMicroarray \ src/hg/makeDb/hgMedianMicroarray \ src/hg/makeDb/hgNibSeq \ src/hg/makeDb/hgPepPred \ src/hg/makeDb/hgRatioMicroarray \ src/hg/makeDb/hgDropSplitTable \ src/hg/makeDb/hgRenameSplitTable \ src/hg/makeDb/hgSanger20 \ src/hg/makeDb/hgSanger22 \ src/hg/makeDb/hgStanfordMicroarray \ src/hg/makeDb/hgStsAlias \ src/hg/makeDb/hgStsMarkers \ src/hg/makeDb/hgTomRough \ src/hg/makeDb/hgTpf \ src/hg/makeDb/hgTraceInfo \ src/hg/makeDb/hgTrackDb \ src/hg/makeDb/hgWaba \ src/hg/makeDb/ldHgGene \ src/hg/makeDb/hgMrnaRefseq \ src/hg/makeDb/schema \ src/hg/makeDb/tfbsConsLoc \ src/hg/makeDb/tfbsConsSort > part${partNumber}Src.zip unzip -o -q part${partNumber}Src.zip ((partNumber++)) echo "fetch kent source part ${partNumber} ${ofN}" 1>&2 git archive --format=zip -9 --remote=git://genome-source.cse.ucsc.edu/kent.git \ --prefix=kent/ ${branch} \ src/parasol \ src/hg/pslToChain \ src/hg/makeDb/outside \ src/hg/makeDb/trackDbRaFormat \ src/hg/makeDb/trackDbPatch \ src/hg/mouseStuff \ src/hg/ratStuff \ src/hg/nci60 \ src/hg/visiGene/knownToVisiGene \ src/hg/visiGene/hgVisiGene > part${partNumber}Src.zip unzip -o -q part${partNumber}Src.zip
#!/bin/sh set -e set -u set -o pipefail function on_error { echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" } trap 'on_error $LINENO' ERR if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy # frameworks to, so exit 0 (signalling the script phase was successful). exit 0 fi echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" # Used as a return value for each invocation of `strip_invalid_archs` function. STRIP_BINARY_RETVAL=0 # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") # Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # Use filter instead of exclude so missing patterns don't throw errors. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" elif [ -L "${binary}" ]; then echo "Destination binary is symlinked..." dirname="$(dirname "${binary}")" binary="${dirname}/$(readlink "${binary}")" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then # Copy the dSYM into a the targets temp dir. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" local basename basename="$(basename -s .framework.dSYM "$source")" binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then strip_invalid_archs "$binary" fi if [[ $STRIP_BINARY_RETVAL == 1 ]]; then # Move the stripped file into its final destination. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" else # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" fi fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identity echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current target binary binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" # Intersect them with the architectures we are building for intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" # If there are no archs supported by this binary then warn the user if [[ -z "$intersected_archs" ]]; then echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." STRIP_BINARY_RETVAL=0 return fi stripped="" for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi STRIP_BINARY_RETVAL=1 } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/AsyncOperations/AsyncOperations.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/AsyncOperations/AsyncOperations.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
from django.conf.urls import url from django.urls import include, path from django.contrib import admin from .views import UserView,activate, LoginView,RegistrationView# LogoutView, from rest_framework import routers from rest_framework_simplejwt import views as jwt_views # router = routers.DefaultRouter() # # router.register(r'user', UserView.as_view(), basename="user") # router.register(r'login/?$'', LoginView.as_view(), basename="login") # # router.register(r'user/logout', LogoutViewSet) # router.register(r'register', RegistrationView.as_view(), basename="register") urlpatterns = ([ path('token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), path('user/', UserView.as_view()), path('register/', RegistrationView.as_view()), path('login/', LoginView.as_view()), # url(r'^social/(?P<backend>[^/]+)/$', exchange_token), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', activate, name='activate') # url(r'^', include(router.urls)), ], 'authentication')
#!/usr/bin/env bash set -e cd "$(dirname "$0")/.." source ci/_ annotate() { ${BUILDKITE:-false} && { buildkite-agent annotate "$@" } } source ci/rust-version.sh stable export RUST_BACKTRACE=1 export RUSTFLAGS="-D warnings" source scripts/ulimit-n.sh # Clear cached json keypair files rm -rf "$HOME/.config/solana" # Run tbe appropriate test based on entrypoint testName=$(basename "$0" .sh) case $testName in test-stable) echo "Executing $testName" _ cargo +"$rust_stable" build --all ${V:+--verbose} _ cargo +"$rust_stable" test --all ${V:+--verbose} -- --nocapture --test-threads=1 ;; test-stable-perf) echo "Executing $testName" ci/affects-files.sh \ .rs$ \ Cargo.lock$ \ Cargo.toml$ \ ci/test-stable-perf.sh \ ci/test-stable.sh \ ^programs/ \ ^sdk/ \ || { annotate --style info \ "Skipped test-stable-perf as no relevant files were modified" exit 0 } # BPF program tests _ make -C programs/bpf/c tests _ programs/bpf/rust/noop/build.sh # Must be built out of band _ cargo +"$rust_stable" test \ --manifest-path programs/bpf/Cargo.toml \ --no-default-features --features=bpf_c,bpf_rust # Run root package tests with these features ROOT_FEATURES=erasure,chacha if [[ $(uname) = Darwin ]]; then ./build-perf-libs.sh else # Enable persistence mode to keep the CUDA kernel driver loaded, avoiding a # lengthy and unexpected delay the first time CUDA is involved when the driver # is not yet loaded. sudo --non-interactive ./net/scripts/enable-nvidia-persistence-mode.sh ./fetch-perf-libs.sh # shellcheck source=/dev/null source ./target/perf-libs/env.sh ROOT_FEATURES=$ROOT_FEATURES,cuda fi # Run root package library tests _ cargo +"$rust_stable" build --all ${V:+--verbose} --features="$ROOT_FEATURES" _ cargo +"$rust_stable" test --manifest-path=core/Cargo.toml ${V:+--verbose} --features="$ROOT_FEATURES" -- --nocapture --test-threads=1 ;; *) echo "Error: Unknown test: $testName" ;; esac # Assumes target/debug is populated. Ensure last build command # leaves target/debug in the state intended for localnet-sanity echo --- ci/localnet-sanity.sh ( set -x export PATH=$PWD/target/debug:$PATH USE_INSTALL=1 ci/localnet-sanity.sh -x )
#!/bin/bash -e SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" PROJECT_DIR=$SCRIPT_DIR/../.. source $PROJECT_DIR/conf/base.conf source $PROJECT_DIR/conf/deps_version.conf echo "platform: \"${platform}\"" echo "proto_version \"${proto_version}\"" #DOWNLOADS_DIR=$SCRIPT_DIR/downloads #GEN_DIR=$SCRIPT_DIR/gen if [[ "${platform}" == "" ]]; then echo "You can not config 'platform' in $PROJECT_DIR/conf/deps.conf. use default platform: 'linux'" platform="linux" fi if [[ "${proto_version}" == "" ]]; then echo "You can not config 'proto_version' in $PROJECT_DIR/conf/deps.conf. use default proto version: 3.5.0" proto_version=3.5.0 fi downloads_protobuf_targz=$DOWNLOADS_DIR/v${proto_version}.tar.gz downloads_protobuf_dir=$DOWNLOADS_DIR/protobuf-${proto_version} gen_protobuf_dir=$GEN_DIR/protobuf/${platform}/$proto_version PROTOBUF_URL="https://github.com/google/protobuf/archive/v${proto_version}.tar.gz" if [ ! -f $downloads_protobuf_targz ]; then mkdir -p $DOWNLOADS_DIR || true wget -P $DOWNLOADS_DIR $PROTOBUF_URL fi rm -rf $downloads_protobuf_dir || true tar -xvf ${downloads_protobuf_targz} -C ${DOWNLOADS_DIR} if [[ ! -f "${DOWNLOADS_DIR}/protobuf-${proto_version}/autogen.sh" ]]; then echo "You need to downloads dependencies before running this script: $(basename $0)" 1>&2 exit 1 fi cd ${DOWNLOADS_DIR}/protobuf-${proto_version} ./autogen.sh if [ $? -ne 0 ]; then echo "./autogen.sh command failed." exit 1 fi mkdir -p $gen_protobuf_dir || true ./configure --prefix="${gen_protobuf_dir}" --with-pic if [ $? -ne 0 ]; then echo "./configure command failed." exit 1 fi make clean && make -j4 && make check if [ $? -ne 0 ]; then echo "make command failed." exit 1 fi make install if [ $? -ne 0 ]; then echo "make install command failed." exit 1 fi echo "$(basename $0) finished successfully!!!"
<gh_stars>0 -- ------------------------------------------------------------- -- TablePlus 3.12.8(368) -- -- https://tableplus.com/ -- -- Database: users_db -- Generation Time: 2021-05-30 02:18:05.0140 -- ------------------------------------------------------------- -- This script only contains the table creation statements and does not fully represent the table in the database. It's still missing: indices, triggers. Do not use it as a backup. -- Sequence and defined type CREATE SEQUENCE IF NOT EXISTS login_db_id_seq; -- Table Definition CREATE TABLE "public"."login_db" ( "id" int4 NOT NULL DEFAULT nextval('login_db_id_seq'::regclass), "user_name" varchar(16), "user_pass" varchar(16), PRIMARY KEY ("id") ); INSERT INTO "public"."login_db" ("id", "user_name", "user_pass") VALUES (1, 'Ben', '<PASSWORD>'), (2, 'Teej', 'jeeT'), (3, 'Ash', 'hsA'), (4, 'Walter', 'retlaW'), (5, 'Arm', '<PASSWORD>'), (6, 'Benedicte', 'etcideneB'), (7, 'Jobe', '<PASSWORD>'), (8, 'Edson', 'nosdE'), (9, 'Johnny', 'ynnohJ'), (10, 'Matty', 'yttaM'), (11, 'Natalia', 'ailataN'), (12, 'Natalie', 'eilataN'), (13, 'Russ', 'ssuR'), (14, 'Isaac', 'caasI'), (15, 'Yoko', 'okoY'), (16, 'Hannah', 'hannaH'), (17, 'Ethan', 'nahtE'), (18, 'Jack', 'kcaJ'), (19, 'Alistair', 'riatsilA'), (20, 'Nandini', 'inidnaN'), (21, 'Alex', 'xelA'), (22, 'Julian', 'nialuJ');
import axios from "axios"; import { toast } from "react-toastify"; axios.interceptors.response.use(null, error => { console.log(error); const expectedError = error.response && error.response.status >= 400 && error.response.status < 500; if (!expectedError) { console.log(error); toast.error("An unexpected error occurrred."); } return Promise.reject(error); }); async function getFetch(apiEndpoint) { let response = await fetch(`${apiEndpoint}`, { method: "GET", headers: { "Content-Type": "application/json", } }); response = await response.json(); if(response.status === 401){ toast.error(response.message); }else{ return response; } } async function deleteFetch(apiEndpoint) { let response = await fetch(`${apiEndpoint}`, { method: "DELETE", headers: { "Content-Type": "application/json", } }); response = await response.json(); if(response.status === 401){ toast.error(response.message); window.location.href = "/"; }else{ return response; } } async function postFetch(apiEndpoint, data) { let response = await fetch(`${apiEndpoint}`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data) }); response = await response.json(); if(response.status === 401){ toast.error(response.message); window.location.href = "/"; }else{ return response; } } async function putFetch(apiEndpoint,data) { let response = await fetch(`${apiEndpoint}`, { method: 'PUT', // Method itself headers: { 'Content-type': 'application/json;', // Indicates the content 'Access-Control-Allow-Origin': '*', }, body: JSON.stringify(data) // We send data in JSON format }); response = await response.json(); if (response.status === 401) { toast.error(response.message); window.location.href = "/"; } else { return response; } } export default { get: getFetch, post: postFetch, put: putFetch, delete: deleteFetch, };
# Function to return nth Fibonacci number def Fibonacci(n): if n<0: print("Incorrect input") # First Fibonacci number is 0 elif n==1: return 0 # Second Fibonacci number is 1 elif n==2: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) # Driver Program print(Fibonacci(9))
const recorder = require('watchtower-recorder'); const eventsStreamName = process.env['WATCHTOWER_EVENT_KINESIS_STREAM']; const debug = process.env.DEBUG_WATCHTOWER; // Loading modules that fail when required via vm2 const aws = require('aws-sdk'); const cp = require('child_process'); let context, lambdaExecutionContext, lambdaInputEvent; function updateContext(name, event, lambdaContext) { context = name; lambdaExecutionContext = lambdaContext; lambdaInputEvent = event; } const mock = { 'aws-sdk' : aws, 'child_process': { 'exec': cp.exec, 'spawn': (...params) => { const command = params[0]; const args = params[1]; const recoveredArgs = [] for (const arg of args) { recoveredArgs.push(arg); } return cp.spawn(command, recoveredArgs); }, }, }; module.exports.handler = recorder.createRecordingHandler('./get-metadata/index.js', 'handler', mock, false, updateContext, true);
#!/bin/bash fyne bundle data/icon.png > bundled.go
<reponame>rsc/client // @flow import {connect, type TypedState} from '../../../../util/container' import {isTeamWithChosenChannels, getTeamMemberCount} from '../../../../constants/teams' import {BigTeamHeader} from '.' const mapStateToProps = (state: TypedState, {teamname}) => ({ badgeSubscribe: !isTeamWithChosenChannels(state, teamname), memberCount: getTeamMemberCount(state, teamname), teamname, }) const mergeProps = (stateProps, dispatchProps, ownProps) => ({ ...dispatchProps, badgeSubscribe: stateProps.badgeSubscribe, memberCount: stateProps.memberCount, teamname: stateProps.teamname, }) export default connect(mapStateToProps, () => ({}), mergeProps)(BigTeamHeader)
<reponame>SkyBlockDev/The-trickster const Discord = require("discord.js"); const Enmap = require("enmap"); const { MessageEmbed } = require('discord.js'); const ms = require("parse-ms"); const maxtags = 25 module.exports = { cooldown: '2s', category: 'tags', aliases: ['createtag'], minArgs: 1, maxArgs: -1, expectedArgs: "Please add a input", description: 'add a tag', callback: async ({message, args, text, client}) => { if (message.member.hasPermission('ADMINISTRATOR') || message.author.id == <PASSWORD> || message.member.hasPermission('MANAGE_MESSAGES')) { let key = Object.keys(client.guild.get(message.guild.id)) bannednames = ['id', message.guild.id, 'guild', 'guildname', 'embed'] key = key.length console.log(key) let name = args[0] if(name.includes(bannednames)) { message.reply('sorry those are banned names') } else if(client.guild.get(message.guild.id, name)) { if(!args[1]) { message.channel.send('What do you want to put in your tag?, type cancel to cancel this action') let input = '' const filter = m => m.author.id === message.author.id const collector = new Discord.MessageCollector(message.channel, filter, { max: 1, time: 1000 * 150 }) collector.on('end', (collected) =>{ collected.forEach(value => { input += value.content }) if(!input){ return message.reply('The tag expired please use !addtag if you want to try again') } else if(input == 'cancel') { return message.reply('action cancelled') } client.guild.set(message.guild.id, input, name); const Embed = new Discord.MessageEmbed() .setTitle('tag edited') .addFields( { name: name, value: input } ) .setColor('#FF0000') message.reply(Embed); }); }else{ let input = args.slice(1).join(' ') client.guild.set(message.guild.id, input, name); const Embed = new Discord.MessageEmbed() .setTitle('tag edited') .addFields( { name: name, value: input } ) .setColor('#FF0000') message.reply(Embed); } } else if(key > maxtags+1) { message.reply(`sorry you can only have a maximum of ${maxtags} tags if you need more tags please join the support server (!info) or message tricked#3777`) } else if(!args[1]) { message.channel.send('What do you want to put in your tag?, type cancel to cancel this action') let input = '' const filter = m => m.author.id === message.author.id const collector = new Discord.MessageCollector(message.channel, filter, { max: 1, time: 1000 * 150 }) collector.on('end', (collected) =>{ collected.forEach(value => { input += value.content }) if(!input){ return message.reply('The tag expired please use !addtag if you want to try again') } else if(input == 'cancel') { return message.reply('action cancelled') } client.guild.set(message.guild.id, input, name); const Embed = new Discord.MessageEmbed() .setTitle('tag created') .addFields( { name: name, value: input } ) .setColor('#FF0000') message.reply(Embed); }); }else{ let input = args.slice(1).join(' ') client.guild.set(message.guild.id, input, name); const Embed = new Discord.MessageEmbed() .setTitle('tag created') .addFields( { name: name, value: input } ) .setColor('#FF0000') message.reply(Embed); } } else { const Embed = new Discord.MessageEmbed() .setColor('#03fc49') .setTitle(`Sorry, you don't have the permission: 'ADMINISTRATOR/MANAGE zMESSAGES' to execute this command`); c message.reply(Embed); } } }
import React from "react"; import { Cartesian3 } from "cesium"; import { Viewer, Entity } from "cesium-react"; const positions = [ Cartesian3.fromDegrees(-74.0707383, 40.7117244, 100), Cartesian3.fromDegrees(139.767052, 35.681167, 100), ]; export default class SimpleEntity extends React.PureComponent { state = { pos: 0, }; changePosition(pos) { this.setState({ pos }); } render() { const { pos } = this.state; return ( <Viewer full> <Entity name="test" description="test" position={positions[pos]} point={{ pixelSize: 10 }} /> <div style={{ position: "absolute", left: "10px", top: "10px", zIndex: "100", }}> <button onClick={() => this.changePosition(0)}>New York</button> <button onClick={() => this.changePosition(1)}>Tokyo</button> </div> </Viewer> ); } }
<filename>pirates/world/FortBarricade.py # File: F (Python 2.4) from pandac.PandaModules import NodePath, Point3 from direct.directnotify import DirectNotifyGlobal from pandac.PandaModules import rad2Deg, Vec3, GeomVertexFormat, GeomVertexData, GeomVertexWriter, Geom, GeomTriangles, GeomNode, CollisionNode, CollisionPolygon import math from pirates.piratesbase import PiratesGlobals class FortBarricade: notify = directNotify.newCategory('FortBarricade') def __init__(self, island, barricadeIds): self.island = island self.barricadeIds = barricadeIds self.colNP = [] self.loadBarricade() def unload(self): for coll in self.colNP: coll.removeNode() self.colNP = [] def loadBarricade(self): colNP1 = self.island.find('**/' + self.barricadeIds[0]) colNP2 = self.island.find('**/' + self.barricadeIds[1]) self.colNP = [ colNP1, colNP2] def disableCollisions(self): for coll in self.colNP: coll.stash() def enableCollisions(self): for coll in self.colNP: coll.unstash()
/* ---------------------------------------------------------------------------- * GTSAM Copyright 2010, Georgia Tech Research Corporation, * Atlanta, Georgia 30332-0415 * All Rights Reserved * Authors: <NAME>, et al. (see THANKS for the full author list) * See LICENSE for the license information * -------------------------------------------------------------------------- */ /** * @file testTableFactor.cpp * @date May 12, 2022 * @author <NAME> */ #include <CppUnitLite/TestHarness.h> #include <gtsam/base/Testable.h> #include <gtsam/discrete/DiscreteDistribution.h> #include <gtsam/discrete/Signature.h> #include <gtsam/discrete/TableFactor.h> #include <gtsam/discrete/DecisionTreeFactor.h> #include <Eigen/Sparse> #include <boost/assign/std/map.hpp> using namespace boost::assign; using namespace std; using namespace gtsam; /* ************************************************************************* */ TEST(TableFactor, constructors) { // Declare a bunch of keys DiscreteKey X(0, 2), Y(1, 3), Z(2, 2), A(3, 5); // Create factors TableFactor f_zeros(A, {0, 0, 0, 0, 1}); TableFactor f1(X, {2, 8}); TableFactor f2(X & Y, "2 5 3 6 4 7"); TableFactor f3(X & Y & Z, "2 5 3 6 4 7 25 55 35 65 45 75"); EXPECT_LONGS_EQUAL(1, f1.size()); EXPECT_LONGS_EQUAL(2, f2.size()); EXPECT_LONGS_EQUAL(3, f3.size()); DiscreteValues values; values[0] = 1; // x values[1] = 2; // y values[2] = 1; // z values[3] = 4; EXPECT_DOUBLES_EQUAL(1, f_zeros(values), 1e-9); EXPECT_DOUBLES_EQUAL(8, f1(values), 1e-9); EXPECT_DOUBLES_EQUAL(7, f2(values), 1e-9); EXPECT_DOUBLES_EQUAL(75, f3(values), 1e-9); } /* ************************************************************************* */ TEST(TableFactor, lazy_cartesian_product) { DiscreteKey v0(0, 2), v1(1, 2), v2(2, 2), A(3, 5); TableFactor f1(v0 & v1, "1 2 3 4"); double actual_v0 = f1.lazy_cp(v0.first, 2); EXPECT_DOUBLES_EQUAL(1, actual_v0, 1e-9); double actual_v1 = f1.lazy_cp(v1.first, 2); EXPECT_DOUBLES_EQUAL(0, actual_v1, 1e-9); TableFactor f_zeros(A, {0, 0, 0, 0, 1}); double actual_zero = f_zeros.lazy_cp(A.first, 3); EXPECT_DOUBLES_EQUAL(3, actual_zero, 1e-9); } /* ************************************************************************* */ TEST(TableFactor, project) { DiscreteKey v0(0, 2), v1(1, 2), v2(2, 2), A(3, 5); TableFactor f1(v0 & v1, "1 2 3 4"); // (v0 = 0) DiscreteValues assignment_1; assignment_1[v0.first] = 0;; std::vector<DiscreteValues> actual_vec1 = f1.project(assignment_1); DiscreteValues expected_1; expected_1[v0.first] = 0; expected_1[v1.first] = 0; DiscreteValues expected_2; expected_2[v0.first] = 0; expected_2[v1.first] = 1; std::vector<DiscreteValues> expected_vec1 = {expected_1, expected_2}; EXPECT(expected_vec1 == actual_vec1); // (v0 = 1) DiscreteValues assignment_2; assignment_2[v0.first] = 1; std::vector<DiscreteValues> actual_vec2 = f1.project(assignment_2); DiscreteValues expected_3; expected_3[v0.first] = 1; expected_3[v1.first] = 0; DiscreteValues expected_4; expected_4[v0.first] = 1; expected_4[v1.first] = 1; std::vector<DiscreteValues> expected_vec2 = {expected_3, expected_4}; EXPECT(expected_vec2 == actual_vec2); // (v1 = 0) DiscreteValues assignment_3; assignment_3[v1.first] = 0; std::vector<DiscreteValues> actual_vec3 = f1.project(assignment_3); DiscreteValues expected_5; expected_5[v0.first] = 0; expected_5[v1.first] = 0; DiscreteValues expected_6; expected_6[v0.first] = 1; expected_6[v1.first] = 0; std::vector<DiscreteValues> expected_vec3 = {expected_5, expected_6}; EXPECT(expected_vec3 == actual_vec3); // (v1 = 1) DiscreteValues assignment_4; assignment_4[v1.first] = 1; std::vector<DiscreteValues> actual_vec4 = f1.project(assignment_4); DiscreteValues expected_7; expected_7[v0.first] = 0; expected_7[v1.first] = 1; DiscreteValues expected_8; expected_8[v0.first] = 1; expected_8[v1.first] = 1; std::vector<DiscreteValues> expected_vec4 = {expected_7, expected_8}; EXPECT(expected_vec4 == actual_vec4); } /* ************************************************************************* */ TEST(TableFactor, find_idx) { DiscreteKey v0(0, 2), v1(1, 3); TableFactor f1(v0 & v1, "1 2 3 4 5 6"); DiscreteValues assignment; assignment[v0.first] = 1; assignment[v1.first] = 1; double actual_1 = f1.findIndex(assignment); EXPECT_LONGS_EQUAL(1 * 3 + 1, actual_1); assignment[v0.first] = 1; assignment[v1.first] = 0; double actual_2 = f1.findIndex(assignment); EXPECT_LONGS_EQUAL(1 * 3 + 0, actual_2); } /* ************************************************************************* */ TEST(TableFactor, multiplication) { DiscreteKey v0(0, 2), v1(1, 2), v2(2, 2); // Multiply with a DiscreteDistribution, i.e., Bayes Law! DiscreteDistribution prior(v1 % "1/3"); TableFactor f1(v0 & v1, "1 2 3 4"); DecisionTreeFactor expected(v0 & v1, "0.25 1.5 0.75 3"); CHECK(assert_equal(expected, static_cast<DecisionTreeFactor>(prior) * f1.toDecisionTreeFactor())); CHECK(assert_equal(expected, f1 * prior)); // Multiply two factors TableFactor f2(v1 & v2, "5 6 7 8"); TableFactor actual = f1 * f2; TableFactor expected2(v0 & v1 & v2, "5 6 14 16 15 18 28 32"); CHECK(assert_equal(expected2, actual)); DiscreteKey A(0, 3), B(1, 2), C(2, 2); TableFactor f_zeros1(A & C, "0 0 0 2 0 3"); TableFactor f_zeros2(B & C, "4 0 0 5"); TableFactor actual_zeros = f_zeros1 * f_zeros2; TableFactor expected3(A & B & C, "0 0 0 0 0 0 0 10 0 0 0 15"); CHECK(assert_equal(expected3, actual_zeros)); } /* ************************************************************************* */ TEST(TableFactor, sum_max) { DiscreteKey v0(0, 3), v1(1, 2); TableFactor f1(v0 & v1, "1 2 3 4 5 6"); TableFactor expected(v1, "9 12"); TableFactor::shared_ptr actual = f1.sum(1); CHECK(assert_equal(expected, *actual, 1e-5)); TableFactor expected2(v1, "5 6"); TableFactor actual2 = f1.max(1); CHECK(assert_equal(expected2, actual2)); TableFactor f2(v1 & v0, "1 2 3 4 5 6"); TableFactor::shared_ptr actual22 = f2.sum(1); } /* ************************************************************************* */ TEST( DecisionTreeFactor, max_ordering) { DiscreteKey v0(0,3), v1(1,2), v2(2, 2); TableFactor f1(v0 & v1 & v2, "1 2 3 10 5 6 7 11 9 4 8 12"); Ordering ordering; ordering += Key(1); TableFactor actual = f1.max(ordering); TableFactor expected(v0 & v2, "3 10 7 11 9 12"); CHECK(assert_equal(expected, actual)); TableFactor f2(v0 & v1 & v2, "0 0 0 0 0 0 0 15 0 0 0 10"); TableFactor actual_zeros = f2.max(ordering); TableFactor expected_zeros(v0 & v2, "0 0 0 15 0 10"); CHECK(assert_equal(expected_zeros, actual_zeros)); } /* ************************************************************************* */ TEST( DecisionTreeFactor, max_assignment) { DiscreteKey v0(0,3), v1(1,2), v2(2, 2); TableFactor f1(v0 & v1 & v2, "1 2 3 10 5 6 7 11 9 4 8 12"); DiscreteValues assignment = f1.maxAssignment(); DiscreteValues expected; expected[v0.first] = 2; expected[v1.first] = 1; expected[v2.first] = 1; CHECK(assert_equal(expected, assignment)); TableFactor f2(v0 & v1 & v2, "0 0 0 0 0 0 0 15 0 0 0 10"); DiscreteValues assignment_zeros = f2.maxAssignment(); DiscreteValues expected_zeros; expected_zeros[v0.first] = 1; expected_zeros[v1.first] = 1; expected_zeros[v2.first] = 1; CHECK(assert_equal(expected_zeros, assignment_zeros)); } /* ************************************************************************* */ // Check enumerate yields the correct list of assignment/value pairs. TEST(TableFactor, enumerate) { DiscreteKey A(12, 3), B(5, 2); TableFactor f(A & B, "1 2 3 4 5 6"); auto actual = f.enumerate(); std::vector<std::pair<DiscreteValues, double>> expected; DiscreteValues values; for (size_t a : {0, 1, 2}) { for (size_t b : {0, 1}) { values[12] = a; values[5] = b; expected.emplace_back(values, f(values)); } } EXPECT(actual == expected); } /* ************************************************************************* */ // Check markdown representation looks as expected. TEST(TableFactor, markdown) { DiscreteKey A(12, 3), B(5, 2); TableFactor f(A & B, "1 2 3 4 5 6"); string expected = "|A|B|value|\n" "|:-:|:-:|:-:|\n" "|0|0|1|\n" "|0|1|2|\n" "|1|0|3|\n" "|1|1|4|\n" "|2|0|5|\n" "|2|1|6|\n"; auto formatter = [](Key key) { return key == 12 ? "A" : "B"; }; string actual = f.markdown(formatter); EXPECT(actual == expected); } /* ************************************************************************* */ // Check markdown representation with a value formatter. TEST(TableFactor, markdownWithValueFormatter) { DiscreteKey A(12, 3), B(5, 2); TableFactor f(A & B, "1 2 3 4 5 6"); string expected = "|A|B|value|\n" "|:-:|:-:|:-:|\n" "|Zero|-|1|\n" "|Zero|+|2|\n" "|One|-|3|\n" "|One|+|4|\n" "|Two|-|5|\n" "|Two|+|6|\n"; auto keyFormatter = [](Key key) { return key == 12 ? "A" : "B"; }; TableFactor::Names names{{12, {"Zero", "One", "Two"}}, {5, {"-", "+"}}}; string actual = f.markdown(keyFormatter, names); EXPECT(actual == expected); } /* ************************************************************************* */ // Check html representation with a value formatter. TEST(TableFactor, htmlWithValueFormatter) { DiscreteKey A(12, 3), B(5, 2); TableFactor f(A & B, "1 2 3 4 5 6"); string expected = "<div>\n" "<table class='TableFactor'>\n" " <thead>\n" " <tr><th>A</th><th>B</th><th>value</th></tr>\n" " </thead>\n" " <tbody>\n" " <tr><th>Zero</th><th>-</th><td>1</td></tr>\n" " <tr><th>Zero</th><th>+</th><td>2</td></tr>\n" " <tr><th>One</th><th>-</th><td>3</td></tr>\n" " <tr><th>One</th><th>+</th><td>4</td></tr>\n" " <tr><th>Two</th><th>-</th><td>5</td></tr>\n" " <tr><th>Two</th><th>+</th><td>6</td></tr>\n" " </tbody>\n" "</table>\n" "</div>"; auto keyFormatter = [](Key key) { return key == 12 ? "A" : "B"; }; TableFactor::Names names{{12, {"Zero", "One", "Two"}}, {5, {"-", "+"}}}; string actual = f.html(keyFormatter, names); EXPECT(actual == expected); } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr); } /* ************************************************************************* */
#!/bin/sh # ============LICENSE_START==================================================== # Copyright (C) 2021. Nordix Foundation. All rights reserved. #!/bin/sh # ============LICENSE_START==================================================== # Copyright (C) 2021. Nordix Foundation. All rights reserved. # ============================================================================= # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 # ============LICENSE_END====================================================== /liquibase/liquibase \ --driver=com.microsoft.sqlserver.jdbc.SQLServerDriver \ --url="jdbc:sqlserver://db:1433;databaseName=${MYSQL_DB};integratedSecurity=false;" \ --changeLogFile="changelog/dbchangelog-master.yaml" \ --username=${MYSQL_USER} \ --password=${MYSQL_PASSWORD} \ --contexts=${CONTEXT} \ update
<reponame>rezaa89/pyamplitude from distutils.core import setup from codecs import open from os import path from setuptools import find_packages setup( name='pyamplitude', version='1.2.0.dev1', packages=['pyamplitude'] ) here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='pyamplitude', version='1.0.0', description='A Python connector for Amplitude Analytics', long_description=long_description, url='https://github.com/marmurar/pyamplitude', author='<NAME>', author_email='<EMAIL>', license='MIT', classifiers=[ 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], keywords='Data Analysis Amplitude Rest Api Amplitude Redshift', packages=find_packages(exclude=['tutorial', 'tests']) )
<filename>app/controllers/index.js<gh_stars>1-10 /** * Initialize the App Navigation object based on the structure of the XML File */ var App = Alloy.Globals.App; App.Navigator.init({ mainView: $.page, // <- The Top Level View menuView: $.menu, // <- The Underlying Menu contentView: $.mainWindow, // <- The content section of the main view that is linked to the Navigator.open() method startPage: 'home' // <- The page you want to start your application }); /** * This function is tied to the click event on the navBar menuBtn element. * It is responsible for sliding the menu out and back */ function showhidemenu(e){ var direction = null; if(e && e.direction){ direction = e.direction; /* Ti.Analytics.featureEvent('app.showMenu.swipe'); */ } else { /* Ti.Analytics.featureEvent('app.showMenu.click'); */ } App.Navigator.showhidemenu(direction); } function updateWindowSize(){ var width; width = Ti.Platform.displayCaps.platformWidth; $.index.width = $.page.width = $.mainWindow.width = width; } Ti.Gesture.addEventListener('orientationchange', updateWindowSize); /* * Set WindowSize based on screen size (see function below) */ updateWindowSize(); /** * Open the main application Window */ $.index.open();
<reponame>bike7/testingtasks<filename>addressbook-web-tests/src/test/java/pl/kasieksoft/addressbook/appmanager/ContactHelper.java<gh_stars>0 package pl.kasieksoft.addressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; import pl.kasieksoft.addressbook.model.ContactData; import pl.kasieksoft.addressbook.model.ContactDataBuilder; import pl.kasieksoft.addressbook.model.Contacts; import pl.kasieksoft.addressbook.model.GroupData; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ContactHelper extends HelperBase { private Contacts contactCache = null; ContactHelper(WebDriver wd) { super(wd); } private void fillNewContactForm(ContactData contactData, boolean creation) { type(By.name("firstname"), contactData.getFirstname()); type(By.name("lastname"), contactData.getLastname()); type(By.name("home"), contactData.getHomePhone()); type(By.name("email"), contactData.getEmail()); selectFromDropdown("bday", contactData.getBday()); selectFromDropdown("bmonth", contactData.getBmonth()); type(By.name("byear"), contactData.getByear()); if (creation) { if (contactData.getGroups().size() > 0) { Assert.assertTrue(contactData.getGroups().size() == 1); new Select(wd.findElement(By.name("new_group"))).selectByVisibleText(contactData.getGroups().iterator().next().getName()); } } else { Assert.assertFalse(isElementPresent(By.name("new_group"))); } } private void submitNewContact() { click(By.xpath("(//input[@name='submit'])[2]")); } private void initNewContact() { click(By.linkText("add new")); } public void deleteSelectedContact() { click(By.xpath("//input[@value='Delete']")); wd.switchTo().alert().accept(); contactCache = null; } public void selectContact(int id) { click(By.cssSelector("input[value='" + id + "']")); } private void initContactModification(int id) { String currentUrl = wd.getCurrentUrl(); wd.get(currentUrl.substring(0, currentUrl.lastIndexOf('/') + 1) + "edit.php?id=" + id); } private void enterContactDetailsPage(int id) { String currentUrl = wd.getCurrentUrl(); wd.get(currentUrl.substring(0, currentUrl.lastIndexOf('/') + 1) + "view.php?id=" + id); } private void submitContactModification() { click(By.name("update")); } public int count() { return wd.findElements(By.name("selected[]")).size(); } public void create(ContactData contact) { initNewContact(); fillNewContactForm(contact, true); contactCache = null; submitNewContact(); } public void modify(ContactData contact) { initContactModification(contact.getId()); fillNewContactForm(contact, false); contactCache = null; submitContactModification(); } public Contacts all() { if (contactCache != null) { return new Contacts(contactCache); } contactCache = new Contacts(); List<WebElement> rows = wd.findElements(By.xpath("//tr[@name='entry']")); for (WebElement row : rows) { contactCache.add(ContactDataBuilder.aContactData() .withId(Integer.parseInt(row.findElement(By.tagName("input")).getAttribute("value"))) .withFirstname(row.findElement(By.xpath("td[3]")).getText()) .withLastname(row.findElement(By.xpath("td[2]")).getText()) .withAllPhones(row.findElement(By.xpath("td[6]")).getText()) .withAllEmails(row.findElement(By.xpath("td[5]")).getText()) .withAddress(row.findElement(By.xpath("td[4]")).getText()) .build()); } return new Contacts(contactCache); } public List<ContactData> list() { List<ContactData> contacts = new ArrayList<>(); List<WebElement> elements = wd.findElements(By.xpath("//tr[@name='entry']")); for (WebElement element : elements) { contacts.add(ContactDataBuilder.aContactData() .withId(Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value"))) .withFirstname(element.findElement(By.xpath("td[3]")).getText()) .withLastname(element.findElement(By.xpath("td[2]")).getText()) .build()); } return contacts; } private void selectFromDropdown(String name, String text) { if (text != null) { click(By.name(name)); new Select(wd.findElement(By.name(name))).selectByVisibleText(text); click(By.name(name)); } } public ContactData infoFromEditForm(ContactData contact) { initContactModification(contact.getId()); return ContactDataBuilder.aContactData() .withFirstname(wd.findElement(By.name("firstname")).getAttribute("value")) .withLastname(wd.findElement(By.name("lastname")).getAttribute("value")) .withHomePhone(wd.findElement(By.name("home")).getAttribute("value")) .withMobilePhone(wd.findElement(By.name("mobile")).getAttribute("value")) .withWorkPhone(wd.findElement(By.name("work")).getAttribute("value")) .withEmail(wd.findElement(By.name("email")).getAttribute("value")) .withEmail2(wd.findElement(By.name("email2")).getAttribute("value")) .withEmail3(wd.findElement(By.name("email3")).getAttribute("value")) .withAddress(wd.findElement(By.name("address")).getText()) .build(); } public List<String> infoFromDetailsPage(ContactData contact) { enterContactDetailsPage(contact.getId()); return Arrays.stream(wd.findElement(By.xpath("//div[@id='content']")).getText().split("\n")) .filter((s) -> !s.equals("")).collect(Collectors.toList()); } public void addToGroup(ContactData contact, GroupData group) { selectContact(contact.getId()); selectFromDropdown("to_group", group.getName()); click(By.name("add")); } public void removeFromGroup(ContactData contact) { selectContact(contact.getId()); click(By.name("remove")); } }
CUDA_VISIBLE_DEVICES=0 \ python main_single_gpu.py \ -cfg='./configs/hvt_s2_patch16_224.yaml' \ -dataset='imagenet2012' \ -batch_size=16 \ -data_path='/dataset/imagenet'
import React, { useState } from 'react'; import axios from 'axios'; const Search = () => { const [ingredients, setIngredients] = useState(''); const [recipes, setRecipes] = useState(null); const handleSubmit = async e => { e.preventDefault(); const response = await axios.get(`/api/recipes?ingredients=${ingredients}`); setRecipes(response.data.recipes); }; return ( <div> <form onSubmit={handleSubmit}> <input type="text" value={ingredients} onChange={e => setIngredients(e.target.value)} /> <button type="submit">Search</button> </form> {recipes && recipes.map(recipe => ( <div key={recipe.id}> <h2>{recipe.name}</h2> <ul> {recipe.ingredients.map(ingredient => ( <li key={ingredient}>{ingredient}</li> ))} </ul> </div> ))} </div> ); }; export default Search;
<reponame>blueshiftone/ngx-grid import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, OnInit, ViewChild } from '@angular/core' import { MatMenuTrigger } from '@angular/material/menu' import { TPrimaryKey } from '@blueshiftone/ngx-grid-core' import { LocalizationService } from '../../services/localization.service' import { ToolbarService } from '../../toolbar.service' import { AutoUnsubscribe } from '../../utils/auto-unsubscribe' @Component({ selector: 'data-grid-toolbar-floating-toolbar', templateUrl: './floating-toolbar.component.html', styleUrls: ['./floating-toolbar.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class FloatingToolbarComponent extends AutoUnsubscribe implements OnInit { @ViewChild('multiEditButton') public multiEditButton?: ElementRef<HTMLElement> @ViewChild('multiEditMenuTrigger', {read: MatMenuTrigger}) public multiEditMenuTrigger?: MatMenuTrigger public canSetValues = false public canRevert = false public canCommit = false public canDelete = true public multiEditorLabels: string[] = [] private readonly txtCopySelection = 'locCopySelection' private readonly txtDeleteRecords = 'locDeleteRecords' private readonly txtClearSelection = 'locClearSelection' constructor( public readonly toolbarService : ToolbarService, private readonly elRef : ElementRef<HTMLElement>, private readonly changeDetection: ChangeDetectorRef, private readonly localizations : LocalizationService, ) { super() } ngOnInit(): void { this._init() this.addSubscription(this.localizations.changes.subscribe(_ => this.changeDetection.detectChanges())) } private async _init() { const controller = this.toolbarService.gridController if (!controller) return await controller.whenInitialised() const viewPort = controller.grid.viewPort if (!viewPort) return const el = viewPort.elementRef.nativeElement.parentElement if (!el) return el.prepend(this.elRef.nativeElement) this.canDelete = controller.dataSource.canDelete this.toolbarService.selectionSlice.subscribe(_ => this._checkChanges()) if (this.toolbarService.gridController) { this.addSubscription(this.toolbarService.gridController.gridEvents.GridWasModifiedEvent.on().subscribe(_ => this._checkChanges())) } } public get locCopySelection() : string { return this.localizations.getLocalizedString(this.txtCopySelection) } public get locDeleteRecords() : string { return this.localizations.getLocalizedString(this.txtDeleteRecords) } public get locClearSelection(): string { return this.localizations.getLocalizedString(this.txtClearSelection) } public setValues(): void { const selection = this.toolbarService.selectionSlice.value?.selection if (!selection) return const distinctType = this.toolbarService.multiCellEditService?.getDistinctType(selection) if (distinctType && distinctType.type.name === 'Boolean') { this.multiEditMenuTrigger?.openMenu() return } this.toolbarService.multiCellEditService?.openValueEditor({ strategy: 'element', element: this.multiEditButton?.nativeElement }, selection) } public runMultiEditor(label: string): void { const selection = this.toolbarService.selectionSlice.value?.selection const multiCellEditService = this.toolbarService.multiCellEditService if (!selection || !multiCellEditService) return multiCellEditService.runMultiEditor(label, selection, { strategy: 'element', element: this.multiEditButton?.nativeElement }) } public copySelection(): void { this.toolbarService.gridController?.selection.CopySelection.run() } public deleteRecords(): void { for (const pk of this._selectedRowKeys) this.toolbarService.gridController?.row.DeleteRow.buffer(pk) } public clearSelection(): void { this.toolbarService.gridController?.selection.ClearSelection.run() } private get _selectedRowKeys(): TPrimaryKey[] { return this.toolbarService.selectionSlice.value?.rowKeys ?? [] } private _checkChanges(): void { const selection = this.toolbarService.selectionSlice.value?.selection const multiCellEditService = this.toolbarService.multiCellEditService if (selection && multiCellEditService) { const distinctType = multiCellEditService.getDistinctType(selection) this.canSetValues = distinctType !== false if (distinctType) { this.multiEditorLabels = distinctType.editors.map(e => new e(null, distinctType.type.name)).map(editor => editor.label).reverse() } const controller = this.toolbarService.gridController if (controller) { this.canDelete = this.toolbarService.currentMeta.rows.find(r => controller.row.GetRowCanDelete.run(r) === true) !== undefined } } this.changeDetection.detectChanges() } }
<reponame>cbarrett/XPC-Calc<filename>XPC Calc/XPC_CalcAppDelegate.h // // XPC_CalcAppDelegate.h // XPC Calc // // Created by <NAME> on 8/6/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import <Cocoa/Cocoa.h> #import <xpc/xpc.h> @interface XPC_CalcAppDelegate : NSObject <NSApplicationDelegate> { NSWindow *window; NSTextField *inputTextField; xpc_connection_t serviceConnection; NSTextView *stackTextView; xpc_object_t stack; } @property (assign) IBOutlet NSTextView *stackTextView; @property (assign) IBOutlet NSTextField *inputTextField; @property (assign) IBOutlet NSWindow *window; - (IBAction)push:(id)sender; - (IBAction)add:(id)sender; - (IBAction)subtract:(id)sender; - (IBAction)multiply:(id)sender; - (IBAction)divide:(id)sender; - (IBAction)clear:(id)sender; @end
json.array!(@game_actions) do |game_action| json.extract! game_action, :description json.url game_action_url(game_action, format: :json) end
public class Group { public string GroupName { get; set; } public string SubjectId { get; set; } public string IdentityProvider { get; set; } // Constructor to initialize the properties public Group(string groupName, string subjectId, string identityProvider) { GroupName = groupName; SubjectId = subjectId; IdentityProvider = identityProvider; } }
<reponame>akkySrivastava/UNIVERSITY-MANAGEMENT-SYSTEM /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package university.management.system; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.sql.*; /** * * @author akky */ public class StudentDetails extends JFrame implements ActionListener { JLabel l,l1,l3,l2; JTable jt; JTextField t; JButton b,b1,b3,b4; Font f=new Font("Serif",Font.BOLD,18); String top[]={"Name","Father's Name","Age","Address","Email","DOB","Phone","X_Marks","XII_Marks","Branch","Aadhar_NO","Course","Roll"}; String down[][]=new String[25][13]; int i=0,j=0; StudentDetails() { setDefaultCloseOperation(EXIT_ON_CLOSE); getContentPane().setBackground(Color.white); setSize(1300,800); setLocation(100,100); setLayout(null); l=new JLabel("STUDENT DETAILS"); l.setFont(f); l.setForeground(new Color(0,0,200)); l.setBounds(550,50,200,30); add(l); try{ connection c=new connection(); ResultSet rs=c.s.executeQuery("select * from studentdetails"); while(rs.next()) { down[i][j++]=rs.getString("s_name"); down[i][j++]=rs.getString("father_name"); down[i][j++]=String.valueOf(rs.getInt("age")); down[i][j++]=rs.getString("address"); down[i][j++]=rs.getString("email"); down[i][j++]=rs.getString("dob"); down[i][j++]=rs.getString("phone"); down[i][j++]=String.valueOf(rs.getFloat("X_marks")); down[i][j++]=String.valueOf(rs.getString("XII_marks")); down[i][j++]=rs.getString("branch"); down[i][j++]=rs.getString("aadhar_no"); down[i][j++]=rs.getString("course"); down[i][j++]=String.valueOf(rs.getInt("roll")); i++; j=0; } jt=new JTable(down,top); jt.setFont(f); JScrollPane js=new JScrollPane(jt); js.setBounds(50,100,1190,400); add(js); } catch(Exception e) { e.getMessage(); } l2=new JLabel("Enter Roll No of Student: "); l2.setFont(f); l2.setBounds(50,550,250,30); add(l2); t=new JTextField(); t.setFont(f); t.setBounds(330,550,180,30); add(t); b=new JButton("Delete"); b.setFont(f); b.setBackground(Color.black); b.setForeground(Color.white); b.setBounds(580,550,180,30); add(b); l3=new JLabel("Add New Students: "); l3.setFont(f); l3.setForeground(Color.green); l3.setBounds(50,600,250,30); add(l3); b1=new JButton("Add"); b1.setFont(f); b1.setForeground(Color.white); b1.setBackground(Color.black); b1.setBounds(330,600,180,30); add(b1); l1=new JLabel("Update Students Details: "); l1.setFont(f); l1.setBounds(50,650,250,30); add(l1); b3=new JButton("Update"); b3.setForeground(Color.white); b3.setBackground(Color.BLACK); b3.setFont(f); b3.setBounds(330,650,180,30); add(b3); b4=new JButton("EXIT"); b4.setForeground(Color.RED); b4.setFont(f); b4.setBounds(580,650,180,30); add(b4); b.addActionListener(this); b1.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); } @Override public void actionPerformed(ActionEvent ae){ if(ae.getSource()==b) { try{ connection conn=new connection (); int roll=Integer.parseInt(t.getText()); conn.s.executeUpdate("delete from studentdetails where roll='"+roll+"'"); JOptionPane.showMessageDialog(null,"Deleted Successfully"); this.setVisible(false); new StudentDetails().setVisible(true); } catch(Exception e) { e.getMessage(); } } if(ae.getSource()==b1) { new AddStudent().setVisible(true); this.setVisible(false); } if(ae.getSource()==b3) { new UpdateStudent().setVisible(true); this.setVisible(false); } if(ae.getSource()==b4) { dispose(); } } public static void main(String[] args){ new StudentDetails().setVisible(true); } }
<gh_stars>1-10 package io.github.yamporg.ifbhfix; import com.buuz135.industrial.tile.block.BlackHoleUnitBlock; import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; public class BlockStorageItem extends BlackHoleUnitBlock.BlockStorageItem { public BlockStorageItem(Block block) { ((BlackHoleUnitBlock) block).super(block); } @Nullable @Override public String getCreatorModId(@Nonnull ItemStack itemStack) { return IFBHFixMod.MOD_ID; } @Nullable @Override public ICapabilityProvider initCapabilities(ItemStack itemStack, @Nullable NBTTagCompound nbt) { return ((BlackHoleUnitBlock) block).new StorageItemHandler(itemStack) { @Nullable @Override public <T> T getCapability( @Nonnull Capability<T> capability, @Nullable EnumFacing facing) { Capability<IItemHandler> itemHandlerCapability = CapabilityItemHandler.ITEM_HANDLER_CAPABILITY; if (capability != itemHandlerCapability) { return null; } IItemHandler itemHandler = super.getCapability(itemHandlerCapability, facing); IItemHandler wrapper = new ItemHandlerWrapper(itemStack, itemHandler); return itemHandlerCapability.cast(wrapper); } }; } }
<filename>src/main/java/evilcraft/render/entity/RenderNetherfish.java package evilcraft.render.entity; import net.minecraft.client.renderer.entity.RenderSilverfish; import net.minecraft.entity.monster.EntitySilverfish; import net.minecraft.util.ResourceLocation; import evilcraft.Reference; import evilcraft.api.config.ExtendedConfig; import evilcraft.api.config.MobConfig; /** * Renderer for a netherfish * * @author rubensworks * */ public class RenderNetherfish extends RenderSilverfish { private ResourceLocation texture; /** * Make a new instance. * @param config Then config. */ public RenderNetherfish(ExtendedConfig<MobConfig> config) { texture = new ResourceLocation(Reference.MOD_ID, Reference.TEXTURE_PATH_ENTITIES + config.NAMEDID + ".png"); } @Override protected ResourceLocation getEntityTexture(EntitySilverfish entity) { return texture; } }
var json2xls = require('../lib/json2xls'); var data = require('../spec/arrayData.json'); var fs = require('fs'); var xls = json2xls(data,{}); fs.writeFileSync('output.xlsx',xls, 'binary');
#!/bin/bash # ============================================================================== # Copyright 2019 Baidu.com, Inc. All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== export LANG=en_US.UTF-8 export LC_ALL=en_US.UTF-8 export LC_CTYPE=en_US.UTF-8 if [ ! -d log ]; then mkdir log else rm -r log/* fi if [ ! -d output ]; then mkdir output else rm -r output/* fi export FLAGS_cudnn_deterministic=true export FLAGS_cpu_deterministic=true PWD_DIR=`pwd` DATA=../data/ BERT_DIR=cased_L-24_H-1024_A-16 WN_CPT_EMBEDDING_PATH=../retrieve_concepts/KB_embeddings/wn_concept2vec.txt NELL_CPT_EMBEDDING_PATH=../retrieve_concepts/KB_embeddings/nell_concept2vec.txt CKPT_DIR=$1 python3 src/run_record_twomemory.py \ --batch_size 6 \ --do_train false \ --do_predict true \ --use_ema false \ --do_lower_case false \ --init_pretraining_params $BERT_DIR/params \ --init_checkpoint $CKPT_DIR \ --train_file $DATA/ReCoRD/train.json \ --predict_file $DATA/ReCoRD/dev.json \ --vocab_path $BERT_DIR/vocab.txt \ --bert_config_path $BERT_DIR/bert_config.json \ --freeze false \ --max_seq_len 384 \ --doc_stride 128 \ --wn_concept_embedding_path $WN_CPT_EMBEDDING_PATH \ --nell_concept_embedding_path $NELL_CPT_EMBEDDING_PATH \ --use_wordnet true \ --use_nell true \ --random_seed 45 \ --checkpoints output/ 1>$PWD_DIR/log/train.log 2>&1
<reponame>andreapatri/cms_journal "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _styledComponents = _interopRequireDefault(require("styled-components")); var _propTypes = _interopRequireDefault(require("prop-types")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _templateObject() { var data = _taggedTemplateLiteral(["\n display: flex;\n justify-content: ", ";\n flex-direction: ", ";\n align-items: ", ";\n flex-wrap: ", ";\n"]); _templateObject = function _templateObject() { return data; }; return data; } function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } var Flex = _styledComponents["default"].div(_templateObject(), function (_ref) { var justifyContent = _ref.justifyContent; return justifyContent; }, function (_ref2) { var flexDirection = _ref2.flexDirection; return flexDirection; }, function (_ref3) { var alignItems = _ref3.alignItems; return alignItems; }, function (_ref4) { var flexWrap = _ref4.flexWrap; return flexWrap; }); Flex.defaultProps = { justifyContent: 'normal', flexDirection: 'row', flexWrap: 'nowrap', alignItems: 'normal' }; Flex.propTypes = { flexDirection: _propTypes["default"].string, flexWrap: _propTypes["default"].string, justifyContent: _propTypes["default"].string }; var _default = Flex; exports["default"] = _default;
#!/bin/bash release_dir=mpm-$1 rm -rf $release_dir/* mkdir -p $release_dir cp -v target/release/mpm $release_dir if [ "$1" == "windows-latest" ]; then 7z a -r $release_dir.zip $release_dir else zip -r $release_dir.zip $release_dir fi
<reponame>menghuanlunhui/springboot-master<gh_stars>0 package com.jf.database.enums; /** * Created by admin on 2017/6/29. */ public enum OrderState { /** -1-订单取消 */ S11(-1, "订单取消"), /** 0-待付款 */ S0(0, "待付款"), /** 2-已支付(待发货) */ S2(2, "已支付(待发货)"), /** 3-已发货(待收货) */ S3(3, "已发货(待收货)"), /** 4-已收货(待评价) */ S4(4, "已收货(待评价)"), /** 5-已评价 */ S5(5, "已评价"); private Integer value; private String desc; OrderState(Integer value, String desc) { this.value = value; this.desc = desc; } public Integer value() { return value; } public String desc() { return desc; } }
<filename>src/main/java/genepi/haplogrep/util/HgClassifier.java package genepi.haplogrep.util; import java.io.IOException; import org.jdom.JDOMException; import core.SampleFile; import core.TestSample; import exceptions.parse.sample.InvalidRangeException; import phylotree.Phylotree; import phylotree.PhylotreeManager; import search.ranking.HammingRanking; import search.ranking.JaccardRanking; import search.ranking.KulczynskiRanking; import search.ranking.RankingMethod; public class HgClassifier { public void run(SampleFile newSampleFile, String phyloTree, String fluctrates, String metric) throws InvalidRangeException, JDOMException, IOException { run(newSampleFile, phyloTree, fluctrates, metric, 1, false); } public void run(SampleFile newSampleFile, String phyloTree, String fluctrates, String metric, int amountResults, boolean fixNomenclature) throws JDOMException, IOException, InvalidRangeException { Phylotree phylotree = PhylotreeManager.getInstance().getPhylotree(phyloTree, fluctrates); RankingMethod newRanker = null; switch (metric) { case "kulczynski": newRanker = new KulczynskiRanking(amountResults); break; case "hamming": newRanker = new HammingRanking(amountResults); break; case "jaccard": newRanker = new JaccardRanking(amountResults); break; default: newRanker = new KulczynskiRanking(amountResults); } if(fixNomenclature) { newSampleFile.applyNomenclatureRules(phylotree, "rules.csv"); } newSampleFile.updateClassificationResults(phylotree, newRanker); } }
const { prepareNextExpressApp } = require('@core/keystone/test.utils') const URL_PREFIX = '/' const NAME = 'FRONT05NEXT' async function prepareBackServer (server) {} async function prepareBackApp () { const { app } = await prepareNextExpressApp(__dirname) return app } module.exports = { NAME, URL_PREFIX, prepareBackApp, prepareBackServer, }
#!/bin/bash ## Copyright (c) 2021 mangalbhaskar. All Rights Reserved. ##__author__ = 'mangalbhaskar' ###---------------------------------------------------------- ## Utilility functions for nvidia, gpu ###---------------------------------------------------------- function lsd-mod.nvidia.get__vars() { lsd-mod.log.echo "NVIDIA_DRIVER_VER: ${bgre}${NVIDIA_DRIVER_VER}${nocolor}" lsd-mod.log.echo "NVIDIA_OS_ARCH: ${bgre}${NVIDIA_OS_ARCH}${nocolor}" lsd-mod.log.echo "NVIDIA_CUDA_REPO_KEY: ${bgre}${NVIDIA_CUDA_REPO_KEY}${nocolor}" lsd-mod.log.echo "NVIDIA_GPGKEY_SUM: ${bgre}${NVIDIA_GPGKEY_SUM}${nocolor}" lsd-mod.log.echo "NVIDIA_GPGKEY_FPR: ${bgre}${NVIDIA_GPGKEY_FPR}${nocolor}" lsd-mod.log.echo "NVIDIA_REPO_BASEURL: ${bgre}${NVIDIA_REPO_BASEURL}${nocolor}" lsd-mod.log.echo "NVIDIA_CUDA_REPO_BASEURL: ${bgre}${NVIDIA_CUDA_REPO_BASEURL}${nocolor}" lsd-mod.log.echo "NVIDIA_ML_REPO_BASEURL: ${bgre}${NVIDIA_ML_REPO_BASEURL}${nocolor}" lsd-mod.log.echo "NVIDIA_DRIVER_INSTALLED: ${bgre}${NVIDIA_DRIVER_INSTALLED}${nocolor}" lsd-mod.log.echo "NVIDIA_DOCKER_CUDA_REPO_URL: ${bgre}${NVIDIA_DOCKER_CUDA_REPO_URL}${nocolor}" lsd-mod.log.echo "NVIDIA_DOCKER_URL: ${bgre}${NVIDIA_DOCKER_URL}${nocolor}" lsd-mod.log.echo "NVIDIA_DOCKER_KEY_URL: ${bgre}${NVIDIA_DOCKER_KEY_URL}${nocolor}" } function lsd-mod.nvidia.get__driver_avail() { declare -a nvidia_driver_avail=($(apt-cache search nvidia-driver | grep -Eo "^nvidia-driver-[0-9]+\s" | cut -d'-' -f3 | sort)) echo "${nvidia_driver_avail[@]}" } function lsd-mod.nvidia.get__driver_info() { ###---------------------------------------------------------- ## After successful Nvidia Driver installation ## check version of Driver installed ###---------------------------------------------------------- lsd-mod.log.info "Checking for version of Driver installed..." nvidia-settings -q gpus # show all attributes #info "" #info "show all attributes" #nvidia-settings -q all nvidia-smi nvidia-smi -q | grep "Driver Version" #nvidia-smi -h #nvidia-smi --help-query-gpu #nvidia-smi --query-gpu=count,gpu_name,memory.total,driver_version,clocks.max.memory,compute_mode --format=csv,noheader nvidia-smi --query-gpu=count,gpu_name,memory.total,driver_version,clocks.max.memory,compute_mode --format=csv lsmod | grep -i nouveau # this should not return anything lsmod | grep -i nvidia # this should not return anything ### sample output ## nvidia_drm 49152 0 ## nvidia_modeset 1114112 1 nvidia_drm ## nvidia 18808832 1 nvidia_modeset ## drm_kms_helper 204800 2 nvidia_drm,i915 ## ipmi_msghandler 65536 2 ipmi_devintf,nvidia ## drm 487424 6 drm_kms_helper,nvidia_drm,i915 prime-select query # should return: nvidia } function lsd-mod.nvidia.get__gpu_stats() { local _delay=$1 [[ ! -z ${_delay} ]] || _delay=5 lsd-mod.log.debug "_delay: ${_delay} seconds" ## dmon is experimental # nvidia-smi dmon nvidia-smi -L # nvidia-smi -L | wc -l # https://stackoverflow.com/a/8225492 # nvidia-smi -q -g 0 -d UTILIZATION -l # https://github.com/Syllo/nvtop # sudo apt install nvtop # https://stackoverflow.com/a/37664194 # ps f -o user,pgrp,pid,pcpu,pmem,start,time,command -p `lsof -n -w -t /dev/nvidia*` # watch -n 0.1 'ps f -o user,pgrp,pid,pcpu,pmem,start,time,command -p `sudo lsof -n -w -t /dev/nvidia*`' # watch -n 1 nvidia-smi --format=csv --query-gpu=power.draw,utilization.gpu,fan.speed,temperature.gpu ## https://www.slideshare.net/databricks/monitoring-of-gpu-usage-with-tensorflow-models-using-prometheus ##nvidia-smi --query-gpu=timestamp,name,pci.bus_id,driver_version,pstate,pcie.link.gen.max,pcie.link.gen.current,temperature.gpu,utilization.gpu,utilization.memory,memory.total,memory.free,memory.used --format=csv -l ${_delay} ## added power.draw nvidia-smi --query-gpu=timestamp,name,pci.bus_id,driver_version,pstate,pcie.link.gen.max,pcie.link.gen.current,temperature.gpu,power.draw,utilization.gpu,utilization.memory,memory.total,memory.free,memory.used --format=csv -l ${_delay} # nvidia-smi --query-gpu=index,timestamp,power.draw,clocks.sm,clocks.mem,clocks.gr --format=csv ## https://github.com/teh/nvidia-smi-prometheus/blob/master/src/Main.hs # nvidia-smi dmon -c 10 # chrome://tracing # nvidia-smi --help-query-gpu # nvidia-smi -l 1 # watch -n 1 nvidia-smi #function lsd-mod.nvidia.better-nvidia-smi () { # nvidia-smi # join -1 1 -2 3 \ # <(nvidia-smi --query-compute-apps=pid,used_memory \ # --format=csv \ # | sed "s/ //g" | sed "s/,/ /g" \ # | awk 'NR<=1 {print toupper($0)} NR>1 {print $0}' \ # | sed "/\[NotSupported\]/d" \ # | awk 'NR<=1{print $0;next}{print $0| "sort -k1"}') \ # <(ps -a -o user,pgrp,pid,pcpu,pmem,time,command \ # | awk 'NR<=1{print $0;next}{print $0| "sort -k3"}') \ # | column -t #} #lsd-mod.nvidia.better-nvidia-smi ## TBD: log gpustats #nvidia-smi --format=csv --query-gpu=power.draw,utilization.gpu,fan.speed,temperature.gpu -l >> hmd-06032019.txt #nvidia-smi --format=csv --query-gpu=power.draw,utilization.gpu,fan.speed,temperature.gpu -lms >> hmd-06032019.txt ## TBD ##---------------------- # nvidia-smi --format=csv --query-gpu=power.draw,utilization.gpu,fan.speed,temperature.gpu -l 1 -f $1 ## https://towardsdatascience.com/burning-gpu-while-training-dl-model-these-commands-can-cool-it-down-9c658b31c171 ## “GPUFanControlState=1” means you can change the fan speed manually, “[fan:0]” means which gpu fan you want to set, “GPUTargetFanSpeed=100” means setting the speed to 100%, but that will be so noisy, you can choose 80%. # nvidia-settings -a "[gpu:0]/GPUFanControlState=1" -a "[fan:0]/GPUTargetFanSpeed=80" ## https://www.andrey-melentyev.com/monitoring-gpus.html # https://github.com/Syllo/nvtop#nvtop-build # https://github.com/wookayin/gpustat # https://timdettmers.com/2018/12/16/deep-learning-hardware-guide/ # https://developer.android.com/ndk/guides/neuralnetworks # https://www.xenonstack.com/blog/log-analytics-deep-machine-learning/ # https://dzone.com/articles/how-to-train-tensorflow-models-using-gpus # https://tutorials.ubuntu.com/tutorial/viewing-and-monitoring-log-files#0 # https://linoxide.com/linux-command/linux-pidstat-monitor-statistics-procesess/ # https://www.ubuntupit.com/most-comprehensive-list-of-linux-monitoring-tools-for-sysadmin/ - **best reference** # https://www.nagios.com/solutions/linux-monitoring/ # https://github.com/nicolargo/glances # https://glances.readthedocs.io/ # pip install glances # pip install 'glances[action,browser,cloud,cpuinfo,docker,export,folders,gpu,graph,ip,raid,snmp,web,wifi]' # https://www.linuxtechi.com/monitor-linux-systems-performance-iostat-command/ # https://www.linuxtechi.com/generate-cpu-memory-io-report-sar-command/ - **best report generation by hands** # cat /etc/sysstat/sysstat # sar 2 5 -o /tmp/data > /dev/null 2>&1 ## https://stackoverflow.com/questions/10508843/what-is-dev-null-21 # https://en.wikipedia.org/wiki/Device_file#Pseudo-devices. # >> /dev/null redirects standard output (stdout) to /dev/null, which discards it. # 2>&1 redirects standard lsd-mod.log.error (2) to standard output (1), which then discards it as well since standard output has already been redirected. # & indicates a file descriptor. There are usually 3 file descriptors - standard input, output, and error. # Let's break >> /dev/null 2>&1 statement into parts: # Part 1: >> output redirection # This is used to redirect the program output and append the output at the end of the file # https://unix.stackexchange.com/questions/89386/what-is-symbol-and-in-unix-linux # Part 2: /dev/null special file # This is a Pseudo-devices special file. # Command ls -l /dev/null will give you details of this file: # crw-rw-rw-. 1 root root 1, 3 Mar 20 18:37 /dev/null # Did you observe crw? Which means it is a pseudo-device file which is of character-special-file type that provides serial access. # /dev/null accepts and discards all input; produces no output (always returns an end-of-file indication on a read) # Part 3: 2>&1 file descriptor # Whenever you execute a program, operating system always opens three files STDIN, STDOUT, and STDERR as we know whenever a file is opened, operating system (from kernel) returns a non-negative integer called as File Descriptor. The file descriptor for these files are 0, 1, 2 respectively. # So 2>&1 simply says redirect STDERR to STDOUT ## https://linoxide.com/tools/vmstat-graphical-mode/ ## https://github.com/joewalnes/websocketd # https://glances.readthedocs.io/en/stable/cmds.html#interactive-commands # https://www.vioan.eu/blog/2016/10/10/deploy-your-flask-python-app-on-ubuntu-with-apache-gunicorn-and-systemd/ # https://www.linode.com/docs/applications/big-data/how-to-move-machine-learning-model-to-production/ # https://www.pyimagesearch.com/2018/01/29/scalable-keras-deep-learning-rest-api/ # https://blog.keras.io/building-a-simple-keras-deep-learning-rest-api.how-to-move-machine-learning-model-to-production }
<filename>irrdb.legacy/src/programs/irr_notify/notify.c /* * $Id: notify.c,v 1.22 2002/10/17 20:25:56 ljb Exp $ */ #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <string.h> #include <sys/types.h> #include <regex.h> #include <unistd.h> #include <time.h> #include <irr_notify.h> #include <pgp.h> extern char *test_addr; /* '\0' terminated set of email addrs. * Theses addrs are used to notify users * that authorised changes have occured * to their objects. */ char notify_addrs[MAX_ADDR_SIZE]; char *nnext; int nndx[MAX_NDX_SIZE]; int num_notify; /* '\0' terminated set of email addrs. * These addrs are used to notify users of * unauthorised updates. */ char forward_addrs[MAX_ADDR_SIZE]; char *fnext; int fndx[MAX_NDX_SIZE]; int num_forward; /* For uniform treatment, even though * there is only one sender, make it * like a forward_addr or notify_addr case */ char sender_addrs[MAX_ADDR_SIZE]; char *snext; int sndx[1]; int num_sender; char buf[MAXLINE]; /* local yokel's */ static void perform_rpsdist_trans (trace_t *, FILE *, ret_info_t *, int, char *, long, char *IRRd_HOST, int IRRd_PORT, char *dbpdir); static void perform_transactions (trace_t *, FILE *, ret_info_t *, int, char *, int, char *); /* static void perform_transactions_new (trace_t *, FILE *, ret_info_t *, int, char *, int, char *); */ static void remove_tempfiles (trace_t *); static FILE *rpsdist_fopen (char *); static char *send_rps_dist_trans (trace_t *, FILE *, ret_info_t *, char *, char *, long, char *, int); static char *init_jentries (trace_t *, char *, long, char *, FILE *); static char *init_irrd_updates (trace_t *, FILE *, FILE *, ret_info_t *, const char *); static char *init_pgp_updates (trace_t *, FILE *, ret_info_t *, char *, int *); static long get_irrd_cs (trace_t *, char *, char *, int); static void pgp_files_backout (char *); static char *rpsdist_timestamp (char *); /* Control the action of performing the udpates and sending * out notifications. Briefly, for auth failures all referenced * upd_to: fields will be notified. For error-free updates (ie, * no syntax and no auth errors) notifications will be sent to * all referenced notify: and mnt_nfy: field addresses. The * sender is always notified unless the '-x' command line flag is set * (see below). * * notify () will send the updates to IRRd. If IRRd encounters * an error and/or cannot apply the update the IRRd error message * will be relayed in the notification. * * 'null_notification' = 1 causes notify () to skip * all notifications. In this case, notify () will send the * updates to IRRd but no notifications will be sent. '*tmpfname' * is the file template for 'mkstemp ()' to use to build * the notification files. There will be one notification file * per unique notify/updto email address. * * 'null_submission' means the user sent in an empty submission. * For an email submission all we have is the email header and an * empty body. For a TCP submission all we have is an empty body * and a return IP address. Note that 'null_submission' would * have been better name 'non_null_lines' since 'null_submission' * equal to 0 means we have a NULL submission. * * Return: * void * Results of the updates are included in the notifications. */ void notify (trace_t *tr, char *tmpfname, FILE *fin, int null_submission, int null_notification, int dump_stdout, char *web_origin_str, int rps_dist_flag, char *IRRd_HOST, int IRRd_PORT, char *db_admin, char *pgpdir, char *dbdir, char *tlogfn, long tlog_fpos, FILE *ack_fd, char * from_ip) { ret_info_t rstart; trans_info_t trans_info; char buf[MAXLINE]; irrd_result_t *p; long offset = 0; char pbuf[256]; /*fprintf (dfile, "Enter notify()\n");*/ rstart.first = rstart.last = NULL; if (rps_dist_flag) perform_rpsdist_trans (tr, fin, &rstart, null_submission, tlogfn, tlog_fpos, IRRd_HOST, IRRd_PORT, dbdir); else perform_transactions (tr, fin, &rstart, null_submission, IRRd_HOST, IRRd_PORT, pgpdir); /* JW want to go to this when we make irr_submit/IRRd transaction compliant perform_transactions_new (tr, fin, &rstart, null_submission, IRRd_HOST, IRRd_PORT, pgpdir); */ p = rstart.first; /* just to be safe rewind */ if (fseek (fin, 0L, SEEK_SET) != 0) { fprintf (stderr, "ERROR: cannot rewind input file, exit!\n"); exit (0); } /* init global data structures */ nnext = notify_addrs; fnext = forward_addrs; snext = sender_addrs; num_notify = num_forward = num_sender = 0; /* pointer to array of file names and handles to * notify/forward mail replies. */ num_hdls = 0; while (fgets (buf, MAXLINE, fin) != NULL) { if (strncmp (HDR_START, buf, strlen (HDR_START) - 1)) continue; /* fprintf (dfile, "found a start header %s strlen-(%d)\n", buf, strlen (buf));*/ if (parse_header (tr, fin, &offset, &trans_info)) break; /* illegal hdr field found or EOF * (ie, no object after hdr) */ /* Make sure sender is not getting duplicate notifications */ if (trans_info.hdr_fields & FROM_F) remove_sender (trans_info.sender_addrs, trans_info.notify_addrs, &(trans_info.nnext)); else if (dump_stdout) { /* We have a tcp user, ie, an IRRj user */ trans_info.hdr_fields |= FROM_F; if(from_ip == NULL) from_ip = "localhost"; sprintf(pbuf,"TCP(%s)", from_ip); strcpy (trans_info.sender_addrs, pbuf); trans_info.snext += strlen (trans_info.sender_addrs) + 1; } trans_info.web_origin_str = web_origin_str; if (web_origin_str != NULL) { sprintf(pbuf,"%s Route Registry Update", trans_info.source ? trans_info.source : ""); trans_info.subject = strdup (pbuf); } /* JW this is for debug only */ /* print_hdr_struct (dfile, &trans_info); */ chk_email_fields (&trans_info); if (!(trans_info.hdr_fields & OP_F)) trans_info.op = strdup ("UPDATE"); if (!(trans_info.hdr_fields & OBJ_KEY_F)) trans_info.obj_key = strdup (""); if (!(trans_info.hdr_fields & OBJ_TYPE_F)) trans_info.obj_type = strdup (""); if (chk_hdr_flds (trans_info.hdr_fields)) { build_notify_responses (tr, tmpfname, fin, &trans_info, p, db_admin, MAX_IRRD_OBJ_SIZE, null_notification); if ((trans_info.hdr_fields & OLD_OBJ_FILE_F) && (*trans_info.old_obj_fname < '0' || *trans_info.old_obj_fname > '9')) unlink (trans_info.old_obj_fname); } /*else fprintf (dfile, "nofify () bad hdr file found, skipping...\n");*/ free_ti_mem (&trans_info); p = p->next; } send_notifies (tr, null_notification, ack_fd, dump_stdout); remove_tempfiles (tr); /*fprintf (dfile, "Exit notify ()\n");*/ } /* Close and remove all the notification temp files. * * Return: * void */ void remove_tempfiles (trace_t *tr) { int i; for (i = 0; i < num_hdls; i++) { fclose (msg_hdl[i].fp); remove (msg_hdl[i].fname); } } /* Move to this function in phase transition 2 when we convert * irr_submit/irrd to transaction * * 'submission_count_lines' is a count of the non-null lines * in the submission. Equal to 0 means the user supplied an * empty submission. * * Return: * */ void perform_transactions_new (trace_t *tr, FILE *fin, ret_info_t *start, int submission_count_lines, char *IRRd_HOST, int IRRd_PORT, char *pgpdir) { int all_noop; char *ret_code; irrd_result_t *p; /* rewind */ fseek (fin, 0L, SEEK_SET); /* JW:!!!!: Need to have pick_off_header_info () check for all NOOP's * want to avoid sending a transaction in which all objects are NOOP's */ /* Loop through the submission file, initializing the 'ti' * struct with the header info and added to the linked list of 'ti's * pointed to by 'start'. If any errors (user or server) * are encountered then abort the transaction. */ if (pick_off_header_info (tr, fin, submission_count_lines, start, &all_noop)) { trace (NORM, tr, "Submission error(s) found. Abort transaction.\n"); /* We are aborting the transaction. So set the proper * user return information to let the user know that the objects * with no errors are being skipped because of transaction * semantics. */ reinit_return_list (tr, start, SKIP_RESULT); } else if (submission_count_lines == 0) trace (ERROR, tr, "NULL submission.\n"); /* if all the obj's in the trans are NOOP's then don't send to irrd/rps-dist */ else if (!all_noop) { trace (NORM, tr, "calling irrd_trans ().\n"); /* Send the transaction to rps dist to be added to the DB */ ret_code = irrd_transaction_new (tr, (char *) WARN_TAG, fin, start, IRRd_HOST, IRRd_PORT); trace (NORM, tr, "return from irrd_trans ().\n"); /* Remove any key certificate files from our temp directory area */ for (p = start->first; p != NULL; p = p->next) { /* check for no IRRd errors and we have a key-cert object */ if (!put_transaction_code_new (tr, p, ret_code) && is_keycert_obj (p)) update_pgp_ring_new (tr, p, pgpdir); if (p->keycertfn != NULL) remove (p->keycertfn); } } trace (NORM, tr, "exit perform_transactions_new ().\n"); } /* * * 'submission_count_lines' is a count of the non-null lines * in the submission. Equal to 0 means the user supplied an * empty submission. * * Return: * */ void perform_rpsdist_trans (trace_t *tr, FILE *fin, ret_info_t *start, int submission_count_lines, char *tlogfn, long tlog_fpos, char *IRRd_HOST, int IRRd_PORT, char *dbdir) { int all_noop; char *ret_code; irrd_result_t *p; /* rewind */ fseek (fin, 0L, SEEK_SET); /* JW:!!!!: need a check to make sure all the sources are consistent, * ie, cannot accept a transaction that spans multiple source DB's */ /* Loop through the submission file, initializing the 'ti' * struct with the header info and added to the linked list of 'ti's * pointed to by 'start'. If any errors (user or server) * are encountered then abort the transaction. */ if (pick_off_header_info (tr, fin, submission_count_lines, start, &all_noop)) { trace (NORM, tr, "Submission error(s) found. Abort transaction.\n"); /* We are aborting the transaction. So set the proper * user return information to let the user know that the objects * with no errors are being skipped because of transaction * semantics. */ reinit_return_list (tr, start, SKIP_RESULT); } else if (submission_count_lines == 0) trace (NORM, tr, "Empty submission.\n"); /* if all the obj's in the trans are NOOP's then don't send to irrd/rps-dist */ else if (!all_noop) { /* send the transaction to RPS-DIST */ ret_code = send_rps_dist_trans (tr, fin, start, dbdir, tlogfn, tlog_fpos, IRRd_HOST, IRRd_PORT); if (ret_code == NULL) trace (NORM, tr, "perform_rpsdist_trans (): back from send_rps_dist_trans (), good trans!\n"); else trace (NORM, tr, "perform_rpsdist_trans (): back from send_rps_dist_trans () bad trans (%s)\n", ret_code); /* Place the irrd result in our linked list for notifications */ for (p = start->first; p != NULL; p = p->next) { if (!(p->svr_res & NOOP_RESULT)) put_transaction_code_new (tr, p, ret_code); /* remove any inital PGP public key files */ if (p->keycertfn != NULL) remove (p->keycertfn); } } trace (NORM, tr, "exit perform_rpsdist_trans ()\n"); return; } /* Build the communication files and send the names to RPS-DIST. Routine * expects that there are no errors in the transaction (auth, syntax, ...) * and that there is at least one valid update to be committed by IRRd * (ie, not a file of all NOOP's or an empty submission). * * Input: * -the canonicalized object file (prepended with pipeline headers) (fin) * -pointer to the 'source' DB for this transaction (start) * -pointer to the absolute directory path of the DB cache. This is where * the RPS-DIST communication files will go (dbdir) * -name of the bcc transaction log (tlogfn) * -starting file position within the transaction log of this transaction. * The user's original entry is needed to build the journal entry for * RPS-DIST (tlog_fpos) * -IRRd host. Might be needed to contact IRRd to determine trans * outcome (IRRd_HOST) * -IRRd port. Might be needed to contact IRRd to determine trans * outcome (IRRd_PORT) * * Return: * -NULL to indicate the transaction was successfully committed by IRRd * -A text message indicating a transaction error occured and was rolled * back. Also is possible transaction outcome can not be determined if * RPS-DIST times out and IRRd cannot be contacted. */ char *send_rps_dist_trans (trace_t *tr, FILE *fin, ret_info_t *start, char *dbdir, char *tlogfn, long tlog_fpos, char *IRRd_HOST, int IRRd_PORT) { int pgp_updates_count; char *ret_code; char template_n [1024], irrd_n[1024], pgp_n[1024], journal_n[1024]; FILE *irrd_f = NULL, *pgp_f = NULL, *journal_f = NULL; /* sanity check */ if (dbdir == NULL) { trace (ERROR, tr, "send_rps_dist_trans () Unspecified DB cache. Abort rps_dist transaction!\n"); return "SERVER ERROR: Unspecified DB cache. Please set the 'irr_directory' in your irrd.conf file"; } /* create the irrd, pgp and journal files */ sprintf (template_n, "%s/irr_submit.XXXXXX", dbdir); strcpy (irrd_n, template_n); strcpy (pgp_n, template_n); strcpy (journal_n, template_n); if (((irrd_f = rpsdist_fopen (irrd_n)) == NULL) || ((pgp_f = rpsdist_fopen (pgp_n)) == NULL) || ((journal_f = rpsdist_fopen (journal_n)) == NULL)) { trace (ERROR, tr, "send_rps_dist_trans () rps dist file creation error. Abort rps_dist transaction!\n"); ret_code = "SERVER ERROR: rps dist file creation error"; goto ABORT_TRANS; } trace (NORM, tr, "Debug. comm file names:\n"); trace (NORM, tr, "Debug. irrd (%s)\n", irrd_n); trace (NORM, tr, "Debug. pgp (%s)\n", pgp_n); trace (NORM, tr, "Debug. jentry (%s)\n", journal_n); /* initialize the irrd, pgp and journal files */ /* This is the !us...!ue data */ if ((ret_code = init_irrd_updates (tr, fin, irrd_f, start, WARN_TAG))) goto ABORT_TRANS; fclose (irrd_f); irrd_f = NULL; /* This is the PGP update data for the server's local pgp ring */ if ((ret_code = init_pgp_updates (tr, pgp_f, start, template_n, &pgp_updates_count))) goto ABORT_TRANS; fclose (pgp_f); pgp_f = NULL; /* 'NULL' file name is a flag value for RPS-DIST that there are * no pgp updates */ if (pgp_updates_count == 0) { remove (pgp_n); strcpy (pgp_n, "NULL"); } /* This is the journal entry for the user's submission */ if ((ret_code = init_jentries (tr, tlogfn, tlog_fpos, start->first->source, journal_f))) goto ABORT_TRANS; fclose (journal_f); trace (NORM, tr, "calling rps_dist_trans ()\n"); /* trace (NORM, tr, "Debug. Bye-bye\n"); exit (0); */ /* Send the transaction to rps dist to be added to the DB */ ret_code = rpsdist_transaction (tr, irrd_n, pgp_n, journal_n, start->first->source, "localhost", 7777); if (ret_code != NULL) trace (NORM, tr, "return from irrd_trans (%s).\n", ret_code); else trace (NORM, tr, "return from irrd_trans (NULL return) Yuck!\n"); /* "C\n means IRRd commited the transaction */ if (!strcmp (ret_code, "C\n")) ret_code = NULL; /* "cs" means we did not get an IRRd trans result. So get the "cs" * from IRRd to see if the trans succeeded */ else if ((*ret_code < '0' || *ret_code >'9') && (get_irrd_cs (tr, start->first->source, IRRd_HOST, IRRd_PORT) < atol (ret_code))) ret_code = "Transaction result not known. Query IRRd to determine transaction result or resubmit your transaction at a later time."; return ret_code; ABORT_TRANS: trace (ERROR, tr, "send_rps_dist_trans () Aborting transaction! (%s)\n", ret_code); /* clean up our rps dist communication files */ if (irrd_f != NULL) fclose (irrd_f); if (pgp_f != NULL) fclose (pgp_f); if (journal_f != NULL) fclose (journal_f); if (strcmp (irrd_n, "")) remove (irrd_n); if (strcmp (pgp_n, "NULL") && strcmp (pgp_n, "")) { pgp_files_backout (pgp_n); remove (pgp_n); } if (strcmp (journal_n, "")) remove (journal_n); return ret_code; } /* Get the latest current serial for DB 'source'. * * Input: * -the DB source to get the current serial for (source) * -the IRRd host (host) * -the IRRd port (port) * * Return: * -the latest current serial * -0 if there was any type of error */ long get_irrd_cs (trace_t *tr, char *source, char *host, int port) { char *data; regmatch_t cs_rm[2]; regex_t cs_re; char *cs = "^[^:]+:[^:]+:[[:digit:]]+-([[:digit:]]+)\n$"; /* get the !j output from IRRd */ data = irrd_curr_serial (tr, source, host, port); /* now parse the output and return the currentserial */ if (data != NULL) { regcomp (&cs_re, cs, REG_EXTENDED); if (regexec (&cs_re, data, 2, cs_rm, 0) == 0) { *(data + cs_rm[1].rm_eo) = '\0'; return atol ((char *) (data + cs_rm[1].rm_so)); } } return 0; } /* Open up a streams file. * * Return: * A stream file pointer if the operation was a success. * NULL if the file could not be opened. */ FILE *rpsdist_fopen (char *fname) { FILE *fp; int fd; fd = mkstemp (fname); if (fd == -1) return NULL; if ((fp = fdopen (fd, "w")) == NULL) { close(fd); return NULL; } return fp; } /* Generate an RFC 2769 timestamp (pg. 13). Timestamps are of * the form: * YYYYMMDD HH:MM:SS [+/-]hh:mm * * eg, 20000717 12:28:51 +04:00 * * Input: * void * * Return: * an RPS DIST RFC 2769 timestamp */ char *rpsdist_timestamp (char *ts) { time_t now; now = time (NULL); strftime (ts, 256, "%Y%m%d %H:%M:%S ", gmtime (&now)); /* UTC_OFFSET is the [+/-]hh:mm value, ie, the amount * we are away from UTC time */ strcat (ts, UTC_OFFSET); return ts; } /* Remove any PGP key files from the RPS-DIST cache area. * See init_pgp_updates () for the file format. * * Input: * -name of the PGP control file which has the fully qualified * path name of the PGP key files (pgpfn) * * Return: * void */ void pgp_files_backout (char *pgpfn) { int rm = 0; char buf[MAXLINE]; FILE *fin; /* sanity check */ if (pgpfn == NULL || (fin = fopen (pgpfn, "r")) == NULL) return; /* we're hosed ... */ /* remove any PGP key files we may have created in the * RPS-DIST cache area */ while (fgets (buf, MAXLINE, fin) != NULL) { if (rm) { buf[strlen (buf) - 1] = '\0'; /* get rid of the '\n' */ remove (buf); } rm = !strcmp ("ADD", buf); } fclose (fin); } /* Build the RPS-DIST journal entry. See RFC 2769, pg 30 for a * description of the journal format. * * Input * -the name of the trace log where the initial user copy is (logfn) * -the file position with the trace log where the submission begins (fpos) * -the journal entry output file for RPS-DIST (fout) * * Return: * NULL if no errors occur in building the ouput file (fout) * otherwise a string message explaining the error condition */ char *init_jentries (trace_t *tr, char *logfn, long fpos, char *source, FILE *fout) { int first_line = 1, in_headers = 1, pgp_reg = 0; int passwd = 0, in_sig = 0, need_sig = 1, in_blankline = 0; regex_t mailfromre, pgpbegre, pgpsigre, pgpendre, blanklinere, passwdre, EOT; char curline[MAXLINE], ts[256], *ret_code; FILE *fin; char *mailfrom = "^From[ \t]"; char *pgpbegin = "^-----BEGIN PGP SIGNED MESSAGE-----"; char *pgpsig = "^-----BEGIN PGP SIGNATURE-----"; char *pgpend = "^-----END PGP SIGNATURE-----"; char *blankline = "^[ \t]*\n$"; char *password = <PASSWORD>:"; char *eot = "^---\n$"; /* sanity check */ if (logfn == NULL) { ret_code = "SERVER ERROR: Can't find the initial submission log."; goto JENTRY_ABORT; } /* open the transaction carbon copy log file */ if ((fin = fopen (logfn, "r")) == NULL) { ret_code = "SERVER ERROR: RPS-DIST PGP fopen () error."; goto JENTRY_ABORT; } /* compile our regular expressions */ regcomp (&mailfromre, mailfrom, REG_EXTENDED|REG_NOSUB); regcomp (&pgpbegre, pgpbegin, REG_EXTENDED|REG_NOSUB); regcomp (&pgpsigre, pgpsig, REG_EXTENDED|REG_NOSUB); regcomp (&pgpendre, pgpend, REG_EXTENDED|REG_NOSUB); regcomp (&blanklinere, blankline, REG_EXTENDED|REG_NOSUB); regcomp (&passwdre, password, REG_EXTENDED|REG_ICASE|REG_NOSUB); regcomp (&EOT, eot, REG_EXTENDED|REG_NOSUB); /* seek to the beginning of the submission */ fseek (fin, fpos, SEEK_SET); /* prepend the redistribution header (RFC 2769, section A.2) */ fprintf (fout, "transaction-label: %s\n", source); fprintf (fout, "sequence: 1234567890\n"); fprintf (fout, "timestamp: %s\n", rpsdist_timestamp (ts)); fprintf (fout, "integrity: authorized\n\n"); /* copy the transaction "as-is" from the user for the RPS-DIST * journal file */ while (fgets (curline, MAXLINE, fin) != NULL) { if (first_line && regexec (&mailfromre, curline, 0, 0, 0) != 0) in_headers = 0; first_line = 0; /* skip email header to conform to the RPS-DIST redistribution encoding */ if (in_headers && regexec (&blanklinere, curline, 0, 0, 0) == 0) in_headers = 0; if (in_headers) continue; in_blankline = 0; /* check for an end of transaction line '---' */ if (regexec (&EOT, curline, 0, 0, 0) == 0) break; /* all done, exit transaction */ /* check for a password, eg, 'password: <PASSWORD>' and skip to * conform to the RPS-DIST redistribution encoding */ if (!pgp_reg && regexec (&passwdre, curline, 0, 0, 0) == 0) { passwd = 1; continue; /* skip the regular signature begin */ } /* check for a '-----BEGIN PGP SIGNED MESSAGE-----' and skip it to * conform to the RPS-DIST redistribution encoding */ if (!pgp_reg && regexec (&pgpbegre, curline, 0, 0, 0) == 0) { pgp_reg = 1; continue; /* skip the regular signature */ } /* check for a '-----BEGIN PGP SIGNATURE-----' and skip if a regular * signature to conform to the RPS-DIST redistribution encoding */ if (regexec (&pgpsigre, curline, 0, 0, 0) == 0) { in_sig = 1; if (!pgp_reg) { fputs ("\nsignature:\n", fout); need_sig = 0; } } /* skip the PGP sig for regular sig's and keep for detached */ if (in_sig) { /* skip pgp regular sig's */ if (pgp_reg) continue; else fputs ("+", fout); } /* check for a '-----END PGP SIGNATURE-----', stop adding * '+'s for RPSL line continuation at the beginning of each line */ if (in_sig && regexec (&pgpendre, curline, 0, 0, 0) == 0) in_sig = 0; /* check for a blank line as the last line. need to know * when adding the 'signature' meta-object as the server * add's a blank line after transactions. on the last * transaction in the file there will not be a blank line * as the last line (ie, from the server). */ if (regexec (&blanklinere, curline, 0, 0, 0) == 0) in_blankline = 1; /* write a line to our journal */ fputs (curline, fout); } /* add a 'signature' meta-object if one is needed */ if (need_sig) { if (!in_blankline) fputs ("\n", fout); if (pgp_reg) fputs ("signature:\n <PGP REGULAR>\n", fout); else if (passwd) fputs ("signature:\n <CLEARTEXT PASSWORD>\n", fout); else fputs ("signature:\n <MAIL FROM>\n", fout); } /* make purify happy */ regfree (&mailfromre); regfree (&pgpbegre); regfree (&pgpsigre); regfree (&pgpendre); regfree (&blanklinere); regfree (&passwdre); regfree (&EOT); fclose (fin); return NULL; JENTRY_ABORT: /* if we get here, someth'in went wrong */ sprintf (curline, "init_jentries() %s Abort rps_dist transaction!", ret_code); trace (ERROR, tr, "%s\n", curline); return strdup (curline); } /* Make the !us...!ue file for submission to IRRd by RPS-DIST. * * Input: * -pipeline input file with all the canonicalized objects (fin) * note that each canonicalized object is preceeded with pipeline * header info. * -routine expects a file to be opened and ready for writing (fout) * -a pointer to the begining of the linked list of updates (start) * * Return: * NULL if no errors occur in building the ouput file (fout) * otherwise a string message explaining the error condition */ char *init_irrd_updates (trace_t *tr, FILE *fin, FILE *fout, ret_info_t *start, const char *warn_tag) { int n, line_cont, line_begin; irrd_result_t *p; char *ret_code; char *OP[] = {"ADD\n\n", "DEL\n\n"}, buf[MAXLINE]; /* !us<DB source> */ fprintf (fout, "!us%s\n", start->first->source); /* Loop through the submission file and build the * !us...!ue IRRd update file */ for (p = start->first; p != NULL; p = p->next) { /* Skip NOOP operations */ if (!(p->svr_res & NOOP_RESULT)) { /* determine the operation, 'ADD' or 'DEL' ... */ n = 0; if (!strcmp (p->op, DEL_OP)) n = 1; /* ... and write the operation to the IRRd update file */ if (fputs (OP[n], fout) == EOF) { ret_code = "SERVER ERROR: RPS-DIST IRRd operation disk error."; goto IRRd_ABORT; } /* seek to the beginning of object */ fseek (fin, p->offset, SEEK_SET); /* line cont in the fgets () sense, not in the rpsl sense. * ie, the current input line was larger than our memory buffer */ line_cont = 0; /* copy the canonicalized submission object from the input * file to the IRR update file */ while (fgets (buf, MAXLINE, fin) != NULL) { n = strlen (buf); line_begin = !line_cont; line_cont = (buf[n - 1] != '\n'); /* skip possible 'WARNING:...' lines at the end of the object */ if (line_begin && !strncmp (buf, warn_tag, strlen (warn_tag))) continue; fputs (buf, fout); if (line_begin && buf[0] == '\n') /* looking for a blank line */ break; } } } /* !ue */ fprintf (fout, "!ue\n"); return NULL; IRRd_ABORT: /* if we get here, someth'in went wrong */ sprintf (buf, "init_irrd_updates() %s Abort rps_dist transaction!", ret_code); trace (ERROR, tr, "%s\n", buf); return strdup (buf); } /* Build the RPS-DIST PGP file. RPS-DIST will use the file built * in this routine to update the server's local PGP rings. The format * of the file will be like this: * * DEL * 0x.... * * ADD * <fully qualified file name> * ... * * Note: the reason for not writing 'ADD' keys directly to the file * is because it is easier to give pgp a file name to add the key * then to read it and send it to pgp's stdin. * * Input: * -routine expects a file to be opened and ready for writing (fout) * -a pointer to the begining of the linked list of updates (start) * * Return: * -a count of the number of PGP udpates (pgp_updates_count) * -NULL if there were no errors encountered * -otherwise a string message explaining the error condition */ char *init_pgp_updates (trace_t *tr, FILE *fout, ret_info_t *start, char *template_n, int *pgp_updates_count) { int n; irrd_result_t *p; char *ret_code; char *OP[] = {"ADD\n", "DEL\n"}, buf[MAXLINE], fn[1024]; FILE *fin = NULL, *dst = NULL; /* keep track of the number of PGP udates we find */ *pgp_updates_count = 0; /* Loop through the submission list and collect data on the PGP updates */ for (p = start->first; p != NULL; p = p->next) { if (!(p->svr_res & NOOP_RESULT) && is_keycert_obj (p)) { /* determine the operation, 'ADD' or 'DEL' ... */ n = 0; if (!strcmp (p->op, DEL_OP)) n = 1; /* ... and write the operation to the PGP update file */ if (fputs (OP[n], fout) == EOF) { ret_code = "SERVER ERROR: RPS-DIST PGP operation disk error."; goto PGP_ABORT; } /* 'DEL' operation */ if (n) fprintf (fout, "0x%s\n\n", (p->obj_key + 7)); /* 'ADD' operation */ else { /* make sure the public key exists ... */ if (p->keycertfn == NULL) { ret_code = "SERVER ERROR: RPS-DIST PGP missing keycert file."; goto PGP_ABORT; } /* ... now open it */ if ((fin = fopen (p->keycertfn, "r")) == NULL) { ret_code = "SERVER ERROR: RPS-DIST PGP fopen () error."; goto PGP_ABORT; } /* open the output public key file */ strcpy (fn, template_n); if ((dst = rpsdist_fopen (fn)) == NULL) { ret_code = "SERVER ERROR: RPS-DIST PGP file creation error."; goto PGP_ABORT; } /* transfer the public key to an rps-dist PGP key update file */ while (fgets (buf, MAXLINE, fin) != NULL) fputs (buf, dst); /* write the PGP key filename to the RPS-DIST PGP control file */ fputs (fn, fout); /* This is the old code * open the public key file * if ((fin = fopen (p->keycertfn, "r")) == NULL) { ret_code = "SERVER ERROR: RPS-DIST PGP fopen () error."; goto PGP_ABORT; } * transfer the public key to the rps-dist PGP update file * while (fgets (buf, MAXLINE, fin) != NULL) fputs (buf, fout); End of old code */ /* close and remove the input public key file */ fputs ("\n", fout); fclose (fin); /* removal of the initial public key files is done in rpsdist_trans () */ fclose (dst); fin = dst = NULL; } /* count the number of PGP updates, there could be 0 */ (*pgp_updates_count)++; } } return NULL; PGP_ABORT: /* if we get here, someth'in went wrong */ if (fin != NULL) fclose (fin); if (dst != NULL) fclose (dst); sprintf (buf, "init_pgp_updates () %s Abort rps_dist transaction!", ret_code); trace (ERROR, tr, "%s\n", buf); return strdup (buf); } /* This is the old guy. We are migrating away from this version of performing * the transactions. However this works and is what we will use for now. * * Our migration path will be like this: * * (old guy) -> (irr_submit, irrd transaction compliant) -> (rpsdist) * * To get to the next step, this routine should be phased out and * perform_transactions_new () should be used. * Then to get to the last step perform_transactions_new () should be * phased out in favor of perform_rpsdist_trans (). */ void perform_transactions (trace_t *tr, FILE *fin, ret_info_t *start, int null_submission, char *IRRd_HOST, int IRRd_PORT, char *pgpdir) { char buf[MAXLINE], *ret_code; int fd, num_trans = 0; int open_conn = 0 /* JW commented out to dup rawhoisd , abort_trans = 0 */; long offset; trans_info_t ti; irrd_result_t *p; /* pgp_data_t pdat; */ /* fprintf (dfile, "\n----\nEnter perform_transactions()\n");*/ /* rewind */ fseek (fin, 0L, SEEK_SET); while (fgets (buf, MAXLINE, fin) != NULL) { if (strncmp (HDR_START, buf, strlen (HDR_START) - 1)) continue; /* JW commented out to dup rawhoisd if (!abort_trans) */ offset = ftell (fin); /* fprintf (dfile, "HDR_START offset (%ld)\n", offset);*/ /* illegal hdr field found or EOF or no object after hdr */ if (parse_header (tr, fin, &offset, &ti)) { /* JW commented out to dup rawhoisd abort_trans = 1; */ /* fprintf (dfile, "calling update_trans_outcome_list (internal error)...\n"); */ update_trans_outcome_list (tr, start, &ti, offset, INTERNAL_ERROR_RESULT, "\" Internal error: malformed header!\"\n"); free_ti_mem (&ti); continue; } else if (update_has_errors (&ti)) /* JW commented out to dup rawhoisd abort_trans = 1 */; else if (null_submission == 0) { update_trans_outcome_list (tr, start, &ti, offset, NULL_SUBMISSION, NULL); continue; } update_trans_outcome_list (tr, start, &ti, offset, 0, NULL); free_ti_mem (&ti); } /* JW commented out to dup rawhoisd * want to bring back for transaction semantic support if (abort_trans) reinit_return_list (dfile, start, SKIP_RESULT); else { */ for (p = start->first; p != NULL; p = p->next) { /* JW want to bring back in later, dup rawhoisd if (p->svr_res & NOOP_RESULT) continue; */ /* JW take next 3 sections out to reverse rawhoisd behavior */ if (p->svr_res & INTERNAL_ERROR_RESULT || p->svr_res & NULL_SUBMISSION) { trace (ERROR, tr, "Internal error or NULL submission. Object not added to IRRd.\n"); continue; } if (p->svr_res & USER_ERROR) { trace (NORM, tr, "Syntax or authorization error. Object not added to IRRd.\n"); continue; } if (p->svr_res & NOOP_RESULT) { trace (NORM, tr, "NOOP object. Object not added to IRRd.\n"); continue; } /* what the eff is this segment doing? */ if (EOF == fseek (fin, p->offset, SEEK_SET)) fprintf (stderr, "ERROR: fseek (%ld)\n", p->offset); else { fgets (buf, MAXLINE, fin); /*fprintf (dfile, "irrd_trans () line: %s", buf);*/ fseek (fin, p->offset, SEEK_SET); } /* fprintf (dfile, "perform_trans () calling irrd_transaction ()...\n");*/ ret_code = irrd_transaction (tr, (char *) WARN_TAG, &fd, fin, p->op, p->source, ++num_trans, &open_conn, IRRd_HOST, IRRd_PORT); /* check for no IRRd errors and we have a key-cert object */ if (!put_transaction_code (tr, p, ret_code) && is_keycert_obj (p) && p->op != NULL) { update_pgp_ring_new (tr, p, pgpdir); /* if (strcmp (p->op, DEL_OP)) { pgp_add (tr, pgpdir, p->keycertfn, &pdat); pgp_free (&pdat); } else pgp_del (tr, pgpdir, p->obj_key + 7); */ } } if (open_conn) { end_irrd_session (tr, fd); /* send '!q' */ fflush (fin); /* JW only needed when irrd commands are sent to terminal */ close_connection (fd); } /* Remove any key certificate files from our temp directory area */ for (p = start->first; p != NULL; p = p->next) if (p->keycertfn != NULL) remove (p->keycertfn); /* JW want to bring back in later, dup rawhoisd } */ /* fprintf (dfile, "Exit perform_transactions()\n----\n");*/ }
/* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ package com.amazon.dataprepper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.env.SimpleCommandLinePropertySource; /** * Execute entry into Data Prepper. */ @ComponentScan public class DataPrepperExecute { private static final Logger LOG = LoggerFactory.getLogger(DataPrepperExecute.class); public static void main(final String ... args) { java.security.Security.setProperty("networkaddress.cache.ttl", "60"); LOG.trace("Reading args"); final SimpleCommandLinePropertySource commandLinePropertySource = new SimpleCommandLinePropertySource(args); LOG.trace("Creating application context"); final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.getEnvironment().getPropertySources().addFirst(commandLinePropertySource); context.register(DataPrepperExecute.class); context.refresh(); final DataPrepper dataPrepper = context.getBean(DataPrepper.class); LOG.trace("Starting Data Prepper execution"); dataPrepper.execute(); } }
<filename>src/org/sosy_lab/cpachecker/util/octagon/Octagon.java /* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2014 <NAME> * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.util.octagon; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.util.ArrayList; import java.util.List; public class Octagon { private final long octId; private final OctagonManager manager; private static List<OctagonPhantomReference> phantomReferences = new ArrayList<>(); private static ReferenceQueue<Octagon> referenceQueue = new ReferenceQueue<>(); Octagon(long l, OctagonManager manager) { octId = l; this.manager = manager; registerPhantomReference(this); } private static void registerPhantomReference(Octagon oct) { phantomReferences.add(new OctagonPhantomReference(oct, referenceQueue)); } public static void removePhantomReferences() { Reference<? extends Octagon> reference; while ((reference = referenceQueue.poll()) != null) { ((OctagonPhantomReference)reference).cleanup(); } } long getOctId() { return octId; } public OctagonManager getManager() { return manager; } @Override public int hashCode() { return (int)octId; } @Override public boolean equals(Object pObj) { if (!(pObj instanceof Octagon)) { return false; } Octagon otherOct = (Octagon) pObj; return manager.dimension(this) == otherOct.manager.dimension(otherOct) && manager.isEqual(this, otherOct); } @Override public String toString() { return "octagon with id: " + octId; } }
import React from 'react'; import { StaticQuery, graphql } from 'gatsby'; import { shape, arrayOf, string } from 'prop-types'; import { MediumStyled, ItemStyled, ThumbnailStyled, LinkStyled, PostTitleStyled, DescriptionStyled, } from './MediumStyled'; const query = graphql` query { allMediumPost(sort: { fields: [createdAt], order: DESC }) { edges { node { id title uniqueSlug virtuals { subtitle previewImage { imageId } } } } } } `; const render = ({ allMediumPost: { edges } }) => { return ( <MediumStyled> {edges.map( ({ node: { title, uniqueSlug, virtuals: { subtitle, previewImage: { imageId }, }, }, }) => ( <ItemStyled key={title}> <LinkStyled href={`https://medium.com/@awitalewski/${uniqueSlug}`} rel="noopener" > <PostTitleStyled>{title}</PostTitleStyled> <ThumbnailStyled src={`https://cdn-images-1.medium.com/max/360/${imageId}`} alt={`Illustration for blog post: ${title}`} /> <DescriptionStyled>{subtitle}</DescriptionStyled> </LinkStyled> </ItemStyled> ) )} </MediumStyled> ); }; render.propTypes = { allMediumPost: shape({ edges: arrayOf( shape({ node: shape({ title: string, uniqueSlug: string, virtuals: shape({ subtitle: string, previewImage: shape({ imageId: string }), }), }), }) ), }).isRequired, }; export const Medium = () => <StaticQuery query={query} render={render} />; export default Medium;
/* * Copyright 2019 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm/gm.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkPaint.h" #include "include/core/SkRect.h" #include "include/core/SkSurface.h" #include "include/core/SkYUVAInfo.h" #include "include/core/SkYUVAPixmaps.h" #include "include/gpu/GrDirectContext.h" #include "include/gpu/GrRecordingContext.h" #include "src/core/SkAutoPixmapStorage.h" #include "src/core/SkScopeExit.h" #include "tools/Resources.h" #include "tools/ToolUtils.h" #include "tools/gpu/YUVUtils.h" namespace { struct AsyncContext { bool fCalled = false; std::unique_ptr<const SkImage::AsyncReadResult> fResult; }; } // anonymous namespace // Making this a lambda in the test functions caused: // "error: cannot compile this forwarded non-trivially copyable parameter yet" // on x86/Win/Clang bot, referring to 'result'. static void async_callback(void* c, std::unique_ptr<const SkImage::AsyncReadResult> result) { auto context = static_cast<AsyncContext*>(c); context->fResult = std::move(result); context->fCalled = true; }; // Draws the image to a surface, does a asyncRescaleAndReadPixels of the image, and then sticks // the result in a raster image. template <typename Src> static sk_sp<SkImage> do_read_and_scale(Src* src, GrDirectContext* direct, const SkIRect& srcRect, const SkImageInfo& ii, SkImage::RescaleGamma rescaleGamma, SkFilterQuality quality) { auto* asyncContext = new AsyncContext(); src->asyncRescaleAndReadPixels(ii, srcRect, rescaleGamma, quality, async_callback, asyncContext); if (direct) { direct->submit(); } while (!asyncContext->fCalled) { // Only GPU should actually be asynchronous. SkASSERT(direct); direct->checkAsyncWorkCompletion(); } if (!asyncContext->fResult) { return nullptr; } SkPixmap pixmap(ii, asyncContext->fResult->data(0), asyncContext->fResult->rowBytes(0)); auto releasePixels = [](const void*, void* c) { delete static_cast<AsyncContext*>(c); }; return SkImage::MakeFromRaster(pixmap, releasePixels, asyncContext); } template <typename Src> static sk_sp<SkImage> do_read_and_scale_yuv(Src* src, GrDirectContext* direct, SkYUVColorSpace yuvCS, const SkIRect& srcRect, SkISize size, SkImage::RescaleGamma rescaleGamma, SkFilterQuality quality, SkScopeExit* cleanup) { SkASSERT(!(size.width() & 0b1) && !(size.height() & 0b1)); SkISize uvSize = {size.width()/2, size.height()/2}; SkImageInfo yII = SkImageInfo::Make(size, kGray_8_SkColorType, kPremul_SkAlphaType); SkImageInfo uvII = SkImageInfo::Make(uvSize, kGray_8_SkColorType, kPremul_SkAlphaType); AsyncContext asyncContext; src->asyncRescaleAndReadPixelsYUV420(yuvCS, SkColorSpace::MakeSRGB(), srcRect, size, rescaleGamma, quality, async_callback, &asyncContext); if (direct) { direct->submit(); } while (!asyncContext.fCalled) { // Only GPU should actually be asynchronous. SkASSERT(direct); direct->checkAsyncWorkCompletion(); } if (!asyncContext.fResult) { return nullptr; } SkYUVAInfo yuvaInfo(size, SkYUVAInfo::PlanarConfig::kY_U_V_420, yuvCS); SkPixmap yuvPMs[] = { {yII, asyncContext.fResult->data(0), asyncContext.fResult->rowBytes(0)}, {uvII, asyncContext.fResult->data(1), asyncContext.fResult->rowBytes(1)}, {uvII, asyncContext.fResult->data(2), asyncContext.fResult->rowBytes(2)} }; auto pixmaps = SkYUVAPixmaps::FromExternalPixmaps(yuvaInfo, yuvPMs); SkASSERT(pixmaps.isValid()); auto lazyYUVImage = sk_gpu_test::LazyYUVImage::Make(pixmaps); SkASSERT(lazyYUVImage); return lazyYUVImage->refImage(direct, sk_gpu_test::LazyYUVImage::Type::kFromTextures); } // Draws a grid of rescales. The columns are none, low, and high filter quality. The rows are // rescale in src gamma and rescale in linear gamma. template <typename Src> static skiagm::DrawResult do_rescale_grid(SkCanvas* canvas, Src* src, GrDirectContext* direct, const SkIRect& srcRect, SkISize newSize, bool doYUV420, SkString* errorMsg, int pad = 0) { if (doYUV420 && !direct) { errorMsg->printf("YUV420 only supported on direct GPU for now."); return skiagm::DrawResult::kSkip; } if (canvas->imageInfo().colorType() == kUnknown_SkColorType) { *errorMsg = "Not supported on recording/vector backends."; return skiagm::DrawResult::kSkip; } const auto ii = canvas->imageInfo().makeDimensions(newSize); SkYUVColorSpace yuvColorSpace = kRec601_SkYUVColorSpace; canvas->save(); for (auto gamma : {SkImage::RescaleGamma::kSrc, SkImage::RescaleGamma::kLinear}) { canvas->save(); for (auto quality : {kNone_SkFilterQuality, kLow_SkFilterQuality, kHigh_SkFilterQuality}) { SkScopeExit cleanup; sk_sp<SkImage> result; if (doYUV420) { result = do_read_and_scale_yuv(src, direct, yuvColorSpace, srcRect, newSize, gamma, quality, &cleanup); if (!result) { errorMsg->printf("YUV420 async call failed. Allowed for now."); return skiagm::DrawResult::kSkip; } int nextCS = static_cast<int>(yuvColorSpace + 1) % (kLastEnum_SkYUVColorSpace + 1); yuvColorSpace = static_cast<SkYUVColorSpace>(nextCS); } else { result = do_read_and_scale(src, direct, srcRect, ii, gamma, quality); if (!result) { errorMsg->printf("async read call failed."); return skiagm::DrawResult::kFail; } } canvas->drawImage(result, 0, 0); canvas->translate(newSize.width() + pad, 0); } canvas->restore(); canvas->translate(0, newSize.height() + pad); } canvas->restore(); return skiagm::DrawResult::kOk; } static skiagm::DrawResult do_rescale_image_grid(SkCanvas* canvas, const char* imageFile, const SkIRect& srcRect, SkISize newSize, bool doSurface, bool doYUV420, SkString* errorMsg) { auto image = GetResourceAsImage(imageFile); if (!image) { errorMsg->printf("Could not load image file %s.", imageFile); return skiagm::DrawResult::kFail; } if (canvas->imageInfo().colorType() == kUnknown_SkColorType) { *errorMsg = "Not supported on recording/vector backends."; return skiagm::DrawResult::kSkip; } auto dContext = GrAsDirectContext(canvas->recordingContext()); if (!dContext && canvas->recordingContext()) { *errorMsg = "Not supported in DDL mode"; return skiagm::DrawResult::kSkip; } if (doSurface) { // Turn the image into a surface in order to call the read and rescale API auto surfInfo = image->imageInfo().makeDimensions(image->dimensions()); auto surface = canvas->makeSurface(surfInfo); if (!surface && surfInfo.colorType() == kBGRA_8888_SkColorType) { surfInfo = surfInfo.makeColorType(kRGBA_8888_SkColorType); surface = canvas->makeSurface(surfInfo); } if (!surface) { *errorMsg = "Could not create surface for image."; // When testing abandoned GrContext we expect surface creation to fail. if (canvas->recordingContext() && canvas->recordingContext()->abandoned()) { return skiagm::DrawResult::kSkip; } return skiagm::DrawResult::kFail; } SkPaint paint; paint.setBlendMode(SkBlendMode::kSrc); surface->getCanvas()->drawImage(image, 0, 0, &paint); return do_rescale_grid(canvas, surface.get(), dContext, srcRect, newSize, doYUV420, errorMsg); } else if (dContext) { image = image->makeTextureImage(dContext); if (!image) { *errorMsg = "Could not create image."; // When testing abandoned GrContext we expect surface creation to fail. if (canvas->recordingContext() && canvas->recordingContext()->abandoned()) { return skiagm::DrawResult::kSkip; } return skiagm::DrawResult::kFail; } } return do_rescale_grid(canvas, image.get(), dContext, srcRect, newSize, doYUV420, errorMsg); } #define DEF_RESCALE_AND_READ_SURF_GM(IMAGE_FILE, TAG, SRC_RECT, W, H) \ DEF_SIMPLE_GM_CAN_FAIL(async_rescale_and_read_##TAG, canvas, errorMsg, 3 * W, 2 * H) { \ ToolUtils::draw_checkerboard(canvas, SK_ColorDKGRAY, SK_ColorLTGRAY, 25); \ return do_rescale_image_grid(canvas, #IMAGE_FILE, SRC_RECT, {W, H}, true, false, \ errorMsg); \ } #define DEF_RESCALE_AND_READ_YUV_SURF_GM(IMAGE_FILE, TAG, SRC_RECT, W, H) \ DEF_SIMPLE_GM_CAN_FAIL(async_rescale_and_read_yuv420_##TAG, canvas, errorMsg, 3 * W, 2 * H) { \ ToolUtils::draw_checkerboard(canvas, SK_ColorDKGRAY, SK_ColorLTGRAY, 25); \ return do_rescale_image_grid(canvas, #IMAGE_FILE, SRC_RECT, {W, H}, true, true, errorMsg); \ } #define DEF_RESCALE_AND_READ_IMG_GM(IMAGE_FILE, TAG, SRC_RECT, W, H) \ DEF_SIMPLE_GM_CAN_FAIL(async_rescale_and_read_##TAG, canvas, errorMsg, 3 * W, 2 * H) { \ ToolUtils::draw_checkerboard(canvas, SK_ColorDKGRAY, SK_ColorLTGRAY, 25); \ return do_rescale_image_grid(canvas, #IMAGE_FILE, SRC_RECT, {W, H}, false, false, \ errorMsg); \ } #define DEF_RESCALE_AND_READ_YUV_IMG_GM(IMAGE_FILE, TAG, SRC_RECT, W, H) \ DEF_SIMPLE_GM_CAN_FAIL(async_rescale_and_read_yuv420_##TAG, canvas, errorMsg, 3 * W, 2 * H) { \ ToolUtils::draw_checkerboard(canvas, SK_ColorDKGRAY, SK_ColorLTGRAY, 25); \ return do_rescale_image_grid(canvas, #IMAGE_FILE, SRC_RECT, {W, H}, true, true, errorMsg); \ } DEF_RESCALE_AND_READ_YUV_SURF_GM( images/yellow_rose.webp, rose, SkIRect::MakeXYWH(50, 5, 200, 150), 410, 376) DEF_RESCALE_AND_READ_YUV_IMG_GM( images/yellow_rose.webp, rose_down, SkIRect::MakeXYWH(50, 5, 200, 150), 106, 60) DEF_RESCALE_AND_READ_SURF_GM( images/yellow_rose.webp, rose, SkIRect::MakeXYWH(100, 20, 100, 100), 410, 410) DEF_RESCALE_AND_READ_SURF_GM(images/dog.jpg, dog_down, SkIRect::MakeXYWH(0, 10, 180, 150), 45, 45) DEF_RESCALE_AND_READ_IMG_GM(images/dog.jpg, dog_up, SkIRect::MakeWH(180, 180), 800, 400) DEF_RESCALE_AND_READ_IMG_GM( images/text.png, text_down, SkIRect::MakeWH(637, 105), (int)(0.7 * 637), (int)(0.7 * 105)) DEF_RESCALE_AND_READ_SURF_GM( images/text.png, text_up, SkIRect::MakeWH(637, 105), (int)(1.2 * 637), (int)(1.2 * 105)) DEF_RESCALE_AND_READ_IMG_GM(images/text.png, text_up_large, SkIRect::MakeXYWH(300, 0, 300, 105), (int)(2.4 * 300), (int)(2.4 * 105)) // Exercises non-scaling YUV420. Reads from the original canvas's surface in order to // exercise case where source surface is not a texture (in glbert config). DEF_SIMPLE_GM_CAN_FAIL(async_yuv_no_scale, canvas, errorMsg, 400, 300) { auto surface = canvas->getSurface(); if (!surface) { *errorMsg = "Not supported on recording/vector backends."; return skiagm::DrawResult::kSkip; } auto dContext = GrAsDirectContext(surface->recordingContext()); if (!dContext && surface->recordingContext()) { *errorMsg = "Not supported in DDL mode"; return skiagm::DrawResult::kSkip; } auto image = GetResourceAsImage("images/yellow_rose.webp"); if (!image) { return skiagm::DrawResult::kFail; } SkPaint paint; canvas->drawImage(image.get(), 0, 0); SkScopeExit scopeExit; auto yuvImage = do_read_and_scale_yuv( surface, dContext, kRec601_SkYUVColorSpace, SkIRect::MakeWH(400, 300), {400, 300}, SkImage::RescaleGamma::kSrc, kNone_SkFilterQuality, &scopeExit); canvas->clear(SK_ColorWHITE); canvas->drawImage(yuvImage.get(), 0, 0); return skiagm::DrawResult::kOk; } DEF_SIMPLE_GM_CAN_FAIL(async_rescale_and_read_no_bleed, canvas, errorMsg, 60, 60) { if (canvas->imageInfo().colorType() == kUnknown_SkColorType) { *errorMsg = "Not supported on recording/vector backends."; return skiagm::DrawResult::kSkip; } auto dContext = GrAsDirectContext(canvas->recordingContext()); if (!dContext && canvas->recordingContext()) { *errorMsg = "Not supported in DDL mode"; return skiagm::DrawResult::kSkip; } static constexpr int kBorder = 5; static constexpr int kInner = 5; const auto srcRect = SkIRect::MakeXYWH(kBorder, kBorder, kInner, kInner); auto surfaceII = SkImageInfo::Make(kInner + 2 * kBorder, kInner + 2 * kBorder, kRGBA_8888_SkColorType, kPremul_SkAlphaType, SkColorSpace::MakeSRGB()); auto surface = canvas->makeSurface(surfaceII); if (!surface) { *errorMsg = "Could not create surface for image."; // When testing abandoned GrContext we expect surface creation to fail. if (canvas->recordingContext() && canvas->recordingContext()->abandoned()) { return skiagm::DrawResult::kSkip; } return skiagm::DrawResult::kFail; } surface->getCanvas()->clear(SK_ColorRED); surface->getCanvas()->save(); surface->getCanvas()->clipRect(SkRect::Make(srcRect), SkClipOp::kIntersect, false); surface->getCanvas()->clear(SK_ColorBLUE); surface->getCanvas()->restore(); static constexpr int kPad = 2; canvas->translate(kPad, kPad); skiagm::DrawResult result; SkISize downSize = {static_cast<int>(kInner/2), static_cast<int>(kInner / 2)}; result = do_rescale_grid(canvas, surface.get(), dContext, srcRect, downSize, false, errorMsg, kPad); if (result != skiagm::DrawResult::kOk) { return result; } canvas->translate(0, 4 * downSize.height()); SkISize upSize = {static_cast<int>(kInner * 3.5), static_cast<int>(kInner * 4.6)}; result = do_rescale_grid(canvas, surface.get(), dContext, srcRect, upSize, false, errorMsg, kPad); if (result != skiagm::DrawResult::kOk) { return result; } return skiagm::DrawResult::kOk; }
<gh_stars>0 //jshint esnext:true const assert = require('assert'); const sinon = require('sinon'); const Suite = require('../suite'); const request = require('superagent'); require('co-mocha'); describe('http component', function() { 'use strict'; describe('act as source', function() { var suite; beforeEach(function() { suite = new Suite() .addComponents('mock', 'http'); }); afterEach(function *() { yield suite.end(); }); it ('listen to specified port', function *() { yield suite.test(function(service) { service.from('http://0.0.0.0:8080') .to('mock:result'); }); var response = yield request('http://localhost:8080') .timeout(500); if (suite.get('mock:result').data.messages.length !== 1) { throw new Error('Message not arrived yet'); } }); it ('attach same daemon to different uris', function *() { yield suite.test(function(service) { service.from('http://0.0.0.0:8080/bar') .to(function() { this.body = this.body.url; }) .to('mock:bar'); service.from('http://0.0.0.0:8080') .to(function() { this.body = this.body.url; }) .to('mock:foo'); }); yield request('http://localhost:8080') .timeout(500); yield request('http://localhost:8080/bar') .timeout(500); if (suite.get('mock:foo').data.messages.length !== 1) { throw new Error('Message not arrived yet'); } if (suite.get('mock:bar').data.messages.length !== 1) { throw new Error('Message not arrived yet'); } }); }); describe('act as processor', function() { var suite; beforeEach(function *() { suite = new Suite() .addComponents('mock', 'http'); yield suite.test(function(service) { service.from('http://0.0.0.0:8080') .to(function() { this.body = { uri: this.headers['http-request-uri'] }; }); service.from('mock:foo') .to('http://localhost:8080/foo'); }); }); afterEach(function *() { yield suite.end(); }); it ('return json on json endpoint', function *() { var result = yield suite.request('mock:foo'); assert.equal(result.body.uri, '/foo'); }); }); });
import command from './command'; import { R, fs, IAction, ICommand, IValidate } from './common'; /** * Loads a set of modules and constructs a command object. */ function toCommand(modulePath: string): ICommand { const m = require(modulePath); let name; name = m.name ? m.name : fs.basename(modulePath, '.js'); name = name.endsWith('.cmd') ? fs.basename(name, '.cmd') : name; let alias = m.alias; if (!R.is(Array, alias)) { alias = [alias]; } alias = R.reject(R.isNil)(alias); const action = m.cmd || m.default; return { name, alias, description: m.description, group: m.group, args: m.args, validate: m.validate as IValidate, action: action as IAction, }; } /** * Loads a set of modules and constructs a command object. */ function toCommands(modulePaths: string[]) { // Retrieve and sort paths. const commands = modulePaths .map(toCommand) .filter(item => R.is(Function, item.action)); // Convert to an object. const result = {}; commands.forEach(cmd => (result[cmd.name] = cmd)); return result; } /** * Converts a path/pattern to a command object */ async function pathToCommands(path: string) { const paths = await fs.glob.find(path); return toCommands(paths); } export default async ( param: string | string[] | { [key: string]: ICommand }, ) => { // A string was passed, assume it was a path or path-pattern. // Convert it to a command object. if (typeof param === 'string') { param = await pathToCommands(param); } // A list of string was passed, assuming it was a list of path/patterns. // Merge all the cmds found into one command object. Later cmds override earlier commands. if (Array.isArray(param)) { let out = {}; for (const path of param) { out = { ...out, ...(await pathToCommands(path)), }; } param = out; } // Process commands. command(param); };
def concatenate_strings(str1, str2, str3): # Initialize an empty string joined_string = "" # Iterate over the strings and concatenate for s in (str1, str2, str3): joined_string += s return joined_string concatenated_string = concatenate_strings(str1, str2, str3) print(concatenated_string)
# shellcheck disable=SC2148 TMP_DIR="${TMPDIR:-/tmp}/rocksdb-sanity-test" if [ "$#" -lt 2 ]; then echo "usage: ./auto_sanity_test.sh [new_commit] [old_commit]" echo "Missing either [new_commit] or [old_commit], perform sanity check with the latest and 10th latest commits." recent_commits=`git log | grep -e "^commit [a-z0-9]\+$"| head -n10 | sed -e 's/commit //g'` commit_new=`echo "$recent_commits" | head -n1` commit_old=`echo "$recent_commits" | tail -n1` echo "the most recent commits are:" echo "$recent_commits" else commit_new=$1 commit_old=$2 fi if [ ! -d $TMP_DIR ]; then mkdir $TMP_DIR fi dir_new="${TMP_DIR}/${commit_new}" dir_old="${TMP_DIR}/${commit_old}" function makestuff() { echo "make clean" make clean > /dev/null echo "make db_sanity_test -j32" make db_sanity_test -j32 > /dev/null if [ $? -ne 0 ]; then echo "[ERROR] Failed to perform 'make db_sanity_test'" exit 1 fi } rm -r -f $dir_new rm -r -f $dir_old echo "Running db sanity check with commits $commit_new and $commit_old." echo "=============================================================" echo "Making build $commit_new" git checkout $commit_new if [ $? -ne 0 ]; then echo "[ERROR] Can't checkout $commit_new" exit 1 fi makestuff mv db_sanity_test new_db_sanity_test echo "Creating db based on the new commit --- $commit_new" ./new_db_sanity_test $dir_new create cp ./tools/db_sanity_test.cc $dir_new cp ./tools/auto_sanity_test.sh $dir_new echo "=============================================================" echo "Making build $commit_old" git checkout $commit_old if [ $? -ne 0 ]; then echo "[ERROR] Can't checkout $commit_old" exit 1 fi cp -f $dir_new/db_sanity_test.cc ./tools/. cp -f $dir_new/auto_sanity_test.sh ./tools/. makestuff mv db_sanity_test old_db_sanity_test echo "Creating db based on the old commit --- $commit_old" ./old_db_sanity_test $dir_old create echo "=============================================================" echo "[Backward Compatibility Check]" echo "Verifying old db $dir_old using the new commit --- $commit_new" ./new_db_sanity_test $dir_old verify if [ $? -ne 0 ]; then echo "[ERROR] Backward Compatibility Check fails:" echo " Verification of $dir_old using commit $commit_new failed." exit 2 fi echo "=============================================================" echo "[Forward Compatibility Check]" echo "Verifying new db $dir_new using the old commit --- $commit_old" ./old_db_sanity_test $dir_new verify if [ $? -ne 0 ]; then echo "[ERROR] Forward Compatibility Check fails:" echo " $dir_new using commit $commit_old failed." exit 2 fi rm old_db_sanity_test rm new_db_sanity_test rm -rf $dir_new rm -rf $dir_old echo "Auto sanity test passed!"