repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
osu-cass/working-waterfronts-api
working_waterfronts/working_waterfronts_api/urls.py
<reponame>osu-cass/working-waterfronts-api from django.conf.urls import patterns from django.conf.urls import url url_base = 'working_waterfronts.working_waterfronts_api' urlpatterns = patterns( '', url(r'^entry/hazards/new/?$', url_base + '.views.entry.hazards.hazard', name='new-hazard'), url(r'^entry/hazards/(?P<id>\d+)/?$', url_base + '.views.entry.hazards.hazard', name='edit-hazard'), url(r'^entry/hazards/?$', url_base + '.views.entry.hazards.list', name='entry-list-hazards'), url(r'^entry/?$', url_base + '.views.entry.home.home', name='home'), url(r'^entry/categories/(?P<id>\d+)/?$', url_base + '.views.entry.categories.category', name='edit-category'), url(r'^entry/categories/new/?$', url_base + '.views.entry.categories.category', name='new-category'), url(r'^entry/categories/?$', url_base + '.views.entry.categories.list', name='entry-list-categories'), url(r'^entry/images/(?P<id>\d+)/?$', url_base + '.views.entry.images.image', name='edit-image'), url(r'^entry/images/new/?$', url_base + '.views.entry.images.image', name='new-image'), url(r'^entry/images/?$', url_base + '.views.entry.images.image_list', name='entry-list-images'), url(r'^entry/pois/(?P<id>\d+)/?$', url_base + '.views.entry.pois.poi', name='edit-poi'), url(r'^entry/pois/new/?$', url_base + '.views.entry.pois.poi', name='new-poi'), url(r'^entry/pois/?$', url_base + '.views.entry.pois.list', name='entry-list-pois'), url(r'^1/pois/?$', url_base + '.views.pointsofinterest.poi_list', name='pois-list'), url(r'^1/pois/(?P<id>\d+)/?$', url_base + '.views.pointsofinterest.poi_details', name='poi-details'), url(r'^entry/pois/?$', url_base + '.views.pointsofinterest.poi_list', name='entry-list-pois'), url(r'^entry/videos/(?P<id>\d+)/?$', url_base + '.views.entry.videos.video', name='edit-video'), url(r'^entry/videos/?$', url_base + '.views.entry.videos.video_list', name='entry-list-videos'), url(r'^entry/videos/new/?$', url_base + '.views.entry.videos.video', name='new-video'), url(r'^1/pois/categories/(?P<id>\d+)/?$', url_base + '.views.pointsofinterest.poi_categories', name='pois-categories'), url(r'^login/?$', url_base + '.views.entry.login.login_user', name='login'), url(r'^logout/?$', url_base + '.views.entry.login.logout_user', name='logout'), url(r'^/?$', url_base + '.views.entry.login.root', name='root') )
jloehr/AdventOfCode
2017/Day17/Day17.cpp
// Day17.cpp : Defines the entry point for the console application. // #include "stdafx.h" constexpr size_t Input = 314; int main() { std::deque<size_t> List{ 0, 1 }; size_t Position = 1; for (auto i = 2; i < 2018; ++i) { Position = ((Position + Input) % List.size()) + 1; auto It = std::begin(List) + Position; List.emplace(It, i); } std::cout << "Part one: " << *(std::begin(List) + ((Position + 1) % List.size())) << std::endl; Position = 1; size_t Value = 1; for (auto i = 2; i <= 50000000; ++i) { Position = ((Position + Input) % i) + 1; if (Position == 1) Value = i; } std::cout << "Part two: " << Value << std::endl; system("pause"); return 0; }
mpicbg-scicomp/imagej-ops
src/main/java/net/imagej/ops/create/img/Imgs.java
package net.imagej.ops.create.img; import net.imglib2.Dimensions; import net.imglib2.Interval; import net.imglib2.img.Img; import net.imglib2.img.ImgFactory; import net.imglib2.img.ImgView; import net.imglib2.type.Type; import net.imglib2.view.Views; /** * Utility methods for working with {@link Img} objects. * * @author <NAME> */ public final class Imgs { private Imgs() { // NB: Prevent instantiation of utility class. } /** * Creates an {@link Img}. * * @param factory The {@link ImgFactory} to use to create the image. * @param dims The dimensional bounds of the newly created image. If the given * bounds are an {@link Interval}, the resultant {@link Img} will * have the same min/max as that {@link Interval} as well (see * {@link #adjustMinMax} for details). * @param type The component type of the newly created image. * @return the newly created {@link Img} */ public static <T extends Type<T>> Img<T> create(final ImgFactory<T> factory, final Dimensions dims, final T type) { return Imgs.adjustMinMax(factory.create(dims, type), dims); } /** * Adjusts the given {@link Img} to match the bounds of the specified * {@link Interval}. * * @param img An image whose min/max bounds might need adjustment. * @param minMax An {@link Interval} whose min/max bounds to use when * adjusting the image. If the provided {@code minMax} object is not * an {@link Interval}, no adjustment is performed. * @return A wrapped version of the input {@link Img} with bounds adjusted to * match the provided {@link Interval}, if any; or the input image * itself if no adjustment was needed/possible. */ public static <T extends Type<T>> Img<T> adjustMinMax(final Img<T> img, final Object minMax) { if (!(minMax instanceof Interval)) return img; final Interval interval = (Interval) minMax; final long[] min = new long[interval.numDimensions()]; interval.min(min); for (int d = 0; d < min.length; d++) { if (min[d] != 0) { return ImgView.wrap(Views.translate(img, min), img.factory()); } } return img; } }
97999/SimpleReader
app/src/main/java/com/example/simplereader/siteparser/Binghuo.java
package com.example.simplereader.siteparser; import com.example.simplereader.sitebean.Book; import com.example.simplereader.sitebean.BookMsg; import com.example.simplereader.sitebean.Chapter; import com.example.simplereader.sitebean.UpdateMsg; import com.example.simplereader.util.HttpUtil; import com.example.simplereader.util.StateCallBack; import com.example.simplereader.util.Utility; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import okhttp3.FormBody; import okhttp3.RequestBody; public class Binghuo extends WebSite { private final String root = "https://www.bhzw.cc"; @Override public void search(String bookName, StateCallBack<Book> callBack){ int maxSize = 5; String href = "https://www.bhzw.cc/modules/article/search.php"; RequestBody requestBody = null; try { requestBody = new FormBody.Builder() .addEncoded("searchkey", URLEncoder.encode(bookName, getEncoding())) .build(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String html = HttpUtil.getWebHtml(href, getEncoding(), requestBody); if(html != null){ Document doc = Jsoup.parse(html); List<Element> elements = doc.select("body > div.wrap > div > div.container-bd > " + "div.mod.mod-clean.pattern-update-list > div > table > tbody > tr"); int count = 0; for(Element e : elements){ if(count >= maxSize) break; String name = e.getElementsByClass("name").first().text(); String url = root + e.getElementsByClass("name").first().attr("href"); String image = getImageUrl(url); String type = e.getElementsByClass("tag").first().text(); String author = e.getElementsByClass("author").first().text(); String intro = getIntro(url); String time = e.getElementsByClass("time").first().text(); callBack.onSuccess(new Book(name, url, author, image, intro, type, time, getSiteName(), getEncoding(), Utility.getMatchValue(bookName, name, author))); count++; } } } @Override public void getCatalog(String url, StateCallBack<List<Chapter>> callBack) { String html = HttpUtil.getWebHtml(url, getEncoding()); if(html != null){ Document doc = Jsoup.parse(html); List<Element> elements = doc.select("body > div:nth-child(2) > div > div > " + "div.c-left > div.mod.pattern-fill-container-mod.chapter-list.mod11 > div > ul > li"); List<Chapter> chapterList = new ArrayList<>(elements.size()); for(Element e : elements){ String chapterName = e.getElementsByTag("a").first().attr("title"); String chapterUrl = url + e.getElementsByTag("a").first().attr("href"); chapterList.add(new Chapter(chapterName, chapterUrl)); } callBack.onSuccess(chapterList); } else { callBack.onFailed("获取目录失败"); } } @Override public void getContent(String url, StateCallBack<String> callBack) { String html = HttpUtil.getWebHtml(url, getEncoding()); if(html != null){ html = html.replaceAll("<br />", "\\$"); Document doc = Jsoup.parse(html); String content = doc.select("#ChapterContents").text(); callBack.onSuccess(content); } else { callBack.onFailed("获取章节内容失败"); } } @Override public void getBookInfo(String url, StateCallBack<UpdateMsg> callBack) { String html = HttpUtil.getWebHtml(url, getEncoding()); if(html != null){ Document doc = Jsoup.parse(html); Element element = doc.select("body > div:nth-child(2) > div > div > " + "div.c-left > div.page-header").first(); String name = element.getElementsByTag("h1").text(); String author = doc.getElementsByTag("h3").text(); if(author.length() > 2) author = author.substring(1); element = doc.select("body > div:nth-child(2) > div > div > div.c-right > " + "div.sidebar-cover.sidebar-first-region > div > div").first(); String img = root + element.select("div > a > img").attr("src"); String intro = element.select("p.intro").text(); String temp = element.select("p.intro > span").text(); if(intro.length() > temp.length()) intro = intro.substring(temp.length()); String time = element.getElementsByClass("name").last().text(); temp = element.getElementsByClass("name").last().getElementsByTag("font").first().text(); if(time.length() > temp.length()) time = time.substring(temp.length()); temp = element.getElementsByClass("name").last().getElementsByTag("a").first().text(); if(time.length() > temp.length()) time = time.substring(temp.length()); if(time.length() > 3) time = time.split("(")[1]; time = time.substring(0, time.length()-1); Book book = new Book(name, url, author, img, intro, null, time, getSiteName(), getEncoding()); List<Element> elements = doc.select("body > div:nth-child(2) > div >" + " div > div.c-left > div.mod.pattern-fill-container-mod.chapter-list.mod11 >" + " div > ul > li"); elements = elements.subList(elements.size()>=6?elements.size()-6:0, elements.size()); List<Chapter> chapters = new ArrayList<>(); for(Element e : elements){ chapters.add(new Chapter(e.getElementsByTag("a").text(), root + e.getElementsByTag("a").attr("href"))); } callBack.onSuccess(new BookMsg(book, chapters)); } else { callBack.onFailed("获取书籍信息失败"); } } @Override public void getUpdateInfo(String url, StateCallBack<UpdateMsg> callBack) { String html = HttpUtil.getWebHtml(url, getEncoding()); if(html != null){ Document doc = Jsoup.parse(html); List<Element> elements = doc.select("body > div:nth-child(2) > div >" + " div > div.c-left > div.mod.pattern-fill-container-mod.chapter-list.mod11 >" + " div > ul > li"); elements = elements.subList(elements.size()>=6?elements.size()-6:0, elements.size()); List<Chapter> chapters = new ArrayList<>(); for(Element e : elements){ chapters.add(new Chapter(e.getElementsByTag("a").text(), root + e.getElementsByTag("a").attr("href"))); } callBack.onSuccess(new UpdateMsg(chapters)); } else { callBack.onFailed("获取书籍信息失败"); } } @Override public String getSiteName() { return "冰火中文"; } /** * 获取图片的完整web地址 * @param url 书籍地址 * @return 图片的完整web地址 */ private String getImageUrl(String url){ String html = HttpUtil.getWebHtml(url, getEncoding()); if(html == null) return null; String imageUrl = Jsoup.parse(html).select("body > div:nth-child(2) > div > div > " + "div.c-right > div.sidebar-cover.sidebar-first-region > div > div > div > a > img") .attr("src"); return root+imageUrl; } private String getIntro(String url){ String html = HttpUtil.getWebHtml(url, getEncoding()); if(html == null) return null; Document doc = Jsoup.parse(html); String temp = doc.select("body > div:nth-child(2) > div > div > div.c-right > " + "div.sidebar-cover.sidebar-first-region > div > div > p.intro > span").text(); String intro = Jsoup.parse(html).select("body > div:nth-child(2) > div > " + "div > div.c-right > div.sidebar-cover.sidebar-first-region > div > div > p.intro") .text(); if(intro.length() > temp.length()) intro = intro.substring(temp.length()); return intro; } }
augerai/a2ml
a2ml/api/auger/impl/cloud/dataset.py
<gh_stars>10-100 import os import time import json import requests import shortuuid import urllib.parse import urllib.request import xml.etree.ElementTree as ElementTree from a2ml.api.utils.dataframe import DataFrame from .cluster import AugerClusterApi from .project_file import AugerProjectFileApi from ..exceptions import AugerException from .cluster_task import AugerClusterTaskApi from a2ml.api.utils import fsclient from a2ml.api.utils.file_uploader import FileUploader, NewlineProgressPercentage SUPPORTED_FORMATS = ['.csv', '.arff', '.gz', '.bz2', '.zip', '.xz', '.json', '.xls', '.xlsx', '.feather', '.h5', '.hdf5', '.parquet'] class AugerDataSetApi(AugerProjectFileApi): """Auger DataSet API.""" def __init__(self, ctx, project_api=None, data_set_name=None, data_set_id=None): super(AugerDataSetApi, self).__init__( ctx, project_api, data_set_name, data_set_id) def do_upload_file(self, data_source_file, data_set_name=None, local_data_source=True): # data_source_file, local_data_source = \ # AugerDataSetApi.verify(data_source_file, self.ctx.config.path) if local_data_source: if DataFrame.is_dataframe(data_source_file): if not data_set_name: self.ctx.exception("Name parameter has to be specified, when import dataframe.") with fsclient.save_atomic("%s.parquet"%data_set_name, move_file=False) as local_path: ds = DataFrame.create_dataframe(data_source_file) ds.saveToParquetFile(local_path) file_url = self._upload_to_cloud(local_path) file_name = data_set_name else: file_url = self._upload_to_cloud(data_source_file) file_name = os.path.basename(data_source_file) if data_set_name: self.object_name = data_set_name else: self.object_name = self._get_data_set_name(file_name) else: file_url = data_source_file url_path = urllib.parse.urlparse(file_url).path file_name = os.path.basename(url_path) self.object_name = file_name return file_url, file_name def create(self, data_source_file, data_set_name=None, local_data_source=True): file_url, file_name = self.do_upload_file(data_source_file, data_set_name=data_set_name, local_data_source=local_data_source) try: return super().create(file_url, file_name) except Exception as exc: if 'en.errors.project_file.url_not_uniq' in str(exc): raise AugerException( 'DataSet already exists for %s' % file_url) raise def download(self, path_to_download): remote_file = self.properties().get('url') unused, ext = os.path.splitext(remote_file) filename, unused = os.path.splitext(self.name) local_file = os.path.abspath( os.path.join(path_to_download, filename+ext)) remote_file = os.path.basename(remote_file) s3_signed_url = self.rest_api.call('get_project_file_url', { 'project_id': self.parent_api.oid, 'file_path': remote_file}).get('url') if not os.path.exists(path_to_download): os.makedirs(path_to_download) urllib.request.urlretrieve(s3_signed_url, local_file) return local_file def _get_readable_name(self): # patch readable name return 'DataSet' @staticmethod def verify(data_source_file, config_path=None): if DataFrame.is_dataframe(data_source_file): return data_source_file, True if urllib.parse.urlparse(data_source_file).scheme in ['http', 'https']: return data_source_file, False if not fsclient.is_s3_path(data_source_file): if config_path is None: config_path = os.getcwd() data_source_file = os.path.join(config_path, data_source_file) if not fsclient.is_s3_path(data_source_file): data_source_file = os.path.abspath(data_source_file) filename, file_extension = os.path.splitext(data_source_file) if not file_extension in SUPPORTED_FORMATS: raise AugerException( 'Source file has to be one of the supported fomats: %s' % ', '.join(SUPPORTED_FORMATS)) if not fsclient.is_file_exists(data_source_file): raise AugerException( 'Can\'t find file to import: %s' % data_source_file) return data_source_file, True def _upload_to_cloud(self, file_to_upload): return self._upload_to_multi_tenant(file_to_upload) # def _upload_to_single_tenant(self, file_to_upload): # # get file_uploader_service from the cluster # # and upload data to that service # project_properties = self.parent_api.properties() # cluster_id = project_properties.get('cluster_id') # cluster_api = AugerClusterApi( # self.ctx, self.parent_api, cluster_id) # cluster_properties = cluster_api.properties() # file_uploader_service = cluster_properties.get('file_uploader_service') # upload_token = file_uploader_service.get('params').get('auger_token') # upload_url = '%s?auger_token=%s' % ( # file_uploader_service.get('url'), upload_token) # file_url = self._upload_file(file_to_upload, upload_url) # self.ctx.log( # 'Uploaded local file to Auger Cloud file: %s' % file_url) # return file_url def _upload_file(self, file_name, url): with open(file_name, 'rb') as f: r = requests.post(url, data=f) if r.status_code == 200: rp = urllib.parse.parse_qs(r.text) return ('files/%s' % rp.get('path')[0].split('files/')[-1]) else: raise AugerException( 'HTTP error [%s] while uploading file to Auger Cloud...' % r.status_code) def _upload_to_multi_tenant(self, file_to_upload): file_path = 'workspace/projects/%s/files/%s-%s' % \ (self.parent_api.object_name, shortuuid.uuid(), os.path.basename(file_to_upload)) res = self.rest_api.call('create_project_file_url', { 'project_id': self.parent_api.object_id, 'file_path': file_path, 'file_size': fsclient.get_file_size(file_to_upload), 'async': True }) cluster_task = AugerClusterTaskApi(self.ctx, cluster_task_id=res['id']) cluster_task.wait_for_status(['pending', 'received', 'started', 'retry']) res = cluster_task.properties().get('result') if not res: raise AugerException( 'Error while uploading file to Auger Cloud...') if 'multipart' in res: upload_details = res['multipart'] config = upload_details['config'] uploader = FileUploader( upload_details['bucket'], config['endpoint'], config['access_key'], config['secret_key'], config['security_token'] ) with fsclient.open_file(file_to_upload, 'rb', encoding=None, auto_decompression=False) as f: return uploader.multipart_upload_obj( f, upload_details['key'], callback=NewlineProgressPercentage(file_to_upload) ) else: url = res['url'] bucket = res['bucket'] file_path = res['fields']['key'] with fsclient.open_file(file_to_upload, 'rb', encoding=None, auto_decompression=False) as f: files = {'file': (file_path, f)} res = requests.post(url, data=res['fields'], files=files) if res.status_code == 201 or res.status_code == 200: return 's3://%s/%s' % (bucket, file_path) else: if res.status_code == 400 and b'EntityTooLarge' in res.content: max_size = ElementTree.fromstring(res.content).find('MaxSizeAllowed').text max_size_mb = int(max_size) / 1024 / 1024 raise AugerException('Data set size is limited to %.1f MB' % max_size_mb) else: raise AugerException( 'HTTP error [%s] "%s" while uploading file' ' to Auger Cloud...' % (res.status_code, res.content)) def _get_data_set_name(self, filename): dot_index = filename.find('.') if dot_index>=0: fname = filename[:dot_index] fext = filename[dot_index:] else: fname = filename # fname, fext = os.path.splitext(file_name) return self._get_uniq_object_name(fname, "")
lburgazzoli/apache-aries
blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation/config/ConfigProperty.java
<reponame>lburgazzoli/apache-aries package org.apache.aries.blueprint.annotation.config; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotate fields with this to inject configuration like: * <code>@ConfigProperty("${mykey}")</code> */ @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface ConfigProperty { String value(); }
nerds-odd-e/doughnut
frontend/tests/notes/NoteWithChildrenCards.spec.js
<filename>frontend/tests/notes/NoteWithChildrenCards.spec.js /** * @jest-environment jsdom */ import { screen } from "@testing-library/vue"; import NoteCardsView from "@/components/notes/views/NoteCardsView.vue"; import store from "../../src/store/index.js"; import { renderWithStoreAndMockRoute } from "../helpers"; import makeMe from "../fixtures/makeMe"; describe("note wth child cards", () => { it("should render note with one child", async () => { const notePosition = makeMe.aNotePosition.please() const noteParent = makeMe.aNote.title("parent").please(); const noteChild = makeMe.aNote.title("child").under(noteParent).please(); store.commit("loadNotes", [noteParent, noteChild]); renderWithStoreAndMockRoute( store, NoteCardsView, { props: { noteId: noteParent.id, notePosition, expandChildren: true } }, ) expect(screen.getAllByRole("title")).toHaveLength(1); await screen.findByText("parent"); await screen.findByText("child"); }) });
GodieSillasca/Java
PatronesDisenio/Decorator/ToppingDecorator.java
<reponame>GodieSillasca/Java<gh_stars>0 package decorator.examples.pizzas; public abstract class ToppingDecorator implements Pizza { protected Pizza temporalPizza; public ToppingDecorator(Pizza temporalPizza) { this.temporalPizza = temporalPizza; } @Override public String getDescription() { return temporalPizza.getDescription(); } @Override public double getPrice() { return temporalPizza.getPrice(); } }
qrsforever/workspace
android/learn/binder/l2/AudioBinder/AudioClient/src/com/hybroad/client/QAudioManager.java
<reponame>qrsforever/workspace package com.hybroad.client; import android.os.IBinder; import android.os.ServiceManager; import com.hybroad.aidl.IQAudioService; public class QAudioManager { final static private String AUDIO_SERVICE_NAME = "Qaudio_service"; private static IQAudioService sAudioservice = null; private QAudioManager() { } static IQAudioService getService() { if (sAudioservice == null) { IBinder binder = ServiceManager.getService(AUDIO_SERVICE_NAME); sAudioservice = IQAudioService.Stub.asInterface(binder); } return sAudioservice; } }
FernandoWL/testcafe-ci-demo
node_modules/testcafe-hammerhead/lib/processing/script/transformers/assignment-destructuring.js
<filename>node_modules/testcafe-hammerhead/lib/processing/script/transformers/assignment-destructuring.js<gh_stars>0 "use strict"; exports.__esModule = true; exports.default = void 0; var _nodeBuilder = require("../node-builder"); var _esotopeHammerhead = require("esotope-hammerhead"); var _destructuring = _interopRequireDefault(require("../destructuring")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // ------------------------------------------------------------- // WARNING: this file is used by both the client and the server. // Do not use any browser or node-specific API! // ------------------------------------------------------------- // Transform: // ({ location: loc } = window); // [{ location }, item] = [window, 6] // --> // var _hh$temp0, _hh$temp1, _hh$temp1$0; // // _hh$temp0 = window, loc = _hh$temp0.location; // _hh$temp1 = [window, 6], _hh$temp1$0 = _hh$temp1[0], location = _hh$temp1$0.location, item = _hh$temp1[1]; const transformer = { nodeReplacementRequireTransform: true, nodeTypes: _esotopeHammerhead.Syntax.AssignmentExpression, condition: node => node.operator === '=' && (node.left.type === _esotopeHammerhead.Syntax.ObjectPattern || node.left.type === _esotopeHammerhead.Syntax.ArrayPattern), run: (node, _parent, _key, tempVars) => { const assignments = []; (0, _destructuring.default)(node.left, node.right, (pattern, value, isTemp) => { assignments.push((0, _nodeBuilder.createAssignmentExpression)(pattern, '=', value)); if (isTemp) tempVars.append(pattern.name); }); return (0, _nodeBuilder.createSequenceExpression)(assignments); } }; var _default = transformer; exports.default = _default; module.exports = exports.default;
gaol/jaxb-ri
jaxb-ri/runtime/impl/src/main/java/com/sun/xml/bind/v2/runtime/property/ArrayElementNodeProperty.java
<gh_stars>1-10 /* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package com.sun.xml.bind.v2.runtime.property; import java.io.IOException; import javax.xml.stream.XMLStreamException; import com.sun.xml.bind.v2.model.runtime.RuntimeElementPropertyInfo; import com.sun.xml.bind.v2.runtime.JAXBContextImpl; import com.sun.xml.bind.v2.runtime.JaxBeanInfo; import com.sun.xml.bind.v2.runtime.XMLSerializer; import org.xml.sax.SAXException; /** * {@link ArrayProperty} that contains node values. * * @author <NAME> */ final class ArrayElementNodeProperty<BeanT,ListT,ItemT> extends ArrayElementProperty<BeanT,ListT,ItemT> { public ArrayElementNodeProperty(JAXBContextImpl p, RuntimeElementPropertyInfo prop) { super(p, prop); } public void serializeItem(JaxBeanInfo expected, ItemT item, XMLSerializer w) throws SAXException, IOException, XMLStreamException { if(item==null) { w.writeXsiNilTrue(); } else { w.childAsXsiType(item,fieldName,expected, false); } } }
tqrg-bot/passenger
ext/common/agents/TempDirToucher.c
<filename>ext/common/agents/TempDirToucher.c<gh_stars>0 /* * Phusion Passenger - https://www.phusionpassenger.com/ * Copyright (c) 2013 Phusion * * "Phusion Passenger" is a trademark of <NAME> & <NAME>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* This tool touches everything in a directory every 30 minutes to prevent * /tmp cleaners from removing it. */ #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <fcntl.h> #include <limits.h> #include <errno.h> #include <string.h> #define ERROR_PREFIX "*** TempDirToucher error" static char *dir; /** * When Passenger Standalone is started with --daemonize, then it will * pass --cleanup to this tool so that this tool is responsible * for cleaning up the Standalone temp dir. */ static int shouldCleanup = 0; static int shouldDaemonize = 0; static const char *pidFile = NULL; static const char *logFile = NULL; static int terminationPipe[2]; static void parseArguments(int argc, char *argv[]) { dir = argv[1]; int i; for (i = 2; i < argc; i++) { if (strcmp(argv[i], "--cleanup") == 0) { shouldCleanup = 1; } else if (strcmp(argv[i], "--daemonize") == 0) { shouldDaemonize = 1; } else if (strcmp(argv[i], "--pid-file") == 0) { pidFile = argv[i + 1]; i++; } else if (strcmp(argv[i], "--log-file") == 0) { logFile = argv[i + 1]; i++; } else { fprintf(stderr, ERROR_PREFIX ": unrecognized argument %s\n", argv[i]); exit(1); } } } static void setNonBlocking(int fd) { int flags, ret, e; do { flags = fcntl(fd, F_GETFL); } while (flags == -1 && errno == EINTR); if (flags == -1) { e = errno; fprintf(stderr, ERROR_PREFIX ": cannot set pipe to non-blocking mode: " "cannot get file descriptor flags. Error: %s (errno %d)\n", strerror(e), e); exit(1); } do { ret = fcntl(fd, F_SETFL, flags | O_NONBLOCK); } while (ret == -1 && errno == EINTR); if (ret == -1) { e = errno; fprintf(stderr, ERROR_PREFIX ": cannot set pipe to non-blocking mode: " "cannot set file descriptor flags. Error: %s (errno %d)\n", strerror(e), e); exit(1); } } static void initialize(int argc, char *argv[]) { int e, fd; parseArguments(argc, argv); if (logFile != NULL) { fd = open(logFile, O_WRONLY | O_APPEND | O_CREAT, 0644); if (fd == -1) { e = errno; fprintf(stderr, ERROR_PREFIX ": cannot open log file %s for writing: %s (errno %d)\n", logFile, strerror(e), e); exit(1); } if (dup2(fd, 1) == -1) { e = errno; fprintf(stderr, ERROR_PREFIX ": cannot dup2(%d, 1): %s (errno %d)\n", fd, strerror(e), e); } if (dup2(fd, 2) == -1) { e = errno; fprintf(stderr, ERROR_PREFIX ": cannot dup2(%d, 2): %s (errno %d)\n", fd, strerror(e), e); } close(fd); } if (pipe(terminationPipe) == -1) { e = errno; fprintf(stderr, ERROR_PREFIX ": cannot create a pipe: %s (errno %d)\n", strerror(e), e); exit(1); } setNonBlocking(terminationPipe[1]); } static void exitHandler(int signo) { (void) write(terminationPipe[1], "x", 1); } static void installSignalHandlers() { struct sigaction action; action.sa_handler = exitHandler; action.sa_flags = SA_RESTART; sigemptyset(&action.sa_mask); sigaction(SIGINT, &action, NULL); sigaction(SIGTERM, &action, NULL); } static void redirectStdinToNull() { int fd = open("/dev/null", O_RDONLY); if (fd != -1) { dup2(fd, 1); close(fd); } } static void maybeDaemonize() { pid_t pid; int e; if (shouldDaemonize) { pid = fork(); if (pid == 0) { setsid(); (void) chdir("/"); redirectStdinToNull(); } else if (pid == -1) { e = errno; fprintf(stderr, ERROR_PREFIX ": cannot fork: %s (errno %d)\n", strerror(e), e); exit(1); } else { _exit(0); } } } static void maybeWritePidfile() { FILE *f; if (pidFile != NULL) { f = fopen(pidFile, "w"); if (f != NULL) { fprintf(f, "%d\n", (int) getpid()); fclose(f); } else { fprintf(stderr, ERROR_PREFIX ": cannot open PID file %s for writing\n", pidFile); exit(1); } } } static int dirExists(const char *dir) { struct stat buf; return stat(dir, &buf) == 0 && S_ISDIR(buf.st_mode); } static void touchDir(const char *dir) { pid_t pid; int e, status; pid = fork(); if (pid == 0) { close(terminationPipe[0]); close(terminationPipe[1]); if (chdir(dir) == -1) { e = errno; fprintf(stderr, ERROR_PREFIX ": cannot change working directory to %s: %s (errno %d)\n", dir, strerror(e), e); _exit(1); } execlp("/bin/sh", "/bin/sh", "-c", "find \"$1\" | xargs touch", "/bin/sh", ".", (const char * const) 0); e = errno; fprintf(stderr, ERROR_PREFIX ": cannot execute /bin/sh: %s (errno %d)\n", strerror(e), e); _exit(1); } else if (pid == -1) { e = errno; fprintf(stderr, ERROR_PREFIX ": cannot fork: %s (errno %d)\n", strerror(e), e); exit(1); } else { if (waitpid(pid, &status, 0) == -1) { if (errno != ESRCH && errno != EPERM) { fprintf(stderr, ERROR_PREFIX ": unable to wait for shell command 'find %s | xargs touch'\n", dir); exit(1); } } else if (WEXITSTATUS(status) != 0) { fprintf(stderr, ERROR_PREFIX ": shell command 'find %s | xargs touch' failed with exit status %d\n", dir, WEXITSTATUS(status)); exit(1); } } } static int doSleep(int sec) { fd_set readfds; struct timeval timeout; int ret, e; FD_ZERO(&readfds); FD_SET(terminationPipe[0], &readfds); timeout.tv_sec = sec; timeout.tv_usec = 0; do { ret = select(terminationPipe[0] + 1, &readfds, NULL, NULL, &timeout); } while (ret == -1 && errno == EINTR); if (ret == -1) { e = errno; fprintf(stderr, ERROR_PREFIX ": cannot select(): %s (errno %d)\n", strerror(e), e); exit(1); return -1; /* Never reached */ } else { return ret == 0; } } static void maybeDeletePidFile() { if (pidFile != NULL) { unlink(pidFile); } } static void performCleanup(const char *dir) { pid_t pid; int e, status; pid = fork(); if (pid == 0) { close(terminationPipe[0]); close(terminationPipe[1]); execlp("/bin/sh", "/bin/sh", "-c", "rm -rf \"$1\"", "/bin/sh", dir, (const char * const) 0); e = errno; fprintf(stderr, ERROR_PREFIX ": cannot execute /bin/sh: %s (errno %d)\n", strerror(e), e); _exit(1); } else if (pid == -1) { e = errno; fprintf(stderr, ERROR_PREFIX ": cannot fork: %s (errno %d)\n", strerror(e), e); exit(1); } else { if (waitpid(pid, &status, 0) == -1) { if (errno != ESRCH && errno != EPERM) { fprintf(stderr, ERROR_PREFIX ": unable to wait for shell command 'rm -rf %s'\n", dir); exit(1); } } else if (WEXITSTATUS(status) != 0) { fprintf(stderr, ERROR_PREFIX ": shell command 'rm -rf %s' failed with exit status %d\n", dir, WEXITSTATUS(status)); exit(1); } } } int main(int argc, char *argv[]) { initialize(argc, argv); installSignalHandlers(); maybeDaemonize(); maybeWritePidfile(); while (1) { if (dirExists(dir)) { touchDir(dir); if (!doSleep(1800)) { break; } } else { break; } } maybeDeletePidFile(); if (shouldCleanup) { performCleanup(dir); } return 0; }
shuchang01/Coding-iPad
CodingForiPad/Request/COTopicRequest.h
// // COTopicRequest.h // CodingModels // // Created by sunguanglei on 15/6/3. // Copyright (c) 2015年 sgl. All rights reserved. // #import "CODataRequest.h" @interface COTopicRequest : COPageRequest //@property (nonatomic, copy) COUriParameters NSString *globalKey; //@property (nonatomic, copy) COUriParameters NSString *projectName; @property (nonatomic, copy) COUriParameters NSString *backendProjectPath; /** * all 全部讨论 * my 我的讨论 */ @property (nonatomic, copy) COQueryParameters NSString *type; @property (nonatomic, copy) COQueryParameters NSString *topicLabelId; /** * 51 最后评论排序 * 49 发布时间排序 * 53 热门排序 */ @property (nonatomic, strong) COQueryParameters NSNumber *orderBy; @end @interface COTopicDetailRequest : CODataRequest @property (nonatomic, copy) COUriParameters NSNumber *topicId; /** * 0 预览 * 1 原始 */ @property (nonatomic, copy) COQueryParameters NSNumber *type; @end // 更新讨论 @interface COTopicUpdateRequest : CODataRequest @property (nonatomic, copy) COUriParameters NSNumber *topicId; @property (nonatomic, copy) COFormParameters NSString *title; @property (nonatomic, copy) COFormParameters NSString *content; @property (nonatomic, copy) COFormParameters NSString *label; @end // 删除讨论的评论 @interface COTopicDeleteRequest : CODataRequest @property (nonatomic, copy) COUriParameters NSNumber *topicId; @end // 新增讨论 @interface COTopicAddRequest : COPageRequest @property (nonatomic, copy) COUriParameters NSNumber *projectId; @property (nonatomic, copy) COFormParameters NSString *title; @property (nonatomic, copy) COFormParameters NSString *content; @property (nonatomic, copy) COFormParameters NSString *label; @end @interface COTopicCommentsRequest : COPageRequest @property (nonatomic, copy) COUriParameters NSNumber *topicId; @end // 讨论增加评论 @interface COTopicCommentAddRequest : COPageRequest @property (nonatomic, copy) COUriParameters NSNumber *projectId; @property (nonatomic, copy) COUriParameters NSNumber *topicId; @property (nonatomic, copy) COQueryParameters NSString *content; @end // 项目的所有标签及被使用计数 @interface COProjectTopicLabelsRequest : CODataRequest @property (nonatomic, assign) COUriParameters NSInteger projectId; @end // 项目新增标签 @interface COProjectTopicLabelAddRequest : CODataRequest @property (nonatomic, assign) COUriParameters NSInteger projectId; @property (nonatomic, copy) COQueryParameters NSString *name;// POST @property (nonatomic, copy) COQueryParameters NSString *color; @end // 项目所有、我参与的讨论数目 @interface COProjectTopicCountRequest : CODataRequest @property (nonatomic, assign) COUriParameters NSInteger projectId; @end // 项目我参与的讨论的标签 @interface COProjectTopicLabelMyRequest : CODataRequest @property (nonatomic, copy) COUriParameters NSString *ownerName; @property (nonatomic, copy) COUriParameters NSString *projectName; @end // 删除项目的标签 @interface COProjectTopicLabelDelRequest : CODataRequest @property (nonatomic, copy) COUriParameters NSNumber *projectId; @property (nonatomic, copy) COUriParameters NSNumber *labelId; @end // 修改项目的标签 @interface COProjectTopicLabelMedifyRequest : CODataRequest @property (nonatomic, copy) COUriParameters NSString *projectOwnerName; @property (nonatomic, copy) COUriParameters NSString *projectName; @property (nonatomic, copy) COUriParameters NSNumber *labelId; @property (nonatomic, copy) COFormParameters NSString *name;// PUT @property (nonatomic, copy) COFormParameters NSString *color; @end // 批量修改项目的标签 @interface COProjectTopicLabelChangesRequest : CODataRequest @property (nonatomic, copy) COUriParameters NSString *projectOwnerName; @property (nonatomic, copy) COUriParameters NSString *projectName; @property (nonatomic, copy) COUriParameters NSNumber *topicId; @property (nonatomic, copy) COFormParameters NSString *labelIds; @end
atlaskerr/titan
http/oci/blob/delete_handler_option.go
package blob import ( "errors" "github.com/atlaskerr/titan/metrics" ) // DeleteHandlerOption applies a parameter to a DeleteHandler. type DeleteHandlerOption func(*DeleteHandler) // DeleteOptionMetrics sets the http.Handler to use for the metrics // endpoint. func DeleteOptionMetrics(collector *metrics.Collector) DeleteHandlerOption { var fn DeleteHandlerOption = func(s *DeleteHandler) { s.metrics = collector } return fn } func NewDeleteHandler(options ...DeleteHandlerOption) (*DeleteHandler, error) { srv := &DeleteHandler{} for _, addOption := range options { addOption(srv) } if srv.metrics == nil { return nil, errors.New("no metrics collector defined") } return srv, nil }
maelvls/ocamlyices2
ext/yices/tests/unit/test_smt_parser.c
/* * The Yices SMT Solver. Copyright 2014 SRI International. * * This program may only be used subject to the noncommercial end user * license agreement which is downloadable along with this program. */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <inttypes.h> #include "api/yices_globals.h" #include "frontend/smt1/smt_lexer.h" #include "frontend/smt1/smt_parser.h" #include "frontend/smt1/smt_term_stack.h" #include "io/term_printer.h" #include "io/type_printer.h" #include "utils/cputime.h" #include "utils/memsize.h" #include "yices.h" #include "yices_exit_codes.h" static lexer_t lexer; static parser_t parser; static tstack_t stack; static smt_benchmark_t bench; static char *status2string[] = { "none", "unsat", "sat", "unknown", }; #if 0 // not used anymore static void print_benchmark(FILE *f, smt_benchmark_t *bench) { uint32_t i, n; n = bench->nformulas; fprintf(f, "Benchmark %s\n", bench->name); fprintf(f, "Logic: %s\n", bench->logic_name); fprintf(f, "Parameter: %"PRId32"\n", bench->logic_parameter); fprintf(f, "Status: %s\n", status2string[bench->status]); fprintf(f, "Number of formulas or assumptions: %"PRIu32"\n", n); for (i=0; i<n; i++) { fprintf(f, "\n---- Assertion %"PRIu32" ----\n", i); print_term(f, bench->formulas[i]); fprintf(f, "\n"); } } #endif /* * Temporary test. Check whether one of the input assertion is reduced * to false by simplification. This is checked independent of the * logic label. */ static bool benchmark_reduced_to_false(smt_benchmark_t *bench) { uint32_t i, n; term_t f; n = bench->nformulas; for (i=0; i<n; i++) { f = bench->formulas[i]; assert(is_boolean_term(__yices_globals.terms, f)); if (f == false_term) { return true; } } return false; } static void dump_benchmark(FILE *f, smt_benchmark_t *bench) { uint32_t i, n; n = bench->nformulas; fprintf(f, "Benchmark %s\n", bench->name); fprintf(f, "Logic: %s\n", bench->logic_name); fprintf(f, "Parameter: %"PRId32"\n", bench->logic_parameter); fprintf(f, "Status: %s\n", status2string[bench->status]); fprintf(f, "Number of formulas or assumptions: %"PRIu32"\n", n); fprintf(f, "Assertions: "); for (i=0; i<n; i++) { if (i % 20 == 19) { fprintf(f, "\n "); } fprintf(f, " "); print_term_id(f, bench->formulas[i]); } fprintf(f, "\n"); fprintf(f, "\n---- All types ----\n"); print_type_table(f, __yices_globals.types); fprintf(f, "\n\n---- All terms ----\n"); print_term_table(f, __yices_globals.terms); fprintf(f, "\n\n"); fflush(f); } int main(int argc, char *argv[]) { char *filename; int32_t code; FILE *dump; double time, mem_used; if (argc > 2) { fprintf(stderr, "Usage: %s <filename>\n", argv[0]); exit(YICES_EXIT_USAGE); } if (argc == 2) { // read from file filename = argv[1]; if (init_smt_file_lexer(&lexer, filename) < 0) { perror(filename); exit(YICES_EXIT_FILE_NOT_FOUND); } } else { // read from stdin init_smt_stdin_lexer(&lexer); } yices_init(); init_smt_tstack(&stack); init_parser(&parser, &lexer, &stack); init_benchmark(&bench); code = parse_smt_benchmark(&parser, &bench); if (code == 0) { printf("No syntax error found\n"); } if (benchmark_reduced_to_false(&bench)) { printf("Reduced to false\n\nunsat\n"); fflush(stdout); } printf("\n"); time = get_cpu_time(); mem_used = mem_size() / (1024 * 1024); printf("Construction time: %.4f s\n", time); printf("Memory used: %.2f MB\n\n", mem_used); fflush(stdout); dump = fopen("yices2new.dmp", "w"); if (dump == NULL) { perror("yices2new.dmp"); } else { dump_benchmark(dump, &bench); fclose(dump); } delete_benchmark(&bench); delete_parser(&parser); close_lexer(&lexer); delete_tstack(&stack); yices_exit(); return YICES_EXIT_SUCCESS; }
konnigud/RuFanWeb
app/is/rufan/team/data/VenueRowMapper.java
<gh_stars>0 package is.rufan.team.data; import is.rufan.team.domain.Venue; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class VenueRowMapper implements RowMapper<Venue> { public Venue mapRow(ResultSet rs, int rowNum) throws SQLException { Venue venue = new Venue(); venue.setVenueId(rs.getInt("venueid")); venue.setName(rs.getString("name")); venue.setCity(rs.getString("city")); return venue; } }
situx/kiwi-postgis
src/org/openrdf/query/algebra/evaluation/function/postgis/geometry/attribute/IsCollection.java
package org.openrdf.query.algebra.evaluation.function.postgis.geometry.attribute; import org.openrdf.model.vocabulary.POSTGIS; import org.locationtech.jts.geom.Geometry; import org.openrdf.query.algebra.evaluation.function.postgis.geometry.base.GeometricBinaryAttributeFunction; public class IsCollection extends GeometricBinaryAttributeFunction { @Override public String getURI() { return POSTGIS.st_isCollection.stringValue(); } @Override public boolean attribute(Geometry geom) { String type=geom.getGeometryType().toUpperCase(); if("GEOMETRYCOLLECTION".equals(type) || "COMPOUNDCURVE".equals(type) || type.startsWith("MUTLI")) { return true; } return false; } }
kashiish/vespa
fbench/src/grpcclient/third_party/googleapis/gens/google/identity/accesscontextmanager/v1/access_level.pb.h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/identity/accesscontextmanager/v1/access_level.proto #ifndef PROTOBUF_INCLUDED_google_2fidentity_2faccesscontextmanager_2fv1_2faccess_5flevel_2eproto #define PROTOBUF_INCLUDED_google_2fidentity_2faccesscontextmanager_2fv1_2faccess_5flevel_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3007000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3007000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/generated_enum_reflection.h> #include <google/protobuf/unknown_field_set.h> #include "google/identity/accesscontextmanager/type/device_resources.pb.h" #include <google/protobuf/timestamp.pb.h> #include "google/type/expr.pb.h" #include "google/api/annotations.pb.h" // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_google_2fidentity_2faccesscontextmanager_2fv1_2faccess_5flevel_2eproto // Internal implementation detail -- do not use these members. struct TableStruct_google_2fidentity_2faccesscontextmanager_2fv1_2faccess_5flevel_2eproto { static const ::google::protobuf::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::AuxillaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::ParseTable schema[6] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; void AddDescriptors_google_2fidentity_2faccesscontextmanager_2fv1_2faccess_5flevel_2eproto(); namespace google { namespace identity { namespace accesscontextmanager { namespace v1 { class AccessLevel; class AccessLevelDefaultTypeInternal; extern AccessLevelDefaultTypeInternal _AccessLevel_default_instance_; class BasicLevel; class BasicLevelDefaultTypeInternal; extern BasicLevelDefaultTypeInternal _BasicLevel_default_instance_; class Condition; class ConditionDefaultTypeInternal; extern ConditionDefaultTypeInternal _Condition_default_instance_; class CustomLevel; class CustomLevelDefaultTypeInternal; extern CustomLevelDefaultTypeInternal _CustomLevel_default_instance_; class DevicePolicy; class DevicePolicyDefaultTypeInternal; extern DevicePolicyDefaultTypeInternal _DevicePolicy_default_instance_; class OsConstraint; class OsConstraintDefaultTypeInternal; extern OsConstraintDefaultTypeInternal _OsConstraint_default_instance_; } // namespace v1 } // namespace accesscontextmanager } // namespace identity namespace protobuf { template<> ::google::identity::accesscontextmanager::v1::AccessLevel* Arena::CreateMaybeMessage<::google::identity::accesscontextmanager::v1::AccessLevel>(Arena*); template<> ::google::identity::accesscontextmanager::v1::BasicLevel* Arena::CreateMaybeMessage<::google::identity::accesscontextmanager::v1::BasicLevel>(Arena*); template<> ::google::identity::accesscontextmanager::v1::Condition* Arena::CreateMaybeMessage<::google::identity::accesscontextmanager::v1::Condition>(Arena*); template<> ::google::identity::accesscontextmanager::v1::CustomLevel* Arena::CreateMaybeMessage<::google::identity::accesscontextmanager::v1::CustomLevel>(Arena*); template<> ::google::identity::accesscontextmanager::v1::DevicePolicy* Arena::CreateMaybeMessage<::google::identity::accesscontextmanager::v1::DevicePolicy>(Arena*); template<> ::google::identity::accesscontextmanager::v1::OsConstraint* Arena::CreateMaybeMessage<::google::identity::accesscontextmanager::v1::OsConstraint>(Arena*); } // namespace protobuf } // namespace google namespace google { namespace identity { namespace accesscontextmanager { namespace v1 { enum BasicLevel_ConditionCombiningFunction { BasicLevel_ConditionCombiningFunction_AND = 0, BasicLevel_ConditionCombiningFunction_OR = 1, BasicLevel_ConditionCombiningFunction_BasicLevel_ConditionCombiningFunction_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::google::protobuf::int32>::min(), BasicLevel_ConditionCombiningFunction_BasicLevel_ConditionCombiningFunction_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::google::protobuf::int32>::max() }; bool BasicLevel_ConditionCombiningFunction_IsValid(int value); const BasicLevel_ConditionCombiningFunction BasicLevel_ConditionCombiningFunction_ConditionCombiningFunction_MIN = BasicLevel_ConditionCombiningFunction_AND; const BasicLevel_ConditionCombiningFunction BasicLevel_ConditionCombiningFunction_ConditionCombiningFunction_MAX = BasicLevel_ConditionCombiningFunction_OR; const int BasicLevel_ConditionCombiningFunction_ConditionCombiningFunction_ARRAYSIZE = BasicLevel_ConditionCombiningFunction_ConditionCombiningFunction_MAX + 1; const ::google::protobuf::EnumDescriptor* BasicLevel_ConditionCombiningFunction_descriptor(); inline const ::std::string& BasicLevel_ConditionCombiningFunction_Name(BasicLevel_ConditionCombiningFunction value) { return ::google::protobuf::internal::NameOfEnum( BasicLevel_ConditionCombiningFunction_descriptor(), value); } inline bool BasicLevel_ConditionCombiningFunction_Parse( const ::std::string& name, BasicLevel_ConditionCombiningFunction* value) { return ::google::protobuf::internal::ParseNamedEnum<BasicLevel_ConditionCombiningFunction>( BasicLevel_ConditionCombiningFunction_descriptor(), name, value); } // =================================================================== class AccessLevel final : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.identity.accesscontextmanager.v1.AccessLevel) */ { public: AccessLevel(); virtual ~AccessLevel(); AccessLevel(const AccessLevel& from); inline AccessLevel& operator=(const AccessLevel& from) { CopyFrom(from); return *this; } #if LANG_CXX11 AccessLevel(AccessLevel&& from) noexcept : AccessLevel() { *this = ::std::move(from); } inline AccessLevel& operator=(AccessLevel&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor() { return default_instance().GetDescriptor(); } static const AccessLevel& default_instance(); enum LevelCase { kBasic = 4, kCustom = 5, LEVEL_NOT_SET = 0, }; static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const AccessLevel* internal_default_instance() { return reinterpret_cast<const AccessLevel*>( &_AccessLevel_default_instance_); } static constexpr int kIndexInFileMessages = 0; void Swap(AccessLevel* other); friend void swap(AccessLevel& a, AccessLevel& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline AccessLevel* New() const final { return CreateMaybeMessage<AccessLevel>(nullptr); } AccessLevel* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<AccessLevel>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const AccessLevel& from); void MergeFrom(const AccessLevel& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx); ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; } #else bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(AccessLevel* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // string name = 1; void clear_name(); static const int kNameFieldNumber = 1; const ::std::string& name() const; void set_name(const ::std::string& value); #if LANG_CXX11 void set_name(::std::string&& value); #endif void set_name(const char* value); void set_name(const char* value, size_t size); ::std::string* mutable_name(); ::std::string* release_name(); void set_allocated_name(::std::string* name); // string title = 2; void clear_title(); static const int kTitleFieldNumber = 2; const ::std::string& title() const; void set_title(const ::std::string& value); #if LANG_CXX11 void set_title(::std::string&& value); #endif void set_title(const char* value); void set_title(const char* value, size_t size); ::std::string* mutable_title(); ::std::string* release_title(); void set_allocated_title(::std::string* title); // string description = 3; void clear_description(); static const int kDescriptionFieldNumber = 3; const ::std::string& description() const; void set_description(const ::std::string& value); #if LANG_CXX11 void set_description(::std::string&& value); #endif void set_description(const char* value); void set_description(const char* value, size_t size); ::std::string* mutable_description(); ::std::string* release_description(); void set_allocated_description(::std::string* description); // .google.protobuf.Timestamp create_time = 6; bool has_create_time() const; void clear_create_time(); static const int kCreateTimeFieldNumber = 6; const ::google::protobuf::Timestamp& create_time() const; ::google::protobuf::Timestamp* release_create_time(); ::google::protobuf::Timestamp* mutable_create_time(); void set_allocated_create_time(::google::protobuf::Timestamp* create_time); // .google.protobuf.Timestamp update_time = 7; bool has_update_time() const; void clear_update_time(); static const int kUpdateTimeFieldNumber = 7; const ::google::protobuf::Timestamp& update_time() const; ::google::protobuf::Timestamp* release_update_time(); ::google::protobuf::Timestamp* mutable_update_time(); void set_allocated_update_time(::google::protobuf::Timestamp* update_time); // .google.identity.accesscontextmanager.v1.BasicLevel basic = 4; bool has_basic() const; void clear_basic(); static const int kBasicFieldNumber = 4; const ::google::identity::accesscontextmanager::v1::BasicLevel& basic() const; ::google::identity::accesscontextmanager::v1::BasicLevel* release_basic(); ::google::identity::accesscontextmanager::v1::BasicLevel* mutable_basic(); void set_allocated_basic(::google::identity::accesscontextmanager::v1::BasicLevel* basic); // .google.identity.accesscontextmanager.v1.CustomLevel custom = 5; bool has_custom() const; void clear_custom(); static const int kCustomFieldNumber = 5; const ::google::identity::accesscontextmanager::v1::CustomLevel& custom() const; ::google::identity::accesscontextmanager::v1::CustomLevel* release_custom(); ::google::identity::accesscontextmanager::v1::CustomLevel* mutable_custom(); void set_allocated_custom(::google::identity::accesscontextmanager::v1::CustomLevel* custom); void clear_level(); LevelCase level_case() const; // @@protoc_insertion_point(class_scope:google.identity.accesscontextmanager.v1.AccessLevel) private: class HasBitSetters; void set_has_basic(); void set_has_custom(); inline bool has_level() const; inline void clear_has_level(); ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::internal::ArenaStringPtr title_; ::google::protobuf::internal::ArenaStringPtr description_; ::google::protobuf::Timestamp* create_time_; ::google::protobuf::Timestamp* update_time_; union LevelUnion { LevelUnion() {} ::google::identity::accesscontextmanager::v1::BasicLevel* basic_; ::google::identity::accesscontextmanager::v1::CustomLevel* custom_; } level_; mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::uint32 _oneof_case_[1]; friend struct ::TableStruct_google_2fidentity_2faccesscontextmanager_2fv1_2faccess_5flevel_2eproto; }; // ------------------------------------------------------------------- class BasicLevel final : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.identity.accesscontextmanager.v1.BasicLevel) */ { public: BasicLevel(); virtual ~BasicLevel(); BasicLevel(const BasicLevel& from); inline BasicLevel& operator=(const BasicLevel& from) { CopyFrom(from); return *this; } #if LANG_CXX11 BasicLevel(BasicLevel&& from) noexcept : BasicLevel() { *this = ::std::move(from); } inline BasicLevel& operator=(BasicLevel&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor() { return default_instance().GetDescriptor(); } static const BasicLevel& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const BasicLevel* internal_default_instance() { return reinterpret_cast<const BasicLevel*>( &_BasicLevel_default_instance_); } static constexpr int kIndexInFileMessages = 1; void Swap(BasicLevel* other); friend void swap(BasicLevel& a, BasicLevel& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline BasicLevel* New() const final { return CreateMaybeMessage<BasicLevel>(nullptr); } BasicLevel* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<BasicLevel>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const BasicLevel& from); void MergeFrom(const BasicLevel& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx); ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; } #else bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BasicLevel* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- typedef BasicLevel_ConditionCombiningFunction ConditionCombiningFunction; static const ConditionCombiningFunction AND = BasicLevel_ConditionCombiningFunction_AND; static const ConditionCombiningFunction OR = BasicLevel_ConditionCombiningFunction_OR; static inline bool ConditionCombiningFunction_IsValid(int value) { return BasicLevel_ConditionCombiningFunction_IsValid(value); } static const ConditionCombiningFunction ConditionCombiningFunction_MIN = BasicLevel_ConditionCombiningFunction_ConditionCombiningFunction_MIN; static const ConditionCombiningFunction ConditionCombiningFunction_MAX = BasicLevel_ConditionCombiningFunction_ConditionCombiningFunction_MAX; static const int ConditionCombiningFunction_ARRAYSIZE = BasicLevel_ConditionCombiningFunction_ConditionCombiningFunction_ARRAYSIZE; static inline const ::google::protobuf::EnumDescriptor* ConditionCombiningFunction_descriptor() { return BasicLevel_ConditionCombiningFunction_descriptor(); } static inline const ::std::string& ConditionCombiningFunction_Name(ConditionCombiningFunction value) { return BasicLevel_ConditionCombiningFunction_Name(value); } static inline bool ConditionCombiningFunction_Parse(const ::std::string& name, ConditionCombiningFunction* value) { return BasicLevel_ConditionCombiningFunction_Parse(name, value); } // accessors ------------------------------------------------------- // repeated .google.identity.accesscontextmanager.v1.Condition conditions = 1; int conditions_size() const; void clear_conditions(); static const int kConditionsFieldNumber = 1; ::google::identity::accesscontextmanager::v1::Condition* mutable_conditions(int index); ::google::protobuf::RepeatedPtrField< ::google::identity::accesscontextmanager::v1::Condition >* mutable_conditions(); const ::google::identity::accesscontextmanager::v1::Condition& conditions(int index) const; ::google::identity::accesscontextmanager::v1::Condition* add_conditions(); const ::google::protobuf::RepeatedPtrField< ::google::identity::accesscontextmanager::v1::Condition >& conditions() const; // .google.identity.accesscontextmanager.v1.BasicLevel.ConditionCombiningFunction combining_function = 2; void clear_combining_function(); static const int kCombiningFunctionFieldNumber = 2; ::google::identity::accesscontextmanager::v1::BasicLevel_ConditionCombiningFunction combining_function() const; void set_combining_function(::google::identity::accesscontextmanager::v1::BasicLevel_ConditionCombiningFunction value); // @@protoc_insertion_point(class_scope:google.identity.accesscontextmanager.v1.BasicLevel) private: class HasBitSetters; ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::RepeatedPtrField< ::google::identity::accesscontextmanager::v1::Condition > conditions_; int combining_function_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2fidentity_2faccesscontextmanager_2fv1_2faccess_5flevel_2eproto; }; // ------------------------------------------------------------------- class Condition final : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.identity.accesscontextmanager.v1.Condition) */ { public: Condition(); virtual ~Condition(); Condition(const Condition& from); inline Condition& operator=(const Condition& from) { CopyFrom(from); return *this; } #if LANG_CXX11 Condition(Condition&& from) noexcept : Condition() { *this = ::std::move(from); } inline Condition& operator=(Condition&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor() { return default_instance().GetDescriptor(); } static const Condition& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const Condition* internal_default_instance() { return reinterpret_cast<const Condition*>( &_Condition_default_instance_); } static constexpr int kIndexInFileMessages = 2; void Swap(Condition* other); friend void swap(Condition& a, Condition& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline Condition* New() const final { return CreateMaybeMessage<Condition>(nullptr); } Condition* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<Condition>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Condition& from); void MergeFrom(const Condition& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx); ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; } #else bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Condition* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated string ip_subnetworks = 1; int ip_subnetworks_size() const; void clear_ip_subnetworks(); static const int kIpSubnetworksFieldNumber = 1; const ::std::string& ip_subnetworks(int index) const; ::std::string* mutable_ip_subnetworks(int index); void set_ip_subnetworks(int index, const ::std::string& value); #if LANG_CXX11 void set_ip_subnetworks(int index, ::std::string&& value); #endif void set_ip_subnetworks(int index, const char* value); void set_ip_subnetworks(int index, const char* value, size_t size); ::std::string* add_ip_subnetworks(); void add_ip_subnetworks(const ::std::string& value); #if LANG_CXX11 void add_ip_subnetworks(::std::string&& value); #endif void add_ip_subnetworks(const char* value); void add_ip_subnetworks(const char* value, size_t size); const ::google::protobuf::RepeatedPtrField<::std::string>& ip_subnetworks() const; ::google::protobuf::RepeatedPtrField<::std::string>* mutable_ip_subnetworks(); // repeated string required_access_levels = 3; int required_access_levels_size() const; void clear_required_access_levels(); static const int kRequiredAccessLevelsFieldNumber = 3; const ::std::string& required_access_levels(int index) const; ::std::string* mutable_required_access_levels(int index); void set_required_access_levels(int index, const ::std::string& value); #if LANG_CXX11 void set_required_access_levels(int index, ::std::string&& value); #endif void set_required_access_levels(int index, const char* value); void set_required_access_levels(int index, const char* value, size_t size); ::std::string* add_required_access_levels(); void add_required_access_levels(const ::std::string& value); #if LANG_CXX11 void add_required_access_levels(::std::string&& value); #endif void add_required_access_levels(const char* value); void add_required_access_levels(const char* value, size_t size); const ::google::protobuf::RepeatedPtrField<::std::string>& required_access_levels() const; ::google::protobuf::RepeatedPtrField<::std::string>* mutable_required_access_levels(); // repeated string members = 6; int members_size() const; void clear_members(); static const int kMembersFieldNumber = 6; const ::std::string& members(int index) const; ::std::string* mutable_members(int index); void set_members(int index, const ::std::string& value); #if LANG_CXX11 void set_members(int index, ::std::string&& value); #endif void set_members(int index, const char* value); void set_members(int index, const char* value, size_t size); ::std::string* add_members(); void add_members(const ::std::string& value); #if LANG_CXX11 void add_members(::std::string&& value); #endif void add_members(const char* value); void add_members(const char* value, size_t size); const ::google::protobuf::RepeatedPtrField<::std::string>& members() const; ::google::protobuf::RepeatedPtrField<::std::string>* mutable_members(); // repeated string regions = 7; int regions_size() const; void clear_regions(); static const int kRegionsFieldNumber = 7; const ::std::string& regions(int index) const; ::std::string* mutable_regions(int index); void set_regions(int index, const ::std::string& value); #if LANG_CXX11 void set_regions(int index, ::std::string&& value); #endif void set_regions(int index, const char* value); void set_regions(int index, const char* value, size_t size); ::std::string* add_regions(); void add_regions(const ::std::string& value); #if LANG_CXX11 void add_regions(::std::string&& value); #endif void add_regions(const char* value); void add_regions(const char* value, size_t size); const ::google::protobuf::RepeatedPtrField<::std::string>& regions() const; ::google::protobuf::RepeatedPtrField<::std::string>* mutable_regions(); // .google.identity.accesscontextmanager.v1.DevicePolicy device_policy = 2; bool has_device_policy() const; void clear_device_policy(); static const int kDevicePolicyFieldNumber = 2; const ::google::identity::accesscontextmanager::v1::DevicePolicy& device_policy() const; ::google::identity::accesscontextmanager::v1::DevicePolicy* release_device_policy(); ::google::identity::accesscontextmanager::v1::DevicePolicy* mutable_device_policy(); void set_allocated_device_policy(::google::identity::accesscontextmanager::v1::DevicePolicy* device_policy); // bool negate = 5; void clear_negate(); static const int kNegateFieldNumber = 5; bool negate() const; void set_negate(bool value); // @@protoc_insertion_point(class_scope:google.identity.accesscontextmanager.v1.Condition) private: class HasBitSetters; ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::RepeatedPtrField<::std::string> ip_subnetworks_; ::google::protobuf::RepeatedPtrField<::std::string> required_access_levels_; ::google::protobuf::RepeatedPtrField<::std::string> members_; ::google::protobuf::RepeatedPtrField<::std::string> regions_; ::google::identity::accesscontextmanager::v1::DevicePolicy* device_policy_; bool negate_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2fidentity_2faccesscontextmanager_2fv1_2faccess_5flevel_2eproto; }; // ------------------------------------------------------------------- class CustomLevel final : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.identity.accesscontextmanager.v1.CustomLevel) */ { public: CustomLevel(); virtual ~CustomLevel(); CustomLevel(const CustomLevel& from); inline CustomLevel& operator=(const CustomLevel& from) { CopyFrom(from); return *this; } #if LANG_CXX11 CustomLevel(CustomLevel&& from) noexcept : CustomLevel() { *this = ::std::move(from); } inline CustomLevel& operator=(CustomLevel&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor() { return default_instance().GetDescriptor(); } static const CustomLevel& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const CustomLevel* internal_default_instance() { return reinterpret_cast<const CustomLevel*>( &_CustomLevel_default_instance_); } static constexpr int kIndexInFileMessages = 3; void Swap(CustomLevel* other); friend void swap(CustomLevel& a, CustomLevel& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline CustomLevel* New() const final { return CreateMaybeMessage<CustomLevel>(nullptr); } CustomLevel* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<CustomLevel>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const CustomLevel& from); void MergeFrom(const CustomLevel& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx); ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; } #else bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CustomLevel* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // .google.type.Expr expr = 1; bool has_expr() const; void clear_expr(); static const int kExprFieldNumber = 1; const ::google::type::Expr& expr() const; ::google::type::Expr* release_expr(); ::google::type::Expr* mutable_expr(); void set_allocated_expr(::google::type::Expr* expr); // @@protoc_insertion_point(class_scope:google.identity.accesscontextmanager.v1.CustomLevel) private: class HasBitSetters; ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::type::Expr* expr_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2fidentity_2faccesscontextmanager_2fv1_2faccess_5flevel_2eproto; }; // ------------------------------------------------------------------- class DevicePolicy final : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.identity.accesscontextmanager.v1.DevicePolicy) */ { public: DevicePolicy(); virtual ~DevicePolicy(); DevicePolicy(const DevicePolicy& from); inline DevicePolicy& operator=(const DevicePolicy& from) { CopyFrom(from); return *this; } #if LANG_CXX11 DevicePolicy(DevicePolicy&& from) noexcept : DevicePolicy() { *this = ::std::move(from); } inline DevicePolicy& operator=(DevicePolicy&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor() { return default_instance().GetDescriptor(); } static const DevicePolicy& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const DevicePolicy* internal_default_instance() { return reinterpret_cast<const DevicePolicy*>( &_DevicePolicy_default_instance_); } static constexpr int kIndexInFileMessages = 4; void Swap(DevicePolicy* other); friend void swap(DevicePolicy& a, DevicePolicy& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline DevicePolicy* New() const final { return CreateMaybeMessage<DevicePolicy>(nullptr); } DevicePolicy* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<DevicePolicy>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const DevicePolicy& from); void MergeFrom(const DevicePolicy& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx); ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; } #else bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(DevicePolicy* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated .google.identity.accesscontextmanager.type.DeviceEncryptionStatus allowed_encryption_statuses = 2; int allowed_encryption_statuses_size() const; void clear_allowed_encryption_statuses(); static const int kAllowedEncryptionStatusesFieldNumber = 2; ::google::identity::accesscontextmanager::type::DeviceEncryptionStatus allowed_encryption_statuses(int index) const; void set_allowed_encryption_statuses(int index, ::google::identity::accesscontextmanager::type::DeviceEncryptionStatus value); void add_allowed_encryption_statuses(::google::identity::accesscontextmanager::type::DeviceEncryptionStatus value); const ::google::protobuf::RepeatedField<int>& allowed_encryption_statuses() const; ::google::protobuf::RepeatedField<int>* mutable_allowed_encryption_statuses(); // repeated .google.identity.accesscontextmanager.v1.OsConstraint os_constraints = 3; int os_constraints_size() const; void clear_os_constraints(); static const int kOsConstraintsFieldNumber = 3; ::google::identity::accesscontextmanager::v1::OsConstraint* mutable_os_constraints(int index); ::google::protobuf::RepeatedPtrField< ::google::identity::accesscontextmanager::v1::OsConstraint >* mutable_os_constraints(); const ::google::identity::accesscontextmanager::v1::OsConstraint& os_constraints(int index) const; ::google::identity::accesscontextmanager::v1::OsConstraint* add_os_constraints(); const ::google::protobuf::RepeatedPtrField< ::google::identity::accesscontextmanager::v1::OsConstraint >& os_constraints() const; // repeated .google.identity.accesscontextmanager.type.DeviceManagementLevel allowed_device_management_levels = 6; int allowed_device_management_levels_size() const; void clear_allowed_device_management_levels(); static const int kAllowedDeviceManagementLevelsFieldNumber = 6; ::google::identity::accesscontextmanager::type::DeviceManagementLevel allowed_device_management_levels(int index) const; void set_allowed_device_management_levels(int index, ::google::identity::accesscontextmanager::type::DeviceManagementLevel value); void add_allowed_device_management_levels(::google::identity::accesscontextmanager::type::DeviceManagementLevel value); const ::google::protobuf::RepeatedField<int>& allowed_device_management_levels() const; ::google::protobuf::RepeatedField<int>* mutable_allowed_device_management_levels(); // bool require_screenlock = 1; void clear_require_screenlock(); static const int kRequireScreenlockFieldNumber = 1; bool require_screenlock() const; void set_require_screenlock(bool value); // bool require_admin_approval = 7; void clear_require_admin_approval(); static const int kRequireAdminApprovalFieldNumber = 7; bool require_admin_approval() const; void set_require_admin_approval(bool value); // bool require_corp_owned = 8; void clear_require_corp_owned(); static const int kRequireCorpOwnedFieldNumber = 8; bool require_corp_owned() const; void set_require_corp_owned(bool value); // @@protoc_insertion_point(class_scope:google.identity.accesscontextmanager.v1.DevicePolicy) private: class HasBitSetters; ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::RepeatedField<int> allowed_encryption_statuses_; mutable std::atomic<int> _allowed_encryption_statuses_cached_byte_size_; ::google::protobuf::RepeatedPtrField< ::google::identity::accesscontextmanager::v1::OsConstraint > os_constraints_; ::google::protobuf::RepeatedField<int> allowed_device_management_levels_; mutable std::atomic<int> _allowed_device_management_levels_cached_byte_size_; bool require_screenlock_; bool require_admin_approval_; bool require_corp_owned_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2fidentity_2faccesscontextmanager_2fv1_2faccess_5flevel_2eproto; }; // ------------------------------------------------------------------- class OsConstraint final : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.identity.accesscontextmanager.v1.OsConstraint) */ { public: OsConstraint(); virtual ~OsConstraint(); OsConstraint(const OsConstraint& from); inline OsConstraint& operator=(const OsConstraint& from) { CopyFrom(from); return *this; } #if LANG_CXX11 OsConstraint(OsConstraint&& from) noexcept : OsConstraint() { *this = ::std::move(from); } inline OsConstraint& operator=(OsConstraint&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor() { return default_instance().GetDescriptor(); } static const OsConstraint& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const OsConstraint* internal_default_instance() { return reinterpret_cast<const OsConstraint*>( &_OsConstraint_default_instance_); } static constexpr int kIndexInFileMessages = 5; void Swap(OsConstraint* other); friend void swap(OsConstraint& a, OsConstraint& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline OsConstraint* New() const final { return CreateMaybeMessage<OsConstraint>(nullptr); } OsConstraint* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<OsConstraint>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const OsConstraint& from); void MergeFrom(const OsConstraint& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx); ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; } #else bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(OsConstraint* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // string minimum_version = 2; void clear_minimum_version(); static const int kMinimumVersionFieldNumber = 2; const ::std::string& minimum_version() const; void set_minimum_version(const ::std::string& value); #if LANG_CXX11 void set_minimum_version(::std::string&& value); #endif void set_minimum_version(const char* value); void set_minimum_version(const char* value, size_t size); ::std::string* mutable_minimum_version(); ::std::string* release_minimum_version(); void set_allocated_minimum_version(::std::string* minimum_version); // .google.identity.accesscontextmanager.type.OsType os_type = 1; void clear_os_type(); static const int kOsTypeFieldNumber = 1; ::google::identity::accesscontextmanager::type::OsType os_type() const; void set_os_type(::google::identity::accesscontextmanager::type::OsType value); // bool require_verified_chrome_os = 3; void clear_require_verified_chrome_os(); static const int kRequireVerifiedChromeOsFieldNumber = 3; bool require_verified_chrome_os() const; void set_require_verified_chrome_os(bool value); // @@protoc_insertion_point(class_scope:google.identity.accesscontextmanager.v1.OsConstraint) private: class HasBitSetters; ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr minimum_version_; int os_type_; bool require_verified_chrome_os_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2fidentity_2faccesscontextmanager_2fv1_2faccess_5flevel_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // AccessLevel // string name = 1; inline void AccessLevel::clear_name() { name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& AccessLevel::name() const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.AccessLevel.name) return name_.GetNoArena(); } inline void AccessLevel::set_name(const ::std::string& value) { name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.AccessLevel.name) } #if LANG_CXX11 inline void AccessLevel::set_name(::std::string&& value) { name_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.identity.accesscontextmanager.v1.AccessLevel.name) } #endif inline void AccessLevel::set_name(const char* value) { GOOGLE_DCHECK(value != nullptr); name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.identity.accesscontextmanager.v1.AccessLevel.name) } inline void AccessLevel::set_name(const char* value, size_t size) { name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.identity.accesscontextmanager.v1.AccessLevel.name) } inline ::std::string* AccessLevel::mutable_name() { // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.AccessLevel.name) return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* AccessLevel::release_name() { // @@protoc_insertion_point(field_release:google.identity.accesscontextmanager.v1.AccessLevel.name) return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void AccessLevel::set_allocated_name(::std::string* name) { if (name != nullptr) { } else { } name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); // @@protoc_insertion_point(field_set_allocated:google.identity.accesscontextmanager.v1.AccessLevel.name) } // string title = 2; inline void AccessLevel::clear_title() { title_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& AccessLevel::title() const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.AccessLevel.title) return title_.GetNoArena(); } inline void AccessLevel::set_title(const ::std::string& value) { title_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.AccessLevel.title) } #if LANG_CXX11 inline void AccessLevel::set_title(::std::string&& value) { title_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.identity.accesscontextmanager.v1.AccessLevel.title) } #endif inline void AccessLevel::set_title(const char* value) { GOOGLE_DCHECK(value != nullptr); title_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.identity.accesscontextmanager.v1.AccessLevel.title) } inline void AccessLevel::set_title(const char* value, size_t size) { title_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.identity.accesscontextmanager.v1.AccessLevel.title) } inline ::std::string* AccessLevel::mutable_title() { // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.AccessLevel.title) return title_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* AccessLevel::release_title() { // @@protoc_insertion_point(field_release:google.identity.accesscontextmanager.v1.AccessLevel.title) return title_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void AccessLevel::set_allocated_title(::std::string* title) { if (title != nullptr) { } else { } title_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), title); // @@protoc_insertion_point(field_set_allocated:google.identity.accesscontextmanager.v1.AccessLevel.title) } // string description = 3; inline void AccessLevel::clear_description() { description_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& AccessLevel::description() const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.AccessLevel.description) return description_.GetNoArena(); } inline void AccessLevel::set_description(const ::std::string& value) { description_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.AccessLevel.description) } #if LANG_CXX11 inline void AccessLevel::set_description(::std::string&& value) { description_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.identity.accesscontextmanager.v1.AccessLevel.description) } #endif inline void AccessLevel::set_description(const char* value) { GOOGLE_DCHECK(value != nullptr); description_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.identity.accesscontextmanager.v1.AccessLevel.description) } inline void AccessLevel::set_description(const char* value, size_t size) { description_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.identity.accesscontextmanager.v1.AccessLevel.description) } inline ::std::string* AccessLevel::mutable_description() { // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.AccessLevel.description) return description_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* AccessLevel::release_description() { // @@protoc_insertion_point(field_release:google.identity.accesscontextmanager.v1.AccessLevel.description) return description_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void AccessLevel::set_allocated_description(::std::string* description) { if (description != nullptr) { } else { } description_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), description); // @@protoc_insertion_point(field_set_allocated:google.identity.accesscontextmanager.v1.AccessLevel.description) } // .google.identity.accesscontextmanager.v1.BasicLevel basic = 4; inline bool AccessLevel::has_basic() const { return level_case() == kBasic; } inline void AccessLevel::set_has_basic() { _oneof_case_[0] = kBasic; } inline void AccessLevel::clear_basic() { if (has_basic()) { delete level_.basic_; clear_has_level(); } } inline ::google::identity::accesscontextmanager::v1::BasicLevel* AccessLevel::release_basic() { // @@protoc_insertion_point(field_release:google.identity.accesscontextmanager.v1.AccessLevel.basic) if (has_basic()) { clear_has_level(); ::google::identity::accesscontextmanager::v1::BasicLevel* temp = level_.basic_; level_.basic_ = nullptr; return temp; } else { return nullptr; } } inline const ::google::identity::accesscontextmanager::v1::BasicLevel& AccessLevel::basic() const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.AccessLevel.basic) return has_basic() ? *level_.basic_ : *reinterpret_cast< ::google::identity::accesscontextmanager::v1::BasicLevel*>(&::google::identity::accesscontextmanager::v1::_BasicLevel_default_instance_); } inline ::google::identity::accesscontextmanager::v1::BasicLevel* AccessLevel::mutable_basic() { if (!has_basic()) { clear_level(); set_has_basic(); level_.basic_ = CreateMaybeMessage< ::google::identity::accesscontextmanager::v1::BasicLevel >( GetArenaNoVirtual()); } // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.AccessLevel.basic) return level_.basic_; } // .google.identity.accesscontextmanager.v1.CustomLevel custom = 5; inline bool AccessLevel::has_custom() const { return level_case() == kCustom; } inline void AccessLevel::set_has_custom() { _oneof_case_[0] = kCustom; } inline void AccessLevel::clear_custom() { if (has_custom()) { delete level_.custom_; clear_has_level(); } } inline ::google::identity::accesscontextmanager::v1::CustomLevel* AccessLevel::release_custom() { // @@protoc_insertion_point(field_release:google.identity.accesscontextmanager.v1.AccessLevel.custom) if (has_custom()) { clear_has_level(); ::google::identity::accesscontextmanager::v1::CustomLevel* temp = level_.custom_; level_.custom_ = nullptr; return temp; } else { return nullptr; } } inline const ::google::identity::accesscontextmanager::v1::CustomLevel& AccessLevel::custom() const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.AccessLevel.custom) return has_custom() ? *level_.custom_ : *reinterpret_cast< ::google::identity::accesscontextmanager::v1::CustomLevel*>(&::google::identity::accesscontextmanager::v1::_CustomLevel_default_instance_); } inline ::google::identity::accesscontextmanager::v1::CustomLevel* AccessLevel::mutable_custom() { if (!has_custom()) { clear_level(); set_has_custom(); level_.custom_ = CreateMaybeMessage< ::google::identity::accesscontextmanager::v1::CustomLevel >( GetArenaNoVirtual()); } // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.AccessLevel.custom) return level_.custom_; } // .google.protobuf.Timestamp create_time = 6; inline bool AccessLevel::has_create_time() const { return this != internal_default_instance() && create_time_ != nullptr; } inline const ::google::protobuf::Timestamp& AccessLevel::create_time() const { const ::google::protobuf::Timestamp* p = create_time_; // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.AccessLevel.create_time) return p != nullptr ? *p : *reinterpret_cast<const ::google::protobuf::Timestamp*>( &::google::protobuf::_Timestamp_default_instance_); } inline ::google::protobuf::Timestamp* AccessLevel::release_create_time() { // @@protoc_insertion_point(field_release:google.identity.accesscontextmanager.v1.AccessLevel.create_time) ::google::protobuf::Timestamp* temp = create_time_; create_time_ = nullptr; return temp; } inline ::google::protobuf::Timestamp* AccessLevel::mutable_create_time() { if (create_time_ == nullptr) { auto* p = CreateMaybeMessage<::google::protobuf::Timestamp>(GetArenaNoVirtual()); create_time_ = p; } // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.AccessLevel.create_time) return create_time_; } inline void AccessLevel::set_allocated_create_time(::google::protobuf::Timestamp* create_time) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete reinterpret_cast< ::google::protobuf::MessageLite*>(create_time_); } if (create_time) { ::google::protobuf::Arena* submessage_arena = reinterpret_cast<::google::protobuf::MessageLite*>(create_time)->GetArena(); if (message_arena != submessage_arena) { create_time = ::google::protobuf::internal::GetOwnedMessage( message_arena, create_time, submessage_arena); } } else { } create_time_ = create_time; // @@protoc_insertion_point(field_set_allocated:google.identity.accesscontextmanager.v1.AccessLevel.create_time) } // .google.protobuf.Timestamp update_time = 7; inline bool AccessLevel::has_update_time() const { return this != internal_default_instance() && update_time_ != nullptr; } inline const ::google::protobuf::Timestamp& AccessLevel::update_time() const { const ::google::protobuf::Timestamp* p = update_time_; // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.AccessLevel.update_time) return p != nullptr ? *p : *reinterpret_cast<const ::google::protobuf::Timestamp*>( &::google::protobuf::_Timestamp_default_instance_); } inline ::google::protobuf::Timestamp* AccessLevel::release_update_time() { // @@protoc_insertion_point(field_release:google.identity.accesscontextmanager.v1.AccessLevel.update_time) ::google::protobuf::Timestamp* temp = update_time_; update_time_ = nullptr; return temp; } inline ::google::protobuf::Timestamp* AccessLevel::mutable_update_time() { if (update_time_ == nullptr) { auto* p = CreateMaybeMessage<::google::protobuf::Timestamp>(GetArenaNoVirtual()); update_time_ = p; } // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.AccessLevel.update_time) return update_time_; } inline void AccessLevel::set_allocated_update_time(::google::protobuf::Timestamp* update_time) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete reinterpret_cast< ::google::protobuf::MessageLite*>(update_time_); } if (update_time) { ::google::protobuf::Arena* submessage_arena = reinterpret_cast<::google::protobuf::MessageLite*>(update_time)->GetArena(); if (message_arena != submessage_arena) { update_time = ::google::protobuf::internal::GetOwnedMessage( message_arena, update_time, submessage_arena); } } else { } update_time_ = update_time; // @@protoc_insertion_point(field_set_allocated:google.identity.accesscontextmanager.v1.AccessLevel.update_time) } inline bool AccessLevel::has_level() const { return level_case() != LEVEL_NOT_SET; } inline void AccessLevel::clear_has_level() { _oneof_case_[0] = LEVEL_NOT_SET; } inline AccessLevel::LevelCase AccessLevel::level_case() const { return AccessLevel::LevelCase(_oneof_case_[0]); } // ------------------------------------------------------------------- // BasicLevel // repeated .google.identity.accesscontextmanager.v1.Condition conditions = 1; inline int BasicLevel::conditions_size() const { return conditions_.size(); } inline void BasicLevel::clear_conditions() { conditions_.Clear(); } inline ::google::identity::accesscontextmanager::v1::Condition* BasicLevel::mutable_conditions(int index) { // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.BasicLevel.conditions) return conditions_.Mutable(index); } inline ::google::protobuf::RepeatedPtrField< ::google::identity::accesscontextmanager::v1::Condition >* BasicLevel::mutable_conditions() { // @@protoc_insertion_point(field_mutable_list:google.identity.accesscontextmanager.v1.BasicLevel.conditions) return &conditions_; } inline const ::google::identity::accesscontextmanager::v1::Condition& BasicLevel::conditions(int index) const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.BasicLevel.conditions) return conditions_.Get(index); } inline ::google::identity::accesscontextmanager::v1::Condition* BasicLevel::add_conditions() { // @@protoc_insertion_point(field_add:google.identity.accesscontextmanager.v1.BasicLevel.conditions) return conditions_.Add(); } inline const ::google::protobuf::RepeatedPtrField< ::google::identity::accesscontextmanager::v1::Condition >& BasicLevel::conditions() const { // @@protoc_insertion_point(field_list:google.identity.accesscontextmanager.v1.BasicLevel.conditions) return conditions_; } // .google.identity.accesscontextmanager.v1.BasicLevel.ConditionCombiningFunction combining_function = 2; inline void BasicLevel::clear_combining_function() { combining_function_ = 0; } inline ::google::identity::accesscontextmanager::v1::BasicLevel_ConditionCombiningFunction BasicLevel::combining_function() const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.BasicLevel.combining_function) return static_cast< ::google::identity::accesscontextmanager::v1::BasicLevel_ConditionCombiningFunction >(combining_function_); } inline void BasicLevel::set_combining_function(::google::identity::accesscontextmanager::v1::BasicLevel_ConditionCombiningFunction value) { combining_function_ = value; // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.BasicLevel.combining_function) } // ------------------------------------------------------------------- // Condition // repeated string ip_subnetworks = 1; inline int Condition::ip_subnetworks_size() const { return ip_subnetworks_.size(); } inline void Condition::clear_ip_subnetworks() { ip_subnetworks_.Clear(); } inline const ::std::string& Condition::ip_subnetworks(int index) const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.Condition.ip_subnetworks) return ip_subnetworks_.Get(index); } inline ::std::string* Condition::mutable_ip_subnetworks(int index) { // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.Condition.ip_subnetworks) return ip_subnetworks_.Mutable(index); } inline void Condition::set_ip_subnetworks(int index, const ::std::string& value) { // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.Condition.ip_subnetworks) ip_subnetworks_.Mutable(index)->assign(value); } #if LANG_CXX11 inline void Condition::set_ip_subnetworks(int index, ::std::string&& value) { // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.Condition.ip_subnetworks) ip_subnetworks_.Mutable(index)->assign(std::move(value)); } #endif inline void Condition::set_ip_subnetworks(int index, const char* value) { GOOGLE_DCHECK(value != nullptr); ip_subnetworks_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.identity.accesscontextmanager.v1.Condition.ip_subnetworks) } inline void Condition::set_ip_subnetworks(int index, const char* value, size_t size) { ip_subnetworks_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:google.identity.accesscontextmanager.v1.Condition.ip_subnetworks) } inline ::std::string* Condition::add_ip_subnetworks() { // @@protoc_insertion_point(field_add_mutable:google.identity.accesscontextmanager.v1.Condition.ip_subnetworks) return ip_subnetworks_.Add(); } inline void Condition::add_ip_subnetworks(const ::std::string& value) { ip_subnetworks_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.identity.accesscontextmanager.v1.Condition.ip_subnetworks) } #if LANG_CXX11 inline void Condition::add_ip_subnetworks(::std::string&& value) { ip_subnetworks_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.identity.accesscontextmanager.v1.Condition.ip_subnetworks) } #endif inline void Condition::add_ip_subnetworks(const char* value) { GOOGLE_DCHECK(value != nullptr); ip_subnetworks_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.identity.accesscontextmanager.v1.Condition.ip_subnetworks) } inline void Condition::add_ip_subnetworks(const char* value, size_t size) { ip_subnetworks_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:google.identity.accesscontextmanager.v1.Condition.ip_subnetworks) } inline const ::google::protobuf::RepeatedPtrField<::std::string>& Condition::ip_subnetworks() const { // @@protoc_insertion_point(field_list:google.identity.accesscontextmanager.v1.Condition.ip_subnetworks) return ip_subnetworks_; } inline ::google::protobuf::RepeatedPtrField<::std::string>* Condition::mutable_ip_subnetworks() { // @@protoc_insertion_point(field_mutable_list:google.identity.accesscontextmanager.v1.Condition.ip_subnetworks) return &ip_subnetworks_; } // .google.identity.accesscontextmanager.v1.DevicePolicy device_policy = 2; inline bool Condition::has_device_policy() const { return this != internal_default_instance() && device_policy_ != nullptr; } inline void Condition::clear_device_policy() { if (GetArenaNoVirtual() == nullptr && device_policy_ != nullptr) { delete device_policy_; } device_policy_ = nullptr; } inline const ::google::identity::accesscontextmanager::v1::DevicePolicy& Condition::device_policy() const { const ::google::identity::accesscontextmanager::v1::DevicePolicy* p = device_policy_; // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.Condition.device_policy) return p != nullptr ? *p : *reinterpret_cast<const ::google::identity::accesscontextmanager::v1::DevicePolicy*>( &::google::identity::accesscontextmanager::v1::_DevicePolicy_default_instance_); } inline ::google::identity::accesscontextmanager::v1::DevicePolicy* Condition::release_device_policy() { // @@protoc_insertion_point(field_release:google.identity.accesscontextmanager.v1.Condition.device_policy) ::google::identity::accesscontextmanager::v1::DevicePolicy* temp = device_policy_; device_policy_ = nullptr; return temp; } inline ::google::identity::accesscontextmanager::v1::DevicePolicy* Condition::mutable_device_policy() { if (device_policy_ == nullptr) { auto* p = CreateMaybeMessage<::google::identity::accesscontextmanager::v1::DevicePolicy>(GetArenaNoVirtual()); device_policy_ = p; } // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.Condition.device_policy) return device_policy_; } inline void Condition::set_allocated_device_policy(::google::identity::accesscontextmanager::v1::DevicePolicy* device_policy) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete device_policy_; } if (device_policy) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { device_policy = ::google::protobuf::internal::GetOwnedMessage( message_arena, device_policy, submessage_arena); } } else { } device_policy_ = device_policy; // @@protoc_insertion_point(field_set_allocated:google.identity.accesscontextmanager.v1.Condition.device_policy) } // repeated string required_access_levels = 3; inline int Condition::required_access_levels_size() const { return required_access_levels_.size(); } inline void Condition::clear_required_access_levels() { required_access_levels_.Clear(); } inline const ::std::string& Condition::required_access_levels(int index) const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.Condition.required_access_levels) return required_access_levels_.Get(index); } inline ::std::string* Condition::mutable_required_access_levels(int index) { // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.Condition.required_access_levels) return required_access_levels_.Mutable(index); } inline void Condition::set_required_access_levels(int index, const ::std::string& value) { // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.Condition.required_access_levels) required_access_levels_.Mutable(index)->assign(value); } #if LANG_CXX11 inline void Condition::set_required_access_levels(int index, ::std::string&& value) { // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.Condition.required_access_levels) required_access_levels_.Mutable(index)->assign(std::move(value)); } #endif inline void Condition::set_required_access_levels(int index, const char* value) { GOOGLE_DCHECK(value != nullptr); required_access_levels_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.identity.accesscontextmanager.v1.Condition.required_access_levels) } inline void Condition::set_required_access_levels(int index, const char* value, size_t size) { required_access_levels_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:google.identity.accesscontextmanager.v1.Condition.required_access_levels) } inline ::std::string* Condition::add_required_access_levels() { // @@protoc_insertion_point(field_add_mutable:google.identity.accesscontextmanager.v1.Condition.required_access_levels) return required_access_levels_.Add(); } inline void Condition::add_required_access_levels(const ::std::string& value) { required_access_levels_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.identity.accesscontextmanager.v1.Condition.required_access_levels) } #if LANG_CXX11 inline void Condition::add_required_access_levels(::std::string&& value) { required_access_levels_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.identity.accesscontextmanager.v1.Condition.required_access_levels) } #endif inline void Condition::add_required_access_levels(const char* value) { GOOGLE_DCHECK(value != nullptr); required_access_levels_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.identity.accesscontextmanager.v1.Condition.required_access_levels) } inline void Condition::add_required_access_levels(const char* value, size_t size) { required_access_levels_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:google.identity.accesscontextmanager.v1.Condition.required_access_levels) } inline const ::google::protobuf::RepeatedPtrField<::std::string>& Condition::required_access_levels() const { // @@protoc_insertion_point(field_list:google.identity.accesscontextmanager.v1.Condition.required_access_levels) return required_access_levels_; } inline ::google::protobuf::RepeatedPtrField<::std::string>* Condition::mutable_required_access_levels() { // @@protoc_insertion_point(field_mutable_list:google.identity.accesscontextmanager.v1.Condition.required_access_levels) return &required_access_levels_; } // bool negate = 5; inline void Condition::clear_negate() { negate_ = false; } inline bool Condition::negate() const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.Condition.negate) return negate_; } inline void Condition::set_negate(bool value) { negate_ = value; // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.Condition.negate) } // repeated string members = 6; inline int Condition::members_size() const { return members_.size(); } inline void Condition::clear_members() { members_.Clear(); } inline const ::std::string& Condition::members(int index) const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.Condition.members) return members_.Get(index); } inline ::std::string* Condition::mutable_members(int index) { // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.Condition.members) return members_.Mutable(index); } inline void Condition::set_members(int index, const ::std::string& value) { // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.Condition.members) members_.Mutable(index)->assign(value); } #if LANG_CXX11 inline void Condition::set_members(int index, ::std::string&& value) { // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.Condition.members) members_.Mutable(index)->assign(std::move(value)); } #endif inline void Condition::set_members(int index, const char* value) { GOOGLE_DCHECK(value != nullptr); members_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.identity.accesscontextmanager.v1.Condition.members) } inline void Condition::set_members(int index, const char* value, size_t size) { members_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:google.identity.accesscontextmanager.v1.Condition.members) } inline ::std::string* Condition::add_members() { // @@protoc_insertion_point(field_add_mutable:google.identity.accesscontextmanager.v1.Condition.members) return members_.Add(); } inline void Condition::add_members(const ::std::string& value) { members_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.identity.accesscontextmanager.v1.Condition.members) } #if LANG_CXX11 inline void Condition::add_members(::std::string&& value) { members_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.identity.accesscontextmanager.v1.Condition.members) } #endif inline void Condition::add_members(const char* value) { GOOGLE_DCHECK(value != nullptr); members_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.identity.accesscontextmanager.v1.Condition.members) } inline void Condition::add_members(const char* value, size_t size) { members_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:google.identity.accesscontextmanager.v1.Condition.members) } inline const ::google::protobuf::RepeatedPtrField<::std::string>& Condition::members() const { // @@protoc_insertion_point(field_list:google.identity.accesscontextmanager.v1.Condition.members) return members_; } inline ::google::protobuf::RepeatedPtrField<::std::string>* Condition::mutable_members() { // @@protoc_insertion_point(field_mutable_list:google.identity.accesscontextmanager.v1.Condition.members) return &members_; } // repeated string regions = 7; inline int Condition::regions_size() const { return regions_.size(); } inline void Condition::clear_regions() { regions_.Clear(); } inline const ::std::string& Condition::regions(int index) const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.Condition.regions) return regions_.Get(index); } inline ::std::string* Condition::mutable_regions(int index) { // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.Condition.regions) return regions_.Mutable(index); } inline void Condition::set_regions(int index, const ::std::string& value) { // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.Condition.regions) regions_.Mutable(index)->assign(value); } #if LANG_CXX11 inline void Condition::set_regions(int index, ::std::string&& value) { // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.Condition.regions) regions_.Mutable(index)->assign(std::move(value)); } #endif inline void Condition::set_regions(int index, const char* value) { GOOGLE_DCHECK(value != nullptr); regions_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.identity.accesscontextmanager.v1.Condition.regions) } inline void Condition::set_regions(int index, const char* value, size_t size) { regions_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:google.identity.accesscontextmanager.v1.Condition.regions) } inline ::std::string* Condition::add_regions() { // @@protoc_insertion_point(field_add_mutable:google.identity.accesscontextmanager.v1.Condition.regions) return regions_.Add(); } inline void Condition::add_regions(const ::std::string& value) { regions_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.identity.accesscontextmanager.v1.Condition.regions) } #if LANG_CXX11 inline void Condition::add_regions(::std::string&& value) { regions_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.identity.accesscontextmanager.v1.Condition.regions) } #endif inline void Condition::add_regions(const char* value) { GOOGLE_DCHECK(value != nullptr); regions_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.identity.accesscontextmanager.v1.Condition.regions) } inline void Condition::add_regions(const char* value, size_t size) { regions_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:google.identity.accesscontextmanager.v1.Condition.regions) } inline const ::google::protobuf::RepeatedPtrField<::std::string>& Condition::regions() const { // @@protoc_insertion_point(field_list:google.identity.accesscontextmanager.v1.Condition.regions) return regions_; } inline ::google::protobuf::RepeatedPtrField<::std::string>* Condition::mutable_regions() { // @@protoc_insertion_point(field_mutable_list:google.identity.accesscontextmanager.v1.Condition.regions) return &regions_; } // ------------------------------------------------------------------- // CustomLevel // .google.type.Expr expr = 1; inline bool CustomLevel::has_expr() const { return this != internal_default_instance() && expr_ != nullptr; } inline const ::google::type::Expr& CustomLevel::expr() const { const ::google::type::Expr* p = expr_; // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.CustomLevel.expr) return p != nullptr ? *p : *reinterpret_cast<const ::google::type::Expr*>( &::google::type::_Expr_default_instance_); } inline ::google::type::Expr* CustomLevel::release_expr() { // @@protoc_insertion_point(field_release:google.identity.accesscontextmanager.v1.CustomLevel.expr) ::google::type::Expr* temp = expr_; expr_ = nullptr; return temp; } inline ::google::type::Expr* CustomLevel::mutable_expr() { if (expr_ == nullptr) { auto* p = CreateMaybeMessage<::google::type::Expr>(GetArenaNoVirtual()); expr_ = p; } // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.CustomLevel.expr) return expr_; } inline void CustomLevel::set_allocated_expr(::google::type::Expr* expr) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete reinterpret_cast< ::google::protobuf::MessageLite*>(expr_); } if (expr) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { expr = ::google::protobuf::internal::GetOwnedMessage( message_arena, expr, submessage_arena); } } else { } expr_ = expr; // @@protoc_insertion_point(field_set_allocated:google.identity.accesscontextmanager.v1.CustomLevel.expr) } // ------------------------------------------------------------------- // DevicePolicy // bool require_screenlock = 1; inline void DevicePolicy::clear_require_screenlock() { require_screenlock_ = false; } inline bool DevicePolicy::require_screenlock() const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.DevicePolicy.require_screenlock) return require_screenlock_; } inline void DevicePolicy::set_require_screenlock(bool value) { require_screenlock_ = value; // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.DevicePolicy.require_screenlock) } // repeated .google.identity.accesscontextmanager.type.DeviceEncryptionStatus allowed_encryption_statuses = 2; inline int DevicePolicy::allowed_encryption_statuses_size() const { return allowed_encryption_statuses_.size(); } inline void DevicePolicy::clear_allowed_encryption_statuses() { allowed_encryption_statuses_.Clear(); } inline ::google::identity::accesscontextmanager::type::DeviceEncryptionStatus DevicePolicy::allowed_encryption_statuses(int index) const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.DevicePolicy.allowed_encryption_statuses) return static_cast< ::google::identity::accesscontextmanager::type::DeviceEncryptionStatus >(allowed_encryption_statuses_.Get(index)); } inline void DevicePolicy::set_allowed_encryption_statuses(int index, ::google::identity::accesscontextmanager::type::DeviceEncryptionStatus value) { allowed_encryption_statuses_.Set(index, value); // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.DevicePolicy.allowed_encryption_statuses) } inline void DevicePolicy::add_allowed_encryption_statuses(::google::identity::accesscontextmanager::type::DeviceEncryptionStatus value) { allowed_encryption_statuses_.Add(value); // @@protoc_insertion_point(field_add:google.identity.accesscontextmanager.v1.DevicePolicy.allowed_encryption_statuses) } inline const ::google::protobuf::RepeatedField<int>& DevicePolicy::allowed_encryption_statuses() const { // @@protoc_insertion_point(field_list:google.identity.accesscontextmanager.v1.DevicePolicy.allowed_encryption_statuses) return allowed_encryption_statuses_; } inline ::google::protobuf::RepeatedField<int>* DevicePolicy::mutable_allowed_encryption_statuses() { // @@protoc_insertion_point(field_mutable_list:google.identity.accesscontextmanager.v1.DevicePolicy.allowed_encryption_statuses) return &allowed_encryption_statuses_; } // repeated .google.identity.accesscontextmanager.v1.OsConstraint os_constraints = 3; inline int DevicePolicy::os_constraints_size() const { return os_constraints_.size(); } inline void DevicePolicy::clear_os_constraints() { os_constraints_.Clear(); } inline ::google::identity::accesscontextmanager::v1::OsConstraint* DevicePolicy::mutable_os_constraints(int index) { // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.DevicePolicy.os_constraints) return os_constraints_.Mutable(index); } inline ::google::protobuf::RepeatedPtrField< ::google::identity::accesscontextmanager::v1::OsConstraint >* DevicePolicy::mutable_os_constraints() { // @@protoc_insertion_point(field_mutable_list:google.identity.accesscontextmanager.v1.DevicePolicy.os_constraints) return &os_constraints_; } inline const ::google::identity::accesscontextmanager::v1::OsConstraint& DevicePolicy::os_constraints(int index) const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.DevicePolicy.os_constraints) return os_constraints_.Get(index); } inline ::google::identity::accesscontextmanager::v1::OsConstraint* DevicePolicy::add_os_constraints() { // @@protoc_insertion_point(field_add:google.identity.accesscontextmanager.v1.DevicePolicy.os_constraints) return os_constraints_.Add(); } inline const ::google::protobuf::RepeatedPtrField< ::google::identity::accesscontextmanager::v1::OsConstraint >& DevicePolicy::os_constraints() const { // @@protoc_insertion_point(field_list:google.identity.accesscontextmanager.v1.DevicePolicy.os_constraints) return os_constraints_; } // repeated .google.identity.accesscontextmanager.type.DeviceManagementLevel allowed_device_management_levels = 6; inline int DevicePolicy::allowed_device_management_levels_size() const { return allowed_device_management_levels_.size(); } inline void DevicePolicy::clear_allowed_device_management_levels() { allowed_device_management_levels_.Clear(); } inline ::google::identity::accesscontextmanager::type::DeviceManagementLevel DevicePolicy::allowed_device_management_levels(int index) const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.DevicePolicy.allowed_device_management_levels) return static_cast< ::google::identity::accesscontextmanager::type::DeviceManagementLevel >(allowed_device_management_levels_.Get(index)); } inline void DevicePolicy::set_allowed_device_management_levels(int index, ::google::identity::accesscontextmanager::type::DeviceManagementLevel value) { allowed_device_management_levels_.Set(index, value); // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.DevicePolicy.allowed_device_management_levels) } inline void DevicePolicy::add_allowed_device_management_levels(::google::identity::accesscontextmanager::type::DeviceManagementLevel value) { allowed_device_management_levels_.Add(value); // @@protoc_insertion_point(field_add:google.identity.accesscontextmanager.v1.DevicePolicy.allowed_device_management_levels) } inline const ::google::protobuf::RepeatedField<int>& DevicePolicy::allowed_device_management_levels() const { // @@protoc_insertion_point(field_list:google.identity.accesscontextmanager.v1.DevicePolicy.allowed_device_management_levels) return allowed_device_management_levels_; } inline ::google::protobuf::RepeatedField<int>* DevicePolicy::mutable_allowed_device_management_levels() { // @@protoc_insertion_point(field_mutable_list:google.identity.accesscontextmanager.v1.DevicePolicy.allowed_device_management_levels) return &allowed_device_management_levels_; } // bool require_admin_approval = 7; inline void DevicePolicy::clear_require_admin_approval() { require_admin_approval_ = false; } inline bool DevicePolicy::require_admin_approval() const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.DevicePolicy.require_admin_approval) return require_admin_approval_; } inline void DevicePolicy::set_require_admin_approval(bool value) { require_admin_approval_ = value; // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.DevicePolicy.require_admin_approval) } // bool require_corp_owned = 8; inline void DevicePolicy::clear_require_corp_owned() { require_corp_owned_ = false; } inline bool DevicePolicy::require_corp_owned() const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.DevicePolicy.require_corp_owned) return require_corp_owned_; } inline void DevicePolicy::set_require_corp_owned(bool value) { require_corp_owned_ = value; // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.DevicePolicy.require_corp_owned) } // ------------------------------------------------------------------- // OsConstraint // .google.identity.accesscontextmanager.type.OsType os_type = 1; inline void OsConstraint::clear_os_type() { os_type_ = 0; } inline ::google::identity::accesscontextmanager::type::OsType OsConstraint::os_type() const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.OsConstraint.os_type) return static_cast< ::google::identity::accesscontextmanager::type::OsType >(os_type_); } inline void OsConstraint::set_os_type(::google::identity::accesscontextmanager::type::OsType value) { os_type_ = value; // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.OsConstraint.os_type) } // string minimum_version = 2; inline void OsConstraint::clear_minimum_version() { minimum_version_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& OsConstraint::minimum_version() const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.OsConstraint.minimum_version) return minimum_version_.GetNoArena(); } inline void OsConstraint::set_minimum_version(const ::std::string& value) { minimum_version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.OsConstraint.minimum_version) } #if LANG_CXX11 inline void OsConstraint::set_minimum_version(::std::string&& value) { minimum_version_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.identity.accesscontextmanager.v1.OsConstraint.minimum_version) } #endif inline void OsConstraint::set_minimum_version(const char* value) { GOOGLE_DCHECK(value != nullptr); minimum_version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.identity.accesscontextmanager.v1.OsConstraint.minimum_version) } inline void OsConstraint::set_minimum_version(const char* value, size_t size) { minimum_version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.identity.accesscontextmanager.v1.OsConstraint.minimum_version) } inline ::std::string* OsConstraint::mutable_minimum_version() { // @@protoc_insertion_point(field_mutable:google.identity.accesscontextmanager.v1.OsConstraint.minimum_version) return minimum_version_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* OsConstraint::release_minimum_version() { // @@protoc_insertion_point(field_release:google.identity.accesscontextmanager.v1.OsConstraint.minimum_version) return minimum_version_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void OsConstraint::set_allocated_minimum_version(::std::string* minimum_version) { if (minimum_version != nullptr) { } else { } minimum_version_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), minimum_version); // @@protoc_insertion_point(field_set_allocated:google.identity.accesscontextmanager.v1.OsConstraint.minimum_version) } // bool require_verified_chrome_os = 3; inline void OsConstraint::clear_require_verified_chrome_os() { require_verified_chrome_os_ = false; } inline bool OsConstraint::require_verified_chrome_os() const { // @@protoc_insertion_point(field_get:google.identity.accesscontextmanager.v1.OsConstraint.require_verified_chrome_os) return require_verified_chrome_os_; } inline void OsConstraint::set_require_verified_chrome_os(bool value) { require_verified_chrome_os_ = value; // @@protoc_insertion_point(field_set:google.identity.accesscontextmanager.v1.OsConstraint.require_verified_chrome_os) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace v1 } // namespace accesscontextmanager } // namespace identity } // namespace google namespace google { namespace protobuf { template <> struct is_proto_enum< ::google::identity::accesscontextmanager::v1::BasicLevel_ConditionCombiningFunction> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::identity::accesscontextmanager::v1::BasicLevel_ConditionCombiningFunction>() { return ::google::identity::accesscontextmanager::v1::BasicLevel_ConditionCombiningFunction_descriptor(); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // PROTOBUF_INCLUDED_google_2fidentity_2faccesscontextmanager_2fv1_2faccess_5flevel_2eproto
djsegal/julia_packages
test/models/user_test.rb
<filename>test/models/user_test.rb # == Schema Information # # Table name: users # # id :bigint not null, primary key # name :string # packages_count :integer # slug :string # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_users_on_packages_count (packages_count) # index_users_on_slug (slug) UNIQUE # require 'test_helper' class UserTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
nckblu/muchnews
src/selectors/articleSources/index.js
<gh_stars>1-10 import articleSources from "./articleSources"; export default articleSources;
UKGovernmentBEIS/beis-psd
db/migrate/20210210122430_migrate_corrective_action_added_audit_record.rb
class MigrateCorrectiveActionAddedAuditRecord < ActiveRecord::Migration[6.1] def change safety_assured do reversible do |dir| dir.up { migrate_legacy_audit_record } end end end private def migrate_legacy_audit_record unmigrated_audits = [] AuditActivity::CorrectiveAction::Add.where(metadata: nil).find_each do |audit_activity| audit_activity.update!(metadata: AuditActivity::CorrectiveAction::Add.metadata_from_legacy_audit_activity(audit_activity)) rescue StandardError => e Rails.logger.error(e) unmigrated_audits << audit_activity.id end Rails.logger.info("Audit not migrated:") Rails.logger.info(unmigrated_audits.join(", ")) end end
tranch/assistant
internal/app/workflow/rpcclient/message.go
package rpcclient import ( "github.com/pkg/errors" "github.com/tsundata/assistant/api/pb" "github.com/tsundata/assistant/internal/pkg/app" "github.com/tsundata/assistant/internal/pkg/transport/rpc" "time" ) func NewMessageClient(client *rpc.Client) (pb.MessageClient, error) { conn, err := client.Dial(app.Message, rpc.WithTimeout(time.Second)) if err != nil { return nil, errors.Wrap(err, "message client dial error") } c := pb.NewMessageClient(conn) return c, nil }
globant-scalable-platforms/bootcamp-java-spring-may-2019
Week2/SantiagoMedina/game/src/main/java/com/bootcamp/springboot/game/configuration/BeansConfiguration.java
package com.bootcamp.springboot.game.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import com.bootcamp.springboot.game.domain.Score; @Configuration public class BeansConfiguration { @Bean @Scope("singleton") public Score scoreSingleton() { return new Score(0,0, "I'm the total score (Singleton)"); } @Bean @Scope("prototype") public Score scorePrototype() { return new Score(0,0, "I'm a prototype bean and I'm the partial score for differents battles"); } }
vazra/envoy
source/common/grpc/common.cc
#include "common/grpc/common.h" #include <atomic> #include <cstdint> #include <cstring> #include <string> #include "common/buffer/buffer_impl.h" #include "common/buffer/zero_copy_input_stream_impl.h" #include "common/common/assert.h" #include "common/common/base64.h" #include "common/common/empty_string.h" #include "common/common/enum_to_int.h" #include "common/common/fmt.h" #include "common/common/macros.h" #include "common/common/safe_memcpy.h" #include "common/common/utility.h" #include "common/http/header_utility.h" #include "common/http/headers.h" #include "common/http/message_impl.h" #include "common/http/utility.h" #include "common/protobuf/protobuf.h" #include "absl/container/fixed_array.h" #include "absl/strings/match.h" namespace Envoy { namespace Grpc { bool Common::hasGrpcContentType(const Http::RequestOrResponseHeaderMap& headers) { const absl::string_view content_type = headers.getContentTypeValue(); // Content type is gRPC if it is exactly "application/grpc" or starts with // "application/grpc+". Specifically, something like application/grpc-web is not gRPC. return absl::StartsWith(content_type, Http::Headers::get().ContentTypeValues.Grpc) && (content_type.size() == Http::Headers::get().ContentTypeValues.Grpc.size() || content_type[Http::Headers::get().ContentTypeValues.Grpc.size()] == '+'); } bool Common::isGrpcRequestHeaders(const Http::RequestHeaderMap& headers) { if (!headers.Path()) { return false; } return hasGrpcContentType(headers); } bool Common::isGrpcResponseHeaders(const Http::ResponseHeaderMap& headers, bool end_stream) { if (end_stream) { // Trailers-only response, only grpc-status is required. return headers.GrpcStatus() != nullptr; } if (Http::Utility::getResponseStatus(headers) != enumToInt(Http::Code::OK)) { return false; } return hasGrpcContentType(headers); } absl::optional<Status::GrpcStatus> Common::getGrpcStatus(const Http::ResponseHeaderOrTrailerMap& trailers, bool allow_user_defined) { const absl::string_view grpc_status_header = trailers.getGrpcStatusValue(); uint64_t grpc_status_code; if (grpc_status_header.empty()) { return absl::nullopt; } if (!absl::SimpleAtoi(grpc_status_header, &grpc_status_code) || (grpc_status_code > Status::WellKnownGrpcStatus::MaximumKnown && !allow_user_defined)) { return {Status::WellKnownGrpcStatus::InvalidCode}; } return {static_cast<Status::GrpcStatus>(grpc_status_code)}; } absl::optional<Status::GrpcStatus> Common::getGrpcStatus(const Http::ResponseTrailerMap& trailers, const Http::ResponseHeaderMap& headers, const StreamInfo::StreamInfo& info, bool allow_user_defined) { // The gRPC specification does not guarantee a gRPC status code will be returned from a gRPC // request. When it is returned, it will be in the response trailers. With that said, Envoy will // treat a trailers-only response as a headers-only response, so we have to check the following // in order: // 1. trailers gRPC status, if it exists. // 2. headers gRPC status, if it exists. // 3. Inferred from info HTTP status, if it exists. const std::array<absl::optional<Grpc::Status::GrpcStatus>, 3> optional_statuses = {{ {Grpc::Common::getGrpcStatus(trailers, allow_user_defined)}, {Grpc::Common::getGrpcStatus(headers, allow_user_defined)}, {info.responseCode() ? absl::optional<Grpc::Status::GrpcStatus>( Grpc::Utility::httpToGrpcStatus(info.responseCode().value())) : absl::nullopt}, }}; for (const auto& optional_status : optional_statuses) { if (optional_status.has_value()) { return optional_status; } } return absl::nullopt; } std::string Common::getGrpcMessage(const Http::ResponseHeaderOrTrailerMap& trailers) { const auto entry = trailers.GrpcMessage(); return entry ? std::string(entry->value().getStringView()) : EMPTY_STRING; } absl::optional<google::rpc::Status> Common::getGrpcStatusDetailsBin(const Http::HeaderMap& trailers) { const auto details_header = trailers.get(Http::Headers::get().GrpcStatusDetailsBin); if (details_header.empty()) { return absl::nullopt; } // Some implementations use non-padded base64 encoding for grpc-status-details-bin. // This is effectively a trusted header so using the first value is fine. auto decoded_value = Base64::decodeWithoutPadding(details_header[0]->value().getStringView()); if (decoded_value.empty()) { return absl::nullopt; } google::rpc::Status status; if (!status.ParseFromString(decoded_value)) { return absl::nullopt; } return {std::move(status)}; } Buffer::InstancePtr Common::serializeToGrpcFrame(const Protobuf::Message& message) { // http://www.grpc.io/docs/guides/wire.html // Reserve enough space for the entire message and the 5 byte header. // NB: we do not use prependGrpcFrameHeader because that would add another BufferFragment and this // (using a single BufferFragment) is more efficient. Buffer::InstancePtr body(new Buffer::OwnedImpl()); const uint32_t size = message.ByteSize(); const uint32_t alloc_size = size + 5; auto reservation = body->reserveSingleSlice(alloc_size); ASSERT(reservation.slice().len_ >= alloc_size); uint8_t* current = reinterpret_cast<uint8_t*>(reservation.slice().mem_); *current++ = 0; // flags const uint32_t nsize = htonl(size); safeMemcpyUnsafeDst(current, &nsize); current += sizeof(uint32_t); Protobuf::io::ArrayOutputStream stream(current, size, -1); Protobuf::io::CodedOutputStream codec_stream(&stream); message.SerializeWithCachedSizes(&codec_stream); reservation.commit(alloc_size); return body; } Buffer::InstancePtr Common::serializeMessage(const Protobuf::Message& message) { auto body = std::make_unique<Buffer::OwnedImpl>(); const uint32_t size = message.ByteSize(); auto reservation = body->reserveSingleSlice(size); ASSERT(reservation.slice().len_ >= size); uint8_t* current = reinterpret_cast<uint8_t*>(reservation.slice().mem_); Protobuf::io::ArrayOutputStream stream(current, size, -1); Protobuf::io::CodedOutputStream codec_stream(&stream); message.SerializeWithCachedSizes(&codec_stream); reservation.commit(size); return body; } absl::optional<std::chrono::milliseconds> Common::getGrpcTimeout(const Http::RequestHeaderMap& request_headers) { const Http::HeaderEntry* header_grpc_timeout_entry = request_headers.GrpcTimeout(); std::chrono::milliseconds timeout; if (header_grpc_timeout_entry) { uint64_t grpc_timeout; // TODO(dnoe): Migrate to pure string_view (#6580) std::string grpc_timeout_string(header_grpc_timeout_entry->value().getStringView()); const char* unit = StringUtil::strtoull(grpc_timeout_string.c_str(), grpc_timeout); if (unit != nullptr && *unit != '\0') { switch (*unit) { case 'H': return std::chrono::hours(grpc_timeout); case 'M': return std::chrono::minutes(grpc_timeout); case 'S': return std::chrono::seconds(grpc_timeout); case 'm': return std::chrono::milliseconds(grpc_timeout); break; case 'u': timeout = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::microseconds(grpc_timeout)); if (timeout < std::chrono::microseconds(grpc_timeout)) { timeout++; } return timeout; case 'n': timeout = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::nanoseconds(grpc_timeout)); if (timeout < std::chrono::nanoseconds(grpc_timeout)) { timeout++; } return timeout; } } } return absl::nullopt; } void Common::toGrpcTimeout(const std::chrono::milliseconds& timeout, Http::RequestHeaderMap& headers) { uint64_t time = timeout.count(); static const char units[] = "mSMH"; const char* unit = units; // start with milliseconds static constexpr size_t MAX_GRPC_TIMEOUT_VALUE = 99999999; if (time > MAX_GRPC_TIMEOUT_VALUE) { time /= 1000; // Convert from milliseconds to seconds unit++; } while (time > MAX_GRPC_TIMEOUT_VALUE) { if (*unit == 'H') { time = MAX_GRPC_TIMEOUT_VALUE; // No bigger unit available, clip to max 8 digit hours. } else { time /= 60; // Convert from seconds to minutes to hours unit++; } } headers.setGrpcTimeout(absl::StrCat(time, absl::string_view(unit, 1))); } Http::RequestMessagePtr Common::prepareHeaders(const std::string& host_name, const std::string& service_full_name, const std::string& method_name, const absl::optional<std::chrono::milliseconds>& timeout) { Http::RequestMessagePtr message(new Http::RequestMessageImpl()); message->headers().setReferenceMethod(Http::Headers::get().MethodValues.Post); message->headers().setPath(absl::StrCat("/", service_full_name, "/", method_name)); message->headers().setHost(host_name); // According to https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md TE should appear // before Timeout and ContentType. message->headers().setReferenceTE(Http::Headers::get().TEValues.Trailers); if (timeout) { toGrpcTimeout(timeout.value(), message->headers()); } message->headers().setReferenceContentType(Http::Headers::get().ContentTypeValues.Grpc); return message; } void Common::checkForHeaderOnlyError(Http::ResponseMessage& http_response) { // First check for grpc-status in headers. If it is here, we have an error. absl::optional<Status::GrpcStatus> grpc_status_code = Common::getGrpcStatus(http_response.headers()); if (!grpc_status_code) { return; } if (grpc_status_code.value() == Status::WellKnownGrpcStatus::InvalidCode) { throw Exception(absl::optional<uint64_t>(), "bad grpc-status header"); } throw Exception(grpc_status_code.value(), Common::getGrpcMessage(http_response.headers())); } void Common::validateResponse(Http::ResponseMessage& http_response) { if (Http::Utility::getResponseStatus(http_response.headers()) != enumToInt(Http::Code::OK)) { throw Exception(absl::optional<uint64_t>(), "non-200 response code"); } checkForHeaderOnlyError(http_response); // Check for existence of trailers. if (!http_response.trailers()) { throw Exception(absl::optional<uint64_t>(), "no response trailers"); } absl::optional<Status::GrpcStatus> grpc_status_code = Common::getGrpcStatus(*http_response.trailers()); if (!grpc_status_code || grpc_status_code.value() < 0) { throw Exception(absl::optional<uint64_t>(), "bad grpc-status trailer"); } if (grpc_status_code.value() != 0) { throw Exception(grpc_status_code.value(), Common::getGrpcMessage(*http_response.trailers())); } } const std::string& Common::typeUrlPrefix() { CONSTRUCT_ON_FIRST_USE(std::string, "type.googleapis.com"); } std::string Common::typeUrl(const std::string& qualified_name) { return typeUrlPrefix() + "/" + qualified_name; } void Common::prependGrpcFrameHeader(Buffer::Instance& buffer) { std::array<char, 5> header; header[0] = 0; // flags const uint32_t nsize = htonl(buffer.length()); safeMemcpyUnsafeDst(&header[1], &nsize); buffer.prepend(absl::string_view(&header[0], 5)); } bool Common::parseBufferInstance(Buffer::InstancePtr&& buffer, Protobuf::Message& proto) { Buffer::ZeroCopyInputStreamImpl stream(std::move(buffer)); return proto.ParseFromZeroCopyStream(&stream); } absl::optional<Common::RequestNames> Common::resolveServiceAndMethod(const Http::HeaderEntry* path) { absl::optional<RequestNames> request_names; if (path == nullptr) { return request_names; } absl::string_view str = path->value().getStringView(); str = str.substr(0, str.find('?')); const auto parts = StringUtil::splitToken(str, "/"); if (parts.size() != 2) { return request_names; } request_names = RequestNames{parts[0], parts[1]}; return request_names; } } // namespace Grpc } // namespace Envoy
nex3/nex3-s-blog-engine
app/helpers/posts_helper.rb
<filename>app/helpers/posts_helper.rb<gh_stars>1-10 module PostsHelper def prev_link_text "&larr; #{h(@post.prev.title)}" end def next_link_text "#{h(@post.next.title)} &rarr;" end def delete_link link_to 'Delete', post_path(@post), :method => :delete, :confirm => "Really delete #{@post.title}?" end def post_content(post) absolute_anchors(find_and_preserve(post.render).gsub(/<img src=("|')\//, "<img src=\\1#{feed[:url]}"), post_path(post)) end def date_links if @prev_link || @next_link open 'div', :class => 'date_links' do open 'div', @prev_link, :class => 'prev' if @prev_link open 'div', @next_link, :class => 'next' if @next_link end end end def spam_comment_link link_to('Spam', post_comment_path(@post, @comment) + '?spam=1', :method => :delete, :confirm => 'Mark comment as spam and delete it?') end def delete_comment_link link_to 'Delete', post_comment_path(@post, @comment), :method => :delete, :confirm => 'Delete comment?' end def edit_comment_link link_to_remote('Edit', { :url => edit_post_comment_path(@post || @comment.post, @comment) + '.html', :update => "comment_#{@comment.id}_content", :method => :get }, :title => 'Edit comment') end # Feed helpers @@feed_info = { :url => "http://#{Nex3::Config['blog']['site']}/", :desc => "#{Nex3::Config['author']['name']}'s blog, all about things that interest him.", :name => Nex3::Config['author']['name'], :email => Nex3::Config['author']['email'], :ttl => 1440, } def self.feed @@feed_info end def feed @@feed_info end end
initforthe/spina-jobs
app/controllers/spina/jobs/job_roles_controller.rb
module Spina module Jobs class JobRolesController < ::Spina::ApplicationController before_action :set_page def index @job_roles = Spina::Jobs::JobRole.available.live.order(published_at: :desc).page(params[:page]) respond_to do |format| format.atom format.html { render layout: "#{current_theme.name.parameterize.underscore}/application" } end end def show @job_role = Spina::Jobs::JobRole.friendly.find params[:id] render layout: "#{current_theme.name.parameterize.underscore}/application" end def set_page @page = Spina::Page.find_or_create_by name: 'jobs' do |page| page.link_url = '/jobs' page.title = 'Jobs' page.view_template = 'show' page.deletable = false end end end end end
gbadner/infinispan
server/hotrod/src/main/java/org/infinispan/server/hotrod/counter/CounterCompareAndSetDecodeContext.java
<reponame>gbadner/infinispan package org.infinispan.server.hotrod.counter; import java.util.Optional; import org.infinispan.server.hotrod.HotRodOperation; import org.infinispan.server.hotrod.logging.Log; import org.infinispan.server.hotrod.transport.ExtendedByteBuf; import org.infinispan.util.logging.LogFactory; import io.netty.buffer.ByteBuf; /** * A decode context for {@link HotRodOperation#COUNTER_CAS} operation. * * @author <NAME> * @since 9.2 */ public class CounterCompareAndSetDecodeContext extends CounterDecodeContext { private static final Log log = LogFactory.getLog(CounterAddDecodeContext.class, Log.class); private static final boolean trace = log.isTraceEnabled(); private long expected; private long update; private DecodeState decodeState = DecodeState.DECODE_EXPECTED; public long getExpected() { return expected; } public long getUpdate() { return update; } @Override DecodeStep nextStep() { switch (decodeState) { case DECODE_UPDATE: return this::decodeUpdate; case DECODE_DONE: return null; case DECODE_EXPECTED: return this::decodeExpected; default: throw new IllegalStateException(); } } @Override boolean trace() { return trace; } @Override Log log() { return log; } private boolean decodeExpected(ByteBuf buffer) { Optional<Long> optValue = ExtendedByteBuf.readMaybeLong(buffer); optValue.ifPresent(value -> { this.expected = value; logDecoded("expected-value", value); decodeState = DecodeState.DECODE_UPDATE; }); return !optValue.isPresent(); } private boolean decodeUpdate(ByteBuf buffer) { Optional<Long> optValue = ExtendedByteBuf.readMaybeLong(buffer); optValue.ifPresent(value -> { this.update = value; logDecoded("update-value", value); decodeState = DecodeState.DECODE_DONE; }); return !optValue.isPresent(); } private enum DecodeState { DECODE_EXPECTED, DECODE_UPDATE, DECODE_DONE } }
project-kotinos/skyarch-networks___skyhopper
app/models/s3.rb
# # Copyright (c) 2013-2017 SKYARCH NETWORKS INC. # # This software is released under the MIT License. # # http://opensource.org/licenses/mit-license.php # # XXX: キャッシュをしているため、変更が生じた場合はインスタンスを作りなおさなければならない。 # もしくは、キャッシュをしている変数をクリアする。 # @website # @web_conf_opt class S3 < SimpleDelegator def initialize(infra, bucket_name) access_key_id = infra.access_key secret_access_key = infra.secret_access_key @region = infra.region @s3 = ::AWS::S3.new( access_key_id: access_key_id, secret_access_key: secret_access_key, s3_endpoint: "s3-#{@region}.amazonaws.com" ) @s3_bucket = @s3.buckets[bucket_name] __setobj__(@s3_bucket) end # 毎回APIを叩かせないためキャッシュ # TODO: websiteかどうかが変更された場合の処理 def website? if @website.nil? return @website = @s3_bucket.website? else return @website end end def web_conf_opt @web_conf_opt ||= @s3_bucket.website_configuration.options end def owner @s3_bucket.owner[:display_name] end def index_document web_conf_opt[:index_document][:suffix] if self.website? end def error_document web_conf_opt[:error_document][:key] if self.website? and web_conf_opt[:error_document] end def public_url "http://#{self.name}.s3-website-#{@region}.amazonaws.com" if self.website? end end
jaxfrank/Voxel-Based-Game-Engine-Java
Workspace/3DGameEngine/src/com/base/engine/rendering/util/RenderUtil.java
<gh_stars>1-10 package com.base.engine.rendering.util; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL32.GL_DEPTH_CLAMP; import com.base.engine.math.Vector3f; public class RenderUtil { public static void clearScreen() { //TODO: Stencil Buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } public static void setTextures(boolean enabled) { if(enabled) glEnable(GL_TEXTURE_2D); else glDisable(GL_TEXTURE_2D); } public static void unbindTextures() { glBindTexture(GL_TEXTURE_2D, 0); } public static void setClearColor(Vector3f color) { glClearColor(color.getX(), color.getY(), color.getZ(), 1.0f); } public static void initGraphics() { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glFrontFace(GL_CW); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_DEPTH_CLAMP); glEnable(GL_TEXTURE_2D); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA); } public static String getOpenGLVersion() { return glGetString(GL_VERSION); } }
martin-jordan/service-manual-publisher
app/models/user.rb
class User < ApplicationRecord include GDS::SSO::User has_many :editions, foreign_key: :author_id def self.authors User.joins(:editions).distinct end end
liongames6000/OpenModsLib
src/main/java/openmods/inventory/ItemMover.java
<reponame>liongames6000/OpenModsLib<gh_stars>10-100 package openmods.inventory; import com.google.common.collect.Lists; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.items.IItemHandler; import openmods.utils.CollectionUtils; import openmods.utils.InventoryUtils; public class ItemMover { private Set<EnumFacing> sides; private boolean randomizeSides = false; private boolean breakAfterFirstTry = false; private int maxSize = 64; private final World world; private final BlockPos pos; public ItemMover(World world, BlockPos pos) { this.world = world; this.pos = pos; } public ItemMover setSides(Set<EnumFacing> sides) { this.sides = sides; return this; } public ItemMover randomizeSides() { this.randomizeSides = true; return this; } public ItemMover breakAfterFirstTry() { this.breakAfterFirstTry = true; return this; } public ItemMover setMaxSize(int maxSize) { this.maxSize = maxSize; return this; } private Collection<IItemHandler> findNeighbours() { if (sides.isEmpty()) return Collections.emptyList(); if (breakAfterFirstTry) { final EnumFacing selectedSide = randomizeSides? CollectionUtils.getRandom(sides) : CollectionUtils.getFirst(sides); final IItemHandler neighbour = InventoryUtils.tryGetHandler(world, pos.offset(selectedSide), selectedSide.getOpposite()); return neighbour != null? Collections.singletonList(neighbour) : Collections.<IItemHandler> emptyList(); } Collection<EnumFacing> sidesToCheck = sides; if (randomizeSides) { final List<EnumFacing> tmp = Lists.newArrayList(sides); Collections.shuffle(tmp); sidesToCheck = tmp; } final List<IItemHandler> handlers = Lists.newArrayList(); for (EnumFacing side : sidesToCheck) { final IItemHandler neighbour = InventoryUtils.tryGetHandler(world, pos.offset(side), side.getOpposite()); if (neighbour != null) handlers.add(neighbour); } return handlers; } public int pullToSlot(IItemHandler target, int targetSlot) { return pullToSlot(target, targetSlot, maxSize, findNeighbours()); } // extracted for testing static int pullToSlot(IItemHandler target, int targetSlot, int maxSize, Iterable<IItemHandler> sources) { int transferedAmount = 0; MAIN: for (IItemHandler source : sources) { for (int sourceSlot = 0; sourceSlot < source.getSlots(); sourceSlot++) { final ItemStack stackToPull = source.getStackInSlot(sourceSlot); if (stackToPull.isEmpty()) continue; final ItemStack leftover = target.insertItem(targetSlot, stackToPull, true); if (leftover.getCount() < stackToPull.getCount()) { final int leftoverAmount = leftover.getCount(); final int amountToExtract = Math.min(maxSize - transferedAmount, stackToPull.getCount() - leftoverAmount); final ItemStack extractedItem = source.extractItem(sourceSlot, amountToExtract, false); if (!extractedItem.isEmpty()) { // don't care about results here, since target already declared space target.insertItem(targetSlot, extractedItem, false); transferedAmount += amountToExtract; } } final ItemStack targetContents = target.getStackInSlot(targetSlot); if (targetContents != null && targetContents.getCount() >= targetContents.getMaxStackSize()) break MAIN; } } return transferedAmount; } public int pushFromSlot(IItemHandler source, int sourceSlot) { return pushFromSlot(source, sourceSlot, maxSize, findNeighbours()); } // extracted for testing static int pushFromSlot(IItemHandler source, int sourceSlot, int maxSize, Iterable<IItemHandler> targets) { int transferedAmount = 0; MAIN: for (IItemHandler target : targets) { ItemStack stackToPush = source.getStackInSlot(sourceSlot); for (int targetSlot = 0; targetSlot < target.getSlots(); targetSlot++) { if (stackToPush.isEmpty()) break MAIN; final ItemStack leftover = target.insertItem(targetSlot, stackToPush, true); if (leftover.getCount() < stackToPush.getCount()) { final int leftoverAmount = leftover.getCount(); final int amountToExtract = Math.min(maxSize - transferedAmount, stackToPush.getCount() - leftoverAmount); final ItemStack extractedItem = source.extractItem(sourceSlot, amountToExtract, false); if (!extractedItem.isEmpty()) { target.insertItem(targetSlot, extractedItem, false); transferedAmount += extractedItem.getCount(); stackToPush = source.getStackInSlot(sourceSlot); } } } } return transferedAmount; } }
matthemsteger/df-tools
src/api/raws/index.js
<reponame>matthemsteger/df-tools<gh_stars>1-10 export * from './rawFiles'; export * from './creature'; export {default as rawFiles} from './rawFiles'; export {default as rawFileTypes} from './types'; export {default as parseRawFile} from './parse';
alljoyn/compliance-tests
cpp/components/validation-ctt/HEAD/ctt_testcases/ECDHEEcdsaStore.cpp
<gh_stars>1-10 /****************************************************************************** * Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source * Project (AJOSP) Contributors and others. * * SPDX-License-Identifier: Apache-2.0 * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Open Connectivity Foundation and Contributors to AllSeen * Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ #include "stdafx.h" #include "ECDHEEcdsaStore.h" AJ_PCSTR ECDHEEcdsaStore::getPrivateKey(std::string t_PeerName) { return m_PrivateKeyStore.empty() ? nullptr : m_PrivateKeyStore.at(t_PeerName); } void ECDHEEcdsaStore::setPrivateKey(std::string t_PeerName, AJ_PCSTR t_PrivateKey) { std::map<std::string, AJ_PCSTR>::iterator iterator = m_PrivateKeyStore.find(t_PeerName); if (iterator != m_PrivateKeyStore.end()) { iterator->second = t_PrivateKey; } else { m_PrivateKeyStore.insert(std::pair<std::string, AJ_PCSTR>(t_PeerName, t_PrivateKey)); } } AJ_PCSTR ECDHEEcdsaStore::getCertChain(std::string t_PeerName) { return m_CertChainStore.empty() ? nullptr : m_CertChainStore.at(t_PeerName); } void ECDHEEcdsaStore::setCertChain(std::string t_PeerName, AJ_PCSTR t_CertChain) { std::map<std::string, AJ_PCSTR>::iterator iterator = m_CertChainStore.find(t_PeerName); if (iterator != m_CertChainStore.end()) { iterator->second = t_CertChain; } else { m_CertChainStore.insert(std::pair<std::string, AJ_PCSTR>(t_PeerName, t_CertChain)); } }
Teleburna/jquery-mobile
js/widgets/loader.backcompat.js
/*! * jQuery Mobile Loader Backcompat @VERSION * http://jquerymobile.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: Loading Message Backcompat //>>group: Widgets //>>description: The backwards compatible portions of the loader widget ( function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery", "./loader" ], factory ); } else { // Browser globals factory( jQuery ); } } )( function( $ ) { if ( $.mobileBackcompat !== false ) { $.widget( "mobile.loader", $.mobile.loader, { options: { // Custom html for the inner content of the loading message html: "" }, // DEPRECATED as of 1.5.0 and will be removed in 1.6.0 - we no longer support browsers // incapable of native fixed support fakeFixLoader: $.noop, // DEPRECATED as of 1.5.0 and will be removed in 1.6.0 - we no longer support browsers // incapable of native fixed support checkLoaderPosition: $.noop, show: function( theme ) { var html; this.resetHtml(); this._superApply( arguments ); html = ( $.type( theme ) === "object" && theme.html || this.options.html ); if ( html ) { this.element.html( html ); } }, resetHtml: function() { this.element .empty() .append( this.loader.span ) .append( this.loader.header.empty() ); } } ); } return $.mobile.loader; } );
skoltech-nlp/coqas
my_functions.py
<filename>my_functions.py<gh_stars>1-10 def do_sum(number1, number2): return number1 + number2 import os.path import torch import sys import spacy import re # for extractor class sys.path.append('/home/vika/targer') sys.path.append('/notebook/cqas') sys.path.append('/notebook/bert_sequence_sayankotor/src') # for responser class import json import requests # for generate answer sys.path.insert(0, "/notebook/cqas/generation") #from generation.generation import diviner import os current_directory_path = os.path.dirname(os.path.realpath(__file__)) # pathes to pretrained extraction model PATH_TO_PRETRAINED = '/external_pretrained_models/' MODEL_NAMES = ['bertttt.hdf5'] # Roberta from typing import Dict, List, Sequence, Iterable import itertools import logging from overrides import overrides from allennlp.common.checks import ConfigurationError from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.dataset_readers.dataset_utils import to_bioul from allennlp.data.fields import TextField, SequenceLabelField, Field, MetadataField from allennlp.data.instance import Instance from allennlp.data.token_indexers import TokenIndexer, SingleIdTokenIndexer from allennlp.data.tokenizers import Token from allennlp.modules.token_embedders import PretrainedTransformerMismatchedEmbedder from allennlp.modules.text_field_embedders import BasicTextFieldEmbedder from allennlp.modules.seq2seq_encoders import PassThroughEncoder from allennlp.models import SimpleTagger from allennlp.data.token_indexers import PretrainedTransformerMismatchedIndexer from allennlp.data.vocabulary import Vocabulary from allennlp.predictors import SentenceTaggerPredictor from allennlp.data.dataset_readers import Conll2003DatasetReader from allennlp.data.dataset_readers import SequenceTaggingDatasetReader def load(checkpoint_fn, gpu=-1): if not os.path.isfile(PATH_TO_PRETRAINED + checkpoint_fn): raise ValueError('Can''t find tagger in file "%s". Please, run the main script with non-empty \ "--save-best-path" param to create it.' % checkpoint_fn) tagger = torch.load(PATH_TO_PRETRAINED + checkpoint_fn) tagger.gpu = gpu tagger.word_seq_indexer.gpu = gpu # hotfix tagger.tag_seq_indexer.gpu = gpu # hotfix if hasattr(tagger, 'char_embeddings_layer'):# very hot hotfix tagger.char_embeddings_layer.char_seq_indexer.gpu = gpu # hotfix tagger.self_ensure_gpu() return tagger def create_sequence_from_sentence(str_sentences): return [re.findall(r"[\w']+|[.,!?;]", str_sentence.lower()) for str_sentence in str_sentences] class extractorRoberta: def __init__(self, my_device = torch.device('cuda:2'), model_name = 'roberta.hdf5', model_path = current_directory_path + '/external_pretrained_models/'): self.answ = "UNKNOWN ERROR" self.model_name = model_name self.model_path = model_path self.first_object = '' self.second_object = '' self.predicates = '' self.aspects = '' cuda_device = my_device self.spans = [] # we can't use set because span object is dict and dict is unchashable. We add function add_span to keep non-repeatability try: print (self.model_path + self.model_name) print (model_path + "vocab_dir") vocab= Vocabulary.from_files(model_path + "vocab_dir") BERT_MODEL = 'google/electra-base-discriminator' embedder = PretrainedTransformerMismatchedEmbedder(model_name=BERT_MODEL) text_field_embedder = BasicTextFieldEmbedder({'tokens': embedder}) seq2seq_encoder = PassThroughEncoder(input_dim=embedder.get_output_dim()) print ("encoder loaded") self.indexer = PretrainedTransformerMismatchedIndexer(model_name=BERT_MODEL) print ("indexer loaded") self.model = SimpleTagger(text_field_embedder=text_field_embedder, vocab=vocab, encoder=seq2seq_encoder, calculate_span_f1=True, label_encoding='IOB1').cuda(device=cuda_device) self.model.load_state_dict(torch.load(self.model_path + self.model_name)) print ("model loaded") self.reader = Conll2003DatasetReader(token_indexers={'tokens': self.indexer}) print ("reader loaded") except: e = sys.exc_info()[0] print ("exeption while mapping to gpu in extractor ", e) raise RuntimeError("Init extractor: can't map to gpu. Maybe it is OOM") try: self.predictor = SentenceTaggerPredictor(self.model, self.reader) except: e = sys.exc_info()[0] print ("exeption in creating predictor ", e) raise RuntimeError("Init extractor: can't map to gpu. Maybe it is WTF") def add_span(self, span_obj): if span_obj not in self.spans: self.spans.append(span_obj) def get_words(): return self.words def get_tags(): return self.tags def from_string(self, input_sentence): self.input_str = input_sentence self.first_object = '' self.second_object = '' self.predicates = '' self.aspects = '' self.spans = [] def get_objects_predicates(self, list_words, list_tags): starts = set() obj_list = [] pred_list = [] asp_list = [] for ind, elem in enumerate(list_tags): if elem == 'B-Object': obj_list.append(list_words[ind]) start = self.input_str.find(list_words[ind]) while (start in starts): print (1) print ("ind, word", ind, list_words[ind]) print ("old start, starts", start, starts) print ("string ", self.input_str[start + len(list_words[ind]):]) start = self.input_str[start + len(list_words[ind]):].find(list_words[ind]) + start + len(list_words[ind]) print ("new start", start) if (start != -1 and {'end': start + len(list_words[ind]), 'start': start, 'type': "OBJ" } not in self.spans): self.spans.append({'end': start + len(list_words[ind]), 'start': start, 'type': "OBJ" }) starts.add(start) if elem == 'I-Object': start = self.input_str.find(list_words[ind]) while (start in starts): start = self.input_str[start:].find(list_words[ind]) + start + len(list_words[ind]) if (start != -1 and {'end': start + len(list_words[ind]), 'start': start, 'type': "OBJ" } not in self.spans): self.spans.append({'end': start + len(list_words[ind]), 'start': start, 'type': "OBJ" }) starts.add(start) if elem == 'B-Predicate': print (2) print ("ind, word", ind, list_words[ind]) print ("old start, starts", start, starts) print ("string ", self.input_str[start + len(list_words[ind]):]) pred_list.append(list_words[ind]) start = self.input_str.find(list_words[ind] + " ") while (start in starts): start = self.input_str[start + len(list_words[ind]):].find(list_words[ind]) + start + len(list_words[ind]) if (start != -1 and { 'end': start + len(list_words[ind]), 'start': start, 'type': "PRED" } not in self.spans): self.spans.append({ 'end': start + len(list_words[ind]), 'start': start, 'type': "PRED" }) starts.add(start) if elem == 'I-Predicate': start = self.input_str.find(list_words[ind]) self.spans.append({ 'end': start + len(list_words[ind]), 'start': start, 'type': "PRED" }) while (start in starts): start = self.input_str[start:].find(list_words[ind]) + start + len(list_words[ind]) if (start != -1 and { 'end': start + len(list_words[ind]), 'start': start, 'type': "PRED" } not in self.spans): self.spans.append({ 'end': start + len(list_words[ind]), 'start': start, 'type': "PRED" }) starts.add(start) if elem == 'I-Aspect': asp_list.append(list_words[ind]) start = self.input_str.find(list_words[ind]) while (start in starts): start = self.input_str[start:].find(list_words[ind]) + start + len(list_words[ind]) if (start != -1 and {'end': start + len(list_words[ind]), 'start': start, 'type': "ASP" } not in self.spans): self.spans.append({ 'end': start + len(list_words[ind]), 'start': start, 'type': "ASP" }) starts.add(start) if elem == 'B-Aspect': asp_list.append(list_words[ind]) start = self.input_str.find(list_words[ind]) while (start in starts): start = self.input_str[start:].find(list_words[ind]) + start + len(list_words[ind]) if (start != -1 and {'end': start + len(list_words[ind]), 'start': start, 'type': "ASP" } not in self.spans): self.spans.append({ 'end': start + len(list_words[ind]), 'start': start, 'type': "ASP" }) starts.add(start) return obj_list, pred_list, asp_list def extract_objects_predicates(self, input_string): preds = self.predictor.predict(input_string) print ("extract_objects_predicates tags", preds['tags']) print ("extract_objects_predicates words", preds['words']) objects, predicates, aspects = self.get_objects_predicates(preds['words'], preds['tags']) print (objects) print (predicates) print (aspects) self.predicates = predicates self.aspects = aspects print ("len(objects)", len(objects)) if len(objects) >= 2: self.first_object = objects[0] self.second_object = objects[1] else: # try to use spacy self.answ = "We can't recognize two objects for compare 2" def get_params(self): print ("in extractor get params 0") print ("self prredicates ", self.predicates) self.extract_objects_predicates(self.input_str) #except: #raise RuntimeError("Can't map to gpu. Maybe it is OOM") return self.first_object.strip(".,!/?"), self.second_object.strip(".,!/?"), self.predicates, self.aspects class responser: def __init__(self): self.URL = 'http://ltdemos.informatik.uni-hamburg.de/cam-api' self.proxies = {"http": "http://172.16.58.3:10015/","https": "https://172.16.17.32:10015/",} def get_response(self, first_object, second_object, fast_search=True, aspects=None, weights=None): print ("aspects", aspects) print ("weights", weights) num_aspects = len(aspects) if aspects is not None else 0 num_weights = len(weights) if weights is not None else 0 if num_aspects != num_weights: raise ValueError( "Number of weights should be equal to the number of aspects") params = { 'objectA': first_object, 'objectB': second_object, 'fs': str(fast_search).lower() } if num_aspects: params.update({'aspect{}'.format(i + 1): aspect for i, aspect in enumerate(aspects)}) params.update({'weight{}'.format(i + 1): weight for i, weight in enumerate(weights)}) print ("get url") print ("params", params) response = requests.get(url=self.URL, params=params, timeout=70) return response def answerer(input_string, tp = 'big'): my_extractor = extractorRoberta() my_extractor.from_string(input_string) my_responser = responser() obj1, obj2, predicates, aspects = my_extractor.get_params() print ("len(obj1), len(obj2)", len(obj1), len(obj2)) print ("obj1, obj2, predicates", obj1, obj2, predicates) if (len(obj1) > 0 and len(obj2) > 0): response = my_responser.get_response(first_object = obj1, second_object = obj2, fast_search=True, aspects = predicates, weights = [1 for predicate in predicates]) try: response_json = response.json() except: return ("smth wrong in response, please try again") try: my_diviner = diviner(tp = tp) print (1) my_diviner.create_from_json(response_json, predicates) print (2) except: return ("smth wrong in diviner, please try again") try: answer = my_diviner.generate_advice() print ("answer", answer) #del my_extractor,my_diviner, my_responser return answer except: #del my_extractor,my_diviner, my_responser return ("smth wrong in answer generation, please try again") elif (len(obj1) > 0 and len(obj2) == 0): print ("len(obj1) > 0 and len(obj2) == 0") response = my_responser.get_response(first_object = obj1, second_object = 'and', fast_search=True, aspects = predicates, weights = [1 for predicate in predicates]) try: response_json = response.json() my_diviner = diviner(tp = tp) my_diviner.create_from_json(response_json, predicates) answer = my_diviner.generate_advice(is_object_single = True) print ("answer", answer) #del my_extractor,my_diviner, my_responser return answer except: #del my_extractor,my_diviner, my_responser return ("smth wrong in response, please try again") else: return ("We can't recognize objects for comparision")
fburato/highwheel-modules
parser/src/test/java/com/example/annotated/AnnotatedAtClassLevel.java
<gh_stars>1-10 package com.example.annotated; @AnAnnotation public class AnnotatedAtClassLevel { }
bfortuner/higgins
higgins/nlp/openai/messaging_completions.py
import os import time from typing import Any import openai from higgins.datasets import messaging_datasets from higgins.nlp import nlp_utils from . import caching from . import completion_utils openai.api_key = os.getenv("OPENAI_API_KEY") def send_message_completion(cmd: str, engine="davinci", cache: Any = None): prompt = completion_utils.build_completion_prompt( question=cmd, action_chains=messaging_datasets.SEND_MESSAGE_DATASET_TRAIN, task_description="Convert the following text into commands", ) # print(f"Prompt: {prompt}") cache = cache if cache is not None else caching.get_default_cache() cache_key = nlp_utils.hash_normalized_text(prompt) if cache_key not in cache: start = time.time() response = openai.Completion.create( engine=engine, model=None, prompt=prompt, temperature=0.2, max_tokens=100, top_p=1.0, frequency_penalty=0.2, presence_penalty=0.0, stop=["<<END>>"], ) # print(f"Time: {time.time() - start:.2f}") answer = response["choices"][0]["text"].strip("Q:").strip() cache.add( key=cache_key, value={ "cmd": cmd, "answer": answer, "response": response } ) else: answer = cache[cache_key]["answer"] response = cache[cache_key]["response"] return answer def test_send_message_completion(): for example in messaging_datasets.SEND_MESSAGE_DATASET_TEST: answer = send_message_completion(example["query"]) actions = completion_utils.convert_string_to_action_chain(answer) print(f"Q: {example['query']}\nA: {answer}\nI: {actions}\nE: {example['actions']}") assert actions == example['actions'] if __name__ == "__main__": test_send_message_completion()
dns/Cafu
Libs/SceneGraph/TerrainNode.cpp
<gh_stars>1-10 /* Cafu Engine, http://www.cafu.de/ Copyright (c) <NAME> and other contributors. This project is licensed under the terms of the MIT license. */ #include "TerrainNode.hpp" #include "_aux.hpp" #include "MaterialSystem/MapComposition.hpp" #include "MaterialSystem/MaterialManager.hpp" #include "MaterialSystem/Mesh.hpp" #include "MaterialSystem/Renderer.hpp" #include "MaterialSystem/TextureMap.hpp" #include "Math3D/Matrix.hpp" #include "Terrain/Terrain.hpp" #include <cassert> using namespace cf::SceneGraph; TerrainNodeT::TerrainNodeT() : Terrain(NULL), TerrainShareID(0), RenderMaterial(NULL), LightMapTexture(NULL) { Init(); } TerrainNodeT::TerrainNodeT(const BoundingBox3dT& BB_, const TerrainT& Terrain_, unsigned long TerrainShareID_, const std::string& MaterialName_, const float LightMapPatchSize) : BB(BB_), Terrain(&Terrain_), TerrainShareID(TerrainShareID_), MaterialName(MaterialName_), LightMap(), SHLMap(), RenderMaterial(NULL), LightMapTexture(NULL) { // Initialize the LightMap. const double BB_DiffX =BB.Max.x-BB.Min.x; const double BB_DiffY =BB.Max.y-BB.Min.y; const double BB_MinDiff =(BB_DiffX<BB_DiffY) ? BB_DiffX : BB_DiffY; const unsigned long NrOfLightMapPatches=(unsigned long)(BB_MinDiff / LightMapPatchSize) + 1; // The +1 is for "ceil()". // Now find the next smaller power of two. unsigned long Pow2NrOfLightMapPatches=1; while (Pow2NrOfLightMapPatches*2<=NrOfLightMapPatches) Pow2NrOfLightMapPatches*=2; if (Pow2NrOfLightMapPatches>256) Pow2NrOfLightMapPatches=256; // This condition is also verified by CaLight, because it doesn't make sense // if a single terrain cell is covered by multiple lightmap elements. if (Pow2NrOfLightMapPatches>Terrain->GetSize()-1) Pow2NrOfLightMapPatches=Terrain->GetSize()-1; // (Now, the true patch size is obtained by (BB.Max.x-BB.Min.x)/Pow2NrOfLightMapPatches and (BB.Max.y-BB.Min.y)/Pow2NrOfLightMapPatches.) // Create a full-bright lightmap. for (unsigned long LMElemNr=0; LMElemNr<3*Pow2NrOfLightMapPatches*Pow2NrOfLightMapPatches; LMElemNr++) LightMap.PushBack(0xFF); // Initialize the SHLMap. // ... // Nothing needs to be done, since we're creating a 0-band SHL map. Init(); } TerrainNodeT* TerrainNodeT::CreateFromFile_cw(std::istream& InFile, aux::PoolT& /*Pool*/, LightMapManT& /*LMM*/, SHLMapManT& /*SMM*/, const ArrayT<const TerrainT*>& ShTe) { TerrainNodeT* TN=new TerrainNodeT(); TN->BB.Min =aux::ReadVector3d(InFile); TN->BB.Max =aux::ReadVector3d(InFile); TN->TerrainShareID=aux::ReadUInt32(InFile); TN->MaterialName =aux::ReadString(InFile); TN->Terrain =ShTe[TN->TerrainShareID]; for (unsigned long Size=aux::ReadUInt32(InFile); Size>0; Size--) { char c; InFile.read(&c, sizeof(c)); TN->LightMap.PushBack(c); } for (unsigned long Size=aux::ReadUInt32(InFile); Size>0; Size--) { float f=0.0; InFile.read((char*)&f, sizeof(f)); TN->SHLMap.PushBack(f); } TN->Init(); return TN; } TerrainNodeT::~TerrainNodeT() { Clean(); } void TerrainNodeT::WriteTo(std::ostream& OutFile, aux::PoolT& /*Pool*/) const { aux::Write(OutFile, "Terrain"); aux::Write(OutFile, BB.Min); aux::Write(OutFile, BB.Max); aux::Write(OutFile, aux::cnc_ui32(TerrainShareID)); aux::Write(OutFile, MaterialName); aux::Write(OutFile, aux::cnc_ui32(LightMap.Size())); for (unsigned long c=0; c<LightMap.Size(); c++) OutFile.write(&LightMap[c], sizeof(char)); aux::Write(OutFile, aux::cnc_ui32(SHLMap.Size())); for (unsigned long c=0; c<SHLMap.Size(); c++) OutFile.write((char*)&SHLMap[c], sizeof(float)); } const BoundingBox3T<double>& TerrainNodeT::GetBoundingBox() const { return BB; } bool TerrainNodeT::IsOpaque() const { return true; } void TerrainNodeT::DrawAmbientContrib(const Vector3dT& ViewerPos) const { assert(MatSys::Renderer!=NULL); assert(MatSys::Renderer->GetCurrentRenderAction()==MatSys::RendererI::AMBIENT); // TODO: Get fov_y directly from OpenGLWindow. // TODO: Try to avoid getting the mp and mv matrices every frame. // TODO: Note that the matrices stuff needs attention only once per frame for all terrains, not for each terrain anew. TerrainT::ViewInfoT VI; const float Window_Width =1024.0; const float Window_Height= 768.0; // The basic formula for fov_x is from soar/main.c, reshape_callback function, rearranged for fov_x. // The 67.5 is a fixed value from OpenGLWindow.cpp. const float tau =4.0; // Error tolerance in pixel. const float fov_y=67.5; const float fov_x=2.0f*atan(Window_Width/Window_Height*tan((fov_y*3.14159265358979323846f/180.0f)/2.0f)); const float kappa=tau/Window_Width*fov_x; VI.cull =true; VI.nu =kappa>0.0f ? 1.0f/kappa : 999999.0f; // Inverse of error tolerance in radians. VI.nu_min =VI.nu*2.0f/3.0f; // Lower morph parameter. VI.nu_max =VI.nu; // Upper morph parameter. VI.viewpoint=ViewerPos.AsVectorOfFloat(); // Set up VI.viewplanes (clip planes) for view frustum culling. MatrixT mpv=MatSys::Renderer->GetMatrix(MatSys::Renderer->PROJECTION)*MatSys::Renderer->GetMatrixModelView(); // Compute view frustum planes. for (unsigned long i=0; i<5; i++) { // m can be used to easily minify / shrink the view frustum. // The values should be between 0 and 8: 0 is the default (no minification), 8 is the reasonable maximum. const char m = 0; const float d = (i < 4) ? 1.0f - 0.75f*m/8.0f : 1.0f; float plane[4]; for (unsigned long j=0; j<4; j++) plane[j]=((i & 1) ? mpv.m[i/2][j] : -mpv.m[i/2][j]) - d*mpv.m[3][j]; const float l=sqrt(plane[0]*plane[0]+plane[1]*plane[1]+plane[2]*plane[2]); VI.viewplanes[i]=Plane3fT(Vector3fT(plane[0]/l, plane[1]/l, plane[2]/l), -plane[3]/l); } // Setup texturing for the terrain, using automatic texture coordinates generation. const float CoordPlane1[4]={ 1.0f/float(BB.Max.x-BB.Min.x), 0.0f, 0.0f, float(-BB.Min.x/(BB.Max.x-BB.Min.x)) }; const float CoordPlane2[4]={ 0.0f, -1.0f/float(BB.Max.y-BB.Min.y), 0.0f, float( BB.Max.y/(BB.Max.y-BB.Min.y)) }; // Texture y-axis points top-down! MatSys::Renderer->SetGenPurposeRenderingParam( 4, CoordPlane1[0]); MatSys::Renderer->SetGenPurposeRenderingParam( 5, CoordPlane1[1]); MatSys::Renderer->SetGenPurposeRenderingParam( 6, CoordPlane1[2]); MatSys::Renderer->SetGenPurposeRenderingParam( 7, CoordPlane1[3]); MatSys::Renderer->SetGenPurposeRenderingParam( 8, CoordPlane2[0]); MatSys::Renderer->SetGenPurposeRenderingParam( 9, CoordPlane2[1]); MatSys::Renderer->SetGenPurposeRenderingParam(10, CoordPlane2[2]); MatSys::Renderer->SetGenPurposeRenderingParam(11, CoordPlane2[3]); MatSys::Renderer->SetCurrentMaterial(RenderMaterial); MatSys::Renderer->SetCurrentLightMap(LightMapTexture); MatSys::Renderer->SetCurrentLightDirMap(NULL); // The MatSys provides a default for LightDirMaps when NULL is set. // Finally, draw the terrain. #if 1 const ArrayT<Vector3fT>& VectorStrip=Terrain->ComputeVectorStrip(VI); static MatSys::MeshT TerrainMesh(MatSys::MeshT::TriangleStrip); TerrainMesh.Vertices.Overwrite(); TerrainMesh.Vertices.PushBackEmpty(VectorStrip.Size()); for (unsigned long VNr=0; VNr<VectorStrip.Size(); VNr++) TerrainMesh.Vertices[VNr].SetOrigin(VectorStrip[VNr]); #else const ArrayT<Vector3fT>& VectorStrip=Terrain->ComputeVectorStripByMorphing(VI); static MatSys::MeshT TerrainMesh(MatSys::MeshT::TriangleStrip); TerrainMesh.Vertices.Overwrite(); TerrainMesh.Vertices.PushBackEmpty(VectorStrip.Size()-1); // Note that the first VectorT at VectorStrip[0] must be skipped! for (unsigned long VNr=1; VNr<VectorStrip.Size(); VNr++) TerrainMesh.Vertices[VNr-1].SetOrigin(VectorStrip[VNr]); #endif MatSys::Renderer->RenderMesh(TerrainMesh); } void TerrainNodeT::DrawStencilShadowVolumes(const Vector3dT& LightPos, const float LightRadius) const { assert(MatSys::Renderer!=NULL); assert(MatSys::Renderer->GetCurrentRenderAction()==MatSys::RendererI::STENCILSHADOW); } void TerrainNodeT::DrawLightSourceContrib(const Vector3dT& ViewerPos, const Vector3dT& LightPos) const { assert(MatSys::Renderer!=NULL); assert(MatSys::Renderer->GetCurrentRenderAction()==MatSys::RendererI::LIGHTING); } void TerrainNodeT::DrawTranslucentContrib(const Vector3dT& ViewerPos) const { assert(MatSys::Renderer!=NULL); assert(MatSys::Renderer->GetCurrentRenderAction()==MatSys::RendererI::AMBIENT); } void TerrainNodeT::Init() { if (MatSys::Renderer ==NULL) return; if (MatSys::TextureMapManager==NULL) return; if (Terrain==NULL) return; if (LightMap.Size()<3) return; Clean(); #if 1 ArrayT<char>& GammaLightMap=LightMap; #else // This code should actually be removed entirely - gamma for lightmaps is now properly applied in CaLight, and thus there is no need for toying around with it elsewhere. ArrayT<char> GammaLightMap; // Wende r_gamma_lm auf die LightMaps an. // Beachte die nette Optimierung (Vorberechnung der 256 möglichen Gammawerte)! // Dieser Code ist identisch zum DrawableMapT Constructor! { char GammaValuesLM[256]; for (unsigned long ValueNr=0; ValueNr<256; ValueNr++) { // FIXME!!!! Changes here require also changes in DrawableMapT::r_gamma_lm! float Value=pow(float(ValueNr)/255.0f, 1.0f/ 1.6f )*255.0f; if (Value<0.0f) Value=0.0f; if (Value>255.0f) Value=255.0f; GammaValuesLM[ValueNr]=char(Value+0.49f); } for (unsigned long Nr=0; Nr<LightMap.Size(); Nr++) GammaLightMap.PushBack(GammaValuesLM[LightMap[Nr]]); } #endif const int LightMapSize=int(sqrt(GammaLightMap.Size()/3.0)+0.5); LightMapTexture=MatSys::TextureMapManager->GetTextureMap2D( &GammaLightMap[0], LightMapSize, LightMapSize, 3, true, // MipMaps and scaling down is no problem here, because the bitmap is not shared with other LightMaps, but ClampToEdge should be set! MapCompositionT(MapCompositionT::Linear_MipMap_Linear, MapCompositionT::Linear, MapCompositionT::ClampToEdge, MapCompositionT::ClampToEdge)); RenderMaterial=MatSys::Renderer->RegisterMaterial(MaterialManager->GetMaterial(MaterialName)); } void TerrainNodeT::Clean() { if (RenderMaterial!=NULL) { // Note that also the MatSys::Renderer pointer can be NULL, but then the RenderMaterial must be NULL, too. assert(MatSys::Renderer!=NULL); MatSys::Renderer->FreeMaterial(RenderMaterial); RenderMaterial=NULL; } if (LightMapTexture!=NULL) { // Note that also the MatSys::TextureMapManager pointer can be NULL, but then the LightMapTexture must be NULL, too. assert(MatSys::TextureMapManager!=NULL); MatSys::TextureMapManager->FreeTextureMap(LightMapTexture); LightMapTexture=NULL; } }
situx/kiwi-postgis
src/org/openrdf/query/algebra/evaluation/function/postgis/util/literals/LiteralType.java
<filename>src/org/openrdf/query/algebra/evaluation/function/postgis/util/literals/LiteralType.java package org.openrdf.query.algebra.evaluation.function.postgis.util.literals; public interface LiteralType { }
tetsutan/bromo
lib/bromo/utils/logger.rb
<reponame>tetsutan/bromo require 'logger' module Bromo module Utils module Logger def self.logger @@logger ||= ::Logger.new(STDOUT).tap do |l| l.level = ::Logger::DEBUG if Env.development? end end def logger self.class.logger end end end end
taozhiheng/MyRepository
Wifi/app/src/main/java/com/example/taozhiheng/wifi/MainActivity.java
<filename>Wifi/app/src/main/java/com/example/taozhiheng/wifi/MainActivity.java package com.example.taozhiheng.wifi; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.NetworkInfo; import android.net.wifi.p2p.WifiP2pConfig; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pDeviceList; import android.net.wifi.p2p.WifiP2pInfo; import android.net.wifi.p2p.WifiP2pManager; import android.os.Handler; import android.os.Message; import android.provider.Settings; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class MainActivity extends ActionBarActivity { private boolean isRun; private TextView textView; private Button button; private ListView list; private EditText input; private Button send; private InputStream inputStream; private OutputStream outputStream; private ArrayAdapter adapter; private WifiP2pManager wifiP2pManager; private WifiP2pManager.Channel channel; private List<WifiP2pDevice> deviceList = new ArrayList<>(); private List<String> deviceNameList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(R.id.text); button = (Button) findViewById(R.id.btn); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(discoverRunnable).start(); } }); list = (ListView) findViewById(R.id.list); adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, deviceNameList); list.setAdapter(adapter); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { WifiP2pDevice device = deviceList.get(position); Log.e("MainActivity", "start to connect:"+device.deviceName); new Thread(new MyRuunable(device)).start(); } }); input = (EditText) findViewById(R.id.input); send = (Button) findViewById(R.id.send); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendMessage(input.getText().toString()); } }); } @Override protected void onResume() { super.onResume(); registerWifiRecevier(); registerPeerReceiver(); regitsterConnectionRecevier(); initWifiDirect(); } private void initWifiDirect() { wifiP2pManager = (WifiP2pManager)getSystemService(Context.WIFI_P2P_SERVICE); channel = wifiP2pManager.initialize(this, getMainLooper(), new WifiP2pManager.ChannelListener() { @Override public void onChannelDisconnected() { initWifiDirect(); } }); } private WifiP2pManager.ActionListener actionListener = new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.e("MainActivity", "succeed"); } @Override public void onFailure(int reason) { String errorMessage = "WiFi Direct Failed:"; switch(reason) { case WifiP2pManager.BUSY: errorMessage += "Framework busy"; break; case WifiP2pManager.ERROR : errorMessage += "Internal error"; break; case WifiP2pManager.P2P_UNSUPPORTED: errorMessage += "Unknown error"; break; default: errorMessage += "Unknown error"; } Log.e("MainActivity", errorMessage); //wifiP2pManager.discoverPeers(channel, null); } }; private void startWifiDirect() { Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS); startActivityForResult(intent, 1); } private Runnable discoverRunnable = new Runnable() { @Override public void run() { discoverPeers(); } }; private void discoverPeers() { wifiP2pManager.discoverPeers(channel, actionListener); Log.e("MainActivity", "try to discover"); } private void connectTo(WifiP2pDevice device) { WifiP2pConfig config = new WifiP2pConfig(); config.deviceAddress = device.deviceAddress; wifiP2pManager.connect(channel, config, actionListener); Log.e("MainActivity", "address:"+config.deviceAddress); } private class MyRuunable implements Runnable{ private WifiP2pDevice device; public MyRuunable(WifiP2pDevice device) { this.device = device; } @Override public void run() { connectTo(device); } } class SocketRunable implements Runnable { private String host; private int which;//0-client, 1-server public SocketRunable(String host,int which) { this.host = host; this.which = which; } @Override public void run() { Socket socket; try { if (which == 0) { InetSocketAddress socketAddress = new InetSocketAddress(host, 6666); socket = new Socket(); socket.bind(null); socket.connect(socketAddress, 5000); } else { ServerSocket serverSocket = new ServerSocket(6666); socket = serverSocket.accept(); } inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); isRun = true; Log.e("MainActivity", "socket connect"); new Thread(new Runnable() { @Override public void run() { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String string; try { while (isRun) { if ((string=bufferedReader.readLine())!=null) { Message message = Message.obtain(); message.what = 1; message.obj = string; handler.sendMessage(message); } } }catch(IOException e) { e.printStackTrace(); } } }).start(); }catch(IOException e) { e.printStackTrace(); } } } private void regitsterConnectionRecevier() { IntentFilter filter = new IntentFilter(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); registerReceiver(connectionChangedRecevier, filter); } private BroadcastReceiver connectionChangedRecevier = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO); if(networkInfo.isConnected()) { Log.e("MainActivity", "connect succeed!"); wifiP2pManager.requestConnectionInfo(channel, new WifiP2pManager.ConnectionInfoListener() { @Override public void onConnectionInfoAvailable(WifiP2pInfo info) { if (info.groupFormed) { if (info.isGroupOwner) { Log.e("MainActivity", "owner" + info.groupOwnerAddress); new Thread(new SocketRunable(info.groupOwnerAddress.getHostAddress(),1)).start(); } else { new Thread(new SocketRunable(info.groupOwnerAddress.getHostAddress(),0)).start(); Log.e("MainActivity", "user:" + info.groupOwnerAddress); } } } }); } else { Log.e("MainActivity", "disconnect"); } } }; private void registerPeerReceiver() { IntentFilter filter = new IntentFilter(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); registerReceiver(peerDiscoveryReceiver, filter); } private BroadcastReceiver peerDiscoveryReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { wifiP2pManager.requestPeers(channel, new WifiP2pManager.PeerListListener() { @Override public void onPeersAvailable(WifiP2pDeviceList peers) { deviceList.clear(); deviceList.addAll(peers.getDeviceList()); deviceNameList.clear(); for(WifiP2pDevice device : deviceList) { deviceNameList.add(device.deviceName); Log.e("MainActivity", device.deviceName); } adapter.notifyDataSetChanged(); } }); } }; private void registerWifiRecevier() { IntentFilter filter = new IntentFilter(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); registerReceiver(wifiStateReceiver, filter); } private BroadcastReceiver wifiStateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, WifiP2pManager.WIFI_P2P_STATE_DISABLED); switch (state) { case WifiP2pManager.WIFI_P2P_STATE_ENABLED: textView.setText("wifi enabled!"); break; default: textView.setText("wifi disabled!"); startWifiDirect(); } } }; private void sendMessage(String message) { if(outputStream == null) return; try { outputStream.write(message.getBytes()); outputStream.flush(); }catch (IOException e) { e.printStackTrace(); } input.setText(null); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Toast.makeText(MainActivity.this, "收到了:"+msg.obj.toString(), Toast.LENGTH_SHORT).show(); } }; @Override protected void onDestroy() { isRun = false; super.onDestroy(); } }
BenHuddleston/kv_engine
daemon/mcbpdestroybuckettask.h
<filename>daemon/mcbpdestroybuckettask.h /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #pragma once #include "bucket_threads.h" #include "buckets.h" #include "connection.h" #include "memcached.h" #include "task.h" #include <string> class McbpDestroyBucketTask : public Task { public: McbpDestroyBucketTask(const std::string& name_, bool force_, Cookie* cookie_) : thread(name_, force_, cookie_, this) { } // start the bucket deletion // May throw std::bad_alloc if we're failing to start the thread void start() { thread.start(); } Status execute() override { return Status::Finished; } void notifyExecutionComplete() override { auto* cookie = thread.getCookie(); if (cookie) { ::notifyIoComplete(*cookie, thread.getResult()); } } protected: DestroyBucketThread thread; };
CPU-Code/java
netty/src/main/java/com/cpucode/netty/io/bin/tomcat/http/CpServlet.java
<gh_stars>1-10 package com.cpucode.netty.io.bin.tomcat.http; /** * @author : cpucode * @date : 2021/8/12 13:47 * @github : https://github.com/CPU-Code * @csdn : https://blog.csdn.net/qq_44226094 */ public abstract class CpServlet { public void service(CpRequest request, CpResponse response) throws Exception{ //由service方法来决定,是调用doGet或者调用doPost if("GET".equalsIgnoreCase(request.getMethod())){ doGet(request, response); }else{ doPost(request, response); } } public abstract void doGet(CpRequest request,CpResponse response) throws Exception; public abstract void doPost(CpRequest request,CpResponse response) throws Exception; }
eniac/parallel-inet-omnet
src/sim/cfsm.cc
<gh_stars>10-100 //======================================================================== // CFSM.CC - part of // // OMNeT++/OMNEST // Discrete System Simulation in C++ // // Member functions of // cFSM : Finite State Machine state // // Author: <NAME> // //======================================================================== /*--------------------------------------------------------------* Copyright (C) 1992-2008 <NAME> Copyright (C) 2006-2008 OpenSim Ltd. This file is distributed WITHOUT ANY WARRANTY. See the file `license' for details on this and other legal matters. *--------------------------------------------------------------*/ #include <stdio.h> // sprintf #include <string.h> // strlen #include <sstream> #include "globals.h" #include "cfsm.h" NAMESPACE_BEGIN using std::ostream; Register_Class(cFSM); cFSM::cFSM(const char *name) : cOwnedObject(name) { _state=0; _statename="INIT"; } void cFSM::copy(const cFSM& vs) { _statename=vs._statename; _state=vs._state; } cFSM& cFSM::operator=(const cFSM& vs) { if (this==&vs) return *this; cOwnedObject::operator=(vs); copy(vs); return *this; } std::string cFSM::info() const { std::stringstream out; if (!_statename) out << "state: " << _state; else out << "state: " << _statename << " (" << _state << ")"; return out.str(); } void cFSM::parsimPack(cCommBuffer *buffer) { throw cRuntimeError(this,"parsimPack() not implemented"); } void cFSM::parsimUnpack(cCommBuffer *buffer) { throw cRuntimeError(this,"parsimUnpack() not implemented"); } NAMESPACE_END
cao2068959/anubis
src/main/java/org/chy/anubis/exception/JavaParserException.java
<reponame>cao2068959/anubis package org.chy.anubis.exception; import com.github.javaparser.Problem; import org.chy.anubis.entity.FileInfo; import org.chy.anubis.utils.StringUtils; import java.util.List; public class JavaParserException extends RuntimeException { public JavaParserException(String message) { super(message); } public JavaParserException(List<Problem> problems) { super("文件解析失败: " + handleErrorList(problems)); } private static String handleErrorList(List<Problem> problems) { return StringUtils.join("[", "]", problems, Problem::toString); } }
CartoDB/cartodb-common
lib/carto/common/action_mailer_log_subscriber.rb
require 'action_mailer/log_subscriber' ## # Extends ActionMailer::LogSubscriber to improve JSON logging capabilities # Original source: https://github.com/rails/rails/blob/4-2-stable/actionmailer/lib/action_mailer/log_subscriber.rb # module Carto module Common class ActionMailerLogSubscriber < ActionMailer::LogSubscriber # Indicates Rails received a request to send an email. # The original payload of this event contains very little information def process(event) payload = event.payload info( message: 'Mail processed', mailer_class: payload[:mailer], mailer_action: payload[:action], duration_ms: event.duration.round(1) ) end # Indicates Rails tried to send the email. Does not imply user received it, # as an error can still happen while sending it. def deliver(event) payload = event.payload info( message: 'Mail sent', mailer_class: payload[:mailer], message_id: payload[:message_id], current_user: current_user(payload), email_subject: payload[:subject], email_to_hint: email_to_hint(payload), email_from: payload[:from], email_date: payload[:date] ) end private def current_user(event_payload) user_klass = defined?(Carto::User) ? Carto::User : User user_klass.find_by(email: event_payload[:to])&.username end def email_to_hint(event_payload) email_to = event_payload[:to] if email_to.is_a?(Array) email_to.map { |address| email_address_hint(address) } else [email_address_hint(email_to)] end end def email_address_hint(address) return unless address.present? if address.exclude?('@') || address.length < 8 || address.split('@').select(&:present?).size != 2 return '[ADDRESS]' end address.split('@').map { |segment| "#{segment[0]}*****#{segment[-1]}" }.join('@') end end end end
trycatchkamal/akka-http
akka-http/src/main/scala/akka/http/scaladsl/marshalling/ToResponseMarshallable.scala
/* * Copyright (C) 2009-2019 Lightbend Inc. <https://www.lightbend.com> */ package akka.http.scaladsl.marshalling import scala.concurrent.{ Future, ExecutionContext } import akka.http.scaladsl.model._ /** Something that can later be marshalled into a response */ trait ToResponseMarshallable { type T def value: T implicit def marshaller: ToResponseMarshaller[T] def apply(request: HttpRequest)(implicit ec: ExecutionContext): Future[HttpResponse] = Marshal(value).toResponseFor(request) } object ToResponseMarshallable { implicit def apply[A](_value: A)(implicit _marshaller: ToResponseMarshaller[A]): ToResponseMarshallable = new ToResponseMarshallable { type T = A def value: T = _value def marshaller: ToResponseMarshaller[T] = _marshaller } implicit val marshaller: ToResponseMarshaller[ToResponseMarshallable] = Marshaller { implicit ec ⇒ marshallable ⇒ marshallable.marshaller(marshallable.value) } }
htjia/vueYrProject
src/directive/only_number/index.js
import onlyNumber from './onlyNumber' const install = Vue => { Vue.directive('only-number', onlyNumber) } /* Vue.use( plugin ) 安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。 如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。 该方法需要在调用 new Vue() 之前被调用。 当 install 方法被同一个插件多次调用,插件将只会被安装一次。 -------------------------------------------------------- 调用示例 最大两位小数 <el-input v-only-number="{ min: 0, max: 100, precision: 2 }" v-model.number="price" /> 只允许输入整数 <input v-only-number="{ min: -10, max: 100, precision: 0 }" v-model.number="price" /> */ if (window.Vue) { window['onlyNumber'] = onlyNumber Vue.use(install); // eslint-disable-line } onlyNumber.install = install export default onlyNumber
joestrouth1/tinkerpop
gremlin-test/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/ProjectTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tinkerpop.gremlin.process.traversal.step.map; import org.apache.tinkerpop.gremlin.LoadGraphWith; import org.apache.tinkerpop.gremlin.process.AbstractGremlinProcessTest; import org.apache.tinkerpop.gremlin.process.traversal.Order; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.junit.Test; import java.util.List; import java.util.Map; import static org.apache.tinkerpop.gremlin.LoadGraphWith.GraphData.MODERN; import static org.junit.Assert.assertEquals; /** * @author <NAME> (http://markorodriguez.com) */ public abstract class ProjectTest extends AbstractGremlinProcessTest { public abstract Traversal<Vertex, Map<String, Number>> get_g_V_hasLabelXpersonX_projectXa_bX_byXoutE_countX_byXageX(); public abstract Traversal<Vertex, String> get_g_V_outXcreatedX_projectXa_bX_byXnameX_byXinXcreatedX_countX_order_byXselectXbX__descX_selectXaX(); @Test @LoadGraphWith(MODERN) public void g_V_hasLabelXpersonX_projectXa_bX_byXoutE_countX_byXageX() { final Traversal<Vertex, Map<String, Number>> traversal = get_g_V_hasLabelXpersonX_projectXa_bX_byXoutE_countX_byXageX(); printTraversalForm(traversal); checkResults(makeMapList(2, "a", 3l, "b", 29, "a", 0l, "b", 27, "a", 2l, "b", 32, "a", 1l, "b", 35), traversal); } @Test @LoadGraphWith(MODERN) public void g_V_outXcreatedX_projectXa_bX_byXnameX_byXinXcreatedX_countX_order_byXselectXbX__descX_selectXaX() { final Traversal<Vertex, String> traversal = get_g_V_outXcreatedX_projectXa_bX_byXnameX_byXinXcreatedX_countX_order_byXselectXbX__descX_selectXaX(); printTraversalForm(traversal); final List<String> names = traversal.toList(); assertEquals(4, names.size()); assertEquals("lop", names.get(0)); assertEquals("lop", names.get(1)); assertEquals("lop", names.get(2)); assertEquals("ripple", names.get(3)); } public static class Traversals extends ProjectTest { @Override public Traversal<Vertex, Map<String, Number>> get_g_V_hasLabelXpersonX_projectXa_bX_byXoutE_countX_byXageX() { return g.V().hasLabel("person").<Number>project("a", "b").by(__.outE().count()).by("age"); } @Override public Traversal<Vertex, String> get_g_V_outXcreatedX_projectXa_bX_byXnameX_byXinXcreatedX_countX_order_byXselectXbX__descX_selectXaX() { return g.V().out("created").project("a", "b").by("name").by(__.in("created").count()).order().by(__.select("b"), Order.desc).select("a"); } } }
JeraKrs/ACM
codes/UVA/01001-01999/uva1425.cpp
<reponame>JeraKrs/ACM #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int N = 55; const double eps = 1e-9; struct point { double x, y; }p[N]; int n, dp[N][N]; bool cmp (const point& a, const point& b) { return a.x < b.x; } bool judge (int a, int b, double d, int key) { for (int i = a + 1; i <= b; i++) { double tmp = p[a].y + d * (p[i].x - p[a].x); if (key == 0 && tmp - p[i].y > -eps) return false; if (key == 1 && tmp - p[i].y < eps) return false; } return true; } int solve () { memset(dp, 0, sizeof(dp)); dp[1][0] = dp[0][1] = 1; for (int i = 2; i < n-1; i++) { int u = i-1; for (int j = 0; j < u; j++) { dp[i][j] += dp[u][j]; dp[j][i] += dp[j][u]; double xi = p[i].x - p[j].x; double yi = p[i].y - p[j].y; double d = yi / xi; if (judge(j, u, d, 0)) dp[u][i] += dp[u][j]; if (judge(j, u, d, 1)) dp[i][u] += dp[j][u]; } } /* for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dp[i][j] && (i == n-2 || j == n-2)) { printf("%d %d: %d\n", i, j, dp[i][j]); } } } */ int ans = 0, u = n-1; for (int i = 0; i < u-1; i++) { double xi = p[u].x - p[i].x; double yi = p[u].y - p[i].y; double d = yi / xi; if (judge(i, u-1, d, 0)) ans += dp[u-1][i]; if (judge(i, u-1, d, 1)) ans += dp[i][u-1]; } return ans; } int main () { int cas; scanf("%d", &cas); while (cas--) { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%lf%lf", &p[i].x, &p[i].y); sort(p, p + n, cmp); printf("%d\n", solve()); } return 0; }
rmrsk/Chombo-3.3
lib/test/BoxTools/stdIVSThreadTest.cpp
<filename>lib/test/BoxTools/stdIVSThreadTest.cpp #ifdef CH_LANG_CC /* * _______ __ * / ___/ / ___ __ _ / / ___ * / /__/ _ \/ _ \/ V \/ _ \/ _ \ * \___/_//_/\___/_/_/_/_.__/\___/ * Please refer to Copyright.txt, in Chombo's root directory. */ #endif #include "REAL.H" #include "parstream.H" #include "LevelData.H" #include "LoadBalance.H" #include "FArrayBox.H" #include "StdSetIVS.H" #include "AMRIO.H" #include "BoxIterator.H" #include "BRMeshRefine.H" // contains domainSplit function #include "CH_Attach.H" #include "UsingNamespace.H" using std::endl; static bool verbose = true; /***************/ /***************/ void dumpmemoryatexit(); /***************/ /***************/ void parseTestOptions( int argc ,char* argv[] ) ; int threadTest(); int main(int argc,char **argv) { #ifdef CH_MPI MPI_Init(&argc, &argv); // registerDebugger(); #endif parseTestOptions( argc ,argv ) ; int retval = 0; retval = threadTest(); if (retval == 0) { pout() << "threadTest passed all tests!" << endl; } else { pout() << "threadTest failed at least one test, return value = " << retval << endl; } #ifdef CH_MPI MPI_Finalize(); #endif return retval; } int threadTest() { int domLength = 128; int maxBoxSize = 8; Box domainBox(IntVect::Zero, (domLength-1)*IntVect::Unit); // start with non-periodic case ProblemDomain domain(domainBox); pout() << "calling domainSplit" << std::endl; Vector<Box> gridBoxes; domainSplit(domainBox, gridBoxes, maxBoxSize); int numBoxes = gridBoxes.size(); Vector<int> procAssign(numBoxes,0); pout() << "calling loadbalance" << std::endl; // for mpi case, distribute boxes among processors LoadBalance(procAssign,gridBoxes); pout() << "calling dbl define" << std::endl; DisjointBoxLayout grids(gridBoxes, procAssign, domain); const int nComp = 1; IntVect ghostVect = IntVect::Unit; LevelData<FArrayBox> data(grids, nComp, ghostVect); StdSetIVS foo; foo |= gridBoxes[0]; const StdSetIVS sharedAndConst = foo; DataIterator dit = grids.dataIterator(); const int nbox = dit.size(); #pragma omp parallel for //schedule(dynamic) for(int ibox=0; ibox<nbox; ibox++) { FArrayBox& fab = data[dit[ibox]]; const Box& fbox = fab.box(); fab.setVal(0.0); StdSetIVS ivs1(fbox); for(StdSetIVSIterator ivit(ivs1); ivit.ok(); ++ivit) { const IntVect& iv = ivit(); fab(iv,0) = ibox; } Box inner = fbox; inner.grow(-1); StdSetIVS ivs2 = ivs1; ivs2 &= inner; for(StdSetIVSIterator ivit(ivs2); ivit.ok(); ++ivit) { const IntVect& iv = ivit(); fab(iv,0) = -ibox; } //#pragma omp critical { StdSetIVS ivs3 = sharedAndConst; ivs3 &= grids.get(dit[ibox]); ivs3 |= grids.get(dit[ibox]); for(StdSetIVSIterator ivit(ivs3); ivit.ok(); ++ivit) { const IntVect& iv = ivit(); fab(iv,0) = 0.5; } } } #ifdef CH_USE_HDF5 writeLevel(&data); #endif return 0; } /// // Parse the standard test options (-v -q) out of the command line. // Stop parsing when a non-option argument is found. /// void parseTestOptions( int argc ,char* argv[] ) { for ( int i = 1 ; i < argc ; ++i ) { if ( argv[i][0] == '-' ) //if it is an option { // compare 3 chars to differentiate -x from -xx if ( strncmp( argv[i] ,"-v" ,3 ) == 0 ) { verbose = true ; // argv[i] = "" ; } else if ( strncmp( argv[i] ,"-q" ,3 ) == 0 ) { verbose = false ; // argv[i] = "" ; } else { break ; } } } return ; }
duke-office-research-informatics/dracs
__tests__/buttons/base/baseTest.js
<reponame>duke-office-research-informatics/dracs import React from "react"; import { mountWithTheme } from "../../../config/scUtils.js"; import { axe } from "jest-axe"; import { Button, IconMenu, theme } from "../../../lib/dracs.es.js"; const mockFn = jest.fn(); describe("base Button", () => { it("matches snapshot", () => { const wrapper = mountWithTheme(<Button label="hello" />); expect(wrapper).toMatchSnapshot(); expect(wrapper.text()).toBe("hello"); }); it("returns no a11y violations", async () => { const wrapper = mountWithTheme(<Button label="hello" />); const results = await axe(wrapper.html()); expect(results).toHaveNoViolations(); }); it("applies the correct styles with no props declared", () => { const wrapper = mountWithTheme(<Button label="hello" />); const btn = wrapper.find("button__StyledBtn"); expect(btn).toHaveStyleRule("display", "flex"); expect(btn).toHaveStyleRule("flex", "0 0 auto"); expect(btn).toHaveStyleRule("justify-content", "center"); expect(btn).toHaveStyleRule("align-items", "center"); expect(btn).toHaveStyleRule("height", "36px"); expect(btn).toHaveStyleRule("line-height", "2.8em"); expect(btn).toHaveStyleRule("white-space", "nowrap"); expect(btn).toHaveStyleRule("min-width", "64px"); expect(btn).toHaveStyleRule("padding", "0 8px"); expect(btn).toHaveStyleRule("font-size", "0.875em"); expect(btn).toHaveStyleRule("font-weight", "400"); expect(btn).toHaveStyleRule("letter-spacing", "0.075em"); expect(btn).toHaveStyleRule("text-transform", "uppercase"); expect(btn).toHaveStyleRule("transition", "all 0.2s ease-in-out"); expect(btn).toHaveStyleRule("backface-visibility", "hidden"); expect(btn).toHaveStyleRule("cursor", "pointer"); expect(btn).toHaveStyleRule("border-radius", "2px"); expect(btn).toHaveStyleRule("appearance", "none"); expect(btn).toHaveStyleRule("background", "none"); expect(btn).toHaveStyleRule("border", "0"); expect(btn).toHaveStyleRule("box-shadow", "none"); expect(btn).toHaveStyleRule("text-decoration", "none"); expect(btn).toHaveStyleRule("user-select", "none"); expect(btn).toHaveStyleRule("color", theme.colors.action); expect(btn).toHaveStyleRule("background-color", theme.colors.bg); expect(btn).toHaveStyleRule("-webkit-font-smoothing", "inherit"); expect(btn).toHaveStyleRule("fill", theme.colors.action, { modifier: "svg", }); expect(btn).toHaveStyleRule("color", theme.colors.actionHover, { modifier: ":hover", }); expect(btn).toHaveStyleRule("color", theme.colors.actionHover, { modifier: ":focus", }); expect(btn).toHaveStyleRule("background-color", theme.colors.bg, { modifier: ":hover", }); expect(btn).toHaveStyleRule("background-color", theme.colors.bg, { modifier: ":focus", }); expect(btn).toHaveStyleRule("fill", theme.colors.actionHover, { modifier: ":hover svg", }); expect(btn).toHaveStyleRule("fill", theme.colors.actionHover, { modifier: ":focus svg", }); expect(btn).toHaveStyleRule("outline-offset", "2px", { modifier: ":focus", }); expect(btn).toHaveStyleRule("outline", "dotted 1px rgb(59,153,252)", { modifier: ":focus", }); }); it("applies a background color via props", () => { const wrapper = mountWithTheme( <Button label="hello" bgColor={theme.colors.muted} /> ); expect(wrapper).toMatchSnapshot(); const btn = wrapper.find("button__StyledBtn"); expect(btn).toHaveStyleRule("background-color", theme.colors.muted); }); it("applies a :hover(background-color) via props", () => { const wrapper = mountWithTheme( <Button label="hello" bgHoverColor={theme.colors.muted} /> ); expect(wrapper).toMatchSnapshot(); const btn = wrapper.find("button__StyledBtn"); expect(btn).toHaveStyleRule("background-color", theme.colors.muted, { modifier: ":focus", }); }); it("applies a classname via props", () => { const wrapper = mountWithTheme(<Button label="hello" className="aclass" />); expect(wrapper).toMatchSnapshot(); const btn = wrapper.find("button__StyledBtn"); expect(btn.hasClass("aclass")).toBe(true); }); it("applies the correct styles when `dense` is set to true", () => { const wrapper = mountWithTheme(<Button label="hello" dense />); expect(wrapper).toMatchSnapshot(); const btn = wrapper.find("button__StyledBtn"); expect(btn).toHaveStyleRule("height", "32px"); expect(btn).toHaveStyleRule("line-height", "2.5em"); }); it("applies an html id via props", () => { const wrapper = mountWithTheme(<Button label="hello" id="anid" />); expect(wrapper).toMatchSnapshot(); expect(wrapper.find("#anid")).toBeDefined(); }); it("applies a label color via props", () => { const wrapper = mountWithTheme( <Button label="hello" labelColor={theme.colors.muted} /> ); expect(wrapper).toMatchSnapshot(); const btn = wrapper.find("button__StyledBtn"); expect(btn).toHaveStyleRule("color", theme.colors.muted); }); it("applies the labelColor as the fill color to an svg passed via the label prop", () => { const wrapper = mountWithTheme(<Button label={<IconMenu />} />); expect(wrapper).toMatchSnapshot(); expect(wrapper.find("button__StyledBtn")).toHaveStyleRule( "fill", theme.colors.action, { modifier: "svg", } ); }); it("applies a label hover color via props", () => { const wrapper = mountWithTheme( <Button label="hello" labelHoverColor={theme.colors.muted} /> ); expect(wrapper).toMatchSnapshot(); const btn = wrapper.find("button__StyledBtn"); expect(btn).toHaveStyleRule("color", theme.colors.muted, { modifier: ":hover", }); }); it("applies the labelHoverColor as the fill color to an svg passed via the label prop", () => { const wrapper = mountWithTheme(<Button label={<IconMenu />} />); expect(wrapper).toMatchSnapshot(); expect(wrapper.find("button__StyledBtn")).toHaveStyleRule( "fill", theme.colors.actionHover, { modifier: ":hover svg", } ); expect(wrapper.find("button__StyledBtn")).toHaveStyleRule( "fill", theme.colors.actionHover, { modifier: ":focus svg", } ); }); it("applies a media query via props", () => { const wrapper = mountWithTheme( <Button label="hello" mediaQuery="@media(max-width:768px){width:30px}" /> ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find("button__StyledBtn")).toHaveStyleRule("width", "30px", { media: "(max-width:768px)", }); }); it("applies the html name attribute via props", () => { const wrapper = mountWithTheme(<Button label="hello" name="testName" />); expect(wrapper).toMatchSnapshot(); expect(wrapper.find("testName")).toBeDefined(); }); it("applies an onBlur function via props and triggers that function on blur", () => { const wrapper = mountWithTheme(<Button label="hello" onBlur={mockFn} />); expect(wrapper).toMatchSnapshot(); wrapper.simulate("blur"); expect(mockFn).toHaveBeenCalled(); }); it("applies an onClick function via props and triggers that function on click", () => { const wrapper = mountWithTheme(<Button label="hello" onClick={mockFn} />); expect(wrapper).toMatchSnapshot(); wrapper.simulate("click"); expect(mockFn).toHaveBeenCalled(); }); it("applies an onFocus function via props and triggers that function on focus", () => { const wrapper = mountWithTheme(<Button label="hello" onFocus={mockFn} />); expect(wrapper).toMatchSnapshot(); wrapper.simulate("focus"); expect(mockFn).toHaveBeenCalled(); }); it("applies an onMouseDown function via props and triggers that function on MouseDown", () => { const wrapper = mountWithTheme( <Button label="hello" onMouseDown={mockFn} /> ); expect(wrapper).toMatchSnapshot(); wrapper.simulate("mousedown"); expect(mockFn).toHaveBeenCalled(); }); it("applies an onMouseEnter function via props and triggers that function on MouseEnter", () => { const wrapper = mountWithTheme( <Button label="hello" onMouseEnter={mockFn} /> ); expect(wrapper).toMatchSnapshot(); wrapper.simulate("mouseenter"); expect(mockFn).toHaveBeenCalled(); }); it("applies an onMouseLeave function via props and triggers that function on MouseLeave", () => { const wrapper = mountWithTheme( <Button label="hello" onMouseLeave={mockFn} /> ); expect(wrapper).toMatchSnapshot(); wrapper.simulate("mouseleave"); expect(mockFn).toHaveBeenCalled(); }); it("applies an onMouseUp function via props and triggers that function on MouseUp", () => { const wrapper = mountWithTheme(<Button label="hello" onMouseUp={mockFn} />); expect(wrapper).toMatchSnapshot(); wrapper.simulate("mouseup"); expect(mockFn).toHaveBeenCalled(); }); it("applies an onTouchStart function via props and triggers that function on TouchStart", () => { const wrapper = mountWithTheme( <Button label="hello" onTouchStart={mockFn} /> ); expect(wrapper).toMatchSnapshot(); wrapper.simulate("blur"); expect(mockFn).toHaveBeenCalled(); }); it("applies an onTouchEnd function via props and triggers that function on TouchEnd", () => { const wrapper = mountWithTheme(<Button label="hello" onBlur={mockFn} />); expect(wrapper).toMatchSnapshot(); wrapper.simulate("touchend"); expect(mockFn).toHaveBeenCalled(); }); it("applies a style object via props", () => { const wrapper = mountWithTheme( <Button label="hello" style={{ width: "30px" }} /> ); expect(wrapper).toMatchSnapshot(); expect(wrapper.find("button__StyledBtn").props().style).toHaveProperty( "width", "30px" ); }); describe("button type", () => { it("matches snapshot when button type = `filled`", () => { const wrapper = mountWithTheme(<Button label="hello" type="filled" />); expect(wrapper).toMatchSnapshot(); }); it("matches snapshot when button type = `inverted`", () => { const wrapper = mountWithTheme(<Button label="hello" type="inverted" />); expect(wrapper).toMatchSnapshot(); }); it("matches snapshot when button type = `error`", () => { const wrapper = mountWithTheme(<Button label="hello" type="error" />); expect(wrapper).toMatchSnapshot(); }); it("matches snapshot when button type = `errorFilled`", () => { const wrapper = mountWithTheme( <Button label="hello" type="errorFilled" /> ); expect(wrapper).toMatchSnapshot(); }); it("matches snapshot when button type = `disabled`", () => { const wrapper = mountWithTheme(<Button label="hello" type="disabled" />); expect(wrapper).toMatchSnapshot(); }); it("matches snapshot when button type = `disabledFilled`", () => { const wrapper = mountWithTheme( <Button label="hello" type="disabledFilled" /> ); expect(wrapper).toMatchSnapshot(); }); it("matches snapshot when button type = `flat`", () => { const wrapper = mountWithTheme(<Button label="hello" type="flat" />); expect(wrapper).toMatchSnapshot(); }); }); });
melf-xyzh/gin-start
menu/model/menu.go
<gh_stars>10-100 /** * @Time :2022/3/6 18:24 * @Author :MELF晓宇 * @Email :<EMAIL> * @FileName:menu.go * @Project :gin-start * @Blog :https://blog.csdn.net/qq_29537269 * @Guide :https://guide.melf.space * @Information: * */ package model import "github.com/melf-xyzh/gin-start/global" type Menu struct { global.Model MenuName string Sort uint Url string RouterName string IsShow int }
SethTisue/http4s
core/src/main/scala/org/http4s/package.scala
<reponame>SethTisue/http4s<gh_stars>0 package org import scalaz.{Kleisli, EitherT, \/} import scalaz.concurrent.Task import scalaz.stream.Process import org.http4s.util.CaseInsensitiveString import scodec.bits.ByteVector package object http4s { // scalastyle:ignore type AuthScheme = CaseInsensitiveString type EntityBody = Process[Task, ByteVector] def EmptyBody: EntityBody = Process.halt type DecodeResult[T] = EitherT[Task, DecodeFailure, T] val ApiVersion: Http4sVersion = Http4sVersion(BuildInfo.apiVersion._1, BuildInfo.apiVersion._2) type ParseResult[+A] = ParseFailure \/ A val DefaultCharset = Charset.`UTF-8` /** * A Service wraps a function of request type `A` to a Task that runs * to response type `B`. By wrapping the [[Service]], we can compose them * using Kleisli operations. */ type Service[A, B] = Kleisli[Task, A, B] /** * A [[Service]] that produces a Task to compute a [[Response]] from a * [[Request]]. An HttpService can be run on any supported http4s * server backend, such as Blaze, Jetty, or Tomcat. */ type HttpService = Service[Request, Response] type AuthedService[T] = Service[AuthedRequest[T], Response] /* Lives here to work around https://issues.scala-lang.org/browse/SI-7139 */ object HttpService { /** * Lifts a total function to an `HttpService`. The function is expected to * handle all requests it is given. If `f` is a `PartialFunction`, use * `apply` instead. */ def lift(f: Request => Task[Response]): HttpService = Service.lift(f) /** Lifts a partial function to an `HttpService`. Responds with * [[org.http4s.Response.fallthrough]], which generates a 404, for any request * where `pf` is not defined. */ def apply(pf: PartialFunction[Request, Task[Response]]): HttpService = lift(req => pf.applyOrElse(req, Function.const(Response.fallthrough))) @deprecated("Use Response.fallthrough instead", "0.15") val notFound: Task[Response] = Response.fallthrough val empty: HttpService = Service.const(Response.fallthrough) } object AuthedService { private [this] val _empty: AuthedService[Any] = Service.const(Response.fallthrough) /** * Lifts a total function to an `HttpService`. The function is expected to * handle all requests it is given. If `f` is a `PartialFunction`, use * `apply` instead. */ def lift[T](f: AuthedRequest[T] => Task[Response]): AuthedService[T] = Service.lift(f) /** Lifts a partial function to an `AuthedService`. Responds with * [[org.http4s.Response.fallthrough]], which generates a 404, for any request * where `pf` is not defined. */ def apply[T](pf: PartialFunction[AuthedRequest[T], Task[Response]]): AuthedService[T] = lift(req => pf.applyOrElse(req, Function.const(Response.fallthrough))) /** * The empty service (all requests fallthrough). * * @tparam T - ignored. * @return */ def empty[T]: AuthedService[T] = _empty.asInstanceOf[AuthedService[T]] // OK as `T` isn't used here. } type Callback[A] = Throwable \/ A => Unit /** A stream of server-sent events */ type EventStream = Process[Task, ServerSentEvent] }
Jorch72/PerFabricaAdAstra
src/main/java/org/pfaa/chemica/Chemica.java
package org.pfaa.chemica; import org.apache.logging.log4j.Logger; import org.pfaa.chemica.integration.ModIntegration; import org.pfaa.core.registration.Registrant; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; @Mod(modid = "PFAAChemica", useMetadata = true) public class Chemica { @Instance("PFAAChemica") public static Chemica instance; public static Chemica getInstance() { return instance; } @SidedProxy(clientSide = "org.pfaa.chemica.client.registration.ClientRegistrant", serverSide = "org.pfaa.chemica.registration.CommonRegistrant") public static Registrant registrant; public static Logger log; private static ChemicaConfiguration configuration; public static ChemicaConfiguration getConfiguration() { return configuration; } @EventHandler public void preload(FMLPreInitializationEvent event) { log = event.getModLog(); configuration = new ChemicaConfiguration(event.getSuggestedConfigurationFile()); registrant.preregister(); } @EventHandler public void load(FMLInitializationEvent event) { ModIntegration.init(); registrant.register(); } @EventHandler public void postload(FMLPostInitializationEvent event) { registrant.postregister(); configuration.save(); } }
c4s4/neon
neon/task/assert.go
<reponame>c4s4/neon package task import ( "fmt" "github.com/c4s4/neon/neon/build" "reflect" ) func init() { build.AddTask(build.TaskDesc{ Name: "assert", Func: assert, Args: reflect.TypeOf(assertArgs{}), Help: `Make an assertion and fail if assertion is false. Arguments: - assert: the assertion to perform (boolean, expression). Examples: # assert that foo == "bar", and fail otherwise - assert: 'foo == "bar"'`, }) } type assertArgs struct { Assert bool `neon:"expression"` } func assert(context *build.Context, args interface{}) error { params := args.(assertArgs) if !params.Assert { return fmt.Errorf("assertion failed") } return nil }
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
src/graphics/display/drivers/amlogic-display/osd.h
<reponame>EnderNightLord-ChromeBook/fuchsia-pine64-pinephone // Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SRC_GRAPHICS_DISPLAY_DRIVERS_AMLOGIC_DISPLAY_OSD_H_ #define SRC_GRAPHICS_DISPLAY_DRIVERS_AMLOGIC_DISPLAY_OSD_H_ #include <lib/device-protocol/platform-device.h> #include <lib/inspect/cpp/inspect.h> #include <lib/mmio/mmio.h> #include <lib/zircon-internal/thread_annotations.h> #include <lib/zx/bti.h> #include <lib/zx/handle.h> #include <lib/zx/interrupt.h> #include <lib/zx/pmt.h> #include <threads.h> #include <zircon/compiler.h> #include <zircon/types.h> #include <cstdint> #include <optional> #include <ddk/protocol/platform/device.h> #include <ddktl/protocol/display/controller.h> #include <fbl/auto_lock.h> #include <fbl/condition_variable.h> #include <fbl/mutex.h> #include "common.h" namespace amlogic_display { struct RdmaTable { uint32_t reg; uint32_t val; }; /* * This is the RDMA table index. Each index points to a specific VPU register. * RDMA engine will be programmed to update all those registers at vsync time. * Since all the fields will be updated at vsync time, we need to make sure all * the fields are updated with a valid value when FlipOnVsync is called. */ enum { IDX_BLK0_CFG_W0, IDX_CTRL_STAT, IDX_CTRL_STAT2, IDX_MATRIX_COEF00_01, IDX_MATRIX_COEF02_10, IDX_MATRIX_COEF11_12, IDX_MATRIX_COEF20_21, IDX_MATRIX_COEF22, IDX_MATRIX_OFFSET0_1, IDX_MATRIX_OFFSET2, IDX_MATRIX_PRE_OFFSET0_1, IDX_MATRIX_PRE_OFFSET2, IDX_MATRIX_EN_CTRL, IDX_GAMMA_EN, IDX_BLK2_CFG_W4, IDX_MALI_UNPACK_CTRL, IDX_PATH_MISC_CTRL, IDX_AFBC_HEAD_BUF_ADDR_LOW, IDX_AFBC_HEAD_BUF_ADDR_HIGH, IDX_AFBC_SURFACE_CFG, // This should be the last element to make sure the entire config // was written IDX_RDMA_CFG_STAMP_HIGH, IDX_RDMA_CFG_STAMP_LOW, IDX_MAX, }; static_assert(IDX_RDMA_CFG_STAMP_HIGH == (IDX_MAX - 2), "Invalid RDMA Index Table"); static_assert(IDX_RDMA_CFG_STAMP_LOW == (IDX_MAX - 1), "Invalid RDMA Index Table"); // Table size for non-AFBC RDMA constexpr size_t kTableSize = (IDX_MAX * sizeof(RdmaTable)); // Single element table for AFBC RDMA constexpr size_t kAfbcTableSize = sizeof(RdmaTable); // Non-AFBC RDMA Region size constexpr size_t kRdmaRegionSize = ZX_PAGE_SIZE; // AFBC RDMA Region Size constexpr size_t kAfbcRdmaRegionSize = ZX_PAGE_SIZE; // Arbitrarily limit table size to maximum 16 constexpr uint32_t kNumberOfTables = std::min(16ul, (kRdmaRegionSize / (kTableSize))); // We should have space for at least 3 tables. If RDMA table has grown too large and cannot // fit more than 3 tables within a PAGE_SIZE, we need to either: // - Re-evaluate why RDMA table has grown so large // - Create a larger RDMA table allocation static_assert(kNumberOfTables >= 3, "RDMA table is too large"); // This value indicates an available entry into the RDMA table constexpr uint64_t kRdmaTableReady = UINT64_MAX - 1; // An entry is marked as unavailable temporarily when there are unapplied configs. This will ensure // new configs are added to end of table since RDMA requires physical contiguous entries constexpr uint64_t kRdmaTableUnavailable = UINT64_MAX; // Use RDMA Channel used constexpr uint8_t kRdmaChannel = 0; // RDMA Channel 7 will be dedicated to AFBC Trigger constexpr uint8_t kAfbcRdmaChannel = 7; enum class GammaChannel { kRed, kGreen, kBlue, }; struct RdmaChannelContainer { zx_paddr_t phys_offset; // offset into physical address uint8_t* virt_offset; // offset into virtual address (vmar buf) }; /* * RDMA Operation Design (non-AFBC): * Allocate kRdmaRegionSize of physical contiguous memory. This region will include * kNumberOfTables of RDMA Tables. * RDMA Tables will get populated with <reg><val> pairs. The last element will be a unique * stamp for a given configuration. The stamp is used to verify how far the RDMA channel was able * to write at vsync time. * _______________ * |<reg><val> | * |<reg><val> | * |... | * |<Config Stamp> | * |_______________| * |<reg><val> | * |<reg><val> | * |... | * |<Config Stamp> | * |_______________| * . * . * . * |<reg><val> | * |<reg><val> | * |... | * |<Config Stamp> | * |_______________| * |<reg><val> | * |<reg><val> | * |... | * |<Config Stamp> | * |_______________| * * The physical and virtual addresses of the above tables are stored in rdma_chnl_container_ * * Each table contains a specific configuration to be applied at Vsync time. RDMA is programmed * to read from [start_index_used_ end_index_used_] inclusive. If more than one configuration is * applied within a vsync period, the new configuration will get added at the * next sequential index and RDMA end_index_used_ will get updated. * * rdma_usage_table_ is used to keep track of tables being used by RDMA. rdma_usage_table_ may * contain three possible values: * kRdmaTableReady: This index may be used by RDMA * kRdmaTableUnavailable: This index is unavailble * <config stamp>: This index is includes a valid config * * When RDMA completes, RdmaThread (which processes RDMA IRQs) checks how far the RDMA was able to * write by comparing the "Config Stamp" in a scratch register to rdma_usage_table_. If RDMA did * not apply all the configs, it will re-schedule a new RDMA transaction. * RdmaThread will also signal the Vsync thread and provide the most recent applied configuration * (latest_applied_config_) */ class Osd { public: Osd(uint32_t fb_width, uint32_t fb_height, uint32_t display_width, uint32_t display_height, inspect::Node* parent_node) : fb_width_(fb_width), fb_height_(fb_height), display_width_(display_width), display_height_(display_height), inspect_node_(parent_node->CreateChild("osd")), rdma_allocation_failures_(inspect_node_.CreateUint("rdma_allocation_failures", 0)) {} zx_status_t Init(zx_device_t* parent); void HwInit(); void Disable(); void Enable(); // This function will apply configuration when VSYNC interrupt occurs using RDMA void FlipOnVsync(uint8_t idx, const display_config_t* config); void Dump(); void Release(); void DumpRdmaState() __TA_REQUIRES(rdma_lock_); // This function converts a float into Signed fixed point 3.10 format // [12][11:10][9:0] = [sign][integer][fraction] static uint32_t FloatToFixed3_10(float f); // This function converts a float into Signed fixed point 2.10 format // [11][10][9:0] = [sign][integer][fraction] static uint32_t FloatToFixed2_10(float f); static constexpr size_t kGammaTableSize = 256; void SetMinimumRgb(uint8_t minimum_rgb); // This function is used by vsync thread to determine the latest config applied uint64_t GetLastImageApplied(); private: void DefaultSetup(); // this function sets up scaling based on framebuffer and actual display // dimensions. The scaling IP and registers and undocumented. void EnableScaling(bool enable); void StopRdma(); zx_status_t SetupRdma(); void ResetRdmaTable(); void SetRdmaTableValue(uint32_t table_index, uint32_t idx, uint32_t val); void FlushRdmaTable(uint32_t table_index); void SetAfbcRdmaTableValue(uint32_t val) const; void FlushAfbcRdmaTable() const; int RdmaThread(); void EnableGamma(); void DisableGamma(); zx_status_t ConfigAfbc(); zx_status_t SetGamma(GammaChannel channel, const float* data); zx_status_t WaitForGammaAddressReady(); zx_status_t WaitForGammaWriteReady(); int GetNextAvailableRdmaTableIndex(); std::optional<ddk::MmioBuffer> vpu_mmio_; pdev_protocol_t pdev_ = {nullptr, nullptr}; zx::bti bti_; // RDMA IRQ handle and thread zx::interrupt rdma_irq_; thrd_t rdma_thread_; fbl::Mutex rdma_lock_; fbl::ConditionVariable rdma_active_cnd_ TA_GUARDED(rdma_lock_); uint64_t rdma_usage_table_[kNumberOfTables]; size_t start_index_used_ TA_GUARDED(rdma_lock_) = 0; size_t end_index_used_ TA_GUARDED(rdma_lock_) = 0; bool rdma_active_ TA_GUARDED(rdma_lock_) = false; uint64_t latest_applied_config_ TA_GUARDED(rdma_lock_) = 0; RdmaChannelContainer rdma_chnl_container_[kNumberOfTables]; // use a single vmo for all channels zx::vmo rdma_vmo_; zx::pmt rdma_pmt_; zx_paddr_t rdma_phys_; uint8_t* rdma_vbuf_; // Container that holds AFBC specific trigger register RdmaChannelContainer afbc_rdma_chnl_container_; zx::vmo afbc_rdma_vmo_; zx_handle_t afbc_rdma_pmt_; zx_paddr_t afbc_rdma_phys_; uint8_t* afbc_rdma_vbuf_; // Framebuffer dimension uint32_t fb_width_; uint32_t fb_height_; // Actual display dimension uint32_t display_width_; uint32_t display_height_; // This flag is set when the driver enables gamma correction. // If this flag is not set, we should not disable gamma in the absence // of a gamma table since that might have been provided by earlier boot stages. bool osd_enabled_gamma_ = false; bool initialized_ = false; inspect::Node inspect_node_; inspect::UintProperty rdma_allocation_failures_; }; } // namespace amlogic_display #endif // SRC_GRAPHICS_DISPLAY_DRIVERS_AMLOGIC_DISPLAY_OSD_H_
stephenlawrence/gravity
web/src/app/modules/settings/flux/tls/store.js
/* Copyright 2018 Gravitational, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { Record } from 'immutable'; import { Store, toImmutable } from 'nuclear-js'; import { SETTINGS_CERT_RECEIVE } from './actionTypes'; export class TlsCert extends Record({ issued_by: null, issued_to: null, validity: null, }) { constructor(props) { super(props); } getByCn() { return this.getIn(['issued_by', 'cn']); } getByOrg() { let org = this.getIn(['issued_by', 'org']); org = org ? org.toJS() : []; return org.join(', '); } getByOrgUnit() { return this.getIn(['issued_by', 'org_unit']); } getToCn() { return this.getIn(['issued_to', 'cn']); } getToOrgUnit() { return this.getIn(['issued_to', 'org_unit']); } getToOrg() { let org = this.getIn(['issued_to', 'org']); org = org ? org.toJS() : []; return org.join(', '); } getStartDate() { let date = this.getIn(['validity', 'not_before']); return new Date(date).toUTCString(); } getEndDate() { let date = this.getIn(['validity', 'not_after']); return new Date(date).toUTCString(); } } export default Store({ getInitialState() { return new TlsCert(); }, initialize() { this.on(SETTINGS_CERT_RECEIVE, setTlsCert); } }) function setTlsCert(state, json) { return new TlsCert(toImmutable(json)); }
ckamtsikis/cmssw
DataFormats/TrackerRecHit2D/src/FastTrackerRecHit.cc
#include "DataFormats/TrackerRecHit2D/interface/FastTrackerRecHit.h" #include "DataFormats/TrackerRecHit2D/interface/OmniClusterRef.h" namespace { const OmniClusterRef nullRef; } OmniClusterRef const& FastTrackerRecHit::firstClusterRef() const { return nullRef; }
JaneMandy/CS
org/apache/xalan/client/XSLTProcessorApplet.java
package org.apache.xalan.client; import java.applet.Applet; import java.awt.Graphics; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.Hashtable; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.xalan.res.XSLMessages; public class XSLTProcessorApplet extends Applet { TransformerFactory m_tfactory = null; private String m_styleURL; private String m_documentURL; private final String PARAM_styleURL = "styleURL"; private final String PARAM_documentURL = "documentURL"; private String m_styleURLOfCached = null; private String m_documentURLOfCached = null; private URL m_codeBase = null; private String m_treeURL = null; private URL m_documentBase = null; private transient Thread m_callThread = null; private transient XSLTProcessorApplet.TrustedAgent m_trustedAgent = null; private transient Thread m_trustedWorker = null; private transient String m_htmlText = null; private transient String m_sourceText = null; private transient String m_nameOfIDAttrOfElemToModify = null; private transient String m_elemIdToModify = null; private transient String m_attrNameToSet = null; private transient String m_attrValueToSet = null; private Enumeration m_keys; transient Hashtable m_parameters; public String getAppletInfo() { return "Name: XSLTProcessorApplet\r\nAuthor: <NAME>"; } public String[][] getParameterInfo() { String[][] info = new String[][]{{"styleURL", "String", "URL to an XSL stylesheet"}, {"documentURL", "String", "URL to an XML document"}}; return info; } public void init() { String param = this.getParameter("styleURL"); this.m_parameters = new Hashtable(); if (param != null) { this.setStyleURL(param); } param = this.getParameter("documentURL"); if (param != null) { this.setDocumentURL(param); } this.m_codeBase = this.getCodeBase(); this.m_documentBase = this.getDocumentBase(); this.resize(320, 240); } public void start() { this.m_trustedAgent = new XSLTProcessorApplet.TrustedAgent(); Thread currentThread = Thread.currentThread(); this.m_trustedWorker = new Thread(currentThread.getThreadGroup(), this.m_trustedAgent); this.m_trustedWorker.start(); try { this.m_tfactory = TransformerFactory.newInstance(); this.showStatus("Causing Transformer and Parser to Load and JIT..."); StringReader xmlbuf = new StringReader("<?xml version='1.0'?><foo/>"); StringReader xslbuf = new StringReader("<?xml version='1.0'?><xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'><xsl:template match='foo'><out/></xsl:template></xsl:stylesheet>"); PrintWriter pw = new PrintWriter(new StringWriter()); TransformerFactory var5 = this.m_tfactory; synchronized(var5) { Templates templates = this.m_tfactory.newTemplates(new StreamSource(xslbuf)); Transformer transformer = templates.newTransformer(); transformer.transform(new StreamSource(xmlbuf), new StreamResult(pw)); } System.out.println("Primed the pump!"); this.showStatus("Ready to go!"); } catch (Exception var10) { this.showStatus("Could not prime the pump!"); System.out.println("Could not prime the pump!"); var10.printStackTrace(); } } public void paint(Graphics g) { } public void stop() { if (null != this.m_trustedWorker) { this.m_trustedWorker.stop(); this.m_trustedWorker = null; } this.m_styleURLOfCached = null; this.m_documentURLOfCached = null; } public void destroy() { if (null != this.m_trustedWorker) { this.m_trustedWorker.stop(); this.m_trustedWorker = null; } this.m_styleURLOfCached = null; this.m_documentURLOfCached = null; } public void setStyleURL(String urlString) { this.m_styleURL = urlString; } public void setDocumentURL(String urlString) { this.m_documentURL = urlString; } public void freeCache() { this.m_styleURLOfCached = null; this.m_documentURLOfCached = null; } public void setStyleSheetAttribute(String nameOfIDAttrOfElemToModify, String elemId, String attrName, String value) { this.m_nameOfIDAttrOfElemToModify = nameOfIDAttrOfElemToModify; this.m_elemIdToModify = elemId; this.m_attrNameToSet = attrName; this.m_attrValueToSet = value; } public void setStylesheetParam(String key, String expr) { this.m_parameters.put(key, expr); } public String escapeString(String s) { StringBuffer sb = new StringBuffer(); int length = s.length(); for(int i = 0; i < length; ++i) { char ch = s.charAt(i); if ('<' == ch) { sb.append("&lt;"); } else if ('>' == ch) { sb.append("&gt;"); } else if ('&' == ch) { sb.append("&amp;"); } else if ('\ud800' <= ch && ch < '\udc00') { if (i + 1 >= length) { throw new RuntimeException(XSLMessages.createMessage("ER_INVALID_UTF16_SURROGATE", new Object[]{Integer.toHexString(ch)})); } ++i; int next = s.charAt(i); if ('\udc00' > next || next >= '\ue000') { throw new RuntimeException(XSLMessages.createMessage("ER_INVALID_UTF16_SURROGATE", new Object[]{Integer.toHexString(ch) + " " + Integer.toHexString(next)})); } int next = (ch - '\ud800' << 10) + next - '\udc00' + 65536; sb.append("&#x"); sb.append(Integer.toHexString(next)); sb.append(";"); } else { sb.append(ch); } } return sb.toString(); } public String getHtmlText() { this.m_trustedAgent.m_getData = true; this.m_callThread = Thread.currentThread(); try { Thread var1 = this.m_callThread; synchronized(var1) { this.m_callThread.wait(); } } catch (InterruptedException var4) { System.out.println(var4.getMessage()); } return this.m_htmlText; } public String getTreeAsText(String treeURL) throws IOException { this.m_treeURL = treeURL; this.m_trustedAgent.m_getData = true; this.m_trustedAgent.m_getSource = true; this.m_callThread = Thread.currentThread(); try { Thread var2 = this.m_callThread; synchronized(var2) { this.m_callThread.wait(); } } catch (InterruptedException var5) { System.out.println(var5.getMessage()); } return this.m_sourceText; } private String getSource() throws TransformerException { StringWriter osw = new StringWriter(); PrintWriter pw = new PrintWriter(osw, false); String text = ""; try { URL docURL = new URL(this.m_documentBase, this.m_treeURL); TransformerFactory var5 = this.m_tfactory; synchronized(var5) { Transformer transformer = this.m_tfactory.newTransformer(); StreamSource source = new StreamSource(docURL.toString()); StreamResult result = new StreamResult(pw); transformer.transform(source, result); text = osw.toString(); } } catch (MalformedURLException var11) { var11.printStackTrace(); System.exit(-1); } catch (Exception var12) { var12.printStackTrace(); } return text; } public String getSourceTreeAsText() throws Exception { return this.getTreeAsText(this.m_documentURL); } public String getStyleTreeAsText() throws Exception { return this.getTreeAsText(this.m_styleURL); } public String getResultTreeAsText() throws Exception { return this.escapeString(this.getHtmlText()); } public String transformToHtml(String doc, String style) { if (null != doc) { this.m_documentURL = doc; } if (null != style) { this.m_styleURL = style; } return this.getHtmlText(); } public String transformToHtml(String doc) { if (null != doc) { this.m_documentURL = doc; } this.m_styleURL = null; return this.getHtmlText(); } private String processTransformation() throws TransformerException { String htmlData = null; this.showStatus("Waiting for Transformer and Parser to finish loading and JITing..."); TransformerFactory var2 = this.m_tfactory; synchronized(var2) { URL documentURL = null; URL styleURL = null; StringWriter osw = new StringWriter(); PrintWriter pw = new PrintWriter(osw, false); StreamResult result = new StreamResult(pw); this.showStatus("Begin Transformation..."); try { documentURL = new URL(this.m_codeBase, this.m_documentURL); StreamSource xmlSource = new StreamSource(documentURL.toString()); styleURL = new URL(this.m_codeBase, this.m_styleURL); StreamSource xslSource = new StreamSource(styleURL.toString()); Transformer transformer = this.m_tfactory.newTransformer(xslSource); this.m_keys = this.m_parameters.keys(); while(this.m_keys.hasMoreElements()) { Object key = this.m_keys.nextElement(); Object expression = this.m_parameters.get(key); transformer.setParameter((String)key, expression); } transformer.transform(xmlSource, result); } catch (TransformerConfigurationException var14) { var14.printStackTrace(); System.exit(-1); } catch (MalformedURLException var15) { var15.printStackTrace(); System.exit(-1); } this.showStatus("Transformation Done!"); htmlData = osw.toString(); return htmlData; } } class TrustedAgent implements Runnable { public boolean m_getData = false; public boolean m_getSource = false; public void run() { while(true) { XSLTProcessorApplet.this.m_trustedWorker; Thread.yield(); if (this.m_getData) { try { this.m_getData = false; XSLTProcessorApplet.this.m_htmlText = null; XSLTProcessorApplet.this.m_sourceText = null; if (this.m_getSource) { this.m_getSource = false; XSLTProcessorApplet.this.m_sourceText = XSLTProcessorApplet.this.getSource(); } else { XSLTProcessorApplet.this.m_htmlText = XSLTProcessorApplet.this.processTransformation(); } } catch (Exception var13) { var13.printStackTrace(); } finally { Thread var4 = XSLTProcessorApplet.this.m_callThread; synchronized(var4) { XSLTProcessorApplet.this.m_callThread.notify(); } } } else { try { XSLTProcessorApplet.this.m_trustedWorker; Thread.sleep(50L); } catch (InterruptedException var15) { var15.printStackTrace(); } } } } } }
joseluisbn/PythonLearningProject
src/inheritance.py
class Animal: # Attributes def __init__(self, name, specie, genre): # __init__ is the constructor self.name = name self.specie = specie self.genre = genre # Methods def eat(self): print(f"is eating") def sleep(self): print("Zzzzzzzz") class Bird(Animal): pass sparrow = Bird() sparrow.eat
gmai2006/fhir
src/main/java/org/fhir/dao/MedicationAdministrationDaoImpl.java
<filename>src/main/java/org/fhir/dao/MedicationAdministrationDaoImpl.java /* * #%L * FHIR Implementation * %% * Copyright (C) 2018 DataScience 9 LLC * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /** * This code is 100% AUTO generated. Please do not modify it DIRECTLY * If you need new features or function or changes please update the templates * then submit the template through our web interface. */ package org.fhir.dao; import static java.util.Objects.requireNonNull; import java.util.List; import java.util.logging.Logger; import org.fhir.entity.*; import javax.inject.Inject; import com.google.inject.persist.Transactional; import javax.persistence.EntityManager; import javax.persistence.Query; import com.google.inject.Provider; import org.fhir.entity.MedicationAdministrationModel; import org.fhir.pojo.MedicationAdministration; import org.fhir.pojo.MedicationAdministrationHelper; import org.fhir.utils.QueryBuilder; /** * Auto generated from the FHIR specification * generated on 07/12/2018 */ public class MedicationAdministrationDaoImpl implements MedicationAdministrationDao { private final Logger logger = Logger.getLogger(this.getClass().getName()); private final Provider<EntityManager> entityManagerProvider; @Inject public MedicationAdministrationDaoImpl (final Provider<EntityManager> entityManagerProvider) { requireNonNull(entityManagerProvider); this.entityManagerProvider = entityManagerProvider; } @Override public MedicationAdministration find(String id) { final EntityManager em = entityManagerProvider.get(); MedicationAdministrationModel model = em.find(MedicationAdministrationModel.class, id); if (null == model) return null; return new MedicationAdministration(model); } @Override public List<MedicationAdministration> select(int maxResult) { final EntityManager em = entityManagerProvider.get(); Query query = em.createQuery("select a from MedicationAdministrationModel a", MedicationAdministrationModel.class).setMaxResults(maxResult); List<MedicationAdministrationModel> models = query.getResultList(); return MedicationAdministrationHelper.fromArray2Array(models); } @Override public List<MedicationAdministration> selectAll() { final EntityManager em = entityManagerProvider.get(); Query query = em.createQuery("select a from MedicationAdministrationModel a", MedicationAdministrationModel.class); List<MedicationAdministrationModel> models = query.getResultList(); return MedicationAdministrationHelper.fromArray2Array(models); } @Override @Transactional public MedicationAdministration create(MedicationAdministration e) { final EntityManager em = entityManagerProvider.get(); em.persist(new MedicationAdministrationModel(e)); return e; } @Transactional public MedicationAdministration update(MedicationAdministration e) { final EntityManager em = entityManagerProvider.get(); MedicationAdministrationModel model = em.merge(new MedicationAdministrationModel(e)); return new MedicationAdministration(model); } @Override @Transactional public void delete(String id) { final EntityManager em = entityManagerProvider.get(); final MedicationAdministrationModel removed = em.find(MedicationAdministrationModel.class, id); em.remove(removed); } @Override public List<MedicationAdministration> findByDefinition(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, Reference b where a.definition_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByPartOf(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, Reference b where a.partOf_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByCategory(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, CodeableConcept b where a.category_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByMedicationCodeableConcept(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, CodeableConcept b where a.medicationCodeableConcept_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByMedicationReference(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, Reference b where a.medicationReference_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findBySubject(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, Reference b where a.subject_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByContext(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, Reference b where a.context_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findBySupportingInformation(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, Reference b where a.supportingInformation_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByPerformer(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, MedicationAdministrationPerformer b where a.performer_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByReasonNotGiven(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, CodeableConcept b where a.reasonNotGiven_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByReasonCode(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, CodeableConcept b where a.reasonCode_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByReasonReference(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, Reference b where a.reasonReference_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByPrescription(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, Reference b where a.prescription_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByDevice(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, Reference b where a.device_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByDosage(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, MedicationAdministrationDosage b where a.dosage_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByEventHistory(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, Reference b where a.eventHistory_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByText(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, Narrative b where a.text_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByMeta(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a, Meta b where a.meta_id=b.parent_id " + queryBuilder.getWhereClause(); return findByQuery(queryBuilder, queryStr); } @Override public List<MedicationAdministration> findByField(QueryBuilder queryBuilder) { final EntityManager em = entityManagerProvider.get(); final String queryStr = "select a from MedicationAdministrationModel a " + queryBuilder.getWhereClause(); logger.info(queryStr); return findByQuery(queryBuilder, queryStr); } private List<MedicationAdministration> findByQuery(QueryBuilder queryBuilder, String queryStr) { final EntityManager em = entityManagerProvider.get(); Query query = em.createQuery(queryStr, MedicationAdministrationModel.class); java.util.Map<String, Object> params = queryBuilder.getParams(); params.keySet() .stream() .forEach(key -> query.setParameter(key, params.get(key))); List<MedicationAdministrationModel> models = query.getResultList(); return MedicationAdministrationHelper.fromArray2Array(models); } }
shanemcd/coreos-assembler
tools/vendor/github.com/minio/console/models/object_legal_hold_status.go
<reponame>shanemcd/coreos-assembler // Code generated by go-swagger; DO NOT EDIT. // This file is part of MinIO Console Server // Copyright (c) 2021 MinIO, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "encoding/json" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/validate" ) // ObjectLegalHoldStatus object legal hold status // // swagger:model objectLegalHoldStatus type ObjectLegalHoldStatus string func NewObjectLegalHoldStatus(value ObjectLegalHoldStatus) *ObjectLegalHoldStatus { v := value return &v } const ( // ObjectLegalHoldStatusEnabled captures enum value "enabled" ObjectLegalHoldStatusEnabled ObjectLegalHoldStatus = "enabled" // ObjectLegalHoldStatusDisabled captures enum value "disabled" ObjectLegalHoldStatusDisabled ObjectLegalHoldStatus = "disabled" ) // for schema var objectLegalHoldStatusEnum []interface{} func init() { var res []ObjectLegalHoldStatus if err := json.Unmarshal([]byte(`["enabled","disabled"]`), &res); err != nil { panic(err) } for _, v := range res { objectLegalHoldStatusEnum = append(objectLegalHoldStatusEnum, v) } } func (m ObjectLegalHoldStatus) validateObjectLegalHoldStatusEnum(path, location string, value ObjectLegalHoldStatus) error { if err := validate.EnumCase(path, location, value, objectLegalHoldStatusEnum, true); err != nil { return err } return nil } // Validate validates this object legal hold status func (m ObjectLegalHoldStatus) Validate(formats strfmt.Registry) error { var res []error // value enum if err := m.validateObjectLegalHoldStatusEnum("", "body", m); err != nil { return err } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } // ContextValidate validates this object legal hold status based on context it is used func (m ObjectLegalHoldStatus) ContextValidate(ctx context.Context, formats strfmt.Registry) error { return nil }
docks-app/docks
lib/docks/tags/pattern_tag.rb
<reponame>docks-app/docks<gh_stars>0 module Docks module Tags class Pattern < Base def initialize @name = :pattern @synonyms = [:page] @multiline = false end def setup_post_processors after_each_pattern(:middle) do |pattern| name = pattern.name pattern.symbols.each do |symbol| symbol.pattern = name end end end end end end
projectPiki/pikmin2
src/JSystem/JSupport/JSUList.cpp
#include "types.h" #include "JSystem/JSupport/JSUList.h" /* Generated from dpostproc */ /* * Decompilation of this file is derived from https://github.com/shibbo/Petari */ /* * __ct__10JSUPtrLinkFPv * --INFO-- * Address: 800267B8 * Size: 000018 */ JSUPtrLink::JSUPtrLink(void* pData) { m_list = nullptr; m_value = pData; m_prev = nullptr; m_next = nullptr; } /* * __dt__10JSUPtrLinkFv * --INFO-- * Address: 800267D0 * Size: 000060 */ JSUPtrLink::~JSUPtrLink() { if (m_list) { m_list->remove(this); } } /* * __ct__10JSUPtrListFb * --INFO-- * Address: 80026830 * Size: 000038 */ JSUPtrList::JSUPtrList(bool doInitialize) { if (doInitialize) { initiate(); } } /* * __dt__10JSUPtrListFv * --INFO-- * Address: 80026868 * Size: 000068 */ JSUPtrList::~JSUPtrList() { JSUPtrLink* curHead = m_head; for (int i = 0; i < m_linkCount; i++) { curHead->m_list = nullptr; curHead = curHead->m_next; } } /* * --INFO-- * Address: 800268D0 * Size: 000014 */ void JSUPtrList::initiate() { m_head = nullptr; m_tail = nullptr; m_linkCount = 0; } /* * --INFO-- * Address: 800268E4 * Size: 0000B8 */ bool JSUPtrList::append(JSUPtrLink* pLink) { bool validity = (pLink->m_list == nullptr); if (!validity) { validity = pLink->m_list->remove(pLink); } if (validity) { if (m_linkCount == 0) { pLink->m_list = this; pLink->m_prev = nullptr; pLink->m_next = nullptr; m_tail = pLink; m_head = pLink; m_linkCount = 1; } else { pLink->m_list = this; pLink->m_prev = m_tail; pLink->m_next = nullptr; m_tail->m_next = pLink; m_tail = pLink; m_linkCount = m_linkCount + 1; } } return validity; } /* * --INFO-- * Address: 8002699C * Size: 0000B8 */ bool JSUPtrList::prepend(JSUPtrLink* pLink) { bool validity = (pLink->m_list == nullptr); if (!validity) { validity = pLink->m_list->remove(pLink); } if (validity) { if (m_linkCount == 0) { pLink->m_list = this; pLink->m_prev = nullptr; pLink->m_next = nullptr; m_tail = pLink; m_head = pLink; m_linkCount = 1; } else { pLink->m_list = this; pLink->m_prev = nullptr; pLink->m_next = m_head; m_head->m_prev = pLink; m_head = pLink; m_linkCount = m_linkCount + 1; } } return validity; } /* * --INFO-- * Address: 80026A54 * Size: 0001D0 */ bool JSUPtrList::insert(JSUPtrLink* pLink1, JSUPtrLink* pLink2) { if (pLink1 == m_head) { return prepend(pLink2); } if (!pLink1) { return append(pLink2); } if (pLink1->m_list != this) { return false; } JSUPtrList* pLink2List = pLink2->m_list; bool validity = (pLink2List == 0); if (!validity) { validity = pLink2List->remove(pLink2); } if (validity) { JSUPtrLink* prev = pLink1->m_prev; pLink2->m_list = this; pLink2->m_prev = prev; pLink2->m_next = pLink1; prev->m_next = pLink2; pLink1->m_prev = pLink2; m_linkCount++; } return validity; } /* * --INFO-- * Address: 80026C24 * Size: 0000B0 */ bool JSUPtrList::remove(JSUPtrLink* pLink) { bool isSameList = (pLink->m_list == this); if (isSameList) { if (m_linkCount == 1) { m_head = nullptr; m_tail = nullptr; } else if (pLink == m_head) { pLink->m_next->m_prev = nullptr; m_head = pLink->m_next; } else if (pLink == m_tail) { pLink->m_prev->m_next = nullptr; m_tail = pLink->m_prev; } else { pLink->m_prev->m_next = pLink->m_next; pLink->m_next->m_prev = pLink->m_prev; } pLink->m_list = nullptr; m_linkCount--; } return isSameList; } /* * --INFO-- * Address: 80026CD4 * Size: 000088 */ JSUPtrLink* JSUPtrList::getNthLink(u32 n) const { if (n >= m_linkCount) { return nullptr; } JSUPtrLink* curHead = m_head; for (int i = 0; i < n; i++) { curHead = curHead->m_next; } return curHead; }
mdblp/platform
log/json/logger_test.go
package json_test import ( "io/ioutil" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/tidepool-org/platform/log" logJson "github.com/tidepool-org/platform/log/json" ) var _ = Describe("Logger", func() { Context("NewLogger", func() { It("returns an error if writer is missing", func() { logger, err := logJson.NewLogger(nil, log.DefaultLevelRanks(), log.DefaultLevel()) Expect(err).To(MatchError("writer is missing")) Expect(logger).To(BeNil()) }) It("returns an error if level ranks is missing", func() { logger, err := logJson.NewLogger(ioutil.Discard, nil, log.DefaultLevel()) Expect(err).To(MatchError("level ranks is missing")) Expect(logger).To(BeNil()) }) It("returns successfully", func() { Expect(logJson.NewLogger(ioutil.Discard, log.DefaultLevelRanks(), log.DefaultLevel())).ToNot(BeNil()) }) }) })
holyketzer/ctci_v6
ruby/spec/08_recursion_and_dp/13_stack_of_boxes.rb
<filename>ruby/spec/08_recursion_and_dp/13_stack_of_boxes.rb class Box attr_reader :w, :d, :h def initialize(w:, d:, h:) @w = w @d = d @h = h end def sizes [w, d, h] end def can_be_on?(top) w < top.w && d < top.d && h < top.h end end def tallest_stack(boxes, available = boxes.map { true }, stack = []) too_big = [] top = stack.last boxes.each_with_index do |box, i| if top && available[i] && !box.can_be_on?(top) too_big << i available[i] = false end end res = if available.none? stack.sum(&:h) else boxes.each_with_index.map do |box, i| if available[i] stack << box available[i] = false height = tallest_stack(boxes, available, stack) available[i] = true stack.pop height else 0 end end.max end too_big.each { |i| available[i] = true } res end RSpec.describe 'tallest_stack' do subject { tallest_stack(boxes) } let(:boxes) do [ Box.new(w: 1.0, d: 1.0, h: 1.0), Box.new(w: 1.0, d: 1.0, h: 1.0), Box.new(w: 1.0, d: 1.0, h: 1.9), Box.new(w: 1.5, d: 1.5, h: 1.5), Box.new(w: 2.0, d: 2.0, h: 2.0), ] end it { is_expected.to eq 2.0 + 1.5 + 1.0 } end
MBrassey/xscreensaver_BlueMatrix
hacks/glx/handsy.c
<filename>hacks/glx/handsy.c /* handsy, Copyright (c) 2018 <NAME> <<EMAIL>> * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation. No representations are made about the suitability of this * software for any purpose. It is provided "as is" without express or * implied warranty. */ #define DEFAULTS "*delay: 30000 \n" \ "*count: 2 \n" \ ".foreground: #8888CC" "\n" \ "*groundColor: #0000FF" "\n" \ "*showFPS: False \n" \ "*wireframe: False \n" # define release_hands 0 #undef countof #define countof(x) (sizeof((x))/sizeof((*x))) #include "xlockmore.h" #include "sphere.h" #include "tube.h" #include "rotator.h" #include "gltrackball.h" #include "gllist.h" #include <ctype.h> #ifdef USE_GL /* whole file */ #define DEF_SPEED "1.0" #define DEF_SPIN "XY" #define DEF_WANDER "True" #define DEF_FACE_FRONT "True" #define DEF_DEBUG "False" extern const struct gllist *handsy_model_finger_distal, *handsy_model_finger_intermediate, *handsy_model_finger_proximal, *handsy_model_finger_metacarpal, *handsy_model_thumb_distal, *handsy_model_thumb_proximal, *handsy_model_thumb_metacarpal, *handsy_model_palm; static struct gllist *ground = 0; static const struct gllist * const *all_objs[] = { &handsy_model_finger_distal, &handsy_model_finger_intermediate, &handsy_model_finger_proximal, &handsy_model_finger_metacarpal, &handsy_model_thumb_distal, &handsy_model_thumb_proximal, &handsy_model_thumb_metacarpal, &handsy_model_palm, (const struct gllist * const *) &ground }; #define FINGER_DISTAL 0 #define FINGER_INTERMEDIATE 1 #define FINGER_PROXIMAL 2 #define FINGER_METACARPAL 3 #define THUMB_DISTAL 4 #define THUMB_PROXIMAL 5 #define THUMB_METACARPAL 6 #define PALM 7 #define GROUND 8 /* 'hand_geom' describes the position and extent of the various joints. 'hand' describes the current flexion of the joints in that model. 'hand_anim' is a list of positions and timings describing an animation. 'hands_configuration' is the usual global state structure. */ typedef struct { double min, max; /* +- pi */ } joint; typedef struct { joint bones[4]; joint base; } finger; typedef struct { finger fingers[5]; joint palm; joint wrist1; joint wrist2; } hand_geom; static const hand_geom human_hand = { {{{{ 0.0, 1.6 }, /* thumb distal */ { 0.0, 1.6 }, /* thumb proximal */ { 0.0, 1.6 }, /* thumb metacarpal */ { 0.0, 0.0 }}, /* none */ { -1.70, 0.00 }}, {{{ -0.2, 1.6 }, /* index distal */ { -0.2, 1.6 }, /* index intermediate */ { -0.2, 1.6 }, /* index proximal */ { 0.0, 0.0 }}, /* index metacarpal */ { -0.25, 0.25 }}, {{{ -0.2, 1.6 }, /* middle distal */ { -0.2, 1.6 }, /* middle intermediate */ { -0.2, 1.6 }, /* middle proximal */ { 0.0, 0.0 }}, /* middle metacarpal */ { -0.25, 0.25 }}, {{{ -0.2, 1.6 }, /* ring distal */ { -0.2, 1.6 }, /* ring intermediate */ { -0.2, 1.6 }, /* ring proximal */ { 0.0, 0.0 }}, /* ring metacarpal */ { -0.25, 0.25 }}, {{{ -0.2, 1.6 }, /* pinky distal */ { -0.2, 1.6 }, /* pinky intermediate */ { -0.2, 1.6 }, /* pinky proximal */ { 0.0, 0.0 }}, /* pinky metacarpal */ { -0.25, 0.25 }}}, { -0.7, 1.5 }, /* palm (wrist up/down) */ { -M_PI, M_PI }, /* wrist left/right */ { -M_PI, M_PI }, /* wrist rotate */ }; typedef struct { double joint[countof(human_hand.fingers)] /* +- pi */ [countof(human_hand.fingers[0].bones)]; double base[countof(human_hand.fingers)]; double wrist[3]; /* up/down, left/right, rotate */ double pos[3]; /* XYZ */ Bool sinister; double alpha; } hand; typedef struct { const hand * const dest; double duration, pause; double pos[3], rot[3]; /* XYZ */ } hand_anim; typedef struct { const hand_anim * const pair[2]; /* L/R */ double delay; /* Delay added to R */ } hand_anim_pair; typedef struct { GLXContext *glx_context; rotator *rot, *rot2; trackball_state *trackball; Bool spinx, spiny, spinz; Bool button_down_p; const hand_geom *geom; GLuint *dlists; int nhands; struct { const hand_anim *anim; int anim_hands; /* frames in animation */ int anim_hand; /* pos in anim, L/R */ double anim_start, anim_time; double tick; double delay; } pair[2]; struct { hand from, to, current; } *hands; GLfloat color[4]; Bool ringp; } hands_configuration; #include "handsy_anim.h" static hands_configuration *bps = NULL; static GLfloat speed; static char *do_spin; static Bool do_wander; static Bool face_front_p; static Bool debug_p; static XrmOptionDescRec opts[] = { { "-speed", ".speed", XrmoptionSepArg, 0 }, { "-spin", ".spin", XrmoptionSepArg, 0 }, { "+spin", ".spin", XrmoptionNoArg, "" }, { "-wander", ".wander", XrmoptionNoArg, "True" }, { "+wander", ".wander", XrmoptionNoArg, "False" }, { "-front", ".faceFront", XrmoptionNoArg, "True" }, { "+front", ".faceFront", XrmoptionNoArg, "False" }, { "-debug", ".debug", XrmoptionNoArg, "True" }, { "+debug", ".debug", XrmoptionNoArg, "False" }, }; static argtype vars[] = { {&do_spin, "spin", "Spin", DEF_SPIN, t_String}, {&do_wander, "wander", "Wander", DEF_WANDER, t_Bool}, {&face_front_p, "faceFront", "FaceFront", DEF_FACE_FRONT, t_Bool}, {&speed, "speed", "Speed", DEF_SPEED, t_Float}, {&debug_p, "debug", "Debug", DEF_DEBUG, t_Bool}, }; ENTRYPOINT ModeSpecOpt hands_opts = {countof(opts), opts, countof(vars), vars, NULL}; /* Returns the current time in seconds as a double. */ static double double_time (void) { struct timeval now; # ifdef GETTIMEOFDAY_TWO_ARGS struct timezone tzp; gettimeofday(&now, &tzp); # else gettimeofday(&now); # endif return (now.tv_sec + ((double) now.tv_usec * 0.000001)); } static double constrain_joint (double v, double min, double max) { if (v < min) v = min; else if (v > max) v = max; return v; } static void draw_hand (ModeInfo *mi, hand *h) { hands_configuration *bp = &bps[MI_SCREEN(mi)]; int wire = MI_IS_WIREFRAME(mi); int finger; int off = h->sinister ? -1 : 1; int nfingers = countof (bp->geom->fingers); int nbones = countof (bp->geom->fingers[0].bones); glLineWidth (1); glPushMatrix(); glTranslatef (off * h->pos[0], h->pos[1], h->pos[2]); glRotatef (h->wrist[1] * 180 / M_PI * -off, 0, 1, 0); glRotatef (h->wrist[2] * 180 / M_PI * -off, 0, 0, 1); glRotatef (h->wrist[0] * 180 / M_PI, 1, 0, 0); bp->color[3] = h->alpha; glColor4fv (bp->color); glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, bp->color); if (!wire) glEnable (GL_BLEND); glPushMatrix(); if (h->sinister) { glScalef (-1, 1, 1); glFrontFace (GL_CW); } else glFrontFace (GL_CCW); glCallList (bp->dlists[PALM]); glPopMatrix(); for (finger = 0; finger < nfingers; finger++) { int bone = nbones - 2; glPushMatrix(); if (finger == 0) /* thumb */ { glTranslatef (off * 0.113, -0.033, 0.093); glRotatef (off * 45, 0, 1, 0); if (h->sinister) glRotatef (180, 0, 0, 1); glRotatef (off * h->base[finger] * -180 / M_PI, 1, 0, 0); bone--; glFrontFace (GL_CCW); glCallList (bp->dlists[THUMB_METACARPAL]); glPushMatrix(); glScalef (1, -1, 1); glFrontFace (GL_CW); glCallList (bp->dlists[THUMB_METACARPAL]); glPopMatrix(); glTranslatef (0, 0, 0.1497); glRotatef (h->joint[finger][bone] * -180 / M_PI, 0, 1, 0); bone--; glFrontFace (GL_CCW); glCallList (bp->dlists[THUMB_PROXIMAL]); glPushMatrix(); glScalef (1, -1, 1); glFrontFace (GL_CW); glCallList (bp->dlists[THUMB_PROXIMAL]); glPopMatrix(); glTranslatef (0, 0, 0.1212); glRotatef (h->joint[finger][bone] * -180 / M_PI, 0, 1, 0); bone--; glFrontFace (GL_CCW); glCallList (bp->dlists[THUMB_DISTAL]); glPushMatrix(); glScalef (1, -1, 1); glFrontFace (GL_CW); glCallList (bp->dlists[THUMB_DISTAL]); glPopMatrix(); } else { switch (finger) { case 1: /* index */ glTranslatef (off * 0.135, 0.004, 0.26835); glRotatef (off * 4, 0, 1, 0); break; case 2: /* middle */ glTranslatef (off * 0.046, 0.004, 0.27152); glRotatef (off * 1, 0, 1, 0); break; case 3: /* ring */ glTranslatef (off * -0.046, 0.004, 0.25577); glRotatef (off * -1, 0, 1, 0); break; case 4: /* pinky */ glTranslatef (off * -0.135, 0.004, 0.22204); glRotatef (off * -4, 0, 1, 0); break; default: abort(); break; } glRotatef (90, 0, 0, 1); glFrontFace (GL_CCW); glCallList (bp->dlists[FINGER_METACARPAL]); glPushMatrix(); glScalef (1, -1, 1); glFrontFace (GL_CW); glCallList (bp->dlists[FINGER_METACARPAL]); glPopMatrix(); glTranslatef (0, 0, 0.1155); glRotatef (off * h->base[finger] * -180 / M_PI, 1, 0, 0); glRotatef (h->joint[finger][bone] * -180 / M_PI, 0, 1, 0); bone--; glFrontFace (GL_CCW); glCallList (bp->dlists[FINGER_PROXIMAL]); glPushMatrix(); glScalef (1, -1, 1); glFrontFace (GL_CW); glCallList (bp->dlists[FINGER_PROXIMAL]); glPopMatrix(); glTranslatef (0, 0, 0.1815); glRotatef (h->joint[finger][bone] * -180 / M_PI, 0, 1, 0); bone--; glFrontFace (GL_CCW); glCallList (bp->dlists[FINGER_INTERMEDIATE]); glPushMatrix(); glScalef (1, -1, 1); glFrontFace (GL_CW); glCallList (bp->dlists[FINGER_INTERMEDIATE]); glPopMatrix(); glTranslatef (0, 0, 0.1003); glRotatef (h->joint[finger][bone] * -180 / M_PI, 0, 1, 0); bone--; glFrontFace (GL_CCW); glCallList (bp->dlists[FINGER_DISTAL]); glPushMatrix(); glScalef (1, -1, 1); glFrontFace (GL_CW); glCallList (bp->dlists[FINGER_DISTAL]); glPopMatrix(); } glPopMatrix(); } glPopMatrix(); if (h->sinister && bp->ringp) { GLfloat color[] = { 1.0, 0.4, 0.4, 1 }; GLfloat center = 0.4; GLfloat th; GLfloat r = center - h->pos[0] + 0.1; GLfloat min = 0.22; if (r < min) r = min; glPushMatrix(); glTranslatef (-center, -0.28, 0.5); glRotatef (h->wrist[2] * 180 / M_PI * -off, 0, 0, 1); glRotatef (h->wrist[0] * 180 / M_PI, 1, 0, 0); glColor4fv (color); glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color); glDisable (GL_LIGHTING); glLineWidth (8); glBegin (GL_LINE_LOOP); for (th = 0; th < M_PI * 2; th += M_PI / 180) glVertex3f (r * cos(th), r * sin(th), 0); glEnd(); if (! wire) glEnable (GL_LIGHTING); glPopMatrix(); } glDisable (GL_BLEND); } static void parse_color (ModeInfo *mi, char *key, GLfloat color[4]) { XColor xcolor; char *string = get_string_resource (mi->dpy, key, "Color"); if (!XParseColor (mi->dpy, mi->xgwa.colormap, string, &xcolor)) { fprintf (stderr, "%s: unparsable color in %s: %s\n", progname, key, string); exit (1); } free (string); color[0] = xcolor.red / 65536.0; color[1] = xcolor.green / 65536.0; color[2] = xcolor.blue / 65536.0; color[3] = 1; } static int draw_ground (ModeInfo *mi) { int wire = MI_IS_WIREFRAME(mi); GLfloat i, j, k; /* When using fog, iOS apparently doesn't like lines or quads that are really long, and extend very far outside of the scene. Maybe? If the length of the line (cells * cell_size) is greater than 25 or so, lines that are oriented steeply away from the viewer tend to disappear (whether implemented as GL_LINES or as GL_QUADS). So we do a bunch of smaller grids instead of one big one. */ int cells = 30; GLfloat cell_size = 0.8; int points = 0; int grids = 12; GLfloat color[4]; if (wire) glLineWidth (1); parse_color (mi, "groundColor", color); glPushMatrix(); glScalef (0.2, 0.2, 0.2); glRotatef (frand(90), 0, 0, 1); if (!wire) { GLfloat fog_color[4] = { 0, 0, 0, 1 }; glLineWidth (4); glEnable (GL_LINE_SMOOTH); glHint (GL_LINE_SMOOTH_HINT, GL_NICEST); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable (GL_BLEND); glFogi (GL_FOG_MODE, GL_EXP2); glFogfv (GL_FOG_COLOR, fog_color); glFogf (GL_FOG_DENSITY, 0.015); glFogf (GL_FOG_START, -cells/2 * cell_size * grids); glEnable (GL_FOG); } glColor4fv (color); glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color); glTranslatef (-cells * grids * cell_size / 2, -cells * grids * cell_size / 2, 0); for (j = 0; j < grids; j++) { glPushMatrix(); for (k = 0; k < grids; k++) { glBegin (GL_LINES); for (i = -cells/2; i < cells/2; i++) { GLfloat a = i * cell_size; GLfloat b = cells/2 * cell_size; glVertex3f (a, -b, 0); glVertex3f (a, b, 0); points++; glVertex3f (-b, a, 0); glVertex3f (b, a, 0); points++; } glEnd(); glTranslatef (cells * cell_size, 0, 0); } glPopMatrix(); glTranslatef (0, cells * cell_size, 0); } if (!wire) { glDisable (GL_LINE_SMOOTH); glDisable (GL_BLEND); glDisable (GL_FOG); } glPopMatrix(); return points; } ENTRYPOINT void reshape_hands (ModeInfo *mi, int width, int height) { GLfloat h = (GLfloat) height / (GLfloat) width; int y = 0; glViewport (0, y, (GLint) width, (GLint) height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective (30.0, 1/h, 1.0, 100.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt( 0.0, 0.0, 30.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); } ENTRYPOINT Bool hands_handle_event (ModeInfo *mi, XEvent *event) { hands_configuration *bp = &bps[MI_SCREEN(mi)]; Bool ok = False; if (gltrackball_event_handler (event, bp->trackball, MI_WIDTH (mi), MI_HEIGHT (mi), &bp->button_down_p)) ok = True; else if (debug_p && event->type == KeyPress) { int nfingers = countof (bp->geom->fingers); int nbones = countof (bp->geom->fingers[0].bones); KeySym keysym; char c = 0; Bool tiltp = False; double delta = 0.02; double sign = 1; int i, j, k; XLookupString (&event->xkey, &c, 1, &keysym, 0); for (i = 0; i < bp->nhands; i++) { hand *h = &bp->hands[i].current; Bool modp = !!event->xkey.state; switch (keysym) { case XK_Up: ok = True; h->pos[(modp ? 1 : 2)] += delta; break; case XK_Down: ok = True; h->pos[(modp ? 1 : 2)] -= delta; break; case XK_Right: ok = True; h->pos[0] += delta; break; case XK_Left: ok = True; h->pos[0] -= delta; break; default: break; } switch (c) { case '?': case '/': ok = True; fprintf (stderr, "\n" " Open fingers: 12345 (1 = pinky, 5 = thumb)\n" " Close fingers: QWERT\n" " Tilt left: ASDFG\n" " Tilt right: ZXCVB\n" " Bend wrist: UJ (up/down)\n" " Bend wrist: IK (left/right)\n" " Rotate wrist: OL\n" " Move origin: arrow keys: XZ plane; shift: XY plane\n" " Tab: print current state to stdout\n" " 0: Reset\n" " ?: This\n\n"); return ok; break; case '1': case '!': j = 4; sign = -1; goto FINGER; case '2': case '@': j = 3; sign = -1; goto FINGER; case '3': case '#': j = 2; sign = -1; goto FINGER; case '4': case '$': j = 1; sign = -1; goto FINGER; case '5': case '%': j = 0; sign = -1; goto FINGER; case 'q': case 'Q': j = 4; sign = 1; goto FINGER; case 'w': case 'W': j = 3; sign = 1; goto FINGER; case 'e': case 'E': j = 2; sign = 1; goto FINGER; case 'r': case 'R': j = 1; sign = 1; goto FINGER; case 't': case 'T': j = 0; sign = 1; goto FINGER; case 'a': case 'A': tiltp = True; j = 4; sign = 1; goto FINGER; case 's': case 'S': tiltp = True; j = 3; sign = 1; goto FINGER; case 'd': case 'D': tiltp = True; j = 2; sign = 1; goto FINGER; case 'f': case 'F': tiltp = True; j = 1; sign = 1; goto FINGER; case 'g': case 'G': tiltp = True; j = 0; sign = 1; goto FINGER; case 'z': case 'Z': tiltp = True; j = 4; sign = -1; goto FINGER; case 'x': case 'X': tiltp = True; j = 3; sign = -1; goto FINGER; case 'c': case 'C': tiltp = True; j = 2; sign = -1; goto FINGER; case 'v': case 'V': tiltp = True; j = 1; sign = -1; goto FINGER; case 'b': case 'B': tiltp = True; j = 0; sign = -1; goto FINGER; FINGER: ok = True; if (tiltp) h->base[j] = constrain_joint (h->base[j] + sign * delta, bp->geom->fingers[j].base.min, bp->geom->fingers[j].base.max); else for (k = 0; k < nbones; k++) h->joint[j][k] = constrain_joint (h->joint[j][k] + sign * delta, bp->geom->fingers[j].bones[k].min, bp->geom->fingers[j].bones[k].max); break; case 'u': case 'U': ok = True; h->wrist[0] -= delta; break; case 'j': case 'J': ok = True; h->wrist[0] += delta; break; case 'i': case 'I': ok = True; h->wrist[1] += delta; break; case 'k': case 'K': ok = True; h->wrist[1] -= delta; break; case 'o': case 'O': ok = True; h->wrist[2] -= delta; break; case 'l': case 'L': ok = True; h->wrist[2] += delta; break; case '0': case ')': ok = True; for (j = 0; j < nfingers; j++) { h->base[j] = 0; for (k = 0; k < nbones; k++) h->joint[j][k] = 0; } for (j = 0; j < 3; j++) h->wrist[j] = 0; for (j = 0; j < 3; j++) h->pos[j] = 0; break; case '\t': ok = True; fprintf (stdout, "\nstatic const hand H = {\n {"); for (i = 0; i < nfingers; i++) { if (i > 0) fprintf (stdout, " "); fprintf (stdout, "{"); for (j = 0; j < nbones; j++) { double v = h->joint[i][j]; if (i == 0 && j == 3) v = 0; /* no thumb intermediate */ if (j == 0) fprintf (stdout, " "); fprintf (stdout, "%.2f", v); if (j < nbones-1) fprintf (stdout, ", "); } fprintf (stdout, " }"); if (i < nfingers-1) fprintf (stdout, ",\n"); } fprintf (stdout, "},\n { "); for (i = 0; i < nfingers; i++) { fprintf (stdout, "%.2f", h->base[i]); if (i < nfingers-1) fprintf (stdout, ", "); } fprintf (stdout, " },\n"); fprintf (stdout, " { %.2f, %.2f, %.2f },\n", h->wrist[0], h->wrist[1], h->wrist[2]); fprintf (stdout, " { %.2f, %.2f, %.2f },\n", h->pos[0], h->pos[1], h->pos[2]); fprintf (stdout, " True\n};\n\n"); fflush (stdout); return ok; break; default: break; } } } return ok; } ENTRYPOINT void init_hands (ModeInfo *mi) { hands_configuration *bp; int wire = MI_IS_WIREFRAME(mi); hand def[2]; int i; MI_INIT (mi, bps); bp = &bps[MI_SCREEN(mi)]; bp->glx_context = init_GL(mi); reshape_hands (mi, MI_WIDTH(mi), MI_HEIGHT(mi)); bp->pair[0].tick = bp->pair[1].tick = 1.0; bp->geom = &human_hand; bp->nhands = MI_COUNT(mi); if (bp->nhands <= 0) bp->nhands = 1; if (bp->nhands & 1) bp->nhands++; /* Even number */ if (debug_p) { bp->nhands = 1; do_spin = ""; do_wander = False; } bp->hands = calloc (bp->nhands, sizeof(*bp->hands)); { double spin_speed = 0.5 * speed; double wander_speed = 0.005 * speed; double tilt_speed = 0.001 * speed; double spin_accel = 0.5; char *s = do_spin; while (*s) { if (*s == 'x' || *s == 'X') bp->spinx = True; else if (*s == 'y' || *s == 'Y') bp->spiny = True; else if (*s == 'z' || *s == 'Z') bp->spinz = True; else if (*s == '0') ; else { fprintf (stderr, "%s: spin must contain only the characters X, Y, or Z (not \"%s\")\n", progname, do_spin); exit (1); } s++; } bp->rot = make_rotator (bp->spinx ? spin_speed : 0, bp->spiny ? spin_speed : 0, bp->spinz ? spin_speed : 0, spin_accel, do_wander ? wander_speed : 0, False); bp->rot2 = (face_front_p ? make_rotator (0, 0, 0, 0, tilt_speed, True) : 0); bp->trackball = gltrackball_init (False); } /* Set default hand to the last hand in the animation list. */ for (i = 0; i <= 1; i++) { int j; for (j = 0; ; j++) if (!all_hand_anims[j+1].pair[i]) { if (! all_hand_anims[j].pair[i]) abort(); def[i] = *all_hand_anims[j].pair[i]->dest; if (debug_p) def[i].alpha = 1; else { def[i].pos[1] = 5; /* off screen */ def[i].pos[2] = 5; } break; } } for (i = 0; i < bp->nhands; i++) { int sinister = (i & 1); bp->hands[i].to = def[sinister]; bp->hands[i].to.sinister = sinister; bp->hands[i].from = bp->hands[i].to; bp->hands[i].current = bp->hands[i].to; } glFrontFace(GL_CW); bp->dlists = (GLuint *) calloc (countof(all_objs)+1, sizeof(GLuint)); for (i = 0; i < countof(all_objs); i++) bp->dlists[i] = glGenLists (1); for (i = 0; i < countof(all_objs); i++) { const struct gllist *gll = *all_objs[i]; GLfloat s = 0.1; glNewList (bp->dlists[i], GL_COMPILE); switch (i) { case GROUND: if (! ground) ground = (struct gllist *) calloc (1, sizeof(*ground)); ground->points = draw_ground (mi); break; default: glPushMatrix(); glScalef (s, s, s); renderList (gll, wire); glPopMatrix(); break; } glEndList (); } if (!wire) { GLfloat pos[4] = {0.4, 0.2, 0.4, 0.0}; GLfloat amb[4] = {0.2, 0.2, 0.2, 1.0}; GLfloat dif[4] = {1.0, 1.0, 1.0, 1.0}; GLfloat spc[4] = {1.0, 1.0, 1.0, 1.0}; glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glLightfv(GL_LIGHT0, GL_POSITION, pos); glLightfv(GL_LIGHT0, GL_AMBIENT, amb); glLightfv(GL_LIGHT0, GL_DIFFUSE, dif); glLightfv(GL_LIGHT0, GL_SPECULAR, spc); } parse_color (mi, "foreground", bp->color); } static void tick_hands (ModeInfo *mi) { hands_configuration *bp = &bps[MI_SCREEN(mi)]; int i, j, k, nfingers, nbones, sinister; double now = double_time(); if (debug_p) return; if (!bp->pair[0].anim && /* Both hands finished. */ !bp->pair[1].anim) /* Pick a new animation. */ { int nanims = 0; while (all_hand_anims[nanims].pair[0] || all_hand_anims[nanims].pair[1]) nanims++; i = random() % nanims; for (sinister = 0; sinister <= 1; sinister++) { bp->pair[sinister].anim = all_hand_anims[i].pair[sinister]; bp->pair[sinister].anim_hand = 0; bp->pair[sinister].anim_hands = 0; while (bp->pair[sinister].anim[bp->pair[sinister].anim_hands].dest) bp->pair[sinister].anim_hands++; bp->pair[sinister].anim_start = now; bp->pair[sinister].tick = 0; if (sinister == 1) bp->pair[sinister].delay = all_hand_anims[i].delay; } bp->ringp = (all_hand_anims[i].pair[0] == goatse_anim); for (i = 0; i < bp->nhands; i++) { sinister = bp->hands[i].from.sinister; bp->hands[i].from = bp->hands[i].current; bp->hands[i].to = *bp->pair[sinister].anim->dest; bp->hands[i].to.sinister = sinister; j = bp->pair[sinister].anim_hand; bp->hands[i].to.alpha = (bp->pair[sinister].anim == hidden_anim ? 0 : 1); /* Anim keyframes can adjust position and rotation */ for (k = 0; k < 3; k++) { bp->hands[i].to.wrist[k] += bp->pair[sinister].anim[j].rot[k]; bp->hands[i].to.pos[k] += bp->pair[sinister].anim[j].pos[k]; } } } for (sinister = 0; sinister <= 1; sinister++) { const hand_anim *h; double elapsed, duration, duration2; if (! bp->pair[sinister].anim) /* Done with this hand, not the other. */ continue; h = &bp->pair[sinister].anim[bp->pair[sinister].anim_hand]; elapsed = now - bp->pair[sinister].anim_start; duration = h->duration / speed; duration2 = duration + (bp->pair[sinister].delay + h->pause) / speed; if (elapsed > duration2 && /* Done animating and pausing this hand. */ bp->pair[sinister].tick >= 1) /* ...and painted final frame. */ { bp->pair[sinister].anim_hand++; bp->pair[sinister].tick = 1; if (bp->pair[sinister].anim_hand >= bp->pair[sinister].anim_hands) { /* Done with all steps of this hand's animation. */ bp->pair[sinister].anim = 0; for (i = 0; i < bp->nhands; i++) if (bp->hands[i].from.sinister == sinister) bp->hands[i].from = bp->hands[i].to = bp->hands[i].current; } else { /* Move to next step of animation. */ for (i = 0; i < bp->nhands; i++) { if (sinister != bp->hands[i].current.sinister) continue; j = bp->pair[sinister].anim_hand; bp->hands[i].from = bp->hands[i].current; bp->hands[i].to = *bp->pair[sinister].anim[j].dest; bp->hands[i].to.alpha = (bp->pair[sinister].anim == hidden_anim ? 0 : 1); /* Anim keyframes can adjust position and rotation */ for (k = 0; k < 3; k++) { bp->hands[i].to.wrist[k] += bp->pair[sinister].anim[j].rot[k]; bp->hands[i].to.pos[k] += bp->pair[sinister].anim[j].pos[k]; } } bp->pair[sinister].anim_start = now; bp->pair[sinister].tick = 0; bp->pair[sinister].delay = 0; } } else if (elapsed > duration) /* Done animating, still pausing. */ bp->pair[sinister].tick = 1; else /* Still animating. */ bp->pair[sinister].tick = elapsed / duration; if (bp->pair[sinister].tick > 1) bp->pair[sinister].tick = 1; /* Move the joints into position: compute 'current' between 'from' and 'to' by ratio 'tick'. */ nfingers = countof (bp->geom->fingers); nbones = countof (bp->geom->fingers[0].bones); for (i = 0; i < bp->nhands; i++) { if (bp->hands[i].current.sinister != sinister) continue; for (j = 0; j < nfingers; j++) { for (k = 0; k < nbones; k++) bp->hands[i].current.joint[j][k] = constrain_joint (bp->hands[i].from.joint[j][k] + bp->pair[sinister].tick * (bp->hands[i].to.joint[j][k] - bp->hands[i].from.joint[j][k]), bp->geom->fingers[j].bones[k].min, bp->geom->fingers[j].bones[k].max); bp->hands[i].current.base[j] = constrain_joint (bp->hands[i].from.base[j] + bp->pair[sinister].tick * (bp->hands[i].to.base[j] - bp->hands[i].from.base[j]), bp->geom->fingers[j].base.min, bp->geom->fingers[j].base.max); } j = 0; bp->hands[i].current.wrist[j] = constrain_joint (bp->hands[i].from.wrist[j] + bp->pair[sinister].tick * (bp->hands[i].to.wrist[j] - bp->hands[i].from.wrist[j]), bp->geom->palm.min, bp->geom->palm.max); j = 1; bp->hands[i].current.wrist[j] = constrain_joint (bp->hands[i].from.wrist[j] + bp->pair[sinister].tick * (bp->hands[i].to.wrist[j] - bp->hands[i].from.wrist[j]), bp->geom->wrist1.min, bp->geom->wrist1.max); j = 2; bp->hands[i].current.wrist[j] = constrain_joint (bp->hands[i].from.wrist[j] + bp->pair[sinister].tick * (bp->hands[i].to.wrist[j] - bp->hands[i].from.wrist[j]), bp->geom->wrist2.min, bp->geom->wrist2.max); for (j = 0; j < 3; j++) bp->hands[i].current.pos[j] = constrain_joint (bp->hands[i].from.pos[j] + bp->pair[sinister].tick * (bp->hands[i].to.pos[j] - bp->hands[i].from.pos[j]), -999, 999); bp->hands[i].current.alpha = bp->hands[i].from.alpha + bp->pair[sinister].tick * (bp->hands[i].to.alpha - bp->hands[i].from.alpha); } } } ENTRYPOINT void draw_hands (ModeInfo *mi) { hands_configuration *bp = &bps[MI_SCREEN(mi)]; Display *dpy = MI_DISPLAY(mi); Window window = MI_WINDOW(mi); GLfloat s; int i; static const GLfloat bspec[4] = {1.0, 1.0, 1.0, 1.0}; static const GLfloat bshiny = 128.0; GLfloat bcolor[4] = { 0.7, 0.7, 1.0, 1.0 }; if (!bp->glx_context) return; glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *bp->glx_context); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_NORMALIZE); glEnable(GL_CULL_FACE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix (); glRotatef(current_device_rotation(), 0, 0, 1); s = 10; glScalef (s, s, s); { double x, y, z; gltrackball_rotate (bp->trackball); if (face_front_p) { double maxx = 120 / 10.0; double maxy = 55 / 10.0; double maxz = 40 / 10.0; get_position (bp->rot2, &x, &y, &z, !bp->button_down_p); if (bp->spinx) glRotatef (maxx/2 - x*maxx, 0, 1, 0); if (bp->spiny) glRotatef (maxy/2 - y*maxy, 1, 0, 0); if (bp->spinz) glRotatef (maxz/2 - z*maxz, 0, 0, 1); } else { get_rotation (bp->rot, &x, &y, &z, !bp->button_down_p); glRotatef (x * 360, 1, 0, 0); glRotatef (y * 360, 0, 1, 0); glRotatef (z * 360, 0, 0, 1); } glRotatef (-70, 1, 0, 0); glTranslatef (0, 0, -0.5); glPushMatrix(); glRotatef ((bp->spiny ? y : bp->spinx ? x : z) * 90, 0, 0, 1); glCallList (bp->dlists[GROUND]); glPopMatrix(); get_position (bp->rot, &x, &y, &z, !bp->button_down_p); z += 1; /* Origin of hands is 1.0 above floor. */ glTranslatef((x - 0.5) * 0.8, (y - 0.5) * 1.1, (z - 0.5) * 0.2); } glMaterialfv (GL_FRONT, GL_SPECULAR, bspec); glMateriali (GL_FRONT, GL_SHININESS, bshiny); glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, bcolor); { /* Lay the pairs out in a square-ish grid, keeping pairs together. */ int rows = sqrt (bp->nhands / 2); int cols; int x, y; cols = ceil (bp->nhands / 2.0 / rows); if (bp->nhands <= 2) rows = cols = 1; if (MI_WIDTH(mi) < MI_HEIGHT(mi)) /* Portrait */ { s = 0.5; glScalef (s, s, s); } if (bp->nhands == 1) glScalef (2, 2, 2); if (cols > 1) { s = 1.0 / rows; glScalef (s, s, s); } if (bp->nhands > 1) { s = 0.8; glTranslatef (-s * rows * 1.5, -s * cols, 0); glTranslatef (s, s, 0); } i = 0; for (y = 0; y < cols; y++) for (x = 0; x < rows; x++) { glPushMatrix(); glTranslatef (x * s * 3, y * s * 2, y * s); if (i < bp->nhands) draw_hand (mi, &bp->hands[i++].current); glTranslatef (s, 0, 0); if (i < bp->nhands) draw_hand (mi, &bp->hands[i++].current); glPopMatrix(); } } glPopMatrix(); tick_hands (mi); if (mi->fps_p) do_fps (mi); glFinish(); glXSwapBuffers(dpy, window); } ENTRYPOINT void free_hands (ModeInfo *mi) { hands_configuration *bp = &bps[MI_SCREEN(mi)]; int i; if (!bp->glx_context) return; glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *bp->glx_context); if (bp->rot) free_rotator (bp->rot); if (bp->trackball) gltrackball_free (bp->trackball); if (bp->dlists) { for (i = 0; i < countof(all_objs); i++) if (glIsList(bp->dlists[i])) glDeleteLists(bp->dlists[i], 1); free (bp->dlists); } } XSCREENSAVER_MODULE_2 ("Handsy", handsy, hands) #endif /* USE_GL */
equinor/radix-api
api/applications/models/application_match.go
<reponame>equinor/radix-api package models import ( "strings" v1 "github.com/equinor/radix-operator/pkg/apis/radix/v1" ) // ApplicationMatch defines a match function that takes a RadixRegistration as parameter and returns a bool indicating if the RR matched the filter or not type ApplicationMatch func(rr *v1.RadixRegistration) bool // MatchByNamesFunc returns a ApplicationMatch that checks if the name of a RadixRegistration matches one of the supplied names func MatchByNamesFunc(names []string) ApplicationMatch { return func(rr *v1.RadixRegistration) bool { return filterByNames(rr, names) } } func filterByNames(rr *v1.RadixRegistration, names []string) bool { if rr == nil { return false } for _, name := range names { if name == rr.Name { return true } } return false } // MatchByNamesFunc returns a ApplicationMatch that checks if the CloneURL of a RadixRegistration matches sshRepo argument func MatchBySSHRepoFunc(sshRepo string) ApplicationMatch { return func(rr *v1.RadixRegistration) bool { return filterBySSHRepo(rr, sshRepo) } } func filterBySSHRepo(rr *v1.RadixRegistration, sshRepo string) bool { return strings.EqualFold(rr.Spec.CloneURL, sshRepo) } // MatchAll returns a ApplicationMatch that always returns true func MatchAll(rr *v1.RadixRegistration) bool { return true }
net-lisias-ksp/Principia
physics/mock_dynamic_frame.hpp
<gh_stars>100-1000  #pragma once #include "geometry/grassmann.hpp" #include "geometry/named_quantities.hpp" #include "gmock/gmock.h" #include "physics/dynamic_frame.hpp" #include "physics/rigid_motion.hpp" namespace principia { namespace physics { namespace internal_dynamic_frame { template<typename InertialFrame, typename ThisFrame> class MockDynamicFrame : public DynamicFrame<InertialFrame, ThisFrame> { public: MOCK_METHOD((RigidMotion<InertialFrame, ThisFrame>), ToThisFrameAtTime, (Instant const& t), (const, override)); MOCK_METHOD((RigidMotion<ThisFrame, InertialFrame>), FromThisFrameAtTime, (Instant const& t), (const, override)); MOCK_METHOD(Instant, t_min, (), (const, override)); MOCK_METHOD(Instant, t_max, (), (const, override)); MOCK_METHOD((Vector<Acceleration, ThisFrame>), GeometricAcceleration, (Instant const& t, DegreesOfFreedom<ThisFrame> const& degrees_of_freedom), (const, override)); using Rot = Rotation<Frenet<ThisFrame>, ThisFrame>; MOCK_METHOD(Rot, FrenetFrame, (Instant const& t, DegreesOfFreedom<ThisFrame> const& degrees_of_freedom), (const, override)); MOCK_METHOD(void, WriteToMessage, (not_null<serialization::DynamicFrame*> message), (const, override)); private: MOCK_METHOD((Vector<Acceleration, InertialFrame>), GravitationalAcceleration, (Instant const& t, Position<InertialFrame> const& q), (const, override)); MOCK_METHOD((AcceleratedRigidMotion<InertialFrame, ThisFrame>), MotionOfThisFrame, (Instant const& t), (const, override)); }; } // namespace internal_dynamic_frame using internal_dynamic_frame::MockDynamicFrame; } // namespace physics } // namespace principia
Andrea-MariaDB-2/WindowsAppSDK
dev/MRTCore/mrt/mrm/mrmmin/BlobResult.h
<filename>dev/MRTCore/mrt/mrm/mrmmin/BlobResult.h // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #pragma once HRESULT DefBlobResult_NewRef(_In_reads_bytes_opt_(cbRef) const void* pRef, _In_ size_t cbRef, _Outptr_ DEFBLOBRESULT** result); HRESULT DefBlobResult_NewBuf(_In_reads_bytes_opt_(cbBuf) const void* pBuf, _In_ size_t cbBuf, _Outptr_ DEFBLOBRESULT** result); HRESULT DefBlobResult_InitRef(_Inout_ DEFBLOBRESULT* pSelf, _In_reads_bytes_opt_(cbRef) const void* pRef, _In_ size_t cbRef); HRESULT DefBlobResult_InitBuf(_Inout_ DEFBLOBRESULT* pSelf, _In_reads_bytes_opt_(cbInitBuf) const void* pInitBuf, _In_ size_t cbInitBuf); HRESULT DefBlobResult_GetCopy(_In_ const DEFBLOBRESULT* pSelf, _Inout_ DEFBLOBRESULT* pResultOut); void DefBlobResult_Clear(_Inout_ DEFBLOBRESULT* pSelf); void DefBlobResult_Delete(_Inout_ DEFBLOBRESULT* pSelf); _Success_(return != nullptr) _Check_return_ const void* DefBlobResult_GetRef(_In_ const DEFBLOBRESULT* pSelf, _Out_opt_ size_t* pcbRefOut); _Success_(return != nullptr) _Check_return_ void* DefBlobResult_GetWritableRef(_In_ DEFBLOBRESULT* pSelf, _Out_opt_ size_t* pcbRefOut); size_t DefBlobResult_GetSize(_In_ const DEFBLOBRESULT* pSelf); DEFRESULTTYPE DefBlobResult_GetType(_In_ const DEFBLOBRESULT* pSelf); DEFCOMPARISON DefBlobResult_Compare(_In_ const DEFBLOBRESULT* pSelf, _In_ const DEFBLOBRESULT* pOther); HRESULT DefBlobResult_SetRef(_Inout_ DEFBLOBRESULT* pSelf, _In_reads_bytes_opt_(cbRef) const void* pRef, _In_ size_t cbRef); HRESULT DefBlobResult_SetCopy(_Inout_ DEFBLOBRESULT* pSelf, _In_reads_bytes_opt_(cbRef) const void* pRef, _In_ size_t cbRef); HRESULT DefBlobResult_SetContents(_Inout_ DEFBLOBRESULT* pSelf, _Inout_updates_bytes_(cbBuffer) void* pBuffer, _In_ size_t cbBuffer); HRESULT DefBlobResult_SetEmptyContents( _Inout_ DEFBLOBRESULT* pSelf, _In_ size_t cbBufferMin, _Outptr_opt_result_bytebuffer_to_(*pcbBufferOut, cbBufferMin) void** buffer, _Out_opt_ size_t* pcbBufferOut); HRESULT DefBlobResult_ReleaseContents( _Inout_ DEFBLOBRESULT* pSelf, _Outptr_result_bytebuffer_(*pcbBufferOut) void** ppBufferOut, _Out_ size_t* pcbBufferOut); #define DefBlobResult_IsInvalid(SELF) \ (((SELF) == NULL) || (((SELF)->pRef == (SELF)->pBuf) && \ (((((SELF)->pBuf == NULL) && ((SELF)->cbBuf > 0)) || (((SELF)->cbBuf == 0) && ((SELF)->pBuf != NULL))) || \ ((SELF)->cbBuf > DEFRESULT_MAX))))
royalfx/ae_snippets
src/ae/ui/as_uiPrefsApply.js
<reponame>royalfx/ae_snippets // Copyright (c) 2021 <NAME> // This code is licensed under MIT license // See also http://www.opensource.org/licenses/mit-license.php /** * @version 1.0.0 * @date Jul 22 2019 * * @description Apply ui elements state * @param {Window} windowObj * @param {obkect} dataPrefs */ function as_uiPrefsApply(windowObj, dataPrefs) { for (var elementName in dataPrefs) { if (dataPrefs.hasOwnProperty(elementName)) { var element = windowObj[elementName]; if(element) { // ITEMS if(element.items !== undefined) { element.removeAll(); for (var i = 0; i < dataPrefs[elementName].items.length; i++) { element.add("item", dataPrefs[elementName].items[i]); } // SELECTION element.selection = dataPrefs[elementName].selection; } // VALUE if (element.value !== undefined) { element.value = dataPrefs[elementName].value; } // TEXT if (element.text !== undefined) { element.text = dataPrefs[elementName].text; } } } } }
tbc3697/dev-toolkit
ratelimit/src/main/java/pub/tbc/toolkit/ratelimit/TokenBucketRateLimiter.java
package pub.tbc.toolkit.ratelimit; /** * @Author tbc by 2021/1/7 13:29 */ public abstract class TokenBucketRateLimiter implements RateLimiter { /** * token 容量 */ private double maxToken; private double stableIntervalMicros; public static void main(String[] args) { // com.google.common.util.concurrent.RateLimiter.create() } }
vanillaes/absurdum
src/strings/camelCase.spec.js
import test from 'tape' import { camelCase } from '@vanillaes/absurdum/strings' test('strings.camelCase(string) - should return the string formatted to camelCase', t => { const expect = 'helpMeWithThis' const actual = camelCase('help me with this') t.equal(Object.prototype.toString.call(actual), '[object String]', 'return type') t.equal(actual, expect, 'output value') t.end() }) test('strings.camelCase(string) - should return the string formatted to camelCase', t => { const expect = 'firmShake' const actual = camelCase('--firm-shake--') t.equal(Object.prototype.toString.call(actual), '[object String]', 'return type') t.equal(actual, expect, 'output value') t.end() }) test('strings.camelCase(string) - should return the string formatted to camelCase', t => { const expect = 'wolfTimber' const actual = camelCase('__WOLF_TIMBER__') t.equal(Object.prototype.toString.call(actual), '[object String]', 'return type') t.equal(actual, expect, 'output value') t.end() }) test('strings.camelCase(string) - should return empty string if provided an empty string', t => { const expect = '' const actual = camelCase('') t.equal(Object.prototype.toString.call(actual), '[object String]', 'return type') t.equal(actual, expect, 'output value') t.end() }) test('strings.camelCase(string) - should not mutate the input', t => { const input = '__WOLF_TIMBER__' const expect = '__WOLF_TIMBER__' camelCase(input) t.deepEqual(input, expect, 'input mutation') t.end() })
alexshepard/inaturalist
spec/lib/denormalizer_spec.rb
require File.expand_path("../../spec_helper", __FILE__) describe 'Denormalizer' do before(:all) do 6.times { Taxon.make! } end after(:all) do Taxon.connection.execute('TRUNCATE TABLE taxa RESTART IDENTITY') end it "should iterate through taxa in batches" do expect { |b| Denormalizer::each_taxon_batch_with_index(2, &b) }.to yield_successive_args( [ [ Taxon.find(1), Taxon.find(2) ], 1, 3 ], [ [ Taxon.find(3), Taxon.find(4) ], 2, 3 ], [ [ Taxon.find(5), Taxon.find(6) ], 3, 3 ] ) end end
xtremespb/zoia
src/modules/backup/web/index.js
<reponame>xtremespb/zoia import admin from "./admin"; import download from "./download"; export default fastify => { fastify.get(fastify.zoiaModulesConfig["backup"].routes.backup, admin()); fastify.get(`/:language${fastify.zoiaModulesConfig["backup"].routes.backup}`, admin()); fastify.get(fastify.zoiaModulesConfig["backup"].routes.download, download()); };
Zardosh/code-forces-solutions
Python/RobotProgram.py
t = int(input()) for _ in range(t): x, y = map(int, input().split()) if abs(x - y) > 1: moves = x + y + abs(x - y) - 1 else: moves = x + y print(moves)
EOL/publishing
app/models/data_integrity_check/has_pair_uri_detailed_report.rb
<gh_stars>10-100 module DataIntegrityCheck::HasPairUriDetailedReport include DataIntegrityCheck::HasDetailedReport def detailed_report_query <<~CYPHER #{query_common} RETURN t1.uri AS uri1, t2.uri AS uri2 CYPHER end end
dongdong1018645785/touch-air-mall
mall-product/src/main/java/com/touch/air/mall/product/dao/AttrGroupDao.java
<reponame>dongdong1018645785/touch-air-mall<filename>mall-product/src/main/java/com/touch/air/mall/product/dao/AttrGroupDao.java package com.touch.air.mall.product.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.touch.air.mall.product.entity.AttrGroupEntity; import com.touch.air.mall.product.vo.SpuItemGroupAttrVo; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 属性分组 * * @author bin.wang * @email <EMAIL> * @date 2020-12-04 13:18:33 */ @Mapper public interface AttrGroupDao extends BaseMapper<AttrGroupEntity> { List<SpuItemGroupAttrVo> getAttrGroupWithAttrsBySpuId(@Param("spuId") Long spuId, @Param("catalogId") Long catalogId); }
embl-cba/fiji-plugin-platyBrowser
src/test/java/projects/OpenRemoteCovidScreen.java
<filename>src/test/java/projects/OpenRemoteCovidScreen.java package projects; import net.imagej.ImageJ; import org.embl.mobie.viewer.MoBIE; import org.embl.mobie.viewer.MoBIESettings; import java.io.IOException; import org.embl.mobie.io.ImageDataFormat; public class OpenRemoteCovidScreen { public static void main( String[] args ) { final ImageJ imageJ = new ImageJ(); imageJ.ui().showUI(); try { new MoBIE("https://github.com/mobie/covid-if-project", MoBIESettings.settings().gitProjectBranch( "main" ).imageDataFormat( ImageDataFormat.OmeZarrS3 ).view( "single_image" ) ); } catch (IOException e) { e.printStackTrace(); } } }
msgilligan/groovy-core
src/main/org/codehaus/groovy/ast/AstToTextHelper.java
<filename>src/main/org/codehaus/groovy/ast/AstToTextHelper.java<gh_stars>100-1000 /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.codehaus.groovy.ast; import java.lang.reflect.Modifier; /** * Helper class for converting AST into text. * @author <NAME> */ public class AstToTextHelper { public static String getClassText(ClassNode node) { if (node == null) return "<unknown>"; if (node.getName() == null) return "<unknown>"; return node.getName(); } public static String getParameterText(Parameter node) { if (node == null) return "<unknown>"; String name = node.getName() == null ? "<unknown>" : node.getName(); String type = getClassText(node.getType()); if (node.getInitialExpression() != null) { return type + " " + name + " = " + node.getInitialExpression().getText(); } return type + " " + name; } public static String getParametersText(Parameter[] parameters) { if (parameters == null) return ""; if (parameters.length == 0) return ""; StringBuilder result = new StringBuilder(); int max = parameters.length; for (int x = 0; x < max; x++) { result.append(getParameterText(parameters[x])); if (x < (max - 1)) { result.append(", "); } } return result.toString(); } public static String getThrowsClauseText(ClassNode[] exceptions) { if (exceptions == null) return ""; if (exceptions.length == 0) return ""; StringBuilder result = new StringBuilder("throws "); int max = exceptions.length; for (int x = 0; x < max; x++) { result.append(getClassText(exceptions[x])); if (x < (max - 1)) { result.append(", "); } } return result.toString(); } public static String getModifiersText(int modifiers) { StringBuilder result = new StringBuilder(); if (Modifier.isPrivate(modifiers)) { result.append("private "); } if (Modifier.isProtected(modifiers)) { result.append("protected "); } if (Modifier.isPublic(modifiers)) { result.append("public "); } if (Modifier.isStatic(modifiers)) { result.append("static "); } if (Modifier.isAbstract(modifiers)) { result.append("abstract "); } if (Modifier.isFinal(modifiers)) { result.append("final "); } if (Modifier.isInterface(modifiers)) { result.append("interface "); } if (Modifier.isNative(modifiers)) { result.append("native "); } if (Modifier.isSynchronized(modifiers)) { result.append("synchronized "); } if (Modifier.isTransient(modifiers)) { result.append("transient "); } if (Modifier.isVolatile(modifiers)) { result.append("volatile "); } return result.toString().trim(); } }
isabella232/axis-axis2-java-sandesha
modules/core/src/main/java/org/apache/sandesha2/storage/inmemory/InMemorySenderBeanMgr.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sandesha2.storage.inmemory; import java.util.Iterator; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import org.apache.axis2.context.AbstractContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.sandesha2.Sandesha2Constants; import org.apache.sandesha2.i18n.SandeshaMessageHelper; import org.apache.sandesha2.i18n.SandeshaMessageKeys; import org.apache.sandesha2.storage.SandeshaStorageException; import org.apache.sandesha2.storage.beanmanagers.SenderBeanMgr; import org.apache.sandesha2.storage.beans.SenderBean; import org.apache.sandesha2.util.LoggingControl; public class InMemorySenderBeanMgr extends InMemoryBeanMgr<SenderBean> implements SenderBeanMgr { private static final Log log = LogFactory.getLog(InMemorySenderBeanMgr.class); ConcurrentHashMap<String, String> sequenceIdandMessNum2MessageId = new ConcurrentHashMap<String, String>(); public InMemorySenderBeanMgr(InMemoryStorageManager mgr, AbstractContext context) { super(mgr, context, Sandesha2Constants.BeanMAPs.RETRANSMITTER); } public boolean delete(String MessageId) throws SandeshaStorageException { SenderBean bean =(SenderBean) super.delete(MessageId); if(bean.getSequenceID()!=null && bean.getMessageNumber()>0){ sequenceIdandMessNum2MessageId.remove(bean.getSequenceID()+":"+bean.getMessageNumber()); } return bean!=null; } public SenderBean retrieve(String MessageId) throws SandeshaStorageException { return (SenderBean) super.retrieve(MessageId); } public SenderBean retrieve(String sequnceId, long messageNumber) throws SandeshaStorageException { String MessageId = (String) sequenceIdandMessNum2MessageId.get(sequnceId+":"+messageNumber); if(MessageId == null){ return null; } return (SenderBean) super.retrieve(MessageId); } public boolean insert(SenderBean bean) throws SandeshaStorageException { if (bean.getMessageID() == null) throw new SandeshaStorageException(SandeshaMessageHelper.getMessage( SandeshaMessageKeys.nullMsgId)); boolean result = super.insert(bean.getMessageID(), bean); if(bean.getSequenceID()!=null && bean.getMessageNumber()>0){ sequenceIdandMessNum2MessageId.put(bean.getSequenceID()+":"+bean.getMessageNumber(), bean.getMessageID()); } mgr.getInMemoryTransaction().setSentMessages(true); return result; } public List<SenderBean> find(String internalSequenceID) throws SandeshaStorageException { SenderBean temp = new SenderBean(); temp.setInternalSequenceID(internalSequenceID); return super.find(temp); } public List<SenderBean> find(SenderBean bean) throws SandeshaStorageException { return super.find(bean); } public SenderBean getNextMsgToSend(String sequenceId) throws SandeshaStorageException { if(LoggingControl.isAnyTracingEnabled() && log.isDebugEnabled()) log.debug("Entry: InMemorySenderBeanManager::getNextMessageToSend " + sequenceId); // Set up match criteria SenderBean matcher = new SenderBean(); matcher.setSend(true); matcher.setSequenceID(sequenceId); matcher.setTimeToSend(System.currentTimeMillis()); matcher.setTransportAvailable(true); List<SenderBean> matches = super.findNoLock(matcher); if(LoggingControl.isAnyTracingEnabled() && log.isDebugEnabled()) log.debug("Found " + matches.size() + " messages"); // Look for the message with the lowest send time, and send that one. SenderBean result = null; Iterator<SenderBean> i = matches.iterator(); while(i.hasNext()) { SenderBean bean = (SenderBean) i.next(); if (bean.getTimeToSend()<0) continue; //Beans with negative timeToSend values are not considered as candidates for sending. if (bean.getSentCount() > 0 && !bean.isReSend()) continue; //Avoid re-sending messages that we should not resend // Check that the Send time has not been updated under another thread if (!bean.match(matcher)) continue; if(result == null) { result = bean; } else if(result.getTimeToSend() > bean.getTimeToSend()) { result = bean; } } // Because the beans weren't locked before, need to do a retrieve to get a locked copy. // And then check that it's still valid if(result!=null){ result = retrieve(result.getMessageID()); if(!result.match(matcher)){ result = null; } } if(LoggingControl.isAnyTracingEnabled() && log.isDebugEnabled()) log.debug("Exit: InMemorySenderBeanManager::getNextMessageToSend " + result); return result; } public boolean update(SenderBean bean) throws SandeshaStorageException { boolean result = super.update(bean.getMessageID(), bean); if(bean.getSequenceID()!=null && bean.getMessageNumber()>0){ sequenceIdandMessNum2MessageId.put(bean.getSequenceID()+":"+bean.getMessageNumber(), bean.getMessageID()); } mgr.getInMemoryTransaction().setSentMessages(true); return result; } public SenderBean findUnique(SenderBean bean) throws SandeshaStorageException { return super.findUnique(bean); } public SenderBean retrieveFromMessageRefKey(String messageContextRefKey) { throw new UnsupportedOperationException("Deprecated method"); } }
zsjdxc251/lesson-chapter
lesson-concurrent/chapter-concurrent-api/chapter-concurrent-api-sample/src/main/java/com/lesson/concurrent/api/sample/ScheduledThreadPoolExecutorSample.java
package com.lesson.concurrent.api.sample; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.RunnableFuture; import java.util.concurrent.RunnableScheduledFuture; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; /** * * 调度线程池 * * {@link ScheduledThreadPoolExecutor} * {@link ScheduledFuture} * {@link RunnableScheduledFuture} * {@link RunnableFuture} * {@code ScheduledFuture} -> {@code RunnableScheduledFuture} -> {@code RunnableFuture} * * {@link RejectedExecutionException} * {@link RejectedExecutionHandler} * {@link Executors.DefaultThreadFactory} * {@link TimeUnit} * @author zhengshijun * @version created on 2018/8/29. */ public class ScheduledThreadPoolExecutorSample { public static void main(String[] args){ ThreadFactory threadFactory = Executors.defaultThreadFactory(); ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(20,threadFactory,(r,e)->{ }); ScheduledFuture scheduled = scheduledThreadPoolExecutor.schedule(()->{ System.out.println("1"); },1, TimeUnit.SECONDS); ScheduledFuture scheduleAtFixedRate = scheduledThreadPoolExecutor.scheduleAtFixedRate(()->{ System.out.println(2); },1,2,TimeUnit.SECONDS); Executors.newCachedThreadPool(); Executors.newFixedThreadPool(1); } }
TheAmeliaDeWitt/YAHoneyPot
modules/MarchCommand/src/main/java/com/marchnetworks/device_ws/Switch.java
package com.marchnetworks.device_ws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; @XmlAccessorType( XmlAccessType.FIELD ) @XmlType( name = "Switch", propOrder = {"id", "type", "switchDeviceId", "switchDeviceAddress", "name", "state", "info"} ) public class Switch { @XmlElement( required = true ) protected String id; @XmlElement( required = true ) protected String type; @XmlElement( required = true ) protected String switchDeviceId; @XmlElement( required = true ) protected String switchDeviceAddress; @XmlElement( required = true ) protected String name; @XmlElement( required = true ) protected String state; protected ArrayOfPair info; public String getId() { return id; } public void setId( String value ) { id = value; } public String getType() { return type; } public void setType( String value ) { type = value; } public String getSwitchDeviceId() { return switchDeviceId; } public void setSwitchDeviceId( String value ) { switchDeviceId = value; } public String getSwitchDeviceAddress() { return switchDeviceAddress; } public void setSwitchDeviceAddress( String value ) { switchDeviceAddress = value; } public String getName() { return name; } public void setName( String value ) { name = value; } public String getState() { return state; } public void setState( String value ) { state = value; } public ArrayOfPair getInfo() { return info; } public void setInfo( ArrayOfPair value ) { info = value; } }
Team-Null-Revature/Icebox
src/main/java/com/revature/_1811_nov27_wvu/icebox/controller/LoginController.java
<gh_stars>0 package com.revature._1811_nov27_wvu.icebox.controller; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.revature._1811_nov27_wvu.icebox.entity.*; import com.revature._1811_nov27_wvu.icebox.services.UserService; @RestController public class LoginController { @Autowired private Logger log; @Autowired private UserService us; @Autowired private HttpSession session; @RequestMapping(method = RequestMethod.GET, value = "/api/login") public User getLogin(HttpSession sess) { return (User) sess.getAttribute("user"); } @RequestMapping(method = RequestMethod.POST, value = "/api/login") public User login(@RequestBody User u) { log.trace("post u:" + u.getUsername() + " " + u.getPass()); User uNew = us.login(u.getUsername(), u.getPass()); if (uNew == null) { log.trace("user not retrieved"); return uNew; } else { session.setAttribute("user", uNew); log.trace("User retrieved" + uNew); log.trace("session object:" + session.getAttribute("user")); return uNew; } } @RequestMapping(method = RequestMethod.DELETE, value = "/api/login") public void logout() { session.invalidate(); log.trace("User logged out."); } }
Oneledger/protocol
scripts/utilities/node_account.py
<filename>scripts/utilities/node_account.py from sdkcom import fullnode, addValidatorWalletAccounts if __name__ == "__main__": account = addValidatorWalletAccounts(fullnode) print account
privosoft/periscope-dsl
dist/es2015/authorization/permissions-manager.js
<filename>dist/es2015/authorization/permissions-manager.js import * as _ from 'lodash'; import { Query } from './../data/query'; import { PermissionsManagerConfiguration } from './permissions-manager-configuration'; export let PermissionsManager = class PermissionsManager { constructor() { this.isConfigured = false; } configure(config) { let normalizedConfig = new PermissionsManagerConfiguration(); config(normalizedConfig); this.permissionsDataSource = normalizedConfig.dataSource; this.isConfigured = true; } hasPermisson(permission, resourceGroup) { if (!this.isConfigured) { return new Promise((resolve, reject) => { resolve(true); }); } return this._getData().then(permissions => { let normalizedPermissions = _.map(permissions, p => { let a = p.toLowerCase().split("-"); if (a.length == 2) return { permission: a[0], group: a[1] }; }); if (_.filter(normalizedPermissions, { 'permission': permission, 'group': resourceGroup }).length > 0) return true; return false; }, err => { return false; }); } _getData() { let q = new Query(); if (this._query) q.filter = this._query; return this.permissionsDataSource.getData(q).then(d => { return d.data; }); } };
sidecar-io/sidecar-arduino-sdk
doc/html/_m_d5_8h.js
var _m_d5_8h = [ [ "MD5", "classqsense_1_1hash_1_1_m_d5.xhtml", "classqsense_1_1hash_1_1_m_d5" ], [ "MD5_HASH_LENGTH", "_m_d5_8h.xhtml#a782c3666ed879b60b7d06c86b8f5fbb5", null ] ];
komiga/hord
src/Hord/LockFile.cpp
/** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <Hord/LockFile.hpp> #include <cstdlib> #include <cstdio> #include <utility> #include <unistd.h> #include <sys/file.h> #include <Hord/detail/gr_ceformat.hpp> namespace Hord { // class LockFile implementation #define HORD_SCOPE_CLASS LockFile LockFile::~LockFile() { release(); } LockFile::LockFile( String path ) noexcept : m_path(std::move(path)) {} #define HORD_SCOPE_FUNC set_path namespace { HORD_DEF_FMT_FQN( s_err_immutable, "cannot change path to `%s` while lock is active" ); } // anonymous namespace void LockFile::set_path( String path ) { if (is_active()) { HORD_THROW_FMT( ErrorCode::lockfile_immutable, s_err_immutable, path ); } else { m_path.assign(std::move(path)); } } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC acquire namespace { HORD_DEF_FMT_FQN( s_err_acquire_failed, "failed to acquire lock for `%s`" ); } // anonymous namespace void LockFile::acquire() { if (!is_active()) { handle_type const fd = ::open( m_path.c_str(), O_CREAT | O_RDONLY, S_IRUSR | S_IRGRP | S_IROTH // 444 ); if (NULL_HANDLE != fd) { if (0 == ::flock(fd, LOCK_EX | LOCK_NB)) { m_handle = fd; } else { ::close(fd); } } if (NULL_HANDLE == m_handle) { // TODO: add std::strerror() HORD_THROW_FMT( ErrorCode::lockfile_acquire_failed, s_err_acquire_failed, m_path ); } } } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC release void LockFile::release() noexcept { if (is_active()) { // TODO: ::remove() on release? ::close(m_handle); m_handle = NULL_HANDLE; } } #undef HORD_SCOPE_FUNC #undef HORD_SCOPE_CLASS } // namespace Hord
camsys/oneclick-core
spec/serializers/api/v2/feedback_serializer_spec.rb
<filename>spec/serializers/api/v2/feedback_serializer_spec.rb require 'rails_helper' RSpec.describe Api::V2::FeedbackSerializer, type: :serializer do let(:feedback) { create(:service_feedback, :acknowledged) } let(:serialization) { Api::V2::FeedbackSerializer.new(feedback).to_h } let(:basic_attributes) { [ :id, :rating, :review, :created_at, :acknowledged, :email, :phone, :subject ] } it "faithfully serializes a feedback with acknowledgement data" do basic_attributes.each do |attr| expect(serialization[attr]).to eq(feedback.send(attr)) end expect(serialization[:acknowledgement_comment]).to eq(feedback.comments.first.comment) expect(serialization[:acknowledged_at]).to eq(feedback.comments.first.updated_at) expect(serialization[:acknowledged_by]).to eq(feedback.comments.first.commenter.full_name) end end
don-reba/peoples-note
src/Test/src/TestUserLoader.cpp
<reponame>don-reba/peoples-note<filename>src/Test/src/TestUserLoader.cpp<gh_stars>0 #include "stdafx.h" #include "UserLoader.h" #include "MockLastUserModel.h" #include "MockNoteListView.h" #include "MockCredentialsModel.h" using namespace boost; using namespace std; struct UserLoaderFixture { MockCredentialsModel credentialsModel; MockLastUserModel lastUserModel; UserLoader userLoader; UserLoaderFixture() : userLoader(credentialsModel, lastUserModel) { } }; BOOST_FIXTURE_TEST_CASE ( UserLoader_Run , UserLoaderFixture ) { lastUserModel.username = L"username"; lastUserModel.password = L"password"; userLoader.Run(); BOOST_CHECK_EQUAL(credentialsModel.username, L"username"); BOOST_CHECK_EQUAL(credentialsModel.password, L"password"); } BOOST_FIXTURE_TEST_CASE ( UserLoader_Commit , UserLoaderFixture ) { credentialsModel.username = L"username"; credentialsModel.password = L"password"; credentialsModel.Commit(); BOOST_CHECK_EQUAL(lastUserModel.username, L"username"); BOOST_CHECK_EQUAL(lastUserModel.password, L"password"); }
ewilde/terraform-provider-form3
client/associations/get_lhv_responses.go
// Code generated by go-swagger; DO NOT EDIT. package associations // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/runtime" "github.com/go-openapi/strfmt" "github.com/form3tech-oss/terraform-provider-form3/models" ) // GetLhvReader is a Reader for the GetLhv structure. type GetLhvReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *GetLhvReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewGetLhvOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 400: result := NewGetLhvBadRequest() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 401: result := NewGetLhvUnauthorized() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 403: result := NewGetLhvForbidden() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 404: result := NewGetLhvNotFound() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 409: result := NewGetLhvConflict() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 429: result := NewGetLhvTooManyRequests() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 500: result := NewGetLhvInternalServerError() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 503: result := NewGetLhvServiceUnavailable() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: return nil, runtime.NewAPIError("unknown error", response, response.Code()) } } // NewGetLhvOK creates a GetLhvOK with default headers values func NewGetLhvOK() *GetLhvOK { return &GetLhvOK{} } /*GetLhvOK handles this case with default header values. List of associations */ type GetLhvOK struct { Payload *models.LhvAssociationDetailsListResponse } func (o *GetLhvOK) Error() string { return fmt.Sprintf("[GET /lhv][%d] getLhvOK %+v", 200, o.Payload) } func (o *GetLhvOK) GetPayload() *models.LhvAssociationDetailsListResponse { return o.Payload } func (o *GetLhvOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.LhvAssociationDetailsListResponse) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvBadRequest creates a GetLhvBadRequest with default headers values func NewGetLhvBadRequest() *GetLhvBadRequest { return &GetLhvBadRequest{} } /*GetLhvBadRequest handles this case with default header values. Bad Request */ type GetLhvBadRequest struct { Payload *models.APIError } func (o *GetLhvBadRequest) Error() string { return fmt.Sprintf("[GET /lhv][%d] getLhvBadRequest %+v", 400, o.Payload) } func (o *GetLhvBadRequest) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvUnauthorized creates a GetLhvUnauthorized with default headers values func NewGetLhvUnauthorized() *GetLhvUnauthorized { return &GetLhvUnauthorized{} } /*GetLhvUnauthorized handles this case with default header values. Authentication credentials were missing or incorrect */ type GetLhvUnauthorized struct { Payload *models.APIError } func (o *GetLhvUnauthorized) Error() string { return fmt.Sprintf("[GET /lhv][%d] getLhvUnauthorized %+v", 401, o.Payload) } func (o *GetLhvUnauthorized) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvForbidden creates a GetLhvForbidden with default headers values func NewGetLhvForbidden() *GetLhvForbidden { return &GetLhvForbidden{} } /*GetLhvForbidden handles this case with default header values. Forbidden */ type GetLhvForbidden struct { Payload *models.APIError } func (o *GetLhvForbidden) Error() string { return fmt.Sprintf("[GET /lhv][%d] getLhvForbidden %+v", 403, o.Payload) } func (o *GetLhvForbidden) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvNotFound creates a GetLhvNotFound with default headers values func NewGetLhvNotFound() *GetLhvNotFound { return &GetLhvNotFound{} } /*GetLhvNotFound handles this case with default header values. Record not found */ type GetLhvNotFound struct { Payload *models.APIError } func (o *GetLhvNotFound) Error() string { return fmt.Sprintf("[GET /lhv][%d] getLhvNotFound %+v", 404, o.Payload) } func (o *GetLhvNotFound) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvConflict creates a GetLhvConflict with default headers values func NewGetLhvConflict() *GetLhvConflict { return &GetLhvConflict{} } /*GetLhvConflict handles this case with default header values. Conflict */ type GetLhvConflict struct { Payload *models.APIError } func (o *GetLhvConflict) Error() string { return fmt.Sprintf("[GET /lhv][%d] getLhvConflict %+v", 409, o.Payload) } func (o *GetLhvConflict) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvTooManyRequests creates a GetLhvTooManyRequests with default headers values func NewGetLhvTooManyRequests() *GetLhvTooManyRequests { return &GetLhvTooManyRequests{} } /*GetLhvTooManyRequests handles this case with default header values. The request cannot be served due to the application’s rate limit */ type GetLhvTooManyRequests struct { Payload *models.APIError } func (o *GetLhvTooManyRequests) Error() string { return fmt.Sprintf("[GET /lhv][%d] getLhvTooManyRequests %+v", 429, o.Payload) } func (o *GetLhvTooManyRequests) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvTooManyRequests) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvInternalServerError creates a GetLhvInternalServerError with default headers values func NewGetLhvInternalServerError() *GetLhvInternalServerError { return &GetLhvInternalServerError{} } /*GetLhvInternalServerError handles this case with default header values. Internal Server Error */ type GetLhvInternalServerError struct { Payload *models.APIError } func (o *GetLhvInternalServerError) Error() string { return fmt.Sprintf("[GET /lhv][%d] getLhvInternalServerError %+v", 500, o.Payload) } func (o *GetLhvInternalServerError) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvServiceUnavailable creates a GetLhvServiceUnavailable with default headers values func NewGetLhvServiceUnavailable() *GetLhvServiceUnavailable { return &GetLhvServiceUnavailable{} } /*GetLhvServiceUnavailable handles this case with default header values. The server is up, but overloaded with requests. Try again later. */ type GetLhvServiceUnavailable struct { Payload *models.APIError } func (o *GetLhvServiceUnavailable) Error() string { return fmt.Sprintf("[GET /lhv][%d] getLhvServiceUnavailable %+v", 503, o.Payload) } func (o *GetLhvServiceUnavailable) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil }
danielil/Data-Structures
Sources/Includes/trees/tbst.cpp
/** * @author <NAME> * * This file contains the methods associated with the following classes: * ThreadedBinarySearchTree : class implementing the actual TBST * TreeIterator : class implementing the TBST iterator */ #include <algorithm> #include <iostream> #include "tbst.hpp" namespace dsa { // Minimum number of nodes required for compressing the tree const int COMPRESSION_MIN_NODES = 3; using namespace std; // Function prototypes static bool isTokenChar(char ch); /** * ThreadedBinarySearchTree() * * Default constructor */ ThreadedBinarySearchTree::ThreadedBinarySearchTree() : rootNode(nullptr), treeSize(0), treeHeight(0) { } /** * ThreadedBinarySearchTree(const ThreadedBinarySearchTree& source) * * Copy constructor * @param source TBST to copy */ ThreadedBinarySearchTree::ThreadedBinarySearchTree( const ThreadedBinarySearchTree& source) : rootNode(nullptr), treeSize(0), treeHeight(0) { Node** nodesList = source.preorderTraverse(); if (nodesList != nullptr) { // We sort the node by ID to ensure that we insert data in the // same order as in the source tree // Sort::quickSort(BY_ID, nodesList, source.getNodesCount()); for (int i = 0; i < source.getNodesCount(); i++) { const Node* list = nodesList[i]; insert(*list); } } delete [] nodesList; } /** * ThreadedBinarySearchTree() * * Destructor */ ThreadedBinarySearchTree::~ThreadedBinarySearchTree() { destroy(rootNode); } /** * isEmpty() const * * Method checking whether the tree is empty or not. * * @pre None * @post Checks whether tree has any node * @return True if tree is empty; false otherwise */ bool ThreadedBinarySearchTree::isEmpty() const { return treeSize == 0; } /** * isVine() const * * Method checking whether the tree was transformed into a Vine. * Vine is a degenerate binary tree resembling a linked list, in which * each node has at most one child. * * @pre None * @post Checks whether tree has any node * @return True if tree is empty; false otherwise */ bool ThreadedBinarySearchTree::isVine() const { return (treeSize > 0) && (treeSize == treeHeight); } /** * getNodesCount() const * * Method retrieving the tree size (in number of nodes). * * @pre None * @post Returns the current tree size * @return tree size */ int ThreadedBinarySearchTree::getNodesCount() const { return treeSize; } /** * getHeigth() const * * Method retrieving the tree height. * * @pre None * @post Returns the current tree height * @return tree height */ int ThreadedBinarySearchTree::getHeigth() const { return treeHeight; } /** * clear() * * Method destroying all the nodes in the tree and initializing its properties * * @pre None * @post Tree is left empty */ void ThreadedBinarySearchTree::clear() { destroy(rootNode); rootNode = nullptr; treeSize = 0; treeHeight = 0; } /** * balance() * * Method for balancing the tree in two steps: * 1. Tree is transformed into a vine (i.e. a linear structure resembling a * linked list) by use of rotations. * 2. Vine is transformed back into a balanced tree. * * @pre Tree is not empty * @post Tree is balanced */ void ThreadedBinarySearchTree::balance() { treeToVine(); vineToTree(); } /** * treeToVine() * * Method for transforming the tree into a vine by use of rotations. * Vine is a degenerate binary tree resembling a linked list, in which * each node has at most one child. * * @pre Tree is not empty * @post Tree is transformed into a Vine */ void ThreadedBinarySearchTree::treeToVine() { if (!isEmpty()) { Node* current = getFirst(); bool run = (current != nullptr); while (run) { Node* next = getNext(current); current->rightNodeType = THREAD; current->rightNode = next; if (next == nullptr) { run = false; } else { next->leftNodeType = CHILD; next->leftNode = current; current = next; } } rootNode = current; // Reset the nodes depths and parents init(nullptr); } } /** * vineToTree() * * Method for transforming a vine into a balanced tree. * Vine is a degenerate binary tree resembling a linked list, in which * each node has at most one child. * The transformation is based on the algorithm defined here: * http://adtinfo.org/libavl.html/Transforming-a-Vine-into-a-Balanced-TBST.html * * @pre Tree was previously transformed into a Vine * @post Vine is transformed into a Tree */ void ThreadedBinarySearchTree::vineToTree() { if (isVine()) { int leaves = treeSize + 1; // Nodes in incomplete bottom level (if any) bool run = true; while (run) { int next = leaves & (leaves - 1); if (next == 0) { run = false; } else { leaves = next; } } leaves = treeSize + 1 - leaves; compress(0, leaves); // nodes in main vine int vine = treeSize - leaves; if (vine > 1) { int nonLeaves = vine / 2; leaves /= 2; if (leaves > nonLeaves) { leaves = nonLeaves; nonLeaves = 0; } else { nonLeaves -= leaves; } compress (leaves, nonLeaves); vine /= 2; } while (vine > 1) { vine /= 2; compress (vine, 0); } // Reset the nodes depths and parents init(nullptr); } } /** * find(const string& token) const * * Method searching for the node holding the input token. * * @param token Data to search for * @pre None * @post Returns node holding the token * @return Node on success; NULL on failure */ Node* ThreadedBinarySearchTree::find(const string& token) const { if (!token.empty() && (rootNode != nullptr)) { Node* current = rootNode; bool run = (current != nullptr); while (run) { int result = current->data.compare(token); if (result == 0) { // Match found! return current; } else if (result > 0) { // Navigate through the left branch if (current->leftNodeType == THREAD) { // No match found; end search. run = false; } else { current = current->leftNode; } } else { // Navigate through the right branch if (current->rightNodeType == THREAD) { // No match found; end search. run = false; } else { current = current->rightNode; } } } } return nullptr; } /** * insert(const string& token) * * Method inserting a new token into the tree. * If the token exists, then it only increments its frequency. * * @param token Data to insert * @pre token is valid (not empty) * @post Returns the outcome of the operation * @return true on success; false on failure */ bool ThreadedBinarySearchTree::insert(const string& token) { bool success = !token.empty(); if (success) { Node* newNode = new Node(token); // If insertHelper returns false, it means that we found // a duplicate whose frequency was incremented. // The operation is still a success if (!insertHelper(newNode)) { delete newNode; } } return success; } /** * insert(const string& token) * * Method inserting a new node into the tree. * If the token exists, then it only increments its frequency. * * @param node Reference node to copy * @pre Reference node is valid * @post Returns the outcome of the operation * @return true on success; false on failure */ bool ThreadedBinarySearchTree::insert(const Node& node) { Node* newNode = new Node(node); bool success = newNode->data.isValid(); if (success) { // If insertHelper returns false, it means that we found // a duplicate whose frequency was incremented. // The operation is still a success if (!insertHelper(newNode)) { delete newNode; } } return success; } /** * remove(const string& token) * * Method removing a token from the tree. * * @param token Data to remove * @pre token is valid (not empty) * @post Returns the outcome of the operation * @return true on success; false on failure */ bool ThreadedBinarySearchTree::remove(const string& token) { bool rightLink = false; // navigation direction: false/true => left/right Node* current = nullptr; // node to remove Node* parent = nullptr; // parent of node to remove bool success = false; // Find node to remove if (!token.empty() && (rootNode != nullptr)) { current = rootNode; bool run = (current != nullptr); while (run) { int result = current->data.compare(token); if (result == 0) { // Match found! success = true; run = false; } else if (result > 0) { // Navigate through the left branch rightLink = false; if (current->leftNodeType == THREAD) { // No match found; end search. run = false; } else { parent = current; current = current->leftNode; } } else { // Navigate through the right branch rightLink = true; if (current->rightNodeType == THREAD) { // No match found; end search. run = false; } else { parent = current; current = current->rightNode; } } } } if (success) { // Assess the links of node to remove if (treeSize == 1) { // We are about to remove the last node in the tree clear(); } else if (current->rightNodeType == THREAD) { if (current->leftNodeType == THREAD) { // Both links are of THREAD type (that is, node to remove // is not the root node; otherwise, the treeSize should // have been 1) if (parent != nullptr) { if (rightLink) { parent->rightNode = current->rightNode; parent->rightNodeType = THREAD; } else { parent->leftNode = current->leftNode; parent->leftNodeType = THREAD; } } } else { // One link (the left one) is a CHILD Node* child = current->leftNode; // Locate the next node (in order) for that child while (child->rightNodeType == CHILD) { child = child->rightNode; } // Reset the links of the child and parent nodes child->rightNode = current->rightNode; if (parent != nullptr) { if (rightLink) { parent->rightNode = current->leftNode; } else { parent->leftNode = current->leftNode; } } else if (current == rootNode) { rootNode = current->leftNode; } } } else { // Right node is CHILD Node* child = current->rightNode; if (child->leftNodeType == THREAD) { // Only the right node is a CHILD child->leftNode = current->leftNode; child->leftNodeType = current->leftNodeType; if (child->leftNodeType == CHILD) { Node* childLink = child->leftNode; while (childLink->rightNodeType == CHILD) { childLink = childLink->rightNode; } childLink->rightNode = child; } // Reset the links of the parent node if (parent != nullptr) { if (rightLink) { parent->rightNode = child; } else { parent->leftNode = child; } } else if (current == rootNode) { rootNode = child; } } else { // Both links are of CHILD type Node* childLink = child->leftNode; // Get the lowest node on left branch while (childLink->leftNodeType == CHILD) { child = childLink; childLink = child->leftNode; } // Reset the links of the child and grandchild nodes if (childLink->rightNodeType == CHILD) { child->leftNode = childLink->rightNode; } else { child->leftNode = childLink; child->leftNodeType = THREAD; } childLink->leftNode = current->leftNode; if (current->leftNodeType == CHILD) { Node* prevLink = current->leftNode; while (prevLink->rightNodeType == CHILD) { prevLink = prevLink->rightNode; } prevLink->rightNode = childLink; childLink->leftNodeType = CHILD; } childLink->rightNode = current->rightNode; childLink->rightNodeType = CHILD; // Reset the links of the parent node if (parent != nullptr) { if (rightLink) { parent->rightNode = childLink; } else { parent->leftNode = childLink; } } else if (current == rootNode) { rootNode = childLink; } } } if (treeSize > 0) { // Delete node to remove, decrement size and reset parent links treeSize--; if (current->leftNodeType == CHILD) { current->leftNode->parentNode = nullptr; } if (current->rightNodeType == CHILD) { current->rightNode->parentNode = nullptr; } delete current; // Reset the nodes depths and parents init(nullptr); } } return success; } /** * getFirst() const * * Method retrieving the node holding the first token (in order). * * @pre None * @post Returns node holding the first token * @return Node on success; NULL on failure */ Node* ThreadedBinarySearchTree::getFirst() const { Node* first = rootNode; while ((first != nullptr) && (first->leftNodeType == CHILD)) { first = first->leftNode; } return first; } /** * getLast() const * * Method retrieving the node holding the last token (in order). * * @pre None * @post Returns node holding the last token * @return Node on success; NULL on failure */ Node* ThreadedBinarySearchTree::getLast() const { Node* last = rootNode; while ((last != nullptr) && (last->rightNodeType == CHILD)) { last = last->rightNode; } return last; } /** * getNext() const * * Method retrieving the node holding the next token. * * @param current Reference node * @pre None * @post Returns node holding the next token * @return Node on success; NULL on failure */ Node* ThreadedBinarySearchTree::getNext(Node* current) const { Node* next; if (current == nullptr) { next = getFirst(); } else if (current->rightNodeType == THREAD) { next = current->rightNode; } else { next = current->rightNode; while (next->leftNodeType == CHILD) { next = next->leftNode; } } return next; } /** * getNext() const * * Method retrieving the node holding the previous token. * * @param current Reference node * @pre None * @post Returns node holding the previous token * @return Node on success; NULL on failure */ Node* ThreadedBinarySearchTree::getPrevious(Node* current) const { Node* previous; if (current == nullptr) { previous = getLast(); } else if (current->leftNodeType == THREAD) { previous = current->leftNode; } else { previous = current->leftNode; while (previous->rightNodeType == CHILD) { previous = previous->rightNode; } } return previous; } /** * begin() * * Method returning a tree iterator initialized for incremental navigation. * * @pre Tree is not empty * @post Constructs and initialize iterator for forward navigation. * @return Initialized iterator */ TreeIterator ThreadedBinarySearchTree::begin() { TreeIterator iter(this); iter.currentNode = getFirst(); return iter; } /** * rbegin() * * Method returning a tree iterator initialized for decremental navigation. * * @pre Tree is not empty * @post Constructs and initialize iterator for backward navigation. * @return Initialized iterator */ TreeIterator ThreadedBinarySearchTree::rbegin() { TreeIterator iter(this); iter.currentNode = getLast(); return iter; } /** * end() * * Method returning a tree iterator initialized for incremental navigation * and having the position moved beyond the last node. * * @pre Tree is not empty * @post Constructs and initialize iterator. * @return Initialized iterator */ TreeIterator ThreadedBinarySearchTree::end() { TreeIterator iter(this); iter.currentNode = getNext(getLast()); return iter; } /** * rend() * * Method returning a tree iterator initialized for decremental navigation * and having the position moved beyond the first node. * * @pre Tree is not empty * @post Constructs and initialize iterator. * @return Initialized iterator */ TreeIterator ThreadedBinarySearchTree::rend() { TreeIterator iter(this); iter.currentNode = getPrevious(getFirst()); return iter; } /** * inorderIterativeTraverse() const * * Method returning the in-order traversal list of nodes. * It employs an iterative approach. * * @pre None * @post Returns list of in-order traversal nodes * @return List of nodes on success; NULL on failure */ Node** ThreadedBinarySearchTree::inorderIterativeTraverse() const { Node** nodesList = createNodesList(); if (nodesList != nullptr) { Node* current = getNext(nullptr); int count = 0; while (current != nullptr) { nodesList[count++] = current; current = getNext(current); } } return nodesList; } /** * preorderTraverse() const * * Method returning the pre-order traversal list of nodes. * It employs an recursive approach. * * @pre None * @post Returns list of pre-order traversal nodes * @return List of nodes on success; NULL on failure */ Node** ThreadedBinarySearchTree::preorderTraverse() const { Node** nodesList = createNodesList(); if (nodesList != nullptr) { int count = 0; traverseHelper(PREORDER, rootNode, nodesList, count); } return nodesList; } /** * inorderTraverse() const * * Method returning the in-order traversal list of nodes. * It employs an recursive approach. * * @pre None * @post Returns list of in-order traversal nodes * @return List of nodes on success; NULL on failure */ Node** ThreadedBinarySearchTree::inorderTraverse() const { Node** nodesList = createNodesList(); if (nodesList != nullptr) { int count = 0; traverseHelper(INORDER, rootNode, nodesList, count); } return nodesList; } /** * postorderTraverse() const * * Method returning the post-order traversal list of nodes. * It employs an recursive approach.h. * * @pre None * @post Returns list of post-order traversal nodes * @return List of nodes on success; NULL on failure */ Node** ThreadedBinarySearchTree::postorderTraverse() const { Node** nodesList = createNodesList(); if (nodesList != nullptr) { int count = 0; traverseHelper(POSTORDER, rootNode, nodesList, count); } return nodesList; } /** * operator>>(istream& is, ThreadedBinarySearchTree& tbst) * * Overloaded operator for populating the tree from an input stream. * * @param is Input stream sourcing the data * @param tbst Tree to populate * @pre None * @post Tree is filled up with data supplied by input stream. * @return Reference to input stream */ istream& operator>>(istream& is, ThreadedBinarySearchTree& tbst) { bool error = false; string data; while (!error && is.good()) { char ch = static_cast<char>(is.get()); if (isTokenChar(ch)) { // alphanumeric - build the token data.push_back(ch); } else { // We reached a word boundary; insert the token built so far. if (!data.empty()) { // Insert the current token (if any) if (tbst.insert(data)) { data.clear(); } else { error = true; } } if (!error && (isprint(ch) != 0) && (isspace(ch) == 0) && (isgraph(ch) == 0)) { // Non white-space delimiter - inserted as a single char data.push_back(ch); if (tbst.insert(data)) { data.clear(); } else { error = true; } } if (error) { cerr << "Failed to insert "; cerr << data.c_str() << "\r\n"; } } } is.clear(); return is; } /** * show(std::ostream& output, bool details) const * * Helper method for pushing the tree information into an output stream. * * @param output Output stream * @param details Whether to display extended info * @pre None * @post data is pushed into the stream. */ void ThreadedBinarySearchTree::show(std::ostream& output, bool details) const { output << "Threaded Binary Search Tree: "; output << "size = " << treeSize; output << ", height = " << treeHeight; output << "\r\n"; if (details) { Node* current = getNext(nullptr); while (current != nullptr) { current->show(output, true); current = getNext(current); } output << "\r\n"; } } /** * show(std::ostream& output, Node** nodesList, bool details) const * * Helper method for pushing the nodes information into an output stream. * * @param output Output stream * @param nodesList List of nodes to display * @param details Whether to display extended info * @pre List is not NULL or empty * @post data is pushed into the stream. */ void ThreadedBinarySearchTree::show( std::ostream& output, Node** nodesList, bool details) const { if ((treeSize > 0) && (nodesList != nullptr)) { for (int i = 0; i < treeSize; i++) { if (details) { nodesList[i]->show(output, true); } else { if ((i % NODES_PER_LINE) == 0) { if (i > 0) { output << "\r\n"; } output << "\t"; } nodesList[i]->show(output, false); output << " "; } } } } /** * showPartial(std::ostream& output, Node** nodesList, bool top) const * * Helper method for pushing the nodes information into an output stream. * Only top of the list is displayed. * @param output Output stream * @param nodesList List of nodes to display * @param top Whether to show the bottom of the top of the list * @pre List is not NULL or empty * @post data is pushed into the stream. */ void ThreadedBinarySearchTree::showPartial( std::ostream& output, Node** nodesList, bool top) const { if ((treeSize > 0) && (nodesList != nullptr)) { if (treeSize <= NODES_DISPLAYED) { ThreadedBinarySearchTree::show( output, nodesList, 0, treeSize - 1); } else if (top) { ThreadedBinarySearchTree::show( output, nodesList, treeSize - NODES_DISPLAYED, treeSize - 1); } else { ThreadedBinarySearchTree::show( output, nodesList, 0, NODES_DISPLAYED - 1); } } } /** * show(std::ostream& output, Node** nodesList, int first, int last) const * * Helper method for pushing the nodes information into an output stream. * * @param output Output stream * @param nodesList List of nodes to display * @param first Index of of first node to display * @param last Index of of last node to display * @pre List is not NULL or empty; first & last parameters are valid. * @post data is pushed into the stream. */ void ThreadedBinarySearchTree::show( std::ostream& output, Node** nodesList, int first, int last) { if ((nodesList != nullptr) && (first >= 0) && (first <= last)) { output << "\t"; for (int i = first, nodes = 0; i <= last; i++, nodes++) { if ((nodes > 0) && ((nodes % NODES_PER_LINE) == 0)) { output << "\r\n"; output << "\t"; } nodesList[i]->show(output, false); output << " "; } output << "\r\n"; } } /** * createNodesList() const * * Helper method for creating a array to hold all the nodes in the tree. * The array will be further filled with traversal nodes. * * @pre The tree is not empty * @post Returns array that can hold all the nodes * @return Array of Node pointers */ Node** ThreadedBinarySearchTree::createNodesList() const { Node** nodesList = nullptr; if (treeSize > 0) { nodesList = new Node*[treeSize]; for (int i = 0; i < treeSize; i++) { nodesList[i] = nullptr; } } return nodesList; } /** * init(Node* node) * * Helper method for re-setting the depth and parent for each node * (starting from a reference node) * * @param Node Initial node to start with * @pre None * @post Depth and parent are set for each node */ void ThreadedBinarySearchTree::init(Node* node) { if (node == nullptr) { if (rootNode != nullptr) { rootNode->depth = 0; rootNode->parentNode = nullptr; treeHeight = 0; init(rootNode); } } else { treeHeight = std::max(treeHeight, node->depth + 1); if (node->leftNodeType == CHILD) { node->leftNode->depth = node->depth + 1; node->leftNode->parentNode = node; init(node->leftNode); } if (node->rightNodeType == CHILD) { node->rightNode->depth = node->depth + 1; node->rightNode->parentNode = node; init(node->rightNode); } } } /** * insertHelper(Node* newNode) * * Helpert method for inserting a new node into the tree. * * @param node Node to insert * @pre Node is valid * @post Returns the outcome of the operation * @return true on success; false on failure */ bool ThreadedBinarySearchTree::insertHelper(Node* newNode) { Node* current = rootNode; // current reference node bool success = false; if ((newNode != nullptr) && newNode->data.isValid()) { if (rootNode == nullptr) { rootNode = newNode; success = true; } else { // Search for the insertion position int result = -1; while (!success && (result != 0)) { result = current->data.compare(newNode->data.getToken()); if (result == 0) { // duplicate found current->data.increaseFrequency(); } else if (result > 0) { // Navigate the left branch if (current->leftNodeType == CHILD) { current = current->leftNode; } else { // Insertion point found on left branch newNode->leftNode = current->leftNode; newNode->rightNode = current; current->leftNode = newNode; current->leftNodeType = CHILD; success = true; } } else { // Navigate the right branch if (current->rightNodeType == CHILD) { current = current->rightNode; } else { // Insertion point found on right branch newNode->leftNode = current; newNode->rightNode = current->rightNode; current->rightNode = newNode; current->rightNodeType = CHILD; success = true; } } } } } if (success) { treeSize++; newNode->id = treeSize; newNode->parentNode = current; newNode->depth = (current == nullptr) ? 0 : (current->depth + 1); treeHeight = std::max(treeHeight, newNode->depth + 1); } return success; } /** * compress(int nonThreadCount, int threadCount) * * Helper method for compressing a tree: * 1. Performs a non-threaded compression operation nonThreadCount times. * 2. Performs a threaded compression operation threadCount times. * Reference: * http://adtinfo.org/libavl.html/Transforming-a-Vine-into-a-Balanced-TBST.html * * @pre Tree has at least 3 nodes * @post Tree is compressed */ void ThreadedBinarySearchTree::compress(int nonThreadCount, int threadCount) const { if (treeSize >= COMPRESSION_MIN_NODES) { Node* root = rootNode; while ((root != nullptr) && (nonThreadCount-- > 0)) { Node* red = root->leftNode; Node* black = red->leftNode; root->leftNode = black; red->leftNode = black->rightNode; black->rightNode = red; root = black; } while ((root != nullptr) && (threadCount-- > 0)) { Node* red = root->leftNode; Node* black = red->leftNode; root->leftNode = black; red->leftNode = black; red->leftNodeType = THREAD; black->rightNodeType = CHILD; root = black; } } } /** * destroy(Node* node) * * Helper method destroying all the nodes (starting from a reference node) * * @param Node Initial node to start with * @pre None * @post All nodes (including the reference) are deleted */ void ThreadedBinarySearchTree::destroy(Node* node) { if (node != nullptr) { if (node->leftNodeType == CHILD) { destroy(node->leftNode); } if (node->rightNodeType == CHILD) { destroy(node->rightNode); } delete node; } } /** * traverseHelper(int traverseType, Node* node, StackNode** nodesList, * int& currentPosition); * * Helpert method for recursive traversal starting from a reference node. * * @param traverseType Type of traversal (PREORDER, INORDER, POSTORDER) * @param node Reference node to start with * @param nodesList Traversal list * @param currentPosition Current position within traversal list * @pre Reference node and traversal list are not NULL */ void ThreadedBinarySearchTree::traverseHelper( int traverseType, Node* node, Node** nodesList, int& currentPosition) { if ((node != nullptr) && (nodesList != nullptr) && (currentPosition >= 0)) { switch (traverseType) { case PREORDER: nodesList[currentPosition++] = node; if (node->leftNodeType == CHILD) { traverseHelper( traverseType, node->leftNode, nodesList, currentPosition); } if (node->rightNodeType == CHILD) { traverseHelper( traverseType, node->rightNode, nodesList, currentPosition); } break; case INORDER: if (node->leftNodeType == CHILD) { traverseHelper( traverseType, node->leftNode, nodesList, currentPosition); } nodesList[currentPosition++] = node; if (node->rightNodeType == CHILD) { traverseHelper( traverseType, node->rightNode, nodesList, currentPosition); } break; case POSTORDER: if (node->leftNodeType == CHILD) { traverseHelper( traverseType, node->leftNode, nodesList, currentPosition); } if (node->rightNodeType == CHILD) { traverseHelper( traverseType, node->rightNode, nodesList, currentPosition); } nodesList[currentPosition++] = node; break; } } } /** * TreeIterator(ThreadedBinarySearchTree* tbst) * * Constructor * @param tbst TBS tree to iterate over */ TreeIterator::TreeIterator(ThreadedBinarySearchTree* tbst) : tbsTree(tbst), currentNode(nullptr) { } /** * TreeIterator(ThreadedBinarySearchTree* tbst) * * Copy constructor * @param treeIter Source iterator */ TreeIterator::TreeIterator(const TreeIterator& treeIter) : tbsTree(treeIter.tbsTree), currentNode(treeIter.currentNode) { } /** * operator*() * * De-reference operator * * @pre None * @post Retrieves the current iteration node * @return current node */ Node*& TreeIterator::operator*() { return currentNode; } /** * operator++() * * Increment operator - prefix form * * @pre None * @post The iterator is advanced forward. * @return A reference to current iterator */ TreeIterator& TreeIterator::operator++() { currentNode = tbsTree->getNext(currentNode); return *this; } /** * operator++() * * Increment operator - postfix form * * @pre None * @post The iterator is advanced forward. * @return A reference to current iterator */ TreeIterator TreeIterator::operator++(int) { TreeIterator iter(*this); operator++(); return iter; } /** * operator--() * * Decrement operator - prefix form * * @pre None * @post The iterator is advanced backward. * @return A reference to current iterator */ TreeIterator& TreeIterator::operator--() { currentNode = tbsTree->getPrevious(currentNode); return *this; } /** * operator--() * * Decrement operator - postfix form * * @pre None * @post The iterator is advanced backward. * @return A reference to current iterator */ TreeIterator TreeIterator::operator--(int) { TreeIterator iter(*this); operator--(); return iter; } /** * operator==(const TreeIterator& treeIter) * * Equality operator * * @param treeIter The iterator used as comparison target. * @pre None * @post The local data is compared against the target data. * @return True if the data are matching; false otherwise. */ bool TreeIterator::operator==(const TreeIterator& treeIter) const { return (tbsTree == treeIter.tbsTree) && (currentNode == treeIter.currentNode); } /** * operator!=(const TreeIterator& treeIter) * * Equality operator * * @param treeIter The iterator used as comparison target. * @pre None * @post The local data is compared against the target data. * @return True if the data are matching; false otherwise. */ bool TreeIterator::operator!=(const TreeIterator& treeIter) const { return (tbsTree != treeIter.tbsTree) || (currentNode != treeIter.currentNode); } /** * isTokenChar(char ch) * * Function checking whether input character is part of word token. * * @param ch Character to check. * @pre None * @post Character is compared against our definition of token data. * @return True of char belongs to a token; false otherwise. */ bool isTokenChar(char ch) { switch (ch) { case '\'': case '\"': case '-': case '_': return true; default: break; } return (isalnum(ch) != 0); } }
joelnewcom/embeddedOracleKv
src/main/resources/oracle-db/kv-18.1.19/src/oracle/kv/impl/admin/plan/NetworkRestorePlan.java
/*- * Copyright (C) 2011, 2018 Oracle and/or its affiliates. All rights reserved. * * This file was distributed by Oracle as part of a version of Oracle NoSQL * Database made available at: * * http://www.oracle.com/technetwork/database/database-technologies/nosqldb/downloads/index.html * * Please see the LICENSE file included in the top-level directory of the * appropriate version of Oracle NoSQL Database for a copy of the license and * additional information. */ package oracle.kv.impl.admin.plan; import java.util.Formatter; import java.util.List; import java.util.Map; import java.util.logging.Logger; import oracle.kv.KVVersion; import oracle.kv.impl.admin.Admin; import oracle.kv.impl.admin.IllegalCommandException; import oracle.kv.impl.admin.plan.task.ParallelBundle; import oracle.kv.impl.admin.plan.task.StartNetworkRestore; import oracle.kv.impl.admin.plan.task.WaitForNetworkRestore; import oracle.kv.impl.security.KVStorePrivilege; import oracle.kv.impl.security.SystemPrivilege; import oracle.kv.impl.sna.StorageNodeStatus; import oracle.kv.impl.topo.RepNodeId; import oracle.kv.impl.topo.ResourceId; import oracle.kv.impl.topo.StorageNodeId; import oracle.kv.impl.topo.Topology; import oracle.kv.impl.util.FormatUtils; import oracle.kv.impl.util.VersionUtil; import oracle.kv.impl.util.registry.RegistryUtils; /** * Performing a plan to run network restore from source to target node. */ public class NetworkRestorePlan extends AbstractPlan { private static final long serialVersionUID = 1L; private final static KVVersion NETWORK_RESTORE_VERSION = KVVersion.R4_4; /* * Using resource id instead of RepNode id for future extension for Admin, * though only RepNode is supported now. */ private final ResourceId sourceId; private final ResourceId targetId; public NetworkRestorePlan(String planName, Planner planner, ResourceId sourceId, ResourceId targetId, boolean retainOriginalLog) { super(planName, planner); this.sourceId = sourceId; this.targetId = targetId; if (sourceId.getType() != targetId.getType()) { throw new IllegalCommandException( "Cannot restore a node from other node with different type. " + "Source node type is " + sourceId.getType() + " but target node type is " + targetId.getType()); } if (!sourceId.getType().isRepNode()) { throw new IllegalCommandException("Only RepNode can be restored."); } if (sourceId.equals(targetId)) { throw new IllegalCommandException( "Source node " + sourceId + " and target node " + targetId + " is the same one."); } final RepNodeId sourceRN = (RepNodeId) sourceId; final RepNodeId targetRN = (RepNodeId) targetId; /* Verify if source and target are in the same replication group */ if (sourceRN.getGroupId() != targetRN.getGroupId()) { throw new IllegalCommandException( "Source RepNode " + sourceRN + " and target RepNode " + targetRN + " are not in the same replication group."); } /* Verify if source and target restore nodes exist in the topology */ StartNetworkRestore.verifyIfNodesExist( getAdmin().getCurrentTopology(), sourceId, targetId); /* Verify if source and target are running a required KVVersion */ verifyNodeVersion(sourceRN); verifyNodeVersion(targetRN); addTask(new StartNetworkRestore( this, sourceId, targetId, retainOriginalLog)); /* Parallel task runner to execute wait task until restore is done */ final ParallelBundle bundle = new ParallelBundle(); bundle.addTask(new WaitForNetworkRestore(this, sourceId, targetId)); addTask(bundle); } /** * Add custom task status information to the TaskRun which records * information about each task execution. Must be synchronized on the * plan instance, to coordinate between different threads who are modifying * task state and persisting the plan instance. */ public synchronized void addTaskDetails(Map<String, String> taskRunStatus, Map<String, String> info) { taskRunStatus.putAll(info); } /** * Verify given RepNode is running with the required KVVersion. */ private void verifyNodeVersion(RepNodeId rnId) { final Admin admin = getAdmin(); final Topology topo = admin.getCurrentTopology(); final RegistryUtils utils = new RegistryUtils(topo, getLoginManager()); try { final StorageNodeId snId = topo.get(rnId).getStorageNodeId(); final StorageNodeStatus snStatus = utils.getStorageNodeAgent(snId).ping(); final KVVersion kvVersion = snStatus.getKVVersion(); if (VersionUtil.compareMinorVersion( kvVersion, NETWORK_RESTORE_VERSION) < 0) { throw new IllegalCommandException(rnId + " version is not capable of executing this plan." + " Required version is " + NETWORK_RESTORE_VERSION.getNumericVersionString() + ", node version is " + kvVersion.getNumericVersionString()); } } catch (Exception e) { throw new IllegalCommandException( "Unable to verify " + rnId + "version, " + e.getMessage(), e); } } @Override public boolean isExclusive() { return false; } @Override public void preExecuteCheck(boolean force, Logger executeLogger) { final Topology topology = getAdmin().getCurrentTopology(); /* Basic verification in case topology has been changed */ StartNetworkRestore.verifyIfNodesExist(topology, sourceId, targetId); /* Verification before restore execution */ StartNetworkRestore.verifyBeforeRestore((RepNodeId)sourceId, (RepNodeId)targetId, topology, getAdmin().getLoginManager(), executeLogger, force); } @Override public String getDefaultName() { return "NetworkRestore"; } @Override public List<? extends KVStorePrivilege> getRequiredPrivileges() { /* Requires SYSOPER */ return SystemPrivilege.sysoperPrivList; } @Override void preExecutionSave() { /* Nothing to do*/ } /** * Describe running tasks, for a status report. */ @Override public void describeRunning(Formatter fm, final List<TaskRun> running, boolean verbose) { TaskRun waitNetworkRestore = null; for (TaskRun tRun : running) { if (tRun.getTask() instanceof WaitForNetworkRestore) { waitNetworkRestore = tRun; } else { fm.format(" Task %d/%s started at %s\n", tRun.getTaskNum(), tRun.getTask(), FormatUtils.formatDateAndTime(tRun.getStartTime())); } } if (waitNetworkRestore != null) { final Map<String, String> details = waitNetworkRestore.getDetails(); String stats =details.get(WaitForNetworkRestore.BACKUP_STATS_KEY); if (stats == null) { stats = "Network backup statistics unavailable"; } fm.format(" Task %d/%s:\n %s\n", waitNetworkRestore.getTaskNum(), waitNetworkRestore.getTask(), stats); } } }
breezechen/zevent
libbt/btpd/content.c
#include "btpd.h" #include <openssl/sha.h> #include <stream.h> #include <io.h> struct content { enum { CM_INACTIVE, CM_STARTING, CM_ACTIVE } state; int error; uint32_t npieces_got; fpos_t ncontent_bytes; size_t bppbf; // bytes per piece block field uint8_t *piece_field; uint8_t *block_field; uint8_t *pos_field; struct bt_stream *rds; struct bt_stream *wrs; struct resume_data *resd; }; #define ZEROBUFLEN (1 << 14) static const uint8_t m_zerobuf[ZEROBUFLEN]; static int fd_cb_rd(const char *path, int *fd, void *arg) { struct torrent *tp = arg; return vopen(fd, O_RDONLY|_O_BINARY, "%s/%s", tp->tl->dir, path); } static int fd_cb_wr(const char *path, int *fd, void *arg) { struct torrent *tp = arg; return vopen(fd, O_RDWR|_O_BINARY, "%s/%s", tp->tl->dir, path); } struct start_test_data { struct torrent *tp; struct file_time_size *fts; uint32_t start; BTPDQ_ENTRY(start_test_data) entry; }; BTPDQ_HEAD(std_tq, start_test_data); static struct std_tq m_startq = BTPDQ_HEAD_INITIALIZER(m_startq); static struct timeout m_workev; #define READBUFLEN (1 << 14) static int test_hash(struct torrent *tp, uint8_t *hash, uint32_t piece) { char piece_hash[SHA_DIGEST_LENGTH]; tlib_read_hash(tp->tl, tp->pieces_off, piece, piece_hash); return memcmp(hash, piece_hash, SHA_DIGEST_LENGTH); } static int test_piece(struct torrent *tp, uint32_t piece, int *ok) { int err; uint8_t hash[SHA_DIGEST_LENGTH]; if ((err = bts_sha(tp->cm->rds, piece * tp->piece_length, torrent_piece_size(tp, piece), hash)) != 0) { btpd_log(BTPD_L_ERROR, "io error on '%s' (%s).\r\n", bts_filename(tp->cm->rds), strerror(err)); return err;; } *ok = test_hash(tp, hash, piece) == 0; return 0; } static int test_hash(struct torrent *tp, uint8_t *hash, uint32_t piece); static void startup_test_run(void); void worker_cb(int fd, short type, void *arg) { startup_test_run(); } void cm_kill(struct torrent *tp) { struct content *cm = tp->cm; tlib_close_resume(cm->resd); free(cm->pos_field); free(cm); tp->cm = NULL; } static int stat_and_adjust(struct torrent *tp, struct file_time_size ret[]); void cm_save(struct torrent *tp) { //struct file_time_size fts[tp->nfiles]; int i = 0; struct file_time_size *fts = malloc(sizeof(struct file_time_size) * tp->nfiles); stat_and_adjust(tp, fts); for (i = 0; i < tp->nfiles; i++) resume_set_fts(tp->cm->resd, i, fts + i); free(fts); } static void cm_on_error(struct torrent *tp) { if (!tp->cm->error) { tp->cm->error = 1; cm_stop(tp); } } static void cm_write_done(struct torrent *tp) { int err; struct content *cm = tp->cm; err = bts_close(cm->wrs); cm->wrs = NULL; if (err && !cm->error) { btpd_log(BTPD_L_ERROR, "error closing write stream for '%s' (%s).\n", torrent_name(tp), strerror(err)); cm_on_error(tp); } if (!cm->error) cm_save(tp); } void cm_stop(struct torrent *tp) { struct content *cm = tp->cm; if (cm->state != CM_STARTING && cm->state != CM_ACTIVE) return; if (cm->state == CM_STARTING) { struct start_test_data *std; BTPDQ_FOREACH(std, &m_startq, entry) if (std->tp == tp) { BTPDQ_REMOVE(&m_startq, std, entry); free(std->fts); free(std); break; } } if (cm->rds != NULL) bts_close(cm->rds); if (cm->wrs != NULL) cm_write_done(tp); cm->state = CM_INACTIVE; } int cm_active(struct torrent *tp) { struct content *cm = tp->cm; return cm->state != CM_INACTIVE; } int cm_error(struct torrent *tp) { return tp->cm->error; } int cm_started(struct torrent *tp) { struct content *cm = tp->cm; return cm->state == CM_ACTIVE; } void cm_create(struct torrent *tp, const char *mi) { size_t pfield_size = ceil(tp->npieces / 8.0); struct content *cm = btpd_calloc(1, sizeof(*cm)); cm->bppbf = ceil((double)tp->piece_length / (1 << 17)); cm->pos_field = btpd_calloc(pfield_size, 1); cm->resd = tlib_open_resume(tp->tl, tp->nfiles, pfield_size, cm->bppbf * tp->npieces); cm->piece_field = resume_piece_field(cm->resd); cm->block_field = resume_block_field(cm->resd); tp->cm = cm; } int cm_get_bytes(struct torrent *tp, uint32_t piece, uint32_t begin, size_t len, uint8_t **buf) { int err; if (tp->cm->error) return EIO; *buf = btpd_malloc(len); err = bts_get(tp->cm->rds, piece * tp->piece_length + begin, *buf, len); if (err != 0) { btpd_log(BTPD_L_ERROR, "io error on '%s' (%s).\n", bts_filename(tp->cm->rds), strerror(err)); cm_on_error(tp); } return err; } void cm_prealloc(struct torrent *tp, uint32_t piece) { struct content *cm = tp->cm; if (cm_alloc_size <= 0) set_bit(cm->pos_field, piece); } void cm_test_piece(struct torrent *tp, uint32_t piece) { int ok; struct content *cm = tp->cm; if ((errno = test_piece(tp, piece, &ok)) != 0) cm_on_error(tp); else if (ok) { assert(cm->npieces_got < tp->npieces); cm->npieces_got++; set_bit(cm->piece_field, piece); if (net_active(tp)) dl_on_ok_piece(tp->net,piece); if (cm_full(tp)) cm_write_done(tp); } else { cm->ncontent_bytes -= torrent_piece_size(tp,piece); memset(cm->block_field + piece * cm->bppbf,0, cm->bppbf); if (net_active(tp)) dl_on_bad_piece(tp->net, piece); } } int cm_put_bytes(struct torrent *tp, uint32_t piece, uint32_t begin, const uint8_t *buf, size_t len) { int err; uint8_t *bf; struct content *cm = tp->cm; fpos_t tmplen,off; size_t wlen; if (cm->error) return EIO; bf = cm->block_field + piece * cm->bppbf; assert(!has_bit(bf, begin / PIECE_BLOCKLEN)); assert(!has_bit(cm->piece_field, piece)); if (!has_bit(cm->pos_field, piece)) { unsigned npieces = ceil((double)cm_alloc_size / tp->piece_length); uint32_t start = piece - piece % npieces; uint32_t end = min(start + npieces, tp->npieces); while (start < end) { if (!has_bit(cm->pos_field, start)) { assert(!has_bit(cm->piece_field, start)); tmplen = torrent_piece_size(tp, start); off = tp->piece_length * start; while (tmplen > 0) { wlen = min(ZEROBUFLEN, tmplen); if ((err = bts_put(cm->wrs, off, m_zerobuf, wlen)) != 0) { btpd_log(BTPD_L_ERROR, "io error on '%s' (%s).\r\n", bts_filename(cm->wrs), strerror(errno)); cm_on_error(tp); return err; } tmplen -= wlen; off += wlen; } set_bit(cm->pos_field, start); } start++; } } err = bts_put(cm->wrs, piece * tp->piece_length + begin, buf, len); if (err != 0) { btpd_log(BTPD_L_ERROR, "io error on '%s' (%s)\r\n", bts_filename(cm->wrs), strerror(err)); cm_on_error(tp); return err; } cm->ncontent_bytes += len; set_bit(bf, begin / PIECE_BLOCKLEN); return 0; } int cm_full(struct torrent *tp) { return tp->cm->npieces_got == tp->npieces; } fpos_t cm_content(struct torrent *tp) { return tp->cm->ncontent_bytes; } uint32_t cm_pieces(struct torrent *tp) { return tp->cm->npieces_got; } uint8_t * cm_get_piece_field(struct torrent *tp) { return tp->cm->piece_field; } uint8_t * cm_get_block_field(struct torrent *tp, uint32_t piece) { return tp->cm->block_field + piece * tp->cm->bppbf; } int cm_has_piece(struct torrent *tp, uint32_t piece) { return has_bit(tp->cm->piece_field, piece); } int cm_range_pieces(struct torrent *tp,uint32_t begin,uint32_t length,uint32_t *piece_start, uint32_t *piece_end) { uint32_t start=0,nums=0,end = 0; if(begin < 0 || length <=0) return -1; start = floor(begin / tp->piece_length); nums = ceil(length / tp->piece_length); end = start + nums; *piece_start = start; *piece_end = end < tp->npieces -1 ? end : tp->npieces - 1; return 0; } int cm_range_ready(struct torrent *tp,uint32_t begin,uint32_t length) { uint32_t piece_start = 0,piece_end = 0,idx = 0; if(cm_range_pieces(tp,begin,length,&piece_start,&piece_end) < 0) return -1; for(idx = piece_start; idx < piece_end && cm_has_piece(tp,idx); ++idx); if(idx == piece_end) return 1; else return 0; } int stat_and_adjust(struct torrent *tp, struct file_time_size ret[]) { int fd; char path[MAX_PATH]; struct stat sb; int i = 0; for (i = 0; i < tp->nfiles; i++) { sprintf(path, "%s/%s", tp->tl->dir, tp->files[i].path); again: if (stat(path, &sb) == -1) { if (errno == ENOENT) { errno = vopen(&fd, O_CREAT|O_RDWR|_O_BINARY, "%s", path); if (errno != 0 || _close(fd) != 0) { btpd_log(BTPD_L_ERROR, "failed to create '%s' (%s).\r\n", path, strerror(errno)); return errno; } goto again; } else { btpd_log(BTPD_L_ERROR, "failed to stat '%s' (%s).\r\n", path, strerror(errno)); return errno; } } else if (sb.st_size > tp->files[i].length) { if (vtruncate(path, tp->files[i].length) != 0) { btpd_log(BTPD_L_ERROR, "failed to truncate '%s' (%s).\r\n", path, strerror(errno)); return errno; } goto again; } else { ret[i].mtime = sb.st_mtime; ret[i].size = sb.st_size; } } return 0; } void startup_test_end(struct torrent *tp, int unclean) { uint32_t piece = 0,*bf,nblocks,nblocks_got; uint32_t i; struct content *cm = tp->cm; memset(cm->pos_field,0, ceil(tp->npieces / 8.0)); for (piece = 0; piece < tp->npieces; piece++) { if (cm_has_piece(tp, piece)) { cm->ncontent_bytes += torrent_piece_size(tp, piece); cm->npieces_got++; set_bit(cm->pos_field, piece); continue; } bf = cm->block_field + cm->bppbf * piece; nblocks = torrent_piece_blocks(tp, piece); nblocks_got = 0; for (i = 0; i < nblocks; i++) { if (has_bit(bf, i)) { nblocks_got++; cm->ncontent_bytes += torrent_block_size(tp, piece, nblocks, i); } } if (nblocks_got == nblocks) { memset(bf,0,cm->bppbf); cm->ncontent_bytes -= torrent_piece_size(tp, piece); } else if (nblocks_got > 0) set_bit(cm->pos_field, piece); } if (unclean) { struct start_test_data *std = BTPDQ_FIRST(&m_startq); BTPDQ_REMOVE(&m_startq, std, entry); for (i = 0; i < tp->nfiles; i++) resume_set_fts(cm->resd, i, std->fts + i); free(std->fts); free(std); } if (!cm_full(tp)) { int err; if ((err = bts_open(&cm->wrs, tp->nfiles, tp->files, fd_cb_wr, tp)) != 0) { btpd_log(BTPD_L_ERROR, "failed to open write stream for '%s' (%s).\r\n", torrent_name(tp), strerror(err)); cm_on_error(tp); return; } } cm->state = CM_ACTIVE; } void startup_test_run(void) { int ok; struct torrent *tp; struct content *cm; struct timespec ts; struct start_test_data * std = BTPDQ_FIRST(&m_startq); uint32_t this; if (std == NULL) return; tp = std->tp; cm = tp->cm; if (test_piece(std->tp, std->start, &ok) != 0) { cm_on_error(std->tp); return; } if (ok) set_bit(cm->piece_field, std->start); else clear_bit(cm->piece_field, std->start); this = std->start; do std->start++; while (std->start < tp->npieces && !has_bit(cm->pos_field, std->start)); if (std->start >= tp->npieces) startup_test_end(tp, 1); if (!BTPDQ_EMPTY(&m_startq)) { ts.tv_sec = 0; ts.tv_nsec = 0; btpd_timer_add(&m_workev, &ts); } } void startup_test_begin(struct torrent *tp, struct file_time_size *fts) { uint32_t piece = 0; struct content *cm = tp->cm; struct timespec ts = {0,0}; while (piece < tp->npieces && !has_bit(cm->pos_field, piece)) piece++; if (piece < tp->npieces) { struct start_test_data *std = btpd_calloc(1, sizeof(*std)); std->tp = tp; std->start = piece; std->fts = fts; BTPDQ_INSERT_TAIL(&m_startq, std, entry); if (std == BTPDQ_FIRST(&m_startq)) { btpd_timer_add(&m_workev, &ts); } } else { free(fts); startup_test_end(tp, 0); } } void cm_start(struct torrent *tp, int force_test) { int err, run_test = force_test; struct file_time_size *fts; struct content *cm = tp->cm; int i; fpos_t off = 0; cm->state = CM_STARTING; if ((errno = bts_open(&cm->rds, tp->nfiles, tp->files, fd_cb_rd, tp)) != 0) { btpd_log(BTPD_L_ERROR, "failed to open stream for '%s' (%s).\r\n", torrent_name(tp), strerror(errno)); cm_on_error(tp); return; } fts = btpd_calloc(tp->nfiles, sizeof(*fts)); if ((err = stat_and_adjust(tp, fts)) != 0) { free(fts); cm_on_error(tp); return; } for (i = 0; i < tp->nfiles; i++) { struct file_time_size rfts; resume_get_fts(cm->resd, i, &rfts); if ((fts[i].mtime != rfts.mtime || fts[i].size != rfts.size)) { run_test = 1; break; } } if (run_test) { memset(cm->pos_field, 0xff, ceil(tp->npieces / 8.0)); for (i = 0; i < tp->nfiles; i++) { if (fts[i].size != tp->files[i].length) { fpos_t start, end; end = (off + tp->files[i].length - 1) / tp->piece_length; start = (off + fts[i].size) / tp->piece_length; while (start <= end) { clear_bit(cm->pos_field, start); clear_bit(cm->piece_field, start); memset(cm->block_field + start * cm->bppbf,0, cm->bppbf); start++; } } off += tp->files[i].length; } } startup_test_begin(tp, fts); } void cm_init(void) { evtimer_init(&m_workev, worker_cb, NULL); }
uxpin-merge/bloom
packages/core/src/utils/propTypeValidations/childrenOf.js
<reponame>uxpin-merge/bloom<gh_stars>10-100 import PropTypes from 'prop-types'; /** * http://stackoverflow.com/a/39457422/6700793 */ const childrenOf = (...types) => { const fieldType = PropTypes.shape({ type: PropTypes.oneOf(types), }); return PropTypes.oneOfType([ fieldType, PropTypes.arrayOf(fieldType), ]); }; export default childrenOf;
chrishoen/Dev_CCLib
LFCCLib/ccBlockPoolLFFreeList.cpp
/*============================================================================== Description: ==============================================================================*/ //****************************************************************************** //****************************************************************************** //****************************************************************************** #include "stdafx.h" #include "cc_functions.h" #include "cc_throw.h" #include "ccMemoryPtr.h" #include "ccBlockPoolLFFreeList.h" using namespace std; namespace CC { //****************************************************************************** //****************************************************************************** //****************************************************************************** // This local class calculates and stores the memory sizes needed by the class. class BlockPoolLFFreeList::MemorySize { public: // Members. int mBlockSize; int mBlockBoxSize; int mBlockBoxArraySize; int mFreeListNextSize; int mMemorySize; // Calculate and store memory sizes. MemorySize(BlockPoolParms* aParms) { mBlockSize = cc_round_upto16(aParms->mBlockSize); mBlockBoxSize = cBlockHeaderSize + mBlockSize; mBlockBoxArraySize = cc_round_upto16(cNewArrayExtraMemory + aParms->mNumBlocks*mBlockBoxSize); mFreeListNextSize = cc_round_upto16(cNewArrayExtraMemory + (aParms->mNumBlocks + 1)*sizeof(AtomicLFIndex)); mMemorySize = mBlockBoxArraySize + mFreeListNextSize; } }; //****************************************************************************** //****************************************************************************** //****************************************************************************** // This returns the number of bytes that an instance of this class // will need to be allocated for it. int BlockPoolLFFreeList::getMemorySize(BlockPoolParms* aParms) { MemorySize tMemorySize(aParms); return tMemorySize.mMemorySize; } //****************************************************************************** //****************************************************************************** //****************************************************************************** //****************************************************************************** //****************************************************************************** //****************************************************************************** // Constructor. BlockPoolLFFreeList::BlockPoolLFFreeList() { mOwnMemoryFlag = false; mMemory = 0; mFreeListNext = 0; mBlockBoxArray=0; mNumBlocks = 0; mBlockSize = 0; mBlockBoxSize = 0; mPoolIndex = 0; mFreeListNumNodes = 0; mFreeListSize = 0; } BlockPoolLFFreeList::~BlockPoolLFFreeList() { finalize(); } //****************************************************************************** ;//****************************************************************************** //****************************************************************************** // This initializes the block pool. It allocates memory for the block array // and initializes the index stack. It is passed the number of blocks to // allocate and the size of the blocks. // // For aNumBlocks==10 blocks will range 0,1,2,3,4,5,6,7,8,9 // A block index of cInvalid indicates an invalid block. // // An index stack is used to manage free list access to the blocks // The stack is initialized for a free list by pushing indices onto it. // For aAllocate==10 this will push 9,7,8,6,5,4,3,2,1,0 // // When a block is allocated, an index is popped off of the stack. // When a block is deallocated, its index is pushed back onto the stack. // void BlockPoolLFFreeList::initialize(BlockPoolParms* aParms) { //*************************************************************************** //*************************************************************************** //*************************************************************************** // Initialize memory. // Deallocate memory, if any exists. finalize(); // If the instance of this class is not to reside in external memory // then allocate memory for it on the system heap. if (aParms->mMemory == 0) { mMemory = malloc(BlockPoolLFFreeList::getMemorySize(aParms)); mOwnMemoryFlag = true; } // If the instance of this class is to reside in external memory // then use the memory pointer that was passed in. else { mMemory = aParms->mMemory; mOwnMemoryFlag = false; } // Calculate memory sizes. MemorySize tMemorySize(aParms); // Calculate memory addresses. MemoryPtr tMemoryPtr(mMemory); char* tBlockBoxArrayMemory = tMemoryPtr.cfetch_add(tMemorySize.mBlockBoxArraySize); char* tFreeListNextMemory = tMemoryPtr.cfetch_add(tMemorySize.mFreeListNextSize); //*************************************************************************** //*************************************************************************** //*************************************************************************** // Initialize state. // Store members. mNumBlocks = aParms->mNumBlocks; mBlockSize = cc_round_upto16(aParms->mBlockSize); mBlockBoxSize = cBlockHeaderSize + mBlockSize; mPoolIndex = aParms->mPoolIndex; // Allocate for one extra dummy node. mFreeListNumNodes = aParms->mNumBlocks + 1; mFreeListSize = 0; //*************************************************************************** //*************************************************************************** //*************************************************************************** // Initialize block box array. // Set the array pointer value. mBlockBoxArray = tBlockBoxArrayMemory; mBlockBoxArrayPtr.set(tBlockBoxArrayMemory); // Initialize block headers. for (int i = 0; i < mNumBlocks; i++) { // Header pointer. BlockHeader* tHeader = getHeaderPtr(i); // Call Header constructor. new(tHeader)BlockHeader; // Set header variables. tHeader->mBlockHandle.set(mPoolIndex, i); } // Construct the linked list array. mFreeListNext = new(tFreeListNextMemory)AtomicLFIndex[mFreeListNumNodes]; //*************************************************************************** //*************************************************************************** //*************************************************************************** // Initialize free list. // Initialize linked list array. Each node next node is the one after it. for (int i = 0; i < mFreeListNumNodes - 1; i++) { mFreeListNext[i].store(LFIndex(i + 1, 0)); } // The last node has no next node. mFreeListNext[mFreeListNumNodes - 1].store(LFIndex(cInvalid, 0)); // List head points to the first node. mFreeListHead.store(LFIndex(0, 0)); // List size is initially a full stack. mFreeListSize = mFreeListNumNodes; // Pop the dummy node. int tDummyNode; listPop(&tDummyNode); //*************************************************************************** //*************************************************************************** //*************************************************************************** // Initialize parameters. // Store the pointer to the parameters. mParms = aParms; // Mark this block pool initialization as valid. aParms->mValidFlag = true; // Store block array parameters. These can be used elsewhere. aParms->mBlockHeaderSize = cBlockHeaderSize; aParms->mBlockBoxSize = tMemorySize.mBlockBoxSize; aParms->mBlockBoxArrayPtr = mBlockBoxArrayPtr; } //****************************************************************************** //****************************************************************************** //****************************************************************************** // Deallocate memory for the block pool. void BlockPoolLFFreeList::finalize() { if (mOwnMemoryFlag) { if (mMemory) { free(mMemory); } } mMemory = 0; mOwnMemoryFlag = false; } //****************************************************************************** //****************************************************************************** //****************************************************************************** // Size, the number of blocks that are available to be allocated. int BlockPoolLFFreeList::size() { return mFreeListSize.load(memory_order_relaxed); } //****************************************************************************** //****************************************************************************** //****************************************************************************** // Get a block from the pool, this allocates a block. // Return true if successful, false if the block pool is empty. bool BlockPoolLFFreeList::allocate(void** aBlockPointer,BlockHandle* aBlockHandle) { int tBlockIndex = 0; // Try to pop a block index from the index stack, as a free list. // If the stack is not empty if (listPop(&tBlockIndex)) { // Return a pointer to the block at that index. if (aBlockPointer) { *aBlockPointer = mBlockBoxArrayPtr.vplus(mBlockBoxSize*tBlockIndex + cBlockHeaderSize); #if 0 *aBlockPointer = getBlockPtr(tBlockIndex); #endif } // Return the memory handle for the block. if (aBlockHandle) { aBlockHandle->set(mParms->mPoolIndex, tBlockIndex); } return true; } // If the stack is empty else { // Return a null pointer. if (aBlockPointer) { *aBlockPointer = 0; } // Return a null memory handle. if (aBlockHandle) { aBlockHandle->setNull(); } return false; } // Done return true; } //****************************************************************************** //****************************************************************************** //****************************************************************************** // Put a block back to the pool, this deallocates a block. void BlockPoolLFFreeList::deallocate(BlockHandle aBlockHandle) { // Push the block index back onto the stack listPush(aBlockHandle.mBlockIndex); } //****************************************************************************** //****************************************************************************** //****************************************************************************** // Return a pointer to a block, given its memory handle. void* BlockPoolLFFreeList::getBlockPtr(BlockHandle aBlockHandle) { return mBlockBoxArrayPtr.vplus(mBlockBoxSize*aBlockHandle.mBlockIndex + cBlockHeaderSize); #if 0 // Return the address of the block within the block array. return getBlockPtr(aBlockHandle.mBlockIndex); #endif } //****************************************************************************** //****************************************************************************** //****************************************************************************** // Return a pointer to a block, based on block array index char* BlockPoolLFFreeList::getBlockBoxPtr(int aBlockIndex) { return mBlockBoxArrayPtr.cplus(mBlockBoxSize*aBlockIndex + cBlockHeaderSize); #if 0 char* tBlockBox = &mBlockBoxArray[mBlockBoxSize*aIndex]; return tBlockBox; #endif } //****************************************************************************** //****************************************************************************** //****************************************************************************** // Return a pointer to a header, based on block array index BlockHeader* BlockPoolLFFreeList::getHeaderPtr(int aIndex) { char* tBlockBox = mBlockBoxArrayPtr.cplus(mBlockBoxSize*aIndex); BlockHeader* tHeader = (BlockHeader*)tBlockBox; return tHeader; #if 0 char* tBlockBox = &mBlockBoxArray[mBlockBoxSize*aIndex]; BlockHeader* tHeader = (BlockHeader*)tBlockBox; return tHeader; #endif } //****************************************************************************** //****************************************************************************** //****************************************************************************** // Return a pointer to a body, based on block array index char* BlockPoolLFFreeList::getBlockPtr(int aBlockIndex) { return mBlockBoxArrayPtr.cplus(mBlockBoxSize*aBlockIndex + cBlockHeaderSize); #if 0 char* tBlockBox = &mBlockBoxArray[mBlockBoxSize*aIndex]; char* tBlock = tBlockBox + cBlockHeaderSize; return tBlock; #endif } //****************************************************************************** //****************************************************************************** //****************************************************************************** // Get the handle of a block, given its address. BlockHandle BlockPoolLFFreeList::getBlockHandle(void* aBlockPointer) { BlockHandle tBlockHandle; if (aBlockPointer==0) return tBlockHandle; MemoryPtr tBlockPtr(aBlockPointer); BlockHeader* tHeader = (BlockHeader*)tBlockPtr.vminus(cBlockHeaderSize); tBlockHandle = tHeader->mBlockHandle; return tBlockHandle; #if 0 BlockHandle tBlockHandle; if (aBlockPtr==0) return tBlockHandle; char* tBlock = (char*)aBlockPtr; BlockHeader* tHeader = (BlockHeader*)(tBlock - cBlockHeaderSize); tBlockHandle = tHeader->mBlockHandle; return tBlockHandle; #endif } //****************************************************************************** //****************************************************************************** //****************************************************************************** // Helpers void BlockPoolLFFreeList::show() { printf("BlockPoolLFFreeList size %d $ %d\n", mParms->mPoolIndex,size()); } //****************************************************************************** //****************************************************************************** //****************************************************************************** // This detaches the head node. // Use an offset of one so that pop and push indices range 0..NumElements-1. bool BlockPoolLFFreeList::listPop(int* aNodeIndex) { // Store the head node in a temp. // This is the node that will be detached. LFIndex tHead = mFreeListHead.load(memory_order_relaxed); int tLoopCount=0; while (true) { // Exit if the list is empty. if (tHead.mIndex == cInvalid) return false; // Set the head node to be the node that is after the head node. if (mFreeListHead.compare_exchange_weak(tHead, LFIndex(mFreeListNext[tHead.mIndex].load(memory_order_relaxed).mIndex,tHead.mCount+1),memory_order_acquire,memory_order_relaxed)) break; if (++tLoopCount==10000) cc_throw(103); } mFreeListSize.fetch_sub(1,memory_order_relaxed); // Return the detached original head node. *aNodeIndex = tHead.mIndex - 1; return true; } //*************************************************************************** //*************************************************************************** //*************************************************************************** // Insert a node into the list before the list head node. // Use an offset of one so that pop and push indices range 0..NumElements-1. bool BlockPoolLFFreeList::listPush(int aNodeIndex) { int tNodeIndex = aNodeIndex + 1; // Store the head node in a temp. LFIndex tHead = mFreeListHead.load(memory_order_relaxed); int tLoopCount=0; while (true) { // Attach the head node to the pushed node. mFreeListNext[tNodeIndex].store(tHead,memory_order_relaxed); // The pushed node is the new head node. atomic<short int>* tListHeadIndexPtr = (std::atomic<short int>*)&mFreeListHead; if ((*tListHeadIndexPtr).compare_exchange_weak(tHead.mIndex, tNodeIndex,memory_order_release,memory_order_relaxed)) break; if (++tLoopCount == 10000) cc_throw(103); } // Done. mFreeListSize.fetch_add(1,memory_order_relaxed); return true; } //*************************************************************************** //*************************************************************************** //*************************************************************************** }//namespace
antholuo/Blob_Traffic
Blob_Lib/Include/glm/detail/_noise.hpp
<filename>Blob_Lib/Include/glm/detail/_noise.hpp version https://git-lfs.github.com/spec/v1 oid sha256:7ee81536e422dca32cef43c0326a0963f485432427a6460c05bc4f8b32a2fd7a size 2360
YoshimitsuMatsutaIe/rmp_test
misc/baxter/cpp_original/include/jry_W0.hpp
<filename>misc/baxter/cpp_original/include/jry_W0.hpp /****************************************************************************** * Code generated with sympy 1.9 * * * * See http://www.sympy.org/ for more information. * * * * This file is part of 'jry_W0_BY_SYMPY_' * ******************************************************************************/ #ifndef JRY_W0_BY_SYMPY___JRY_W0__H #define JRY_W0_BY_SYMPY___JRY_W0__H void jry_W0(double *out_210064141964992050); #endif
linuxfood/pyobjc-framework-Cocoa-test
PyObjCTest/test_nsnotification.py
import Foundation from PyObjCTools.TestSupport import TestCase, min_os_level class TestNSNotification(TestCase): def testMethods(self): self.assertArgIsSEL( Foundation.NSNotificationCenter.addObserver_selector_name_object_, 1, b"v@:@", ) @min_os_level("10.6") def testMethods10_6(self): self.assertArgIsBlock( Foundation.NSNotificationCenter.addObserverForName_object_queue_usingBlock_, 3, b"v@", )