repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
tedwen/transmem
src/com/transmem/utils/Security.java
1277
package com.transmem.utils; import java.security.MessageDigest; public class Security { /** * Converts a byte to hex digit and writes to the supplied buffer */ public static void byte2hex(byte b, StringBuffer buf) { char[] hexChars = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; int high = ((b & 0xf0) >> 4); int low = (b & 0x0f); buf.append(hexChars[high]); buf.append(hexChars[low]); } /** * Converts a byte array to hex string * @param bytes - bytes to convert to hex string * @return string of hex digits */ public static String fromBytes(byte[] bytes) { int len = bytes.length; StringBuffer buf = new StringBuffer(len*2); for (int i=0; i<len; i++) { byte2hex(bytes[i], buf); } return buf.toString(); } public static String md5(String str) { String result; try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] passbytes = md.digest(str.getBytes()); result = fromBytes(passbytes); } catch (Exception x) { result = str; System.err.println(x.toString()); } return result; } public static void main(String[] args) { if (args.length < 1) { System.out.println("Security <string>"); } else { System.out.println(Security.md5(args[0])); } } }
apache-2.0
ieewbbwe/studySpace
coreLib/src/main/java/com/android_mobile/core/ui/comp/pullListView/IListViewComp.java
252
package com.android_mobile.core.ui.comp.pullListView; import com.android_mobile.core.adapter.BasicRecycleAdapter; public interface IListViewComp { void getListView(); void setAdapter(BasicRecycleAdapter adapter); void setListener(); }
apache-2.0
YangYongZhi/cpims
src/com/gtm/cpims/business/workflow/variable/ProcessStatusMap.java
1427
package com.gtm.cpims.business.workflow.variable; import java.util.HashMap; import java.util.Map; public class ProcessStatusMap { private static Map<String, String> PROCESSSTATUS; static { PROCESSSTATUS = new HashMap<String, String>(); PROCESSSTATUS.put("WATING_REVIEW", "待复核"); PROCESSSTATUS.put("WAITING_SELF_PERFORMCE", "等待人行录入自行处理结果"); PROCESSSTATUS.put("WAITING_OTHER_ORG_PERFORMCE", "等待人行录入自行处理结果"); PROCESSSTATUS.put("WAITING_DISTRIBUTE_INPUT", "等待分发金融机构录入处理结果"); PROCESSSTATUS.put("WAITING_VISIT_INPUT", "等待人行录入回访结果"); PROCESSSTATUS.put("WAITING_AUDIT_INPUT", "等待人行录入处理审核结果"); PROCESSSTATUS.put("WAITING_FILLING", "等待归档"); PROCESSSTATUS.put("ENDED", "流程已结束"); PROCESSSTATUS.put("WAITING_THIRD_ORG_REVIEW", "等待第三方机构审核"); PROCESSSTATUS.put("WATING_RECORD_INPUT", "等待记录录入"); } /** * 根据流程步骤英文代码获取对应流程步骤中文描述 * * @param statusCode * @return */ public static String getStatusString(String statusCode) { return PROCESSSTATUS.get(statusCode); } public static void main(String[] a) { System.out.println(ProcessStatusMap.getStatusString("a")); System.out.println(ProcessStatusMap.getStatusString("WATING_REVIEW")); } }
apache-2.0
ajeddeloh/ignition
internal/exec/stages/files/passwd.go
2603
// Copyright 2018 CoreOS, 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. package files import ( "fmt" "github.com/coreos/ignition/internal/config/types" ) // createPasswd creates the users and groups as described in config.Passwd. func (s *stage) createPasswd(config types.Config) error { if err := s.createGroups(config); err != nil { return fmt.Errorf("failed to create groups: %v", err) } if err := s.createUsers(config); err != nil { return fmt.Errorf("failed to create users: %v", err) } // to be safe, just blanket mark all passwd-related files rather than // trying to make it more granular based on which executables we ran if len(config.Passwd.Groups) != 0 || len(config.Passwd.Users) != 0 { s.relabel( "/etc/passwd*", "/etc/group*", "/etc/shadow*", "/etc/gshadow*", "/etc/.pwd.lock", "/home", "/root", // for OSTree-based systems (newer restorecon doesn't follow symlinks) "/var/home", "/var/roothome", ) } return nil } // createUsers creates the users as described in config.Passwd.Users. func (s stage) createUsers(config types.Config) error { if len(config.Passwd.Users) == 0 { return nil } s.Logger.PushPrefix("createUsers") defer s.Logger.PopPrefix() for _, u := range config.Passwd.Users { if err := s.EnsureUser(u); err != nil { return fmt.Errorf("failed to create user %q: %v", u.Name, err) } if err := s.SetPasswordHash(u); err != nil { return fmt.Errorf("failed to set password for %q: %v", u.Name, err) } if err := s.AuthorizeSSHKeys(u); err != nil { return fmt.Errorf("failed to add keys to user %q: %v", u.Name, err) } } return nil } // createGroups creates the users as described in config.Passwd.Groups. func (s stage) createGroups(config types.Config) error { if len(config.Passwd.Groups) == 0 { return nil } s.Logger.PushPrefix("createGroups") defer s.Logger.PopPrefix() for _, g := range config.Passwd.Groups { if err := s.CreateGroup(g); err != nil { return fmt.Errorf("failed to create group %q: %v", g.Name, err) } } return nil }
apache-2.0
cloudkick/cast
tests/simple/test-required-params-middleware.js
2192
/* * Licensed to Cloudkick, Inc ('Cloudkick') under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Cloudkick 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. */ var requiredParams = require('http/middleware/required-params').attachMiddleware; exports['test_all_no_required_params_specified'] = function(test, assert) { var called = 0; requiredParams(null)({}, {}, function() { called++; }); requiredParams([])({}, {}, function() { called++; }); setTimeout(function() { assert.equal(called, 2); test.finish(); }, 100); }; exports['test_missing_params'] = function(test, assert) { var resBuffer = ''; var resCode = null; var called = 0; var errSent = false; var res = { write: function(data) { resBuffer += data; }, writeHead: function(code) { resCode = code; }, end: function(data) { resBuffer += data; } }; requiredParams(['parameter_one'])({}, res, function() { called++; }); setTimeout(function() { assert.equal(called, 0); assert.equal(resCode, 400); assert.match(resBuffer, /missing required parameters/i); test.finish(); }, 100); }; exports['test_all_required_params_provided'] = function(test, assert) { var resBuffer = ''; var resCode = null; var called = 0; var errSent = false; var req = { 'body': { 'parameter_one': 'foobar' } }; requiredParams(['parameter_one'])(req, {}, function() { called++; }); setTimeout(function() { assert.equal(called, 1); test.finish(); }, 100); };
apache-2.0
nortal/spring-mvc-component-web
modules/component-web-core/src/main/java/com/nortal/spring/cw/core/web/helper/FieldHelper.java
12671
package com.nortal.spring.cw.core.web.helper; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.math.BigDecimal; import java.sql.Time; import java.sql.Timestamp; import java.util.Collection; import java.util.Date; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.Range; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import com.nortal.spring.cw.core.model.FileHolderModel; import com.nortal.spring.cw.core.model.LangModel; import com.nortal.spring.cw.core.web.annotation.component.BooleanField; import com.nortal.spring.cw.core.web.annotation.component.DateTimeField; import com.nortal.spring.cw.core.web.annotation.component.DoubleField; import com.nortal.spring.cw.core.web.annotation.component.IntegerCollectionField; import com.nortal.spring.cw.core.web.annotation.component.IntegerField; import com.nortal.spring.cw.core.web.annotation.component.LongCollectionField; import com.nortal.spring.cw.core.web.annotation.component.LongField; import com.nortal.spring.cw.core.web.annotation.component.StringCollectionField; import com.nortal.spring.cw.core.web.annotation.component.StringField; import com.nortal.spring.cw.core.web.component.element.AbstractBaseElement; import com.nortal.spring.cw.core.web.component.element.FormElement; import com.nortal.spring.cw.core.web.component.multiple.FileCollectionElement; import com.nortal.spring.cw.core.web.component.multiple.IntegerCollectionElement; import com.nortal.spring.cw.core.web.component.multiple.LanguageElement; import com.nortal.spring.cw.core.web.component.multiple.LongCollectionElement; import com.nortal.spring.cw.core.web.component.multiple.StringCollectionElement; import com.nortal.spring.cw.core.web.component.single.BooleanElement; import com.nortal.spring.cw.core.web.component.single.DateTimeElement; import com.nortal.spring.cw.core.web.component.single.DoubleElement; import com.nortal.spring.cw.core.web.component.single.FileElement; import com.nortal.spring.cw.core.web.component.single.IntegerElement; import com.nortal.spring.cw.core.web.component.single.LongElement; import com.nortal.spring.cw.core.web.component.single.StringElement; import com.nortal.spring.cw.core.web.exception.FieldNotFoundException; import com.nortal.spring.cw.core.web.util.BeanUtil; /** * Klass koondab endas erinevaid vahendeid vormi väljadega manipuleerimiseks * * @author Margus Hanni */ public final class FieldHelper { private FieldHelper() { super(); } /** * Välja baasil vormi elemendi loomine. Kui Elemendi loomine ei õnnestunud, mis tähendab üldjuhul seda et tüüp ei ole lubatud, kutsutakse * välja RuntimeException * * @param elementFieldPath * @param objClass * @return */ public static <T extends FormElement> T createElement(Class<?> objClass, String elementFieldPath) { return createElement(BeanUtil.getMethodByFieldPath(objClass, elementFieldPath), elementFieldPath); } /** * Meetodi baasil vormi elemendi loomine. Kui Elemendi loomine ei õnnestunud, mis tähendab üldjuhul seda et tüüp ei ole lubatud, * kutsutakse välja RuntimeException * * @param method * @param elementFieldPath * @return */ public static <T extends FormElement> T createElement(Method method, String elementFieldPath) { T element = createElementByAnnotation(method, elementFieldPath); if (element == null) { element = createElementByType(method, elementFieldPath); } if (element == null) { throw new FieldNotFoundException(elementFieldPath); } return element; } @SuppressWarnings("unchecked") private static <T extends FormElement> T createElementByType(Method method, String elementFieldPath) { T element = null; Class<?> returnType = method.getReturnType(); String label = elementFieldPath; boolean mandatory = false; if (returnType.equals(String.class)) { element = (T) new StringElement(); } else if (returnType.equals(Long.class)) { element = (T) new LongElement(); } else if (returnType.equals(Integer.class)) { element = (T) new IntegerElement(); } else if (returnType.equals(BigDecimal.class)) { element = (T) new DoubleElement(); } else if (returnType.equals(Boolean.class)) { element = (T) new BooleanElement(); } else if (returnType.equals(Date.class) || returnType.equals(Time.class) || returnType.equals(Timestamp.class)) { element = (T) new DateTimeElement(); } else if (FileHolderModel.class.isAssignableFrom(returnType)) { element = (T) new FileElement().setModelClass((Class<? extends FileHolderModel>) returnType); } else if (Collection.class.isAssignableFrom(returnType)) { element = createCollectionElementByType(method); } if (element != null) { elementBaseData((AbstractBaseElement<?>) element, elementFieldPath, mandatory, label); } return element; } @SuppressWarnings("unchecked") private static <T extends FormElement> T createCollectionElementByType(Method method) { T element = null; Type type = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0]; if (type.equals(String.class)) { element = (T) new StringCollectionElement(); } else if (type.equals(Long.class)) { element = (T) new LongCollectionElement(); } else if (type.equals(Integer.class)) { element = (T) new IntegerCollectionElement(); } else if (LangModel.class.isAssignableFrom((Class<?>) type)) { element = (T) new LanguageElement().setModelClass((Class<? extends LangModel>) type); } else if (FileHolderModel.class.isAssignableFrom((Class<?>) type)) { element = (T) new FileCollectionElement().setModelClass((Class<FileHolderModel>) type); } else { throw new NotImplementedException("Not implemented type: " + type); } return element; } @SuppressWarnings("unchecked") private static <T extends FormElement> T createElementByAnnotation(Method method, String elementFieldPath) { T element = null; if (method.isAnnotationPresent(StringField.class)) { element = (T) FieldHelper.createStringElement(method, elementFieldPath); } else if (method.isAnnotationPresent(LongField.class)) { element = (T) FieldHelper.createLongElement(method, elementFieldPath); } else if (method.isAnnotationPresent(DoubleField.class)) { element = (T) FieldHelper.createDoubleElement(method, elementFieldPath); } else if (method.isAnnotationPresent(IntegerField.class)) { element = (T) FieldHelper.createIntegerElement(method, elementFieldPath); } else if (method.isAnnotationPresent(BooleanField.class)) { element = (T) FieldHelper.createBooleanElement(method, elementFieldPath); } else if (method.isAnnotationPresent(DateTimeField.class)) { element = (T) FieldHelper.createDateTimeElement(method, elementFieldPath); } else if (method.isAnnotationPresent(StringCollectionField.class)) { element = (T) FieldHelper.createStringCollectionElement(method, elementFieldPath); } else if (method.isAnnotationPresent(LongCollectionField.class)) { element = (T) FieldHelper.createLongCollectionElement(method, elementFieldPath); } else if (method.isAnnotationPresent(IntegerCollectionField.class)) { element = (T) FieldHelper.createIntegerCollectionElement(method, elementFieldPath); } return element; } private static BooleanElement createBooleanElement(Method method, String elementFieldPath) { BooleanField field = method.getAnnotation(BooleanField.class); BooleanElement elementComp = new BooleanElement(); elementBaseData(elementComp, elementFieldPath, false, field.label()); return elementComp; } public static DoubleElement createDoubleElement(Method method, String elementFieldPath) { DoubleField field = method.getAnnotation(DoubleField.class); String label = StringUtils.isEmpty(field.label()) ? elementFieldPath : field.label(); boolean mandatory = field.required(); DoubleElement elementComp = new DoubleElement(); Range<BigDecimal> range = Range.between(BigDecimal.valueOf(field.between()[0]), BigDecimal.valueOf(field.between()[1])); elementComp.setRange(range); elementBaseData(elementComp, elementFieldPath, mandatory, label); return elementComp; } private static LongElement createLongElement(Method method, String elementFieldPath) { LongField field = method.getAnnotation(LongField.class); boolean mandatory = field.required(); LongElement elementComp = new LongElement(); Range<Long> longRange = Range.between(field.between()[0], field.between()[1]); elementComp.setRange(longRange); elementBaseData(elementComp, elementFieldPath, mandatory, field.label()); return elementComp; } private static IntegerElement createIntegerElement(Method method, String elementFieldPath) { IntegerField field = method.getAnnotation(IntegerField.class); boolean mandatory = field.required(); IntegerElement elementComp = new IntegerElement(); Range<Integer> intRange = Range.between(field.between()[0], field.between()[1]); elementComp.setRange(intRange); elementBaseData(elementComp, elementFieldPath, mandatory, field.label()); return elementComp; } private static StringElement createStringElement(Method method, String elementFieldPath) { StringField field = method.getAnnotation(StringField.class); boolean mandatory = field.required(); StringElement elementComp = new StringElement(); elementComp.setLength(field.length()); elementComp.setRows(field.rows()); elementComp.setCols(field.cols()); elementBaseData(elementComp, elementFieldPath, mandatory, field.label()); return elementComp; } private static DateTimeElement createDateTimeElement(Method method, String elementFieldPath) { DateTimeField field = method.getAnnotation(DateTimeField.class); boolean mandatory = field.required(); DateTimeElement elementComp = new DateTimeElement(); Date min = StringUtils.isEmpty(field.between()[0]) ? null : DateTime.parse(field.between()[0]).toDate(); Date max = StringUtils.isEmpty(field.between()[1]) ? null : DateTime.parse(field.between()[1]).toDate(); Range<Long> longRange = null; if (min != null && max != null) { longRange = Range.between(min.getTime(), max.getTime()); } else if (min != null || max != null) { longRange = Range.is((min == null ? max : min).getTime()); } elementComp.setRange(longRange); elementBaseData(elementComp, elementFieldPath, mandatory, field.label()); return elementComp; } private static StringCollectionElement createStringCollectionElement(Method method, String elementFieldPath) { StringCollectionField field = method.getAnnotation(StringCollectionField.class); boolean mandatory = field.required(); StringCollectionElement elementComp = new StringCollectionElement(); elementBaseData(elementComp, elementFieldPath, mandatory, field.label()); return elementComp; } private static LongCollectionElement createLongCollectionElement(Method method, String elementFieldPath) { LongCollectionField field = method.getAnnotation(LongCollectionField.class); boolean mandatory = field.required(); LongCollectionElement elementComp = new LongCollectionElement(); elementBaseData(elementComp, elementFieldPath, mandatory, field.label()); return elementComp; } private static IntegerCollectionElement createIntegerCollectionElement(Method method, String elementFieldPath) { IntegerCollectionField field = method.getAnnotation(IntegerCollectionField.class); boolean mandatory = field.required(); IntegerCollectionElement elementComp = new IntegerCollectionElement(); elementBaseData(elementComp, elementFieldPath, mandatory, field.label()); return elementComp; } private static void elementBaseData(AbstractBaseElement<?> baseElementComp, String elementFieldPath, boolean mandatory, String label) { baseElementComp.setId(elementFieldPath); baseElementComp.setMandatory(mandatory); baseElementComp.setLabel(label); } }
apache-2.0
directonlijn/app
public_html/agenda.php
2979
<?php exit(); global $page_tite; $page_tite = ' - agenda'; ?> <!doctype html> <html lang="en"> <?php include_once('components/head.php'); ?> <body class="home"> <div id="wrapper" class="container"> <?php include_once('components/header.php'); ?> <div class="content"> <h1 class="page-title"> Agenda </h1> <p> Vanuit de Agenda kunnen standhouders zich inschrijven voor de komende evenementen van Direct events. Ook zijn de plannen van de komende evenementen al gepland. Hou de website of de facebookpagina van Direct events in de gaten voor nieuw toegevoegde evenementen en voor de mogelijkheid om in te schrijven! </p> <div class="agenda hidden-xs"> <div class="row agenda-item"> <div class="col-xs-4 text-center date"> Zondag 24 maart </div> <div class="col-xs-4 text-center name"> <h3> Hippiemarkt Amsterdam XL </h3> </div> <div class="col-xs-4 text-center registration"> <a href="#" class="btn btn-default">Inscrhijving open</a> </div> </div> <div class="row agenda-item"> <div class="col-xs-4 text-center date"> Zondag 24 maart </div> <div class="col-xs-4 text-center name"> <h3> Hippiemarkt Amsterdam XL </h3> </div> <div class="col-xs-4 text-center registration"> Onder voorbehoud </div> </div> </div> <div class="agenda visible-xs"> <div class="row agenda-item"> <div class="col-xs-6 text-center date"> <h3> Hippiemarkt Amsterdam XL </h3> <div> Zondag 24 maart </div> </div> <div class="col-xs-6 text-center registration"> <a href="#" class="btn btn-default">Inscrhijving open</a> </div> </div> <div class="row agenda-item"> <div class="col-xs-6 text-center date"> <h3> Hippiemarkt Amsterdam XL </h3> <div> Zondag 24 maart </div> </div> <div class="col-xs-6 text-center registration"> Onder voorbehoud </div> </div> </div> </div> <?php include_once('components/footer.php'); ?> </div> <?php include_once('components/bottom_scripts.php'); ?> </body> </html>
apache-2.0
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/storage/tasks/StreamingExport.java
1242
package org.fcrepo.server.storage.tasks; import java.io.IOException; import java.io.OutputStream; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.StreamingOutput; import org.fcrepo.server.errors.ServerException; import org.fcrepo.server.storage.translation.DOTranslator; import org.fcrepo.server.storage.types.DigitalObject; public class StreamingExport implements StreamingOutput { final DOTranslator m_translator; final DigitalObject m_object; final String m_exportFormat; final String m_encoding; final int m_transContext; public StreamingExport(DOTranslator translator, DigitalObject object, String exportFormat, String encoding, int transContext) { m_translator = translator; m_object = object; m_exportFormat = exportFormat; m_encoding = encoding; m_transContext = transContext; } @Override public void write(OutputStream output) throws IOException, WebApplicationException { try { m_translator.serialize(m_object, output, m_exportFormat, m_encoding, m_transContext); } catch (ServerException e) { throw new WebApplicationException(e); } } }
apache-2.0
Muyoo/gold_pred
train_lda/view_model.py
3950
#!/usr/bin/env python #encoding=utf8 ''' Author: xmuyoo@163.com Date: 2015/11/24 Content: 将生成的主体模型格式化输出 输入:主体模型文件,word的倒排文件 输出:格式化后的主题文件 ''' import pdb import sys MIN_SCORE = 10.0 TOPIC_LENGTH = 10 class Translator(object): '''''' def __init__(self, output_fname, word_idx_file, mod_file, output_score): '''''' self.word_idx_dic = self.__load_idx(word_idx_file) self.word_topic_dic = self.__load_topic(mod_file) self.output_score = output_score == 1 self.output_fname = output_fname def __load_idx(self, word_idx_file): '''''' print 'loading word index file' def parse(item): '''''' idx, _, word = item.strip().partition('\t') return idx, word word_idx_dic = {} with open(word_idx_file, 'r') as reader: word_idx_dic = dict([parse(line) for line in reader]) return word_idx_dic def __load_topic(self, mod_file): '''''' print 'loading model file' word_topic_dic = {} with open(mod_file, 'r') as reader: for line in reader: word, _, topics = line.strip().partition('\t') target_topic = None max_score = -1 word_topic_dic[word] = set() for topic, score in enumerate(topics.split()): score = float(score) if score > MIN_SCORE and score > max_score: max_score = score target_topic = topic if target_topic: word_topic_dic[word] = (target_topic, max_score) ''' if score > MIN_SCORE: if score > max_score: max_score = score target_topic = topic if not target_topic: word_topic_dic[word].add((target_topic, score)) ''' return word_topic_dic def view_topics(self): '''''' print 'view topics' topic_word_dic = {} for word_idx, topic in self.word_topic_dic.iteritems(): if not topic: continue topic, score = topic word = self.word_idx_dic[word_idx] if topic not in topic_word_dic: topic_word_dic[topic] = set() topic_word_dic[topic].add((word, score)) ''' word = self.word_idx_dic[word_idx] for topic, score in sorted(topic_set, key=lambda x:x[1], reverse=True)[:2]: if topic not in topic_word_dic: topic_word_dic[topic] = set() topic_word_dic[topic].add((word, score)) ''' writer = open('%s.topic'%self.output_fname, 'w') filtered_cnt = 0 for topic, words_set in topic_word_dic.iteritems(): if len(words_set) < TOPIC_LENGTH: filtered_cnt += 1 continue #pdb.set_trace() if self.output_score: outstr = '%s\t%s\n' % (topic, ' '.join(['%s:%s'%(word, score) \ for word, score in sorted(words_set, key=lambda x:x[1], reverse=True)])) else: outstr = '%s\t%s\n' % (topic, ' '.join([word \ for word, score in sorted(words_set, key=lambda x:x[1], reverse=True)])) writer.write(outstr) writer.close() print 'Filtered %s Topics' % filtered_cnt def main(output_fname, word_idx_file, mod_file, output_score): '''''' # input_fname is not used for now tranlator = Translator(output_fname, word_idx_file, mod_file, output_score) tranlator.view_topics() if __name__ == '__main__': main(sys.argv[1], sys.argv[2], sys.argv[3], 1)
apache-2.0
jiwanlimbu/aura
keystone/contrib/s3/core.py
4752
# Copyright 2012 OpenStack Foundation # # 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. """Main entry point into the S3 Credentials service. This service provides S3 token validation for services configured with the s3_token middleware to authorize S3 requests. This service uses the same credentials used by EC2. Refer to the documentation for the EC2 module for how to generate the required credentials. """ import base64 import hashlib import hmac import six from keystone.common import extension from keystone.common import json_home from keystone.common import utils from keystone.common import wsgi from keystone.contrib.ec2 import controllers from keystone import exception from keystone.i18n import _ EXTENSION_DATA = { 'name': 'OpenStack S3 API', 'namespace': 'https://docs.openstack.org/identity/api/ext/' 's3tokens/v1.0', 'alias': 's3tokens', 'updated': '2013-07-07T12:00:0-00:00', 'description': 'OpenStack S3 API.', 'links': [ { 'rel': 'describedby', 'type': 'text/html', 'href': 'https://developer.openstack.org/' 'api-ref-identity-v2-ext.html', } ]} extension.register_admin_extension(EXTENSION_DATA['alias'], EXTENSION_DATA) class S3Extension(wsgi.V3ExtensionRouter): def add_routes(self, mapper): controller = S3Controller() # validation self._add_resource( mapper, controller, path='/s3tokens', post_action='authenticate', rel=json_home.build_v3_extension_resource_relation( 's3tokens', '1.0', 's3tokens')) class S3Controller(controllers.Ec2Controller): def check_signature(self, creds_ref, credentials): string_to_sign = base64.urlsafe_b64decode(str(credentials['token'])) if string_to_sign[0:4] != b'AWS4': signature = self._calculate_signature_v1(string_to_sign, creds_ref['secret']) else: signature = self._calculate_signature_v4(string_to_sign, creds_ref['secret']) if not utils.auth_str_equal(credentials['signature'], signature): raise exception.Unauthorized( message=_('Credential signature mismatch')) def _calculate_signature_v1(self, string_to_sign, secret_key): """Calculate a v1 signature. :param bytes string_to_sign: String that contains request params and is used for calculate signature of request :param text secret_key: Second auth key of EC2 account that is used to sign requests """ key = str(secret_key).encode('utf-8') if six.PY2: b64_encode = base64.encodestring else: b64_encode = base64.encodebytes signed = b64_encode(hmac.new(key, string_to_sign, hashlib.sha1) .digest()).decode('utf-8').strip() return signed def _calculate_signature_v4(self, string_to_sign, secret_key): """Calculate a v4 signature. :param bytes string_to_sign: String that contains request params and is used for calculate signature of request :param text secret_key: Second auth key of EC2 account that is used to sign requests """ parts = string_to_sign.split(b'\n') if len(parts) != 4 or parts[0] != b'AWS4-HMAC-SHA256': raise exception.Unauthorized(message=_('Invalid EC2 signature.')) scope = parts[2].split(b'/') if len(scope) != 4 or scope[2] != b's3' or scope[3] != b'aws4_request': raise exception.Unauthorized(message=_('Invalid EC2 signature.')) def _sign(key, msg): return hmac.new(key, msg, hashlib.sha256).digest() signed = _sign(('AWS4' + secret_key).encode('utf-8'), scope[0]) signed = _sign(signed, scope[1]) signed = _sign(signed, scope[2]) signed = _sign(signed, b'aws4_request') signature = hmac.new(signed, string_to_sign, hashlib.sha256) return signature.hexdigest()
apache-2.0
mc7246/WeiXinMPSDK
src/Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/Scan/ScanJson/ScanTicketCheckJsonResult.cs
2508
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2021 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2021 Senparc 文件名:ScanTicketCheckJsonResult.cs 文件功能描述: 检查wxticket参数的返回结果 创建标识:Senparc - 20160520 ----------------------------------------------------------------*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Senparc.Weixin.Entities; namespace Senparc.Weixin.MP.AdvancedAPIs.Scan { /// <summary> /// 检查wxticket参数的返回结果 /// </summary> public class ScanTicketCheckJsonResult : WxJsonResult { /// <summary> /// 商品编码标准。 /// </summary> public string keystandard { get; set; } /// <summary> /// 商品编码内容。 /// </summary> public string keystr { get; set; } /// <summary> /// 当前访问者的openid,可唯一标识用户。 /// </summary> public string openid { get; set; } /// <summary> /// 打开商品主页的场景,scan为扫码,others为其他场景,可能是会话、收藏或朋友圈。 /// </summary> public string scene { get; set; } /// <summary> /// 该条码(二维码)是否被扫描,true为是,false为否。 /// </summary> public string is_check { get; set; } /// <summary> /// 是否关注公众号,true为已关注,false为未关注。 /// </summary> public string is_contact { get; set; } } }
apache-2.0
cnbdragon/DungeonCreator
src/dungeoncreator/Matterial.java
368
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dungeoncreator; /** * * @author jwulf */ public interface Matterial { public void getName(); public void getHardness(); public void getAC(); }
apache-2.0
AntonVasilyuk/Aduma
chapter_002/tracker/src/main/java/ru/job4j/tracker/package-info.java
156
/** * chapter_002. * Interface for tracker * * @author Anton Vasilyuk (wrajina99@gmail.com) * @version $Id$ * @since 0.1 */ package ru.job4j.tracker;
apache-2.0
GAIPS-INESC-ID/FAtiMA-Emotional-Appraisal
Assets/SocialImportance/Properties/AssemblyInfo.cs
1379
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SocialImportanceAsset")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SocialImportanceAsset")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("823e8a41-5231-4b06-bbab-e62651e15bc7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.5.0.0")] [assembly: AssemblyFileVersion("1.5.0.0")]
apache-2.0
Pardus-Engerek/engerek
model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractSearchIterativeTaskHandler.java
25723
/* * Copyright (c) 2010-2017 Evolveum * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.evolveum.midpoint.model.impl.util; import com.evolveum.midpoint.repo.common.expression.ExpressionFactory; import com.evolveum.midpoint.repo.common.expression.ExpressionUtil; import com.evolveum.midpoint.repo.common.expression.ExpressionVariables; import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.model.common.SystemObjectCache; import com.evolveum.midpoint.model.impl.ModelObjectResolver; import com.evolveum.midpoint.model.impl.expr.ExpressionEnvironment; import com.evolveum.midpoint.model.impl.expr.ModelExpressionThreadLocalHolder; import com.evolveum.midpoint.model.impl.sync.TaskHandlerUtil; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.query.QueryJaxbConvertor; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.ResultHandler; import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.security.api.SecurityEnforcer; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskHandler; import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.task.api.TaskRunResult; import com.evolveum.midpoint.task.api.TaskRunResult.TaskRunResultStatus; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ModelExecuteOptionsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; import com.evolveum.prism.xml.ns._public.query_3.QueryType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import javax.xml.namespace.QName; import java.util.*; /** * @author semancik * */ public abstract class AbstractSearchIterativeTaskHandler<O extends ObjectType, H extends AbstractSearchIterativeResultHandler<O>> implements TaskHandler { // WARNING! This task handler is efficiently singleton! // It is a spring bean and it is supposed to handle all search task instances // Therefore it must not have task-specific fields. It can only contain fields specific to // all tasks of a specified type private String taskName; private String taskOperationPrefix; private boolean logFinishInfo = false; private boolean countObjectsOnStart = true; // todo make configurable per task instance (if necessary) private boolean preserveStatistics = true; private boolean enableIterationStatistics = true; // beware, this controls whether task stores these statistics; see also recordIterationStatistics in AbstractSearchIterativeResultHandler private boolean enableSynchronizationStatistics = false; private boolean enableActionsExecutedStatistics = true; // If you need to store fields specific to task instance or task run the ResultHandler is a good place to do that. // This is not ideal, TODO: refactor // Note: The key is task OID. Originally here was the whole task, which caused occasional ConcurrentModificationException // when computing hashCode of TaskQuartzImpl objects (not sure why). Anyway, OIDs are better; assuming we are dealing with // persistent tasks only - which is obviously true. private Map<String, H> handlers = Collections.synchronizedMap(new HashMap<String, H>()); @Autowired protected TaskManager taskManager; @Autowired protected ModelObjectResolver modelObjectResolver; @Autowired @Qualifier("cacheRepositoryService") protected RepositoryService repositoryService; @Autowired protected PrismContext prismContext; @Autowired protected SecurityEnforcer securityEnforcer; @Autowired protected ExpressionFactory expressionFactory; @Autowired protected SystemObjectCache systemObjectCache; private static final transient Trace LOGGER = TraceManager.getTrace(AbstractSearchIterativeTaskHandler.class); protected AbstractSearchIterativeTaskHandler(String taskName, String taskOperationPrefix) { super(); this.taskName = taskName; this.taskOperationPrefix = taskOperationPrefix; } public boolean isLogFinishInfo() { return logFinishInfo; } public boolean isPreserveStatistics() { return preserveStatistics; } public boolean isEnableIterationStatistics() { return enableIterationStatistics; } public void setEnableIterationStatistics(boolean enableIterationStatistics) { this.enableIterationStatistics = enableIterationStatistics; } public boolean isEnableSynchronizationStatistics() { return enableSynchronizationStatistics; } public void setEnableSynchronizationStatistics(boolean enableSynchronizationStatistics) { this.enableSynchronizationStatistics = enableSynchronizationStatistics; } public boolean isEnableActionsExecutedStatistics() { return enableActionsExecutedStatistics; } public void setEnableActionsExecutedStatistics(boolean enableActionsExecutedStatistics) { this.enableActionsExecutedStatistics = enableActionsExecutedStatistics; } public void setPreserveStatistics(boolean preserveStatistics) { this.preserveStatistics = preserveStatistics; } public void setLogFinishInfo(boolean logFinishInfo) { this.logFinishInfo = logFinishInfo; } @Override public TaskRunResult run(Task coordinatorTask) { LOGGER.trace("{} run starting (coordinator task {})", taskName, coordinatorTask); if (isPreserveStatistics()) { coordinatorTask.startCollectingOperationStatsFromStoredValues(isEnableIterationStatistics(), isEnableSynchronizationStatistics(), isEnableActionsExecutedStatistics()); } else { coordinatorTask.startCollectingOperationStatsFromZero(isEnableIterationStatistics(), isEnableSynchronizationStatistics(), isEnableActionsExecutedStatistics()); } try { return runInternal(coordinatorTask); } finally { coordinatorTask.storeOperationStats(); } } public TaskRunResult runInternal(Task coordinatorTask) { OperationResult opResult = new OperationResult(taskOperationPrefix + ".run"); opResult.setStatus(OperationResultStatus.IN_PROGRESS); TaskRunResult runResult = new TaskRunResult(); runResult.setOperationResult(opResult); H resultHandler; try { resultHandler = createHandler(runResult, coordinatorTask, opResult); } catch (SecurityViolationException|SchemaException|RuntimeException e) { LOGGER.error("{}: Error while creating a result handler: {}", taskName, e.getMessage(), e); opResult.recordFatalError("Error while creating a result handler: " + e.getMessage(), e); runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); runResult.setProgress(coordinatorTask.getProgress()); return runResult; } if (resultHandler == null) { // the error should already be in the runResult return runResult; } // copying relevant configuration items from task to handler resultHandler.setEnableIterationStatistics(isEnableIterationStatistics()); resultHandler.setEnableSynchronizationStatistics(isEnableSynchronizationStatistics()); resultHandler.setEnableActionsExecutedStatistics(isEnableActionsExecutedStatistics()); boolean cont = initializeRun(resultHandler, runResult, coordinatorTask, opResult); if (!cont) { return runResult; } // TODO: error checking - already running if (coordinatorTask.getOid() == null) { throw new IllegalArgumentException("Transient tasks cannot be run by " + AbstractSearchIterativeTaskHandler.class + ": " + coordinatorTask); } handlers.put(coordinatorTask.getOid(), resultHandler); ObjectQuery query; try { query = createQuery(resultHandler, runResult, coordinatorTask, opResult); } catch (SchemaException ex) { logErrorAndSetResult(runResult, resultHandler, "Schema error while creating a search filter", ex, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR); return runResult; } if (LOGGER.isTraceEnabled()) { LOGGER.trace("{}: using a query (before evaluating expressions):\n{}", taskName, DebugUtil.debugDump(query)); } if (query == null) { // the error should already be in the runResult return runResult; } try { // TODO consider which variables should go here (there's no focus, shadow, resource - only configuration) if (ExpressionUtil.hasExpressions(query.getFilter())) { PrismObject<SystemConfigurationType> configuration = systemObjectCache.getSystemConfiguration(opResult); ExpressionVariables variables = Utils.getDefaultExpressionVariables(null, null, null, configuration != null ? configuration.asObjectable() : null); try { ExpressionEnvironment<?> env = new ExpressionEnvironment<>(coordinatorTask, opResult); ModelExpressionThreadLocalHolder.pushExpressionEnvironment(env); query = ExpressionUtil.evaluateQueryExpressions(query, variables, expressionFactory, prismContext, "evaluate query expressions", coordinatorTask, opResult); } finally { ModelExpressionThreadLocalHolder.popExpressionEnvironment(); } } } catch (SchemaException|ObjectNotFoundException|ExpressionEvaluationException e) { logErrorAndSetResult(runResult, resultHandler, "Error while evaluating expressions in a search filter", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR); return runResult; } Class<? extends ObjectType> type = getType(coordinatorTask); Collection<SelectorOptions<GetOperationOptions>> queryOptions = createQueryOptions(resultHandler, runResult, coordinatorTask, opResult); boolean useRepository = useRepositoryDirectly(resultHandler, runResult, coordinatorTask, opResult); if (LOGGER.isTraceEnabled()) { LOGGER.trace("{}: searching {} with options {}, using query:\n{}", taskName, type, queryOptions, query.debugDump()); } try { // counting objects can be within try-catch block, because the handling is similar to handling errors within searchIterative Long expectedTotal = null; if (countObjectsOnStart) { if (!useRepository) { Integer expectedTotalInt = modelObjectResolver.countObjects(type, query, queryOptions, coordinatorTask, opResult); if (expectedTotalInt != null) { expectedTotal = (long) expectedTotalInt; // conversion would fail on null } } else { expectedTotal = (long) repositoryService.countObjects(type, query, opResult); } LOGGER.trace("{}: expecting {} objects to be processed", taskName, expectedTotal); } runResult.setProgress(0); coordinatorTask.setProgress(0); if (expectedTotal != null) { coordinatorTask.setExpectedTotal(expectedTotal); } try { coordinatorTask.savePendingModifications(opResult); } catch (ObjectAlreadyExistsException e) { // other exceptions are handled in the outer try block throw new IllegalStateException("Unexpected ObjectAlreadyExistsException when updating task progress/expectedTotal", e); } resultHandler.createWorkerThreads(coordinatorTask, opResult); if (!useRepository) { modelObjectResolver.searchIterative((Class<O>) type, query, queryOptions, resultHandler, coordinatorTask, opResult); } else { repositoryService.searchObjectsIterative(type, query, (ResultHandler) resultHandler, queryOptions, false, opResult); // TODO think about this } resultHandler.completeProcessing(coordinatorTask, opResult); } catch (ObjectNotFoundException e) { // This is bad. The resource does not exist. Permanent problem. logErrorAndSetResult(runResult, resultHandler, "Object not found", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR); return runResult; } catch (CommunicationException e) { // Error, but not critical. Just try later. logErrorAndSetResult(runResult, resultHandler, "Communication error", e, OperationResultStatus.PARTIAL_ERROR, TaskRunResultStatus.TEMPORARY_ERROR); return runResult; } catch (SchemaException e) { // Not sure about this. But most likely it is a misconfigured resource or connector // It may be worth to retry. Error is fatal, but may not be permanent. logErrorAndSetResult(runResult, resultHandler, "Error dealing with schema", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.TEMPORARY_ERROR); return runResult; } catch (RuntimeException e) { // Can be anything ... but we can't recover from that. // It is most likely a programming error. Does not make much sense to retry. logErrorAndSetResult(runResult, resultHandler, "Internal error", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR); return runResult; } catch (ConfigurationException e) { // Not sure about this. But most likely it is a misconfigured resource or connector // It may be worth to retry. Error is fatal, but may not be permanent. logErrorAndSetResult(runResult, resultHandler, "Configuration error", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.TEMPORARY_ERROR); return runResult; } catch (SecurityViolationException e) { logErrorAndSetResult(runResult, resultHandler, "Security violation", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR); return runResult; } catch (ExpressionEvaluationException e) { logErrorAndSetResult(runResult, resultHandler, "Expression error", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR); return runResult; } // TODO: check last handler status handlers.remove(coordinatorTask.getOid()); runResult.setProgress(resultHandler.getProgress()); runResult.setRunResultStatus(TaskRunResultStatus.FINISHED); if (logFinishInfo) { String finishMessage = "Finished " + taskName + " (" + coordinatorTask + "). "; String statistics = "Processed " + resultHandler.getProgress() + " objects in " + resultHandler.getWallTime()/1000 + " seconds, got " + resultHandler.getErrors() + " errors."; if (resultHandler.getProgress() > 0) { statistics += " Average time for one object: " + resultHandler.getAverageTime() + " milliseconds" + " (wall clock time average: " + resultHandler.getWallAverageTime() + " ms)."; } if (!coordinatorTask.canRun()) { statistics += " Task was interrupted during processing."; } opResult.createSubresult(taskOperationPrefix + ".statistics").recordStatus(OperationResultStatus.SUCCESS, statistics); TaskHandlerUtil.appendLastFailuresInformation(taskOperationPrefix, coordinatorTask, opResult); LOGGER.info("{}", finishMessage + statistics); } try { finish(resultHandler, runResult, coordinatorTask, opResult); } catch (SchemaException e) { logErrorAndSetResult(runResult, resultHandler, "Schema error while finishing the run", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR); return runResult; } LOGGER.trace("{} run finished (task {}, run result {})", taskName, coordinatorTask, runResult); return runResult; } private TaskRunResult logErrorAndSetResult(TaskRunResult runResult, H resultHandler, String message, Throwable e, OperationResultStatus opStatus, TaskRunResultStatus status) { LOGGER.error("{}: {}: {}", taskName, message, e.getMessage(), e); runResult.getOperationResult().recordStatus(opStatus, message + ": " + e.getMessage(), e); runResult.setRunResultStatus(status); runResult.setProgress(resultHandler.getProgress()); return runResult; } protected void finish(H handler, TaskRunResult runResult, Task task, OperationResult opResult) throws SchemaException { } private H getHandler(Task task) { return handlers.get(task.getOid()); } @Override public Long heartbeat(Task task) { // Delegate heartbeat to the result handler if (getHandler(task) != null) { return getHandler(task).heartbeat(); } else { // most likely a race condition. return null; } } protected <T extends ObjectType> T resolveObjectRef(Class<T> type, TaskRunResult runResult, Task task, OperationResult opResult) { String typeName = type.getClass().getSimpleName(); String objectOid = task.getObjectOid(); if (objectOid == null) { LOGGER.error("Import: No {} OID specified in the task", typeName); opResult.recordFatalError("No "+typeName+" OID specified in the task"); runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return null; } T objectType; try { objectType = modelObjectResolver.getObject(type, objectOid, null, task, opResult); } catch (ObjectNotFoundException ex) { LOGGER.error("Import: {} {} not found: {}", typeName, objectOid, ex.getMessage(), ex); // This is bad. The resource does not exist. Permanent problem. opResult.recordFatalError(typeName+" not found " + objectOid, ex); runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return null; } catch (SchemaException ex) { LOGGER.error("Import: Error dealing with schema: {}", ex.getMessage(), ex); // Not sure about this. But most likely it is a misconfigured resource or connector // It may be worth to retry. Error is fatal, but may not be permanent. opResult.recordFatalError("Error dealing with schema: " + ex.getMessage(), ex); runResult.setRunResultStatus(TaskRunResultStatus.TEMPORARY_ERROR); return null; } catch (RuntimeException ex) { LOGGER.error("Import: Internal Error: {}", ex.getMessage(), ex); // Can be anything ... but we can't recover from that. // It is most likely a programming error. Does not make much sense to retry. opResult.recordFatalError("Internal Error: " + ex.getMessage(), ex); runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return null; } catch (CommunicationException ex) { LOGGER.error("Import: Error getting {} {}: {}", typeName, objectOid, ex.getMessage(), ex); opResult.recordFatalError("Error getting "+typeName+" " + objectOid+": "+ex.getMessage(), ex); runResult.setRunResultStatus(TaskRunResultStatus.TEMPORARY_ERROR); return null; } catch (ConfigurationException ex) { LOGGER.error("Import: Error getting {} {}: {}", typeName, objectOid, ex.getMessage(), ex); opResult.recordFatalError("Error getting "+typeName+" " + objectOid+": "+ex.getMessage(), ex); runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return null; } catch (SecurityViolationException ex) { LOGGER.error("Import: Error getting {} {}: {}", typeName, objectOid, ex.getMessage(), ex); opResult.recordFatalError("Error getting "+typeName+" " + objectOid+": "+ex.getMessage(), ex); runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return null; } catch (ExpressionEvaluationException ex) { LOGGER.error("Import: Error getting {} {}: {}", typeName, objectOid, ex.getMessage(), ex); opResult.recordFatalError("Error getting "+typeName+" " + objectOid+": "+ex.getMessage(), ex); runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return null; } if (objectType == null) { LOGGER.error("Import: No "+typeName+" specified"); opResult.recordFatalError("No "+typeName+" specified"); runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return null; } return objectType; } @Override public void refreshStatus(Task task) { // Local task. No refresh needed. The Task instance has always fresh data. } /** * Handler parameter may be used to pass task instance state between the calls. */ protected abstract ObjectQuery createQuery(H handler, TaskRunResult runResult, Task task, OperationResult opResult) throws SchemaException; // useful e.g. to specify noFetch options for shadow-related queries protected Collection<SelectorOptions<GetOperationOptions>> createQueryOptions(H resultHandler, TaskRunResult runResult, Task coordinatorTask, OperationResult opResult) { return null; } // as provisioning service does not allow searches without specifying resource or objectclass/kind, we need to be able to contact repository directly // for some specific tasks protected boolean useRepositoryDirectly(H resultHandler, TaskRunResult runResult, Task coordinatorTask, OperationResult opResult) { return false; } protected abstract Class<? extends ObjectType> getType(Task task); protected abstract H createHandler(TaskRunResult runResult, Task coordinatorTask, OperationResult opResult) throws SchemaException, SecurityViolationException; /** * Used to properly initialize the "run", which is kind of task instance. The result handler is already created at this stage. * Therefore this method may be used to "enrich" the result handler with some instance-specific data. */ protected boolean initializeRun(H handler, TaskRunResult runResult, Task task, OperationResult opResult) { // Nothing to do by default return true; } /** * Ready-made implementation of createQuery - gets and parses objectQuery extension property. */ protected ObjectQuery createQueryFromTask(H handler, TaskRunResult runResult, Task task, OperationResult opResult) throws SchemaException { Class<? extends ObjectType> objectClass = getType(task); LOGGER.trace("Object class = {}", objectClass); QueryType queryFromTask = getObjectQueryTypeFromTask(task); if (queryFromTask != null) { ObjectQuery query = QueryJaxbConvertor.createObjectQuery(objectClass, queryFromTask, prismContext); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Using object query from the task: {}", query.debugDump()); } return query; } else { // Search all objects return new ObjectQuery(); } } protected ModelExecuteOptions getExecuteOptionsFromTask(Task task) { PrismProperty<ModelExecuteOptionsType> property = task.getExtensionProperty(SchemaConstants.MODEL_EXTENSION_EXECUTE_OPTIONS); return property != null ? ModelExecuteOptions.fromModelExecutionOptionsType(property.getRealValue()) : null; } protected QueryType getObjectQueryTypeFromTask(Task task) { PrismProperty<QueryType> objectQueryPrismProperty = task.getExtensionProperty(SchemaConstants.MODEL_EXTENSION_OBJECT_QUERY); if (objectQueryPrismProperty != null && objectQueryPrismProperty.getRealValue() != null) { return objectQueryPrismProperty.getRealValue(); } else { return null; } } protected Class<? extends ObjectType> getTypeFromTask(Task task, Class<? extends ObjectType> defaultType) { Class<? extends ObjectType> objectClass; PrismProperty<QName> objectTypePrismProperty = task.getExtensionProperty(SchemaConstants.MODEL_EXTENSION_OBJECT_TYPE); if (objectTypePrismProperty != null && objectTypePrismProperty.getRealValue() != null) { objectClass = ObjectTypes.getObjectTypeFromTypeQName(objectTypePrismProperty.getRealValue()).getClassDefinition(); } else { objectClass = defaultType; } return objectClass; } }
apache-2.0
NextCenturyCorporation/digapp-microcap-fraud
server/config/local.env.sample.js
442
'use strict'; // Use local.env.js for environment variables that grunt will set when the server starts locally. // Use for your api keys, secrets, etc. This file should not be tracked by git. // // You will need to set these on the server you deploy to. module.exports = { DOMAIN: 'http://localhost:9000', SESSION_SECRET: 'digentitygraph-secret', // Control debug level for modules using visionmedia/debug DEBUG: '' };
apache-2.0
botelhojp/apache-jmeter-2.10
src/components/org/apache/jmeter/assertions/ResponseAssertion.java
19684
/* * 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.jmeter.assertions; import java.io.Serializable; import java.net.URL; import java.util.ArrayList; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.testelement.AbstractScopedAssertion; import org.apache.jmeter.testelement.property.CollectionProperty; import org.apache.jmeter.testelement.property.IntegerProperty; import org.apache.jmeter.testelement.property.JMeterProperty; import org.apache.jmeter.testelement.property.NullProperty; import org.apache.jmeter.testelement.property.PropertyIterator; import org.apache.jmeter.testelement.property.StringProperty; import org.apache.jmeter.util.Document; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; import org.apache.oro.text.MalformedCachePatternException; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; // @see org.apache.jmeter.assertions.ResponseAssertionTest for unit tests /** * Test element to handle Response Assertions, @see AssertionGui */ public class ResponseAssertion extends AbstractScopedAssertion implements Serializable, Assertion { private static final Logger log = LoggingManager.getLoggerForClass(); private static final long serialVersionUID = 240L; private static final String TEST_FIELD = "Assertion.test_field"; // $NON-NLS-1$ // Values for TEST_FIELD // N.B. we cannot change the text value as it is in test plans private static final String SAMPLE_URL = "Assertion.sample_label"; // $NON-NLS-1$ private static final String RESPONSE_DATA = "Assertion.response_data"; // $NON-NLS-1$ private static final String RESPONSE_DATA_AS_DOCUMENT = "Assertion.response_data_as_document"; // $NON-NLS-1$ private static final String RESPONSE_CODE = "Assertion.response_code"; // $NON-NLS-1$ private static final String RESPONSE_MESSAGE = "Assertion.response_message"; // $NON-NLS-1$ private static final String RESPONSE_HEADERS = "Assertion.response_headers"; // $NON-NLS-1$ private static final String ASSUME_SUCCESS = "Assertion.assume_success"; // $NON-NLS-1$ private static final String TEST_STRINGS = "Asserion.test_strings"; // $NON-NLS-1$ private static final String TEST_TYPE = "Assertion.test_type"; // $NON-NLS-1$ /* * Mask values for TEST_TYPE TODO: remove either MATCH or CONTAINS - they * are mutually exckusive */ private static final int MATCH = 1 << 0; private static final int CONTAINS = 1 << 1; private static final int NOT = 1 << 2; private static final int EQUALS = 1 << 3; private static final int SUBSTRING = 1 << 4; // Mask should contain all types (but not NOT) private static final int TYPE_MASK = CONTAINS | EQUALS | MATCH | SUBSTRING; private static final int EQUALS_SECTION_DIFF_LEN = JMeterUtils.getPropDefault("assertion.equals_section_diff_len", 100); /** Signifies truncated text in diff display. */ private static final String EQUALS_DIFF_TRUNC = "..."; private static final String RECEIVED_STR = "****** received : "; private static final String COMPARISON_STR = "****** comparison: "; private static final String DIFF_DELTA_START = JMeterUtils.getPropDefault("assertion.equals_diff_delta_start", "[[["); private static final String DIFF_DELTA_END = JMeterUtils.getPropDefault("assertion.equals_diff_delta_end", "]]]"); public ResponseAssertion() { setProperty(new CollectionProperty(TEST_STRINGS, new ArrayList<String>())); } @Override public void clear() { super.clear(); setProperty(new CollectionProperty(TEST_STRINGS, new ArrayList<String>())); } private void setTestField(String testField) { setProperty(TEST_FIELD, testField); } public void setTestFieldURL(){ setTestField(SAMPLE_URL); } public void setTestFieldResponseCode(){ setTestField(RESPONSE_CODE); } public void setTestFieldResponseData(){ setTestField(RESPONSE_DATA); } public void setTestFieldResponseDataAsDocument(){ setTestField(RESPONSE_DATA_AS_DOCUMENT); } public void setTestFieldResponseMessage(){ setTestField(RESPONSE_MESSAGE); } public void setTestFieldResponseHeaders(){ setTestField(RESPONSE_HEADERS); } public boolean isTestFieldURL(){ return SAMPLE_URL.equals(getTestField()); } public boolean isTestFieldResponseCode(){ return RESPONSE_CODE.equals(getTestField()); } public boolean isTestFieldResponseData(){ return RESPONSE_DATA.equals(getTestField()); } public boolean isTestFieldResponseDataAsDocument() { return RESPONSE_DATA_AS_DOCUMENT.equals(getTestField()); } public boolean isTestFieldResponseMessage(){ return RESPONSE_MESSAGE.equals(getTestField()); } public boolean isTestFieldResponseHeaders(){ return RESPONSE_HEADERS.equals(getTestField()); } private void setTestType(int testType) { setProperty(new IntegerProperty(TEST_TYPE, testType)); } private void setTestTypeMasked(int testType) { int value = getTestType() & ~(TYPE_MASK) | testType; setProperty(new IntegerProperty(TEST_TYPE, value)); } public void addTestString(String testString) { getTestStrings().addProperty(new StringProperty(String.valueOf(testString.hashCode()), testString)); } public void clearTestStrings() { getTestStrings().clear(); } @Override public AssertionResult getResult(SampleResult response) { AssertionResult result; // None of the other Assertions check the response status, so remove // this check // for the time being, at least... // if (!response.isSuccessful()) // { // result = new AssertionResult(); // result.setError(true); // byte [] ba = response.getResponseData(); // result.setFailureMessage( // ba == null ? "Unknown Error (responseData is empty)" : new String(ba) // ); // return result; // } result = evaluateResponse(response); return result; } /*************************************************************************** * !ToDoo (Method description) * * @return !ToDo (Return description) **************************************************************************/ public String getTestField() { return getPropertyAsString(TEST_FIELD); } /*************************************************************************** * !ToDoo (Method description) * * @return !ToDo (Return description) **************************************************************************/ public int getTestType() { JMeterProperty type = getProperty(TEST_TYPE); if (type instanceof NullProperty) { return CONTAINS; } return type.getIntValue(); } /*************************************************************************** * !ToDoo (Method description) * * @return !ToDo (Return description) **************************************************************************/ public CollectionProperty getTestStrings() { return (CollectionProperty) getProperty(TEST_STRINGS); } public boolean isEqualsType() { return (getTestType() & EQUALS) != 0; } public boolean isSubstringType() { return (getTestType() & SUBSTRING) != 0; } public boolean isContainsType() { return (getTestType() & CONTAINS) != 0; } public boolean isMatchType() { return (getTestType() & MATCH) != 0; } public boolean isNotType() { return (getTestType() & NOT) != 0; } public void setToContainsType() { setTestTypeMasked(CONTAINS); } public void setToMatchType() { setTestTypeMasked(MATCH); } public void setToEqualsType() { setTestTypeMasked(EQUALS); } public void setToSubstringType() { setTestTypeMasked(SUBSTRING); } public void setToNotType() { setTestType((getTestType() | NOT)); } public void unsetNotType() { setTestType(getTestType() & ~NOT); } public boolean getAssumeSuccess() { return getPropertyAsBoolean(ASSUME_SUCCESS, false); } public void setAssumeSuccess(boolean b) { setProperty(ASSUME_SUCCESS, b); } /** * Make sure the response satisfies the specified assertion requirements. * * @param response * an instance of SampleResult * @return an instance of AssertionResult */ private AssertionResult evaluateResponse(SampleResult response) { AssertionResult result = new AssertionResult(getName()); String toCheck = ""; // The string to check (Url or data) if (getAssumeSuccess()) { response.setSuccessful(true);// Allow testing of failure codes } // What are we testing against? if (isScopeVariable()){ toCheck = getThreadContext().getVariables().get(getVariableName()); } else if (isTestFieldResponseData()) { toCheck = response.getResponseDataAsString(); // (bug25052) } else if (isTestFieldResponseDataAsDocument()) { toCheck = Document.getTextFromDocument(response.getResponseData()); } else if (isTestFieldResponseCode()) { toCheck = response.getResponseCode(); } else if (isTestFieldResponseMessage()) { toCheck = response.getResponseMessage(); } else if (isTestFieldResponseHeaders()) { toCheck = response.getResponseHeaders(); } else { // Assume it is the URL toCheck = ""; final URL url = response.getURL(); if (url != null){ toCheck = url.toString(); } } result.setFailure(false); result.setError(false); boolean notTest = (NOT & getTestType()) > 0; boolean contains = isContainsType(); // do it once outside loop boolean equals = isEqualsType(); boolean substring = isSubstringType(); boolean matches = isMatchType(); boolean debugEnabled = log.isDebugEnabled(); if (debugEnabled){ log.debug("Type:" + (contains?"Contains":"Match") + (notTest? "(not)": "")); } if (toCheck.length() == 0) { if (notTest) { // Not should always succeed against an empty result return result; } if (debugEnabled){ log.debug("Not checking empty response field in: "+response.getSampleLabel()); } return result.setResultForNull(); } boolean pass = true; try { // Get the Matcher for this thread Perl5Matcher localMatcher = JMeterUtils.getMatcher(); PropertyIterator iter = getTestStrings().iterator(); while (iter.hasNext()) { String stringPattern = iter.next().getStringValue(); Pattern pattern = null; if (contains || matches) { pattern = JMeterUtils.getPatternCache().getPattern(stringPattern, Perl5Compiler.READ_ONLY_MASK); } boolean found; if (contains) { found = localMatcher.contains(toCheck, pattern); } else if (equals) { found = toCheck.equals(stringPattern); } else if (substring) { found = toCheck.indexOf(stringPattern) != -1; } else { found = localMatcher.matches(toCheck, pattern); } pass = notTest ? !found : found; if (!pass) { if (debugEnabled){log.debug("Failed: "+stringPattern);} result.setFailure(true); result.setFailureMessage(getFailText(stringPattern,toCheck)); break; } if (debugEnabled){log.debug("Passed: "+stringPattern);} } } catch (MalformedCachePatternException e) { result.setError(true); result.setFailure(false); result.setFailureMessage("Bad test configuration " + e); } return result; } /** * Generate the failure reason from the TestType * * @param stringPattern * @return the message for the assertion report */ // TODO strings should be resources private String getFailText(String stringPattern, String toCheck) { StringBuilder sb = new StringBuilder(200); sb.append("Test failed: "); if (isScopeVariable()){ sb.append("variable(").append(getVariableName()).append(')'); } else if (isTestFieldResponseData()) { sb.append("text"); } else if (isTestFieldResponseCode()) { sb.append("code"); } else if (isTestFieldResponseMessage()) { sb.append("message"); } else if (isTestFieldResponseHeaders()) { sb.append("headers"); } else if (isTestFieldResponseDataAsDocument()) { sb.append("document"); } else // Assume it is the URL { sb.append("URL"); } switch (getTestType()) { case CONTAINS: case SUBSTRING: sb.append(" expected to contain "); break; case NOT | CONTAINS: case NOT | SUBSTRING: sb.append(" expected not to contain "); break; case MATCH: sb.append(" expected to match "); break; case NOT | MATCH: sb.append(" expected not to match "); break; case EQUALS: sb.append(" expected to equal "); break; case NOT | EQUALS: sb.append(" expected not to equal "); break; default:// should never happen... sb.append(" expected something using "); } sb.append("/"); if (isEqualsType()){ sb.append(equalsComparisonText(toCheck, stringPattern)); } else { sb.append(stringPattern); } sb.append("/"); return sb.toString(); } private static String trunc(final boolean right, final String str) { if (str.length() <= EQUALS_SECTION_DIFF_LEN) { return str; } else if (right) { return str.substring(0, EQUALS_SECTION_DIFF_LEN) + EQUALS_DIFF_TRUNC; } else { return EQUALS_DIFF_TRUNC + str.substring(str.length() - EQUALS_SECTION_DIFF_LEN, str.length()); } } /** * Returns some helpful logging text to determine where equality between two strings * is broken, with one pointer working from the front of the strings and another working * backwards from the end. * * @param received String received from sampler. * @param comparison String specified for "equals" response assertion. * @return Two lines of text separated by newlines, and then forward and backward pointers * denoting first position of difference. */ private static StringBuilder equalsComparisonText(final String received, final String comparison) { int firstDiff; int lastRecDiff = -1; int lastCompDiff = -1; final int recLength = received.length(); final int compLength = comparison.length(); final int minLength = Math.min(recLength, compLength); final String startingEqSeq; String recDeltaSeq = ""; String compDeltaSeq = ""; String endingEqSeq = ""; final StringBuilder text = new StringBuilder(Math.max(recLength, compLength) * 2); for (firstDiff = 0; firstDiff < minLength; firstDiff++) { if (received.charAt(firstDiff) != comparison.charAt(firstDiff)){ break; } } if (firstDiff == 0) { startingEqSeq = ""; } else { startingEqSeq = trunc(false, received.substring(0, firstDiff)); } lastRecDiff = recLength - 1; lastCompDiff = compLength - 1; while ((lastRecDiff > firstDiff) && (lastCompDiff > firstDiff) && received.charAt(lastRecDiff) == comparison.charAt(lastCompDiff)) { lastRecDiff--; lastCompDiff--; } endingEqSeq = trunc(true, received.substring(lastRecDiff + 1, recLength)); if (endingEqSeq.length() == 0) { recDeltaSeq = trunc(true, received.substring(firstDiff, recLength)); compDeltaSeq = trunc(true, comparison.substring(firstDiff, compLength)); } else { recDeltaSeq = trunc(true, received.substring(firstDiff, lastRecDiff + 1)); compDeltaSeq = trunc(true, comparison.substring(firstDiff, lastCompDiff + 1)); } final StringBuilder pad = new StringBuilder(Math.abs(recDeltaSeq.length() - compDeltaSeq.length())); for (int i = 0; i < pad.capacity(); i++){ pad.append(' '); } if (recDeltaSeq.length() > compDeltaSeq.length()){ compDeltaSeq += pad.toString(); } else { recDeltaSeq += pad.toString(); } text.append("\n\n"); text.append(RECEIVED_STR); text.append(startingEqSeq); text.append(DIFF_DELTA_START); text.append(recDeltaSeq); text.append(DIFF_DELTA_END); text.append(endingEqSeq); text.append("\n\n"); text.append(COMPARISON_STR); text.append(startingEqSeq); text.append(DIFF_DELTA_START); text.append(compDeltaSeq); text.append(DIFF_DELTA_END); text.append(endingEqSeq); text.append("\n\n"); return text; } }
apache-2.0
thalman/dds
src/responderDBBlocked.php
893
<?php // Copyright 2015 Tomas Halman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. include_once "database.php"; header('Content-Type: text/plain'); header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1. header('Pragma: no-cache'); // HTTP 1.0. header('Expires: 0'); // Proxies. $db = new DDSDatabase(); echo ( $db->isResetBlocked() ? "true" : "false" ); ?>
apache-2.0
stellar/js-stellar-base
test/unit/keypair_test.js
5145
describe('Keypair.contructor', function() { it('fails when passes secret key does not match public key', function() { let secret = 'SD7X7LEHBNMUIKQGKPARG5TDJNBHKC346OUARHGZL5ITC6IJPXHILY36'; let kp = StellarBase.Keypair.fromSecret(secret); let secretKey = kp.rawSecretKey(); let publicKey = StellarBase.StrKey.decodeEd25519PublicKey(kp.publicKey()); publicKey[0] = 0; // Make public key invalid expect( () => new StellarBase.Keypair({ type: 'ed25519', secretKey, publicKey }) ).to.throw(/secretKey does not match publicKey/); }); it('fails when secretKey length is invalid', function() { let secretKey = Buffer.alloc(33); expect( () => new StellarBase.Keypair({ type: 'ed25519', secretKey }) ).to.throw(/secretKey length is invalid/); }); it('fails when publicKey length is invalid', function() { let publicKey = Buffer.alloc(33); expect( () => new StellarBase.Keypair({ type: 'ed25519', publicKey }) ).to.throw(/publicKey length is invalid/); }); }); describe('Keypair.fromSecret', function() { it('creates a keypair correctly', function() { let secret = 'SD7X7LEHBNMUIKQGKPARG5TDJNBHKC346OUARHGZL5ITC6IJPXHILY36'; let kp = StellarBase.Keypair.fromSecret(secret); expect(kp).to.be.instanceof(StellarBase.Keypair); expect(kp.publicKey()).to.eql( 'GDFQVQCYYB7GKCGSCUSIQYXTPLV5YJ3XWDMWGQMDNM4EAXAL7LITIBQ7' ); expect(kp.secret()).to.eql(secret); }); it("throw an error if the arg isn't strkey encoded as a seed", function() { expect(() => StellarBase.Keypair.fromSecret('hel0')).to.throw(); expect(() => StellarBase.Keypair.fromSecret( 'SBWUBZ3SIPLLF5CCXLWUB2Z6UBTYAW34KVXOLRQ5HDAZG4ZY7MHNBWJ1' ) ).to.throw(); expect(() => StellarBase.Keypair.fromSecret('masterpassphrasemasterpassphrase') ).to.throw(); expect(() => StellarBase.Keypair.fromSecret( 'gsYRSEQhTffqA9opPepAENCr2WG6z5iBHHubxxbRzWaHf8FBWcu' ) ).to.throw(); }); }); describe('Keypair.fromRawEd25519Seed', function() { it('creates a keypair correctly', function() { let seed = 'masterpassphrasemasterpassphrase'; let kp = StellarBase.Keypair.fromRawEd25519Seed(seed); expect(kp).to.be.instanceof(StellarBase.Keypair); expect(kp.publicKey()).to.eql( 'GAXDYNIBA5E4DXR5TJN522RRYESFQ5UNUXHIPTFGVLLD5O5K552DF5ZH' ); expect(kp.secret()).to.eql( 'SBWWC43UMVZHAYLTONYGQ4TBONSW2YLTORSXE4DBONZXA2DSMFZWLP2R' ); expect(kp.rawPublicKey().toString('hex')).to.eql( '2e3c35010749c1de3d9a5bdd6a31c12458768da5ce87cca6aad63ebbaaef7432' ); }); it("throws an error if the arg isn't 32 bytes", function() { expect(() => StellarBase.Keypair.fromRawEd25519Seed('masterpassphrasemasterpassphras') ).to.throw(); expect(() => StellarBase.Keypair.fromRawEd25519Seed( 'masterpassphrasemasterpassphrase1' ) ).to.throw(); expect(() => StellarBase.Keypair.fromRawEd25519Seed(null)).to.throw(); expect(() => StellarBase.Keypair.fromRawEd25519Seed()).to.throw(); }); }); describe('Keypair.fromPublicKey', function() { it('creates a keypair correctly', function() { let kp = StellarBase.Keypair.fromPublicKey( 'GAXDYNIBA5E4DXR5TJN522RRYESFQ5UNUXHIPTFGVLLD5O5K552DF5ZH' ); expect(kp).to.be.instanceof(StellarBase.Keypair); expect(kp.publicKey()).to.eql( 'GAXDYNIBA5E4DXR5TJN522RRYESFQ5UNUXHIPTFGVLLD5O5K552DF5ZH' ); expect(kp.rawPublicKey().toString('hex')).to.eql( '2e3c35010749c1de3d9a5bdd6a31c12458768da5ce87cca6aad63ebbaaef7432' ); }); it("throw an error if the arg isn't strkey encoded as a accountid", function() { expect(() => StellarBase.Keypair.fromPublicKey('hel0')).to.throw(); expect(() => StellarBase.Keypair.fromPublicKey('masterpassphrasemasterpassphrase') ).to.throw(); expect(() => StellarBase.Keypair.fromPublicKey( 'sfyjodTxbwLtRToZvi6yQ1KnpZriwTJ7n6nrASFR6goRviCU3Ff' ) ).to.throw(); }); it("throws an error if the address isn't 32 bytes", function() { expect(() => StellarBase.Keypair.fromPublicKey('masterpassphrasemasterpassphrase') ).to.throw(); expect(() => StellarBase.Keypair.fromPublicKey('masterpassphrasemasterpassphrase') ).to.throw(); expect(() => StellarBase.Keypair.fromPublicKey(null)).to.throw(); expect(() => StellarBase.Keypair.fromPublicKey()).to.throw(); }); }); describe('Keypair.random', function() { it('creates a keypair correctly', function() { let kp = StellarBase.Keypair.random(); expect(kp).to.be.instanceof(StellarBase.Keypair); }); }); describe('Keypair.xdrMuxedAccount', function() { it('returns a valid MuxedAccount with a Ed25519 key type', function() { const kp = StellarBase.Keypair.fromPublicKey( 'GAXDYNIBA5E4DXR5TJN522RRYESFQ5UNUXHIPTFGVLLD5O5K552DF5ZH' ); const muxed = kp.xdrMuxedAccount(); expect(muxed).to.be.instanceof(StellarBase.xdr.MuxedAccount); expect(muxed.switch()).to.be.equal( StellarBase.xdr.CryptoKeyType.keyTypeEd25519() ); }); });
apache-2.0
zimmermatt/flink
flink-core/src/main/java/org/apache/flink/core/memory/DataOutputSerializer.java
9105
/* * 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.flink.core.memory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.EOFException; import java.io.IOException; import java.io.UTFDataFormatException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; /** * A simple and efficient serializer for the {@link java.io.DataOutput} interface. */ public class DataOutputSerializer implements DataOutputView { private static final Logger LOG = LoggerFactory.getLogger(DataOutputSerializer.class); private static final int PRUNE_BUFFER_THRESHOLD = 5 * 1024 * 1024; // ------------------------------------------------------------------------ private final byte[] startBuffer; private byte[] buffer; private int position; private ByteBuffer wrapper; // ------------------------------------------------------------------------ public DataOutputSerializer(int startSize) { if (startSize < 1) { throw new IllegalArgumentException(); } this.startBuffer = new byte[startSize]; this.buffer = this.startBuffer; this.wrapper = ByteBuffer.wrap(buffer); } public ByteBuffer wrapAsByteBuffer() { this.wrapper.position(0); this.wrapper.limit(this.position); return this.wrapper; } public byte[] getByteArray() { return buffer; } public byte[] getCopyOfBuffer() { return Arrays.copyOf(buffer, position); } public void clear() { this.position = 0; } public int length() { return this.position; } public void pruneBuffer() { if (this.buffer.length > PRUNE_BUFFER_THRESHOLD) { if (LOG.isDebugEnabled()) { LOG.debug("Releasing serialization buffer of " + this.buffer.length + " bytes."); } this.buffer = this.startBuffer; this.wrapper = ByteBuffer.wrap(this.buffer); } } @Override public String toString() { return String.format("[pos=%d cap=%d]", this.position, this.buffer.length); } // ---------------------------------------------------------------------------------------- // Data Output // ---------------------------------------------------------------------------------------- @Override public void write(int b) throws IOException { if (this.position >= this.buffer.length) { resize(1); } this.buffer[this.position++] = (byte) (b & 0xff); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { if (len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } if (this.position > this.buffer.length - len) { resize(len); } System.arraycopy(b, off, this.buffer, this.position, len); this.position += len; } @Override public void writeBoolean(boolean v) throws IOException { write(v ? 1 : 0); } @Override public void writeByte(int v) throws IOException { write(v); } @Override public void writeBytes(String s) throws IOException { final int sLen = s.length(); if (this.position >= this.buffer.length - sLen) { resize(sLen); } for (int i = 0; i < sLen; i++) { writeByte(s.charAt(i)); } this.position += sLen; } @Override public void writeChar(int v) throws IOException { if (this.position >= this.buffer.length - 1) { resize(2); } this.buffer[this.position++] = (byte) (v >> 8); this.buffer[this.position++] = (byte) v; } @Override public void writeChars(String s) throws IOException { final int sLen = s.length(); if (this.position >= this.buffer.length - 2 * sLen) { resize(2 * sLen); } for (int i = 0; i < sLen; i++) { writeChar(s.charAt(i)); } } @Override public void writeDouble(double v) throws IOException { writeLong(Double.doubleToLongBits(v)); } @Override public void writeFloat(float v) throws IOException { writeInt(Float.floatToIntBits(v)); } @SuppressWarnings("restriction") @Override public void writeInt(int v) throws IOException { if (this.position >= this.buffer.length - 3) { resize(4); } if (LITTLE_ENDIAN) { v = Integer.reverseBytes(v); } UNSAFE.putInt(this.buffer, BASE_OFFSET + this.position, v); this.position += 4; } @SuppressWarnings("restriction") @Override public void writeLong(long v) throws IOException { if (this.position >= this.buffer.length - 7) { resize(8); } if (LITTLE_ENDIAN) { v = Long.reverseBytes(v); } UNSAFE.putLong(this.buffer, BASE_OFFSET + this.position, v); this.position += 8; } @Override public void writeShort(int v) throws IOException { if (this.position >= this.buffer.length - 1) { resize(2); } this.buffer[this.position++] = (byte) ((v >>> 8) & 0xff); this.buffer[this.position++] = (byte) (v & 0xff); } @Override public void writeUTF(String str) throws IOException { int strlen = str.length(); int utflen = 0; int c; /* use charAt instead of copying String to char array */ for (int i = 0; i < strlen; i++) { c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { utflen++; } else if (c > 0x07FF) { utflen += 3; } else { utflen += 2; } } if (utflen > 65535) { throw new UTFDataFormatException("Encoded string is too long: " + utflen); } else if (this.position > this.buffer.length - utflen - 2) { resize(utflen + 2); } byte[] bytearr = this.buffer; int count = this.position; bytearr[count++] = (byte) ((utflen >>> 8) & 0xFF); bytearr[count++] = (byte) (utflen & 0xFF); int i; for (i = 0; i < strlen; i++) { c = str.charAt(i); if (!((c >= 0x0001) && (c <= 0x007F))) { break; } bytearr[count++] = (byte) c; } for (; i < strlen; i++) { c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { bytearr[count++] = (byte) c; } else if (c > 0x07FF) { bytearr[count++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); bytearr[count++] = (byte) (0x80 | ((c >> 6) & 0x3F)); bytearr[count++] = (byte) (0x80 | (c & 0x3F)); } else { bytearr[count++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); bytearr[count++] = (byte) (0x80 | (c & 0x3F)); } } this.position = count; } private void resize(int minCapacityAdd) throws IOException { int newLen = Math.max(this.buffer.length * 2, this.buffer.length + minCapacityAdd); byte[] nb; try { nb = new byte[newLen]; } catch (NegativeArraySizeException e) { throw new IOException("Serialization failed because the record length would exceed 2GB (max addressable array size in Java)."); } catch (OutOfMemoryError e) { // this was too large to allocate, try the smaller size (if possible) if (newLen > this.buffer.length + minCapacityAdd) { newLen = this.buffer.length + minCapacityAdd; try { nb = new byte[newLen]; } catch (OutOfMemoryError ee) { // still not possible. give an informative exception message that reports the size throw new IOException("Failed to serialize element. Serialized size (> " + newLen + " bytes) exceeds JVM heap space", ee); } } else { throw new IOException("Failed to serialize element. Serialized size (> " + newLen + " bytes) exceeds JVM heap space", e); } } System.arraycopy(this.buffer, 0, nb, 0, this.position); this.buffer = nb; this.wrapper = ByteBuffer.wrap(this.buffer); } @Override public void skipBytesToWrite(int numBytes) throws IOException { if (buffer.length - this.position < numBytes){ throw new EOFException("Could not skip " + numBytes + " bytes."); } this.position += numBytes; } @Override public void write(DataInputView source, int numBytes) throws IOException { if (buffer.length - this.position < numBytes){ throw new EOFException("Could not write " + numBytes + " bytes. Buffer overflow."); } source.readFully(this.buffer, this.position, numBytes); this.position += numBytes; } // ------------------------------------------------------------------------ // Utilities // ------------------------------------------------------------------------ @SuppressWarnings("restriction") private static final sun.misc.Unsafe UNSAFE = MemoryUtils.UNSAFE; @SuppressWarnings("restriction") private static final long BASE_OFFSET = UNSAFE.arrayBaseOffset(byte[].class); private static final boolean LITTLE_ENDIAN = (MemoryUtils.NATIVE_BYTE_ORDER == ByteOrder.LITTLE_ENDIAN); }
apache-2.0
google-code/actorom
src/main/java/com/googlecode/actorom/local/support/SymbolicHostBinder.java
1462
/** * Copyright 2009 Sergio Bossa * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.actorom.local.support; import java.util.HashSet; import java.util.Set; import net.jcip.annotations.ThreadSafe; /** * @author Sergio Bossa */ @ThreadSafe public class SymbolicHostBinder { private static SymbolicHostBinder instance = new SymbolicHostBinder(); private final Set<String> binds = new HashSet<String>(); public static SymbolicHostBinder getInstance() { return instance; } public synchronized void bind(String symbolicHost) { if (!binds.contains(symbolicHost)) { binds.add(symbolicHost); } else { throw new SymbolicHostAlreadyBoundException("Symbolic host already bound to another topology: " + symbolicHost); } } public synchronized void unbind(String symbolicHost) { binds.remove(symbolicHost); } }
apache-2.0
binrui/smart-dream-shop
shop-base/src/main/java/com/smart/shop/base/utils/BigDecimalUtil.java
2237
package com.smart.shop.base.utils; import java.math.BigDecimal; public class BigDecimalUtil { // 默认除法运算精度,及即保留小数点多少位 private static final int DEF_DIV_SCALE = 6; // 这个类不能实例化 public BigDecimalUtil() { } /** * 提供精确的加法运算。 * * @param v1 * 被加数 * @param v2 * 加数 * @return 两个参数的和 */ public static BigDecimal add(String v1, String v2) { BigDecimal b1 = new BigDecimal(v1); BigDecimal b2 = new BigDecimal(v2); return b1.add(b2); } /** * 提供精确的减法运算。 * * @param v1 * 被减数 * @param v2 * 减数 * @return 两个参数的差 */ public static BigDecimal sub(String v1, String v2) { BigDecimal b1 = new BigDecimal(v1); BigDecimal b2 = new BigDecimal(v2); return b1.subtract(b2); } /** * 提供精确的乘法运算。 * * @param v1 * 被乘数 * @param v2 * 乘数 * @return 两个参数的积 */ public static BigDecimal mul(String v1, String v2) { BigDecimal b1 = new BigDecimal(v1); BigDecimal b2 = new BigDecimal(v2); return (b1.multiply(b2)); } /** * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后多少位,以后的数字四舍五入。 * * @param v1 * 被除数 * @param v2 * 除数 * @return 两个参数的商 */ public static BigDecimal div(String v1, String v2) { return div(v1, v2, DEF_DIV_SCALE); } /** * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。 * * @param v1 * 被除数 * @param v2 * 除数 * @param scale * 表示表示需要精确到小数点以后几位。 * @return 两个参数的商 */ public static BigDecimal div(String v1, String v2, int scale) { if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b1 = new BigDecimal(v1); BigDecimal b2 = new BigDecimal(v2); return (b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP)); } }
apache-2.0
steveb/heat
heat/tests/test_hacking.py
1777
# Copyright 2016 NTT DATA. # # 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. from heat.hacking import checks from heat.tests import common class HackingTestCase(common.HeatTestCase): def test_dict_iteritems(self): self.assertEqual(1, len(list(checks.check_python3_no_iteritems( "obj.iteritems()")))) self.assertEqual(0, len(list(checks.check_python3_no_iteritems( "obj.items()")))) self.assertEqual(0, len(list(checks.check_python3_no_iteritems( "six.iteritems(ob))")))) def test_dict_iterkeys(self): self.assertEqual(1, len(list(checks.check_python3_no_iterkeys( "obj.iterkeys()")))) self.assertEqual(0, len(list(checks.check_python3_no_iterkeys( "obj.keys()")))) self.assertEqual(0, len(list(checks.check_python3_no_iterkeys( "six.iterkeys(ob))")))) def test_dict_itervalues(self): self.assertEqual(1, len(list(checks.check_python3_no_itervalues( "obj.itervalues()")))) self.assertEqual(0, len(list(checks.check_python3_no_itervalues( "obj.values()")))) self.assertEqual(0, len(list(checks.check_python3_no_itervalues( "six.itervalues(ob))"))))
apache-2.0
efeavsar/bbplayer
mobile/src/main/java/com/lonict/android/bbplayer/VoiceSearchParams.java
4809
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lonict.android.bbplayer; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.text.TextUtils; /** * For more information about voice search parameters, * check https://developer.android.com/guide/components/intents-common.html#PlaySearch */ public final class VoiceSearchParams { public final String query; public boolean isAny; public boolean isUnstructured; public boolean isGenreFocus; public boolean isArtistFocus; public boolean isAlbumFocus; public boolean isSongFocus; public String genre; public String artist; public String album; public String song; /** * Creates a simple object describing the search criteria from the query and extras. * @param query the query parameter from a voice search * @param extras the extras parameter from a voice search */ public VoiceSearchParams(String query, Bundle extras) { this.query = query; if (TextUtils.isEmpty(query)) { // A generic search like "Play music" sends an empty query isAny = true; } else { if (extras == null) { isUnstructured = true; } else { String genreKey; if (Build.VERSION.SDK_INT >= 21) { genreKey = MediaStore.EXTRA_MEDIA_GENRE; } else { genreKey = "android.intent.extra.genre"; } String mediaFocus = extras.getString(MediaStore.EXTRA_MEDIA_FOCUS); if (TextUtils.equals(mediaFocus, MediaStore.Audio.Genres.ENTRY_CONTENT_TYPE)) { // for a Genre focused search, only genre is set: isGenreFocus = true; genre = extras.getString(genreKey); if (TextUtils.isEmpty(genre)) { // Because of a bug on the platform, genre is only sent as a query, not as // the semantic-aware extras. This check makes it future-proof when the // bug is fixed. genre = query; } } else if (TextUtils.equals(mediaFocus, MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE)) { // for an Artist focused search, both artist and genre are set: isArtistFocus = true; genre = extras.getString(genreKey); artist = extras.getString(MediaStore.EXTRA_MEDIA_ARTIST); } else if (TextUtils.equals(mediaFocus, MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE)) { // for an Album focused search, album, artist and genre are set: isAlbumFocus = true; album = extras.getString(MediaStore.EXTRA_MEDIA_ALBUM); genre = extras.getString(genreKey); artist = extras.getString(MediaStore.EXTRA_MEDIA_ARTIST); } else if (TextUtils.equals(mediaFocus, MediaStore.Audio.Media.ENTRY_CONTENT_TYPE)) { // for a Song focused search, title, album, artist and genre are set: isSongFocus = true; song = extras.getString(MediaStore.EXTRA_MEDIA_TITLE); album = extras.getString(MediaStore.EXTRA_MEDIA_ALBUM); genre = extras.getString(genreKey); artist = extras.getString(MediaStore.EXTRA_MEDIA_ARTIST); } else { // If we don't know the focus, we treat it is an unstructured query: isUnstructured = true; } } } } @Override public String toString() { return "query=" + query + " isAny=" + isAny + " isUnstructured=" + isUnstructured + " isGenreFocus=" + isGenreFocus + " isArtistFocus=" + isArtistFocus + " isAlbumFocus=" + isAlbumFocus + " isSongFocus=" + isSongFocus + " genre=" + genre + " artist=" + artist + " album=" + album + " song=" + song; } }
apache-2.0
weiwenqiang/GitHub
expert/jackson-core/src/main/java/com/fasterxml/jackson/core/base/ParserMinimalBase.java
25953
package com.fasterxml.jackson.core.base; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.core.io.JsonEOFException; import com.fasterxml.jackson.core.io.NumberInput; import com.fasterxml.jackson.core.sym.FieldNameMatcher; import com.fasterxml.jackson.core.type.ResolvedType; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.util.ByteArrayBuilder; import com.fasterxml.jackson.core.util.VersionUtil; import static com.fasterxml.jackson.core.JsonTokenId.*; /** * Intermediate base class used by all Jackson {@link JsonParser} * implementations, but does not add any additional fields that depend * on particular method of obtaining input. *<p> * Note that 'minimal' here mostly refers to minimal number of fields * (size) and functionality that is specific to certain types * of parser implementations; but not necessarily to number of methods. */ public abstract class ParserMinimalBase extends JsonParser { // Control chars: protected final static int INT_TAB = '\t'; protected final static int INT_LF = '\n'; protected final static int INT_CR = '\r'; protected final static int INT_SPACE = 0x0020; // Markup protected final static int INT_LBRACKET = '['; protected final static int INT_RBRACKET = ']'; protected final static int INT_LCURLY = '{'; protected final static int INT_RCURLY = '}'; protected final static int INT_QUOTE = '"'; protected final static int INT_APOS = '\''; protected final static int INT_BACKSLASH = '\\'; protected final static int INT_SLASH = '/'; protected final static int INT_ASTERISK = '*'; protected final static int INT_COLON = ':'; protected final static int INT_COMMA = ','; protected final static int INT_HASH = '#'; // Number chars protected final static int INT_0 = '0'; protected final static int INT_9 = '9'; protected final static int INT_MINUS = '-'; protected final static int INT_PLUS = '+'; protected final static int INT_PERIOD = '.'; protected final static int INT_e = 'e'; protected final static int INT_E = 'E'; protected final static char CHAR_NULL = '\0'; protected final static byte[] NO_BYTES = new byte[0]; protected final static int[] NO_INTS = new int[0]; /* /********************************************************** /* Constants and fields of former 'JsonNumericParserBase' /********************************************************** */ protected final static int NR_UNKNOWN = 0; // First, integer types protected final static int NR_INT = 0x0001; protected final static int NR_LONG = 0x0002; protected final static int NR_BIGINT = 0x0004; // And then floating point types protected final static int NR_DOUBLE = 0x008; protected final static int NR_BIGDECIMAL = 0x0010; /** * NOTE! Not used by JSON implementation but used by many of binary codecs */ protected final static int NR_FLOAT = 0x020; // Also, we need some numeric constants protected final static BigInteger BI_MIN_INT = BigInteger.valueOf(Integer.MIN_VALUE); protected final static BigInteger BI_MAX_INT = BigInteger.valueOf(Integer.MAX_VALUE); protected final static BigInteger BI_MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); protected final static BigInteger BI_MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); protected final static BigDecimal BD_MIN_LONG = new BigDecimal(BI_MIN_LONG); protected final static BigDecimal BD_MAX_LONG = new BigDecimal(BI_MAX_LONG); protected final static BigDecimal BD_MIN_INT = new BigDecimal(BI_MIN_INT); protected final static BigDecimal BD_MAX_INT = new BigDecimal(BI_MAX_INT); protected final static long MIN_INT_L = (long) Integer.MIN_VALUE; protected final static long MAX_INT_L = (long) Integer.MAX_VALUE; // These are not very accurate, but have to do... (for bounds checks) protected final static double MIN_LONG_D = (double) Long.MIN_VALUE; protected final static double MAX_LONG_D = (double) Long.MAX_VALUE; protected final static double MIN_INT_D = (double) Integer.MIN_VALUE; protected final static double MAX_INT_D = (double) Integer.MAX_VALUE; /* /********************************************************** /* Misc other constants /********************************************************** */ /** * Maximum number of characters to include in token reported * as part of error messages. */ protected final static int MAX_ERROR_TOKEN_LENGTH = 256; /* /********************************************************** /* Minimal generally useful state /********************************************************** */ /** * Context object provided by higher level functionality like * databinding for two reasons: passing configuration information * during construction, and to allow calling of some databind * operations via parser instance. * * @since 3.0 */ protected final ObjectReadContext _objectReadContext; /** * Last token retrieved via {@link #nextToken}, if any. * Null before the first call to <code>nextToken()</code>, * as well as if token has been explicitly cleared */ protected JsonToken _currToken; /** * Last cleared token, if any: that is, value that was in * effect when {@link #clearCurrentToken} was called. */ protected JsonToken _lastClearedToken; /* /********************************************************** /* Life-cycle /********************************************************** */ protected ParserMinimalBase(ObjectReadContext readCtxt) { _objectReadContext = readCtxt; } protected ParserMinimalBase(ObjectReadContext readCtxt, int features) { super(features); _objectReadContext = readCtxt; } /* /********************************************************** /* Configuration overrides if any /********************************************************** */ @Override public ObjectReadContext getObjectReadContext() { return _objectReadContext; } // from base class: //public void enableFeature(Feature f) //public void disableFeature(Feature f) //public void setFeature(Feature f, boolean state) //public boolean isFeatureEnabled(Feature f) /* /********************************************************** /* JsonParser impl: open / close /********************************************************** */ //public JsonToken getCurrentToken() //public boolean hasCurrentToken() @Override public abstract void close() throws IOException; @Override public abstract boolean isClosed(); /* /********************************************************** /* JsonParser impl: basic state access /********************************************************** */ @Override public abstract TokenStreamContext getParsingContext(); // public abstract JsonLocation getTokenLocation(); // public abstract JsonLocation getCurrentLocation(); /** * Method sub-classes need to implement */ protected abstract void _handleEOF() throws JsonParseException; @Override public abstract String currentName() throws IOException; /* /********************************************************** /* JsonParser impl: basic stream iteration /********************************************************** */ @Override public abstract JsonToken nextToken() throws IOException; @Override public void finishToken() throws IOException { ; /* nothing */ } @Override public JsonToken currentToken() { return _currToken; } @Override public int currentTokenId() { final JsonToken t = _currToken; return (t == null) ? JsonTokenId.ID_NO_TOKEN : t.id(); } @Override public boolean hasCurrentToken() { return _currToken != null; } @Override public boolean hasTokenId(int id) { final JsonToken t = _currToken; if (t == null) { return (JsonTokenId.ID_NO_TOKEN == id); } return t.id() == id; } @Override public boolean hasToken(JsonToken t) { return (_currToken == t); } @Override public boolean isExpectedStartArrayToken() { return _currToken == JsonToken.START_ARRAY; } @Override public boolean isExpectedStartObjectToken() { return _currToken == JsonToken.START_OBJECT; } @Override public JsonToken nextValue() throws IOException { // Implementation should be as trivial as follows; only needs to change if // we are to skip other tokens (for example, if comments were exposed as tokens) JsonToken t = nextToken(); if (t == JsonToken.FIELD_NAME) { t = nextToken(); } return t; } @Override public JsonParser skipChildren() throws IOException { if (_currToken != JsonToken.START_OBJECT && _currToken != JsonToken.START_ARRAY) { return this; } int open = 1; // Since proper matching of start/end markers is handled // by nextToken(), we'll just count nesting levels here while (true) { JsonToken t = nextToken(); if (t == null) { _handleEOF(); /* given constraints, above should never return; * however, FindBugs doesn't know about it and * complains... so let's add dummy break here */ return this; } if (t.isStructStart()) { ++open; } else if (t.isStructEnd()) { if (--open == 0) { return this; } } } } /* /********************************************************** /* JsonParser impl: stream iteration, field names /********************************************************** */ @Override public String nextFieldName() throws IOException { return (nextToken() == JsonToken.FIELD_NAME) ? currentName() : null; } @Override public boolean nextFieldName(SerializableString str) throws IOException { return (nextToken() == JsonToken.FIELD_NAME) && str.getValue().equals(currentName()); } // Base implementation that should work well for most implementations but that // is typically overridden for performance optimization purposes @Override public int nextFieldName(FieldNameMatcher matcher) throws IOException { String str = nextFieldName(); if (str != null) { return matcher.matchAnyName(str); } if (_currToken == JsonToken.END_OBJECT) { return FieldNameMatcher.MATCH_END_OBJECT; } return FieldNameMatcher.MATCH_ODD_TOKEN; } @Override public int currentFieldName(FieldNameMatcher matcher) throws IOException { if (_currToken == JsonToken.FIELD_NAME) { return matcher.matchAnyName(currentName()); } if (_currToken == JsonToken.END_OBJECT) { return FieldNameMatcher.MATCH_END_OBJECT; } return FieldNameMatcher.MATCH_ODD_TOKEN; } /* /********************************************************** /* Public API, token state overrides /********************************************************** */ @Override public void clearCurrentToken() { if (_currToken != null) { _lastClearedToken = _currToken; _currToken = null; } } @Override public JsonToken getLastClearedToken() { return _lastClearedToken; } @Override public abstract void overrideCurrentName(String name); /* /********************************************************** /* Public API, access to token information, text /********************************************************** */ @Override public abstract String getText() throws IOException; @Override public abstract char[] getTextCharacters() throws IOException; @Override public abstract boolean hasTextCharacters(); @Override public abstract int getTextLength() throws IOException; @Override public abstract int getTextOffset() throws IOException; /* /********************************************************** /* Public API, access to token information, binary /********************************************************** */ @Override public abstract byte[] getBinaryValue(Base64Variant b64variant) throws IOException; /* /********************************************************** /* Public API, access with conversion/coercion /********************************************************** */ @Override public boolean getValueAsBoolean(boolean defaultValue) throws IOException { JsonToken t = _currToken; if (t != null) { switch (t.id()) { case ID_STRING: String str = getText().trim(); if ("true".equals(str)) { return true; } if ("false".equals(str)) { return false; } if (_hasTextualNull(str)) { return false; } break; case ID_NUMBER_INT: return getIntValue() != 0; case ID_TRUE: return true; case ID_FALSE: case ID_NULL: return false; case ID_EMBEDDED_OBJECT: Object value = getEmbeddedObject(); if (value instanceof Boolean) { return (Boolean) value; } break; default: } } return defaultValue; } @Override public int getValueAsInt() throws IOException { JsonToken t = _currToken; if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) { return getIntValue(); } return getValueAsInt(0); } @Override public int getValueAsInt(int defaultValue) throws IOException { JsonToken t = _currToken; if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) { return getIntValue(); } if (t != null) { switch (t.id()) { case ID_STRING: String str = getText(); if (_hasTextualNull(str)) { return 0; } return NumberInput.parseAsInt(str, defaultValue); case ID_TRUE: return 1; case ID_FALSE: return 0; case ID_NULL: return 0; case ID_EMBEDDED_OBJECT: Object value = getEmbeddedObject(); if (value instanceof Number) { return ((Number) value).intValue(); } } } return defaultValue; } @Override public long getValueAsLong() throws IOException { JsonToken t = _currToken; if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) { return getLongValue(); } return getValueAsLong(0L); } @Override public long getValueAsLong(long defaultValue) throws IOException { JsonToken t = _currToken; if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) { return getLongValue(); } if (t != null) { switch (t.id()) { case ID_STRING: String str = getText(); if (_hasTextualNull(str)) { return 0L; } return NumberInput.parseAsLong(str, defaultValue); case ID_TRUE: return 1L; case ID_FALSE: case ID_NULL: return 0L; case ID_EMBEDDED_OBJECT: Object value = getEmbeddedObject(); if (value instanceof Number) { return ((Number) value).longValue(); } } } return defaultValue; } @Override public double getValueAsDouble(double defaultValue) throws IOException { JsonToken t = _currToken; if (t != null) { switch (t.id()) { case ID_STRING: String str = getText(); if (_hasTextualNull(str)) { return 0L; } return NumberInput.parseAsDouble(str, defaultValue); case ID_NUMBER_INT: case ID_NUMBER_FLOAT: return getDoubleValue(); case ID_TRUE: return 1.0; case ID_FALSE: case ID_NULL: return 0.0; case ID_EMBEDDED_OBJECT: Object value = this.getEmbeddedObject(); if (value instanceof Number) { return ((Number) value).doubleValue(); } } } return defaultValue; } @Override public String getValueAsString() throws IOException { if (_currToken == JsonToken.VALUE_STRING) { return getText(); } if (_currToken == JsonToken.FIELD_NAME) { return currentName(); } return getValueAsString(null); } @Override public String getValueAsString(String defaultValue) throws IOException { if (_currToken == JsonToken.VALUE_STRING) { return getText(); } if (_currToken == JsonToken.FIELD_NAME) { return currentName(); } if (_currToken == null || _currToken == JsonToken.VALUE_NULL || !_currToken.isScalarValue()) { return defaultValue; } return getText(); } /* /********************************************************** /* Databind callbacks /********************************************************** */ @Override public <T> T readValueAs(Class<T> valueType) throws IOException { return _objectReadContext.readValue(this, valueType); } @SuppressWarnings("unchecked") @Override public <T> T readValueAs(TypeReference<?> valueTypeRef) throws IOException { return (T) _objectReadContext.readValue(this, valueTypeRef); } @SuppressWarnings("unchecked") @Override public <T> T readValueAs(ResolvedType type) throws IOException { return (T) _objectReadContext.readValue(this, type); } @SuppressWarnings("unchecked") @Override public <T extends TreeNode> T readValueAsTree() throws IOException { return (T) _objectReadContext.readTree(this); } /* /********************************************************** /* Helper methods: Base64 decoding /********************************************************** */ /** * Helper method that can be used for base64 decoding in cases where * encoded content has already been read as a String. */ protected void _decodeBase64(String str, ByteArrayBuilder builder, Base64Variant b64variant) throws IOException { try { b64variant.decode(str, builder); } catch (IllegalArgumentException e) { _reportError(e.getMessage()); } } /* /********************************************************** /* Coercion helper methods (overridable) /********************************************************** */ /** * Helper method used to determine whether we are currently pointing to * a String value of "null" (NOT a null token); and, if so, that parser * is to recognize and return it similar to if it was real null token. */ protected boolean _hasTextualNull(String value) { return "null".equals(value); } /* /********************************************************** /* Error reporting /********************************************************** */ protected void reportUnexpectedNumberChar(int ch, String comment) throws JsonParseException { String msg = String.format("Unexpected character (%s) in numeric value", _getCharDesc(ch)); if (comment != null) { msg += ": "+comment; } _reportError(msg); } protected void reportInvalidNumber(String msg) throws JsonParseException { _reportError("Invalid numeric value: "+msg); } protected void reportOverflowInt() throws IOException { _reportError(String.format("Numeric value (%s) out of range of int (%d - %s)", getText(), Integer.MIN_VALUE, Integer.MAX_VALUE)); } protected void reportOverflowLong() throws IOException { _reportError(String.format("Numeric value (%s) out of range of long (%d - %s)", getText(), Long.MIN_VALUE, Long.MAX_VALUE)); } protected void _reportUnexpectedChar(int ch, String comment) throws JsonParseException { if (ch < 0) { // sanity check _reportInvalidEOF(); } String msg = String.format("Unexpected character (%s)", _getCharDesc(ch)); if (comment != null) { msg += ": "+comment; } _reportError(msg); } protected void _reportInvalidEOF() throws JsonParseException { _reportInvalidEOF(" in "+_currToken, _currToken); } protected void _reportInvalidEOFInValue(JsonToken type) throws JsonParseException { String msg; if (type == JsonToken.VALUE_STRING) { msg = " in a String value"; } else if ((type == JsonToken.VALUE_NUMBER_INT) || (type == JsonToken.VALUE_NUMBER_FLOAT)) { msg = " in a Number value"; } else { msg = " in a value"; } _reportInvalidEOF(msg, type); } protected void _reportInvalidEOF(String msg, JsonToken currToken) throws JsonParseException { throw new JsonEOFException(this, currToken, "Unexpected end-of-input"+msg); } protected void _reportMissingRootWS(int ch) throws JsonParseException { _reportUnexpectedChar(ch, "Expected space separating root-level values"); } protected void _throwInvalidSpace(int i) throws JsonParseException { char c = (char) i; String msg = "Illegal character ("+_getCharDesc(c)+"): only regular white space (\\r, \\n, \\t) is allowed between tokens"; _reportError(msg); } /** * Method called to report a problem with unquoted control character. * Note: starting with version 1.4, it is possible to suppress * exception by enabling {@link Feature#ALLOW_UNQUOTED_CONTROL_CHARS}. */ protected void _throwUnquotedSpace(int i, String ctxtDesc) throws JsonParseException { // JACKSON-208; possible to allow unquoted control chars: if (!isEnabled(Feature.ALLOW_UNQUOTED_CONTROL_CHARS) || i > INT_SPACE) { char c = (char) i; String msg = "Illegal unquoted character ("+_getCharDesc(c)+"): has to be escaped using backslash to be included in "+ctxtDesc; _reportError(msg); } } protected char _handleUnrecognizedCharacterEscape(char ch) throws JsonProcessingException { // as per [JACKSON-300] if (isEnabled(Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)) { return ch; } // and [JACKSON-548] if (ch == '\'' && isEnabled(Feature.ALLOW_SINGLE_QUOTES)) { return ch; } _reportError("Unrecognized character escape "+_getCharDesc(ch)); return ch; } /* /********************************************************** /* Error reporting, generic /********************************************************** */ protected final static String _getCharDesc(int ch) { char c = (char) ch; if (Character.isISOControl(c)) { return "(CTRL-CHAR, code "+ch+")"; } if (ch > 255) { return "'"+c+"' (code "+ch+" / 0x"+Integer.toHexString(ch)+")"; } return "'"+c+"' (code "+ch+")"; } protected final void _reportError(String msg) throws JsonParseException { throw _constructError(msg); } protected final void _reportError(String msg, Object arg) throws JsonParseException { throw _constructError(String.format(msg, arg)); } protected final void _reportError(String msg, Object arg1, Object arg2) throws JsonParseException { throw _constructError(String.format(msg, arg1, arg2)); } protected final void _wrapError(String msg, Throwable t) throws JsonParseException { throw _constructError(msg, t); } protected final void _throwInternal() { VersionUtil.throwInternal(); } protected final JsonParseException _constructError(String msg, Throwable t) { return new JsonParseException(this, msg, t); } protected static byte[] _asciiBytes(String str) { byte[] b = new byte[str.length()]; for (int i = 0, len = str.length(); i < len; ++i) { b[i] = (byte) str.charAt(i); } return b; } protected static String _ascii(byte[] b) { try { return new String(b, "US-ASCII"); } catch (IOException e) { // never occurs throw new RuntimeException(e); } } }
apache-2.0
djarosz/embedded-elasticsearch
core/src/main/java/pl/allegro/tech/embeddedelasticsearch/EmbeddedElastic.java
9995
package pl.allegro.tech.embeddedelasticsearch; import pl.allegro.tech.embeddedelasticsearch.InstallationDescription.Plugin; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; public final class EmbeddedElastic { private final String esJavaOpts; private final InstanceSettings instanceSettings; private final IndicesDescription indicesDescription; private final InstallationDescription installationDescription; private final long startTimeoutInMs; private ElasticServer elasticServer; private ElasticRestClient elasticRestClient; public static Builder builder() { return new Builder(); } private EmbeddedElastic(String esJavaOpts, InstanceSettings instanceSettings, IndicesDescription indicesDescription, InstallationDescription installationDescription, long startTimeoutInMs) { this.esJavaOpts = esJavaOpts; this.instanceSettings = instanceSettings; this.indicesDescription = indicesDescription; this.installationDescription = installationDescription; this.startTimeoutInMs = startTimeoutInMs; } /** * Downloads Elasticsearch with specified plugins, setups them and starts */ public EmbeddedElastic start() throws IOException, InterruptedException { installElastic(); startElastic(); createRestClient(); createIndices(); return this; } private void installElastic() throws IOException, InterruptedException { ElasticSearchInstaller elasticSearchInstaller = new ElasticSearchInstaller(instanceSettings, installationDescription); elasticSearchInstaller.install(); File executableFile = elasticSearchInstaller.getExecutableFile(); File installationDirectory = elasticSearchInstaller.getInstallationDirectory(); elasticServer = new ElasticServer(esJavaOpts, installationDirectory, executableFile, startTimeoutInMs, installationDescription.isCleanInstallationDirectoryOnStop()); } private void startElastic() throws IOException, InterruptedException { if (!elasticServer.isStarted()) { elasticServer.start(); } } private void createRestClient() throws UnknownHostException { elasticRestClient = new ElasticRestClient(elasticServer.getHttpPort(), new HttpClient(), indicesDescription); } /** * Stops Elasticsearch instance and removes data */ public void stop() { elasticServer.stop(); } /** * Index documents * * @param indexName target index * @param indexType target index type * @param idJsonMap map where keys are documents ids and values are documents represented as JSON */ public void index(String indexName, String indexType, Map<CharSequence, CharSequence> idJsonMap) { elasticRestClient.indexWithIds(indexName, indexType, idJsonMap.entrySet().stream() .map(entry -> new DocumentWithId(entry.getKey().toString(), entry.getValue().toString())) .collect(toList())); } /** * Index documents * * @param indexName target index * @param indexType target index name * @param json document represented as JSON */ public void index(String indexName, String indexType, String... json) { index(indexName, indexType, Arrays.asList(json)); } /** * Index documents * * @param indexName target index * @param indexType target index name * @param jsons documents represented as JSON */ public void index(String indexName, String indexType, List<CharSequence> jsons) { elasticRestClient.indexWithIds(indexName, indexType, jsons.stream().map(json -> new DocumentWithId(null, json.toString())).collect(Collectors.toList())); } /** * Recreates all instances (i.e. deletes and creates them again) */ public void recreateIndices() { deleteIndices(); createIndices(); } /** * Recreates specified index (i.e. deletes and creates it again) * * @param indexName index to recreate */ public void recreateIndex(String indexName) { deleteIndex(indexName); createIndex(indexName); } /** * Delete all indices */ public void deleteIndices() { elasticRestClient.deleteIndices(); } /** * Delete specified index * * @param indexName index do delete */ public void deleteIndex(String indexName) { elasticRestClient.deleteIndex(indexName); } /** * Create all indices */ public void createIndices() { elasticRestClient.createIndices(); } /** * Create specified index. Note that you can specify only index from list of indices specified during EmbeddedElastic creation * * @param indexName index to create */ public void createIndex(String indexName) { elasticRestClient.createIndex(indexName); } /** * Refresh indices. Can be useful in tests that uses multiple threads */ public void refreshIndices() { elasticRestClient.refresh(); } /** * Fetch all documents from specified indices. Useful for logging and debugging * * @return list containing documents sources represented as JSON */ public List<String> fetchAllDocuments(String... indices) throws UnknownHostException { return elasticRestClient.fetchAllDocuments(indices); } /** * Get transport tcp port number used by Elasticsearch */ public int getTransportTcpPort() { return elasticServer.getTransportTcpPort(); } /** * Get http port number */ public int getHttpPort() { return elasticServer.getHttpPort(); } public static final class Builder { private Optional<String> version = Optional.empty(); private List<Plugin> plugins = new ArrayList<>(); private Optional<URL> downloadUrl = Optional.empty(); private Map<String, IndexSettings> indices = new HashMap<>(); private InstanceSettings settings = new InstanceSettings(); private String esJavaOpts = ""; private long startTimeoutInMs = 15_000; private boolean cleanInstallationDirectoryOnStop = true; private Optional<File> installationDirectory = Optional.empty(); private Optional<File> downloadDirectory = Optional.empty(); private Builder() { } public Builder withSetting(String name, Object value) { settings = settings.withSetting(name, value); return this; } public Builder withEsJavaOpts(String javaOpts) { this.esJavaOpts = javaOpts; return this; } public Builder withInstallationDirectory(File installationDirectory) { this.installationDirectory = Optional.of(installationDirectory); return this; } public Builder withDownloadDirectory(File downloadDirectory) { this.downloadDirectory = Optional.of(downloadDirectory); return this; } public Builder withCleanInstallationDirectoryOnStop(boolean cleanInstallationDirectoryOnStop) { this.cleanInstallationDirectoryOnStop = cleanInstallationDirectoryOnStop; return this; } /** * Desired version of Elasticsearch. It will be used to generate download URL to official mirrors */ public Builder withElasticVersion(String version) { this.version = Optional.of(version); return this; } /** * <p>Elasticsearch download URL. Will overwrite download url generated by withElasticVersion method.</p> * <p><strong>Specify urls only to locations that you trust!</strong></p> */ public Builder withDownloadUrl(URL downloadUrl) { this.downloadUrl = Optional.of(downloadUrl); return this; } /** * Plugin that should be installed with created instance. Treat invocation of this method as invocation of elasticsearch-plugin install command: * <p> * <pre>./elasticsearch-plugin install EXPRESSION</pre> */ public Builder withPlugin(String expression) { this.plugins.add(new Plugin(expression)); return this; } /** * Index that will be created in created Elasticsearch cluster */ public Builder withIndex(String indexName) { return withIndex(indexName, IndexSettings.builder().build()); } /** * Index that will be created in created Elasticsearch cluster */ public Builder withIndex(String indexName, IndexSettings indexSettings) { this.indices.put(indexName, indexSettings); return this; } /** * How long should embedded-elasticsearch wait for elasticsearch to startup. Defaults to 15 seconds */ public Builder withStartTimeout(long value, TimeUnit unit) { startTimeoutInMs = unit.toMillis(value); return this; } public EmbeddedElastic build() { return new EmbeddedElastic( esJavaOpts, settings, new IndicesDescription(indices), new InstallationDescription(version, downloadUrl, downloadDirectory, installationDirectory, cleanInstallationDirectoryOnStop, plugins), startTimeoutInMs); } } }
apache-2.0
wav/osgi-tooling
karaf-packaging/src/main/scala/wav/devtools/karaf/packaging/FeaturesXmlFormats.scala
6555
package wav.devtools.karaf.packaging import org.osgi.framework.{Version, VersionRange} import scala.xml.Elem trait XmlFormat[T] { def write(value: T): Option[Elem] def read(elem: Elem): Option[T] = this._read .andThen(Some(_: T)) .applyOrElse(elem, (_: Elem) => None) val _read: PartialFunction[Elem, T] } private[packaging] case class ValueWriter[T](value: T, default: T) { import Util._ // if the selected value matches the default return None. An empty string will return None def apply[V](get: T => V, str: V => String = (_: V).toString): Option[String] = { val v = get(value) if (v == get(default)) None else Some(str(v)).nonEmptyString } } private[packaging] case class AttrReader[T](e: Elem, default: T) { import Util._ def apply[V](attrName: String, conversion: String => V, getDefault: T => V): V = e.attributes.asAttrMap.get(attrName).nonEmptyString .map(conversion) .getOrElse(getDefault(default)) } object FeaturesXmlFormats { import Util._ import FeaturesXml._ object repositoryFormat extends XmlFormat[Repository] { def write(r: Repository) = Some(<repository>{r.url}</repository>) val _read: PartialFunction[Elem, Repository] = { case e: Elem if e.label == "repository" => Repository(e.text) } } object bundleFormat extends XmlFormat[Bundle] { def write(b: Bundle) = { val url = MavenUrl.unapply(b.url).getOrElse(b.url) val str = ValueWriter(b, emptyBundle) Some(setAttrs(<bundle>{url}</bundle>, Map( "dependency" -> str(_.dependency), "prerequisite" -> str(_.prerequisite), "start" -> str(_.start), "start-level" -> str(_.`start-level`) ))) } val _read: PartialFunction[Elem, Bundle] = { case e: Elem if e.label == "bundle" => val rd = AttrReader(e,emptyBundle) Bundle(e.text, rd("dependency", _.toBoolean, _.dependency), rd("prerequisite", _.toBoolean, _.prerequisite), rd("start", _.toBoolean, _.start), rd("start-level", _.toInt, _.`start-level`)) } } object dependencyFormat extends XmlFormat[Dependency] { def write(d: Dependency) = { val str = ValueWriter(d, emptyDependency) Some(setAttrs(<feature>{d.name}</feature>, Map( "version" -> str(_.version), "prerequisite" -> str(_.prerequisite), "dependency" -> str(_.dependency) ))) } val _read: PartialFunction[Elem, Dependency] = { case e: Elem if e.label == "feature" => val rd = AttrReader(e,emptyDependency) Dependency(e.text, rd("version", new VersionRange(_), _.version), rd("prerequisite", _.toBoolean, _.prerequisite), rd("dependency", _.toBoolean, _.dependency)) } } object configFormat extends XmlFormat[Config] { def write(c: Config) = { val str = ValueWriter(c, emptyConfig) Some(setAttrs(<config>{c.value}</config>, Map( "name" -> Some(c.name), "append" -> str(_.append) ))) } val _read: PartialFunction[Elem, Config] = { case e: Elem if e.label == "config" => val rd = AttrReader(e,emptyConfig) Config( rd("name", identity, _.name), e.text, rd("append", _.toBoolean, _.append)) } } object configFileFormat extends XmlFormat[ConfigFile] { def write(cf: ConfigFile) = { val str = ValueWriter(cf, emptyConfigFile) Some(setAttrs(<configfile>{cf.value}</configfile>, Map( "finalname" -> Some(cf.finalname), "override" -> str(_.`override`) ))) } val _read: PartialFunction[Elem, ConfigFile] = { case e: Elem if e.label == "configfile" => val rd = AttrReader(e,emptyConfigFile) ConfigFile( rd("finalname", identity, _.finalname), e.text, rd("override", _.toBoolean, _.`override`)) } } object featureFormat extends XmlFormat[Feature] { def write(f: Feature) = { val str = ValueWriter(f, emptyFeature) Some(setAttrs(<feature>{ f.deps.collect { case d: Dependency => dependencyFormat.write(d) case b: Bundle => bundleFormat.write(b) case c: Config => configFormat.write(c) }.flatten }</feature>, Map( "name" -> Some(f.name), "version" -> str(_.version), "description" -> str(_.description) ))) } def _readDep(e: Elem): Option[FeatureOption] = dependencyFormat._read .orElse(bundleFormat._read) .orElse(configFormat._read) .andThen(Some(_)) .applyOrElse(e, (_: Elem) => None) val _read: PartialFunction[Elem, Feature] = { case e: Elem if e.label == "feature" => val rd = AttrReader(e,emptyFeature) Feature( rd("name", identity, _.name), rd("version", Version.parseVersion, _.version), e.child.collect { case e: Elem => _readDep(e) }.flatten.toSet, rd("description", identity, _.description)) } } object featuresFormat extends XmlFormat[FeaturesXml] { def write(fd: FeaturesXml) = { Some(setAttrs(<features>{ fd.elems.collect { case r: Repository => repositoryFormat.write(r) case f: Feature => featureFormat.write(f) }.flatten }</features>, Map( "name" -> Some(fd.name), "xmlns" -> Some("http://karaf.apache.org/xmlns/features/v1.3.0") ))) } def _readDep(e: Elem): Option[FeaturesOption] = repositoryFormat._read .orElse(featureFormat._read) .andThen(Some(_)) .applyOrElse(e, (_: Elem) => None) val _read: PartialFunction[Elem, FeaturesXml] = { case e: Elem if e.label == "features" => val rd = AttrReader(e,emptyFeaturesXml) FeaturesXml( rd("name", identity, _.name), e.child.collect { case e: Elem => _readDep(e) }.flatten) } } val featuresSchemas = Seq( "1.3.0", /* is a super set of 1.2.0 */ "1.2.0") .map(v => v -> (s"http://karaf.apache.org/xmlns/features/v$v" -> s"org/apache/karaf/features/karaf-features-$v.xsd")) val (featuresXsdUrl, featuresXsd) = featuresSchemas.head._2 def makeFeaturesXml[N <: scala.xml.Node](featuresXml: FeaturesXml): Elem = featuresFormat.write(featuresXml).get def readFeaturesXml[N <: scala.xml.Node](source: N): Option[FeaturesXml] = (source \\ "features" collectFirst { case e: Elem => featuresFormat.read(e) }).flatten }
apache-2.0
marklogic/java-client-api
marklogic-client-api/src/main/java/com/marklogic/client/io/marker/DocumentMetadataReadHandle.java
808
/* * Copyright (c) 2019 MarkLogic Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.marklogic.client.io.marker; /** * A Metadata Read Handle can represent metadata read from the database. * */ public interface DocumentMetadataReadHandle extends AbstractReadHandle { }
apache-2.0
izhbg/typz
typz-all/typz-sso/src/main/java/com/izhbg/typz/sso/auth/service/TXtJgService.java
2678
package com.izhbg.typz.sso.auth.service; import java.util.List; import java.util.concurrent.ExecutionException; import net.sf.json.JSONArray; import com.izhbg.typz.base.page.Page; import com.izhbg.typz.sso.auth.dto.TXtJg; import com.izhbg.typz.sso.auth.dto.TXtJgQuery; /** * 组织机构service * @author caixl * @date 2016-5-20 上午10:16:07 * */ public interface TXtJgService { /** * 根据ID查询机构信息 * @param jgId * @return * @throws Exception */ public TXtJg queryById(String jgId) throws Exception; /** * 根据jgDm获取机构信息 * @param jgDm * @return * @throws Exception */ public TXtJg queryByJgDm(String jgDm) throws Exception; /** * 添加机构信息 * @param tXtJg * @throws Exception */ public void add(TXtJg tXtJg) throws Exception; /** * 根据ID删除机构信息 * @param jgId * @throws Exception */ public void deleteById(String jgId) throws Exception; /** * 批量删除机构信息 * @param jgIds * @throws Exception */ public void deleteByIds(String[] jgIds) throws Exception; /** * 根据上级机构删除机构信息 * @param sjjgId * @throws Exception */ public void deleteBySjjgId(String sjjgId) throws Exception; /** * 更新机构信息 * @param tXtJg * @throws Exception */ public void update(TXtJg tXtJg) throws Exception; /** * 批量更新状态 * @param jgIds * @throws Exception */ public void updateStatus(String[] jgIds) throws Exception; /** * 根据上级机构ID获取子机构IDS * @param sjjgId * @return * @throws Exception */ public List getOrganIds(String sjjgId)throws Exception; /** * 获取机构json树结构串 * @return * @throws Exception */ public String getJgsJSON(String currentAppId)throws Exception; /** * 获取子机构json * @param sjjgId * @return * @throws Exception */ public String getSubOrgan(String sjjgId,String appId) throws Exception; /** * 获取机构下的用户 * @param sjjgId * @param iJgId * @param appId * @return * @throws Exception */ public JSONArray getSubUserOrgan(String sjjgId, String iJgId,String appId) throws Exception; /** * 获取机构下的角色 * @param sjjgId * @param jgId * @param appId * @return * @throws Exception */ public JSONArray getSubRoleOrgan(String sjjgId, String jgId,String appId) throws Exception; /** * 分页查询 * @param page * @param tXtJgQuery * @return * @throws Exception */ public Page queryPageList(Page page,TXtJgQuery tXtJgQuery) throws Exception; }
apache-2.0
vimaier/conqat
org.conqat.engine.sourcecode/test-data/org.conqat.engine.sourcecode.analysis.findings/ComplexNesting02.java
513
package foo; public class ComplexNesting01 { static boolean a; public static void main(String[] args) { for (int i = 0; i < 10; ++i) { if (a) { if (i > 3) { if (args.length > i) { if (args[i] != null) { System.err.println("foo"); } } } } } for (int i = 0; i < 10; ++i) { if (a) { if (i > 3) { if (args.length > i) { if (args[i] != null) { if (3 > 5) { System.err.println("foo"); } } } } } } } }
apache-2.0
ui-icts/spring-utils
src/main/java/edu/uiowa/icts/delegate/SwitchUser.java
1828
package edu.uiowa.icts.delegate; /* * #%L * spring-utils * %% * Copyright (C) 2010 - 2015 University of Iowa Institute for Clinical and Translational Science (ICTS) * %% * 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% */ import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.switchuser.SwitchUserFilter; public class SwitchUser extends SwitchUserFilter { @Autowired private DelegateService delegateService; @Override public Authentication attemptSwitchUser( HttpServletRequest request ) throws AuthenticationException { if ( delegateService.checkAuthentication( request ) ) { return super.attemptSwitchUser( request ); } return SecurityContextHolder.getContext().getAuthentication(); } @Override public Authentication attemptExitUser( HttpServletRequest request ) throws AuthenticationException { if ( delegateService.checkExitAuthentication( request ) ) { return super.attemptExitUser( request ); } return SecurityContextHolder.getContext().getAuthentication(); } }
apache-2.0
rhuss/gofabric8
vendor/github.com/prometheus/common/route/route.go
2553
package route import ( "net/http" "sync" "github.com/julienschmidt/httprouter" "golang.org/x/net/context" ) var ( mtx = sync.RWMutex{} ctxts = map[*http.Request]context.Context{} ) // Context returns the context for the request. func Context(r *http.Request) context.Context { mtx.RLock() defer mtx.RUnlock() return ctxts[r] } type param string // Param returns param p for the context. func Param(ctx context.Context, p string) string { return ctx.Value(param(p)).(string) } // WithParam returns a new context with param p set to v. func WithParam(ctx context.Context, p, v string) context.Context { return context.WithValue(ctx, param(p), v) } // handle turns a Handle into httprouter.Handle func handle(h http.HandlerFunc) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, params httprouter.Params) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() for _, p := range params { ctx = context.WithValue(ctx, param(p.Key), p.Value) } mtx.Lock() ctxts[r] = ctx mtx.Unlock() h(w, r) mtx.Lock() delete(ctxts, r) mtx.Unlock() } } // Router wraps httprouter.Router and adds support for prefixed sub-routers. type Router struct { rtr *httprouter.Router prefix string } // New returns a new Router. func New() *Router { return &Router{rtr: httprouter.New()} } // WithPrefix returns a router that prefixes all registered routes with prefix. func (r *Router) WithPrefix(prefix string) *Router { return &Router{rtr: r.rtr, prefix: r.prefix + prefix} } // Get registers a new GET route. func (r *Router) Get(path string, h http.HandlerFunc) { r.rtr.GET(r.prefix+path, handle(h)) } // Del registers a new DELETE route. func (r *Router) Del(path string, h http.HandlerFunc) { r.rtr.DELETE(r.prefix+path, handle(h)) } // Put registers a new PUT route. func (r *Router) Put(path string, h http.HandlerFunc) { r.rtr.PUT(r.prefix+path, handle(h)) } // Post registers a new POST route. func (r *Router) Post(path string, h http.HandlerFunc) { r.rtr.POST(r.prefix+path, handle(h)) } // ServeHTTP implements http.Handler. func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { r.rtr.ServeHTTP(w, req) } // FileServe returns a new http.HandlerFunc that serves files from dir. // Using routes must provide the *filepath parameter. func FileServe(dir string) http.HandlerFunc { fs := http.FileServer(http.Dir(dir)) return func(w http.ResponseWriter, r *http.Request) { r.URL.Path = Param(Context(r), "filepath") fs.ServeHTTP(w, r) } }
apache-2.0
njpatel/skizze
src/sketches/hllpp_test.go
1614
package sketches import ( "strconv" "testing" "datamodel" pb "datamodel/protobuf" "utils" ) func TestAddHLLPP(t *testing.T) { utils.SetupTests() defer utils.TearDownTests() info := datamodel.NewEmptyInfo() info.Properties.MaxUniqueItems = utils.Int64p(1024) info.Name = utils.Stringp("marvel") sketch, err := NewHLLPPSketch(info) if err != nil { t.Error("expected avengers to have no error, got", err) } values := [][]byte{ []byte("sabertooth"), []byte("thunderbolt"), []byte("havoc"), []byte("cyclops"), []byte("cyclops"), []byte("cyclops"), []byte("havoc")} if _, err := sketch.Add(values); err != nil { t.Error("expected no errors, got", err) } const expectedCardinality int64 = 4 if res, err := sketch.Get(values); err != nil { t.Error("expected no errors, got", err) } else { tmp := res.(*pb.CardinalityResult) mres := tmp.GetCardinality() if mres != int64(expectedCardinality) { t.Error("expected cardinality == "+strconv.FormatInt(expectedCardinality, 10)+", got", mres) } } } func BenchmarkHLLPP(b *testing.B) { values := make([][]byte, 10) for i := 0; i < 1024; i++ { avenger := "avenger" + strconv.Itoa(i) values = append(values, []byte(avenger)) } for n := 0; n < b.N; n++ { info := datamodel.NewEmptyInfo() info.Properties.Size = utils.Int64p(1000) info.Name = utils.Stringp("marvel3") sketch, err := NewHLLPPSketch(info) if err != nil { b.Error("expected no errors, got", err) } for i := 0; i < 1000; i++ { if _, err := sketch.Add(values); err != nil { b.Error("expected no errors, got", err) } } } }
apache-2.0
Yufan-l/vertx-playground
vertx-java/src/main/java/vertx/playground/java/api/Whisky.java
902
package vertx.playground.java.api; import io.vertx.core.json.JsonObject; import java.util.concurrent.atomic.AtomicInteger; public class Whisky { private final int id; private String name; private String origin; public Whisky(String name, String origin) { this.name = name; this.origin = origin; this.id = -1; } public Whisky(JsonObject json) { this.name = json.getString("NAME"); this.origin = json.getString("ORIGIN"); this.id = json.getInteger("ID"); } public Whisky() { this.id = -1; } public Whisky(int id, String name, String origin) { this.id = id; this.name = name; this.origin = origin; } public String getName() { return name; } public String getOrigin() { return origin; } public int getId() { return id; } public void setName(String name) { this.name = name; } public void setOrigin(String origin) { this.origin = origin; } }
apache-2.0
meta-magic/amexio.github.io
src/module/map/treemap/treemap.map.component.ts
8002
/* * Copyright [2019] [Metamagic] * * 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. * * Created by sagar on 18/8/17. */ import { AfterContentInit, Component, ContentChildren, ElementRef, EventEmitter, Input, OnInit, Output, QueryList, ViewChild } from '@angular/core'; import { MapTitleComponent } from '../maptitle/map.title.component'; import { MapLoaderService } from '../map.loader.service'; declare var google: any; @Component({ selector: 'amexio-map-treemap', template: ` <div *ngIf="showChart" #treemapmap [style.width]="width" [style.height]="height" (window:resize)="onResize($event)" > <div *ngIf="!hasLoaded" class="lmask"> </div> </div> `, styles: [`.lmask { position: absolute; height: 100%; width: 100%; background-color: #000; bottom: 0; left: 0; right: 0; top: 0; z-index: 9999; opacity: 0.4; } .lmask.fixed { position: fixed; } .lmask:before { content: ''; background-color: transparent; border: 5px solid rgba(0, 183, 229, 0.9); opacity: .9; border-right: 5px solid transparent; border-left: 5px solid transparent; border-radius: 50px; box-shadow: 0 0 35px #2187e7; width: 50px; height: 50px; -moz-animation: spinPulse 1s infinite ease-in-out; -webkit-animation: spinPulse 1s infinite linear; margin: -25px 0 0 -25px; position: absolute; top: 50%; left: 50%; } .lmask:after { content: ''; background-color: transparent; border: 5px solid rgba(0, 183, 229, 0.9); opacity: .9; border-left: 5px solid transparent; border-right: 5px solid transparent; border-radius: 50px; box-shadow: 0 0 15px #2187e7; width: 30px; height: 30px; -moz-animation: spinoffPulse 1s infinite linear; -webkit-animation: spinoffPulse 1s infinite linear; margin: -15px 0 0 -15px; position: absolute; top: 50%; left: 50%; } @-moz-keyframes spinPulse { 0% { -moz-transform: rotate(160deg); opacity: 0; box-shadow: 0 0 1px #2187e7; } 50% { -moz-transform: rotate(145deg); opacity: 1; } 100% { -moz-transform: rotate(-320deg); opacity: 0; } } @-moz-keyframes spinoffPulse { 0% { -moz-transform: rotate(0deg); } 100% { -moz-transform: rotate(360deg); } } @-webkit-keyframes spinPulse { 0% { -webkit-transform: rotate(160deg); opacity: 0; box-shadow: 0 0 1px #2187e7; } 50% { -webkit-transform: rotate(145deg); opacity: 1; } 100% { -webkit-transform: rotate(-320deg); opacity: 0; } } @-webkit-keyframes spinoffPulse { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } } `], }) export class TreeMapComponent implements AfterContentInit, OnInit { private options: any; private treemapData: any; private chart: any; hasLoaded: boolean; id: any; /* Properties name : width datatype : string version : 4.0 onwards default : none description : Width of chart. */ @Input() width: string; /* Properties name : height datatype : string version : 4.0 onwards default : none description : height of chart. */ @Input() height: string; showChart: boolean; _data: any; get data(): any { return this._data; } /* Properties name : data datatype : any version : 4.0 onwards default : none description : Local data for TreeMap. */ @Input('data') set data(data: any) { if (data) { this._data = data; this.showChart = true; } else { this.showChart = false; } } /* Properties name : min-color datatype : string version : 4.0 onwards default : none description : The color for a rectangle with the column 3 value of min-colorValue. Specify an HTML color value. */ @Input('min-color') mincolor: string; /* Properties name : mid-color datatype : string version : 4.0 onwards default : none description : The color for a rectangle with a column 3 value midway between max-colorValue and min-colorValue. Specify an HTML color value. */ @Input('mid-color') midcolor: string; /* Properties name : max-color datatype : string version : 4.0 onwards default : none description : The color for a rectangle with a column 3 value of max-colorValue. Specify an HTML color value. */ @Input('max-color') maxcolor: string; /* Properties name : show-scale datatype : boolean version : 4.0 onwards default : none description : Whether or not to show a color gradient scale from min-color to max-color along the top of the chart. Specify true to show the scale. */ @Input('show-scale') showscale: boolean; /* Properties name : max-post-depth datatype : number version : 4.0 onwards default : none description : number of levels of nodes beyond maxDepth to show in 'hinted' fashion. */ @Input('max-post-depth') maxpostdepth: number; @Output() onClick = new EventEmitter<any>(); @ContentChildren(MapTitleComponent) maptleComp: QueryList<MapTitleComponent>; mapTitleArray: MapTitleComponent[]; mapTitleComponent: MapTitleComponent; @ViewChild('treemapmap') private treemapmap: ElementRef; constructor(private loader: MapLoaderService) { this.width = '100%'; } drawChart() { let chart: any; const localData = this._data; if (this.showChart) { this.treemapData = google.visualization.arrayToDataTable(this._data); this.initializeOptions(); if (this.treemapData) { chart = new google.visualization.TreeMap(this.treemapmap.nativeElement); this.hasLoaded = true; chart.draw(this.treemapData, this.options); google.visualization.events.addListener(chart, 'select', (eve: any, event: any) => { localData.forEach((element: any, index: any) => { if ((chart.getSelection())[0].row + 1 === index) { this.onClick.emit(element); } }); }); } } } initializeOptions() { this.options = { title: this.mapTitleComponent ? this.mapTitleComponent.title : null, titleTextStyle: this.mapTitleComponent ? this.mapTitleTextStyle() : null, mincolor: this.mincolor ? this.mincolor : null, midcolor: this.midcolor ? this.midcolor : null, maxcolor: this.maxcolor ? this.maxcolor : null, headerHeight: 15, fontcolor: 'black', showscale: this.showscale ? this.showscale : false, maxpostdepth: this.maxpostdepth ? this.maxpostdepth : 1, }; } mapTitleTextStyle() { return { color: this.mapTitleComponent.color ? this.mapTitleComponent.color : null, fontName: this.mapTitleComponent.fontname ? this.mapTitleComponent.fontname : null, bold: this.mapTitleComponent.bold ? this.mapTitleComponent.bold : null, italic: this.mapTitleComponent.italic ? this.mapTitleComponent.italic : null, }; } click(e: any) { } ngAfterContentInit(): void { this.mapTitleArray = this.maptleComp.toArray(); if (this.mapTitleArray.length === 1) { this.mapTitleComponent = this.mapTitleArray.pop(); } } ngOnInit(): void { this.hasLoaded = false; this.loader.loadCharts('TreeMap').subscribe((value) => console.log(), (errror) => console.error(errror), () => { this.drawChart(); }); } onResize(event: any) { this.drawChart(); } }
apache-2.0
imoblife/filemanager
FileManager/src/com/filemanager/compatibility/HomeIconHelper.java
812
package com.filemanager.compatibility; import com.filemanager.FileManagerActivity; import android.app.Activity; import android.content.Intent; public class HomeIconHelper { public static void activity_actionbar_setHomeButtonEnabled(Activity act){ act.getActionBar().setHomeButtonEnabled(true); } public static void activity_actionbar_setDisplayHomeAsUpEnabled(Activity act){ if (act != null && act.getActionBar() != null){ act.getActionBar().setDisplayHomeAsUpEnabled(true); } } /** * Launch the home activity. * @param act The currently displayed activity. */ public static void showHome(Activity act) { Intent intent = new Intent(act, FileManagerActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); act.startActivity(intent); } }
apache-2.0
tolbertam/java-driver
driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/LocalDateCodecTest.java
2572
/* * Copyright (C) 2012-2017 DataStax 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. */ package com.datastax.driver.extras.codecs.jdk8; import com.datastax.driver.core.Assertions; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.time.LocalDate; import static com.datastax.driver.core.ProtocolVersion.V4; import static org.assertj.core.api.Assertions.assertThat; public class LocalDateCodecTest { private static final LocalDate EPOCH = LocalDate.ofEpochDay(0); private static final LocalDate MIN = LocalDate.parse("-5877641-06-23"); @DataProvider(name = "LocalDateCodecTest.parse") public Object[][] parseParameters() { return new Object[][]{ {null, null}, {"", null}, {"NULL", null}, {"0", MIN}, {"'2147483648'", EPOCH}, {"'-5877641-06-23'", MIN}, {"'1970-01-01'", EPOCH}, {"'2014-01-01'", LocalDate.parse("2014-01-01")} }; } @DataProvider(name = "LocalDateCodecTest.format") public Object[][] formatParameters() { return new Object[][]{ {null, "NULL"}, {LocalDate.ofEpochDay(0), "'1970-01-01'"}, {LocalDate.parse("2010-06-30"), "'2010-06-30'"} }; } @Test(groups = "unit", dataProvider = "LocalDateCodecTest.parse") public void should_parse_valid_formats(String input, LocalDate expected) { // when LocalDate actual = LocalDateCodec.instance.parse(input); // then assertThat(actual).isEqualTo(expected); } @Test(groups = "unit", dataProvider = "LocalDateCodecTest.format") public void should_serialize_and_format_valid_object(LocalDate input, String expected) { // when String actual = LocalDateCodec.instance.format(input); // then Assertions.assertThat(LocalDateCodec.instance).withProtocolVersion(V4).canSerialize(input); assertThat(actual).isEqualTo(expected); } }
apache-2.0
jdillon/gshell
gshell-testharness/src/main/java/com/planet57/gshell/testharness/BufferIO.java
2171
/* * Copyright (c) 2009-present the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.planet57.gshell.testharness; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import com.planet57.gshell.util.io.IO; import com.planet57.gshell.util.io.StreamSet; import org.jline.terminal.Terminal; import org.slf4j.Logger; /** * Buffering {@link IO} to capture output for assertions. * * @since 3.0 */ public class BufferIO extends IO { private ByteArrayOutputStream output; private ByteArrayOutputStream error; public BufferIO(final Terminal terminal) { this(new ByteArrayOutputStream(), new ByteArrayOutputStream(), terminal); } private BufferIO(final ByteArrayOutputStream output, final ByteArrayOutputStream error, final Terminal terminal) { super(new StreamSet(System.in, new PrintStream(output), new PrintStream(error)), terminal); this.output = output; this.error = error; } public ByteArrayOutputStream getOutput() { return output; } public String getOutputString() { return new String(getOutput().toByteArray()); } public ByteArrayOutputStream getError() { return error; } public String getErrorString() { return new String(getError().toByteArray()); } /** * Dump output streams to logging. */ public void dump(final Logger logger) { String out = getOutputString(); if (!out.trim().isEmpty()) { logger.debug("OUT:\n-----8<-----\n{}\n----->8-----", out); } String err = getErrorString(); if (!err.trim().isEmpty()) { logger.debug("ERR:\n-----8<-----\n{}\n----->8-----", err); } } }
apache-2.0
moley/leguan
leguan-plugins/leguan-plugin-unuseddeps/src/test/java/org/leguan/unuseddeps/testprojectWithout/TestProjectWithout.java
152
package org.leguan.unuseddeps.testprojectWithout; public class TestProjectWithout { public TestProjectWithout() { String hello = "hello"; } }
apache-2.0
cwpenhale/red5-mobileconsole
red5_server/src/main/java/org/red5/server/api/statistics/IStatisticsService.java
3904
/* * RED5 Open Source Flash Server - http://code.google.com/p/red5/ * * Copyright 2006-2012 by respective authors (see below). All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.red5.server.api.statistics; import java.util.Set; import org.red5.server.api.scope.IScope; import org.red5.server.api.so.ISharedObject; import org.red5.server.exception.ScopeNotFoundException; import org.red5.server.exception.SharedObjectException; /** * Statistics methods for Red5. They can be used to poll for updates of * given elements inside the server. Statistics data will be stored as * properties of different shared objects. * * Use <code>getScopeStatisticsSO</code> and <code>getSharedObjectStatisticsSO</code> * to get these shared objects. The property names are <code>scopeName</code> * for scope attributes and <code>scopeName|sharedObjectName</code> for * shared object attributes. Each property holds a Map containing key/value * mappings of the corresponding attributes. * * Sometime in the future, the updates on the shared objects will be done * automatically so a client doesn't need to poll for them. * * @author The Red5 Project (red5@osflash.org) * @author Joachim Bauch (jojo@struktur.de) */ public interface IStatisticsService { /** * Return the shared object that will be used to keep scope statistics. * * @param scope A scope to return the shared object for. * @return the shared object containing scope statistics */ public ISharedObject getScopeStatisticsSO(IScope scope); /** * Return the shared object that will be used to keep SO statistics. * * @param scope A scope to return the shared object for. * @return the shared object containing SO statistics */ public ISharedObject getSharedObjectStatisticsSO(IScope scope); /** * Return a list of all scopes that currently exist on the server. * * @return list of scope names */ public Set<String> getScopes(); /** * Return a list of all scopes that currently exist on the server * below a current path. * * @param path Path to start looking for scopes. * @return list of scope names * @throws ScopeNotFoundException if the path on the server doesn't exist */ public Set<String> getScopes(String path) throws ScopeNotFoundException; /** * Update statistics for a given scope. * * @param path Path to scope to update. * @throws ScopeNotFoundException if the given scope doesn't exist */ public void updateScopeStatistics(String path) throws ScopeNotFoundException; /** * Return informations about shared objects for a given scope. * * @param path Path to scope to return shared object names for. * @return list of informations about shared objects */ public Set<ISharedObjectStatistics> getSharedObjects(String path); /** * Update informations about a shared object in a given scope. * * @param path Path to scope that contains the shared object. * @param name Name of shared object to update. * @throws ScopeNotFoundException if the given scope doesn't exist * @throws SharedObjectException if no shared object with the given name exists */ public void updateSharedObjectStatistics(String path, String name) throws ScopeNotFoundException, SharedObjectException; }
apache-2.0
CCI-MOC/GUI-Frontend
troposphere/static/js/components/projects/resources/instance/details/sections/metrics/CPUGraph.js
341
import Graph from "./Graph"; import { extend } from "underscore"; let CPUGraph = function(settings) { let defaults = { transform: "derivative" }; Graph.call(this, extend(defaults, settings)); }; CPUGraph.prototype = Object.create(Graph.prototype); CPUGraph.prototype.constructor = CPUGraph; export default CPUGraph;
apache-2.0
Leeo1124/test
src/main/java/com/leeo/web/entity/CopyOfUser.java
814
package com.leeo.web.entity; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name="t_sys_user") public class CopyOfUser extends IdEntity<Long>{ private static final long serialVersionUID = -6416431995690017358L; private String username; private String password; private String realName; public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getRealName() { return this.realName; } public void setRealName(String realName) { this.realName = realName; } }
apache-2.0
matteocaberlotto/TeoCoreBundle
Resources/public/js/jquery.pte.js
4552
/* * jQuery getPathToElement plugin calculates one of the * jquery unique path to reach an element of the DOM. * It will use id, classname or tagname to identify * the element itself and all the parents up to the body or * the first element with an unique ID. * For human readability it is prefered a tagname + id or * tagname + class for the element. and id or class or tagname * for parents. * It simply returns the array of element selectors, up to you * to join or do whatever you want. * * Usage examples: * * Get path with (default) * * $(myElement).getPathToElement(); * * Will return a string like this "#path > .to:eq(1) > a.element" * * $(myElement).getPathToElement(true); * * Will return a string like this "#path .to:eq(1) a.element:eq(3)" * * You can get raw selectors array by passing 'true' as second parameter: * * $(myElement).getPathToElement(false, true); * * Will return an array like this ["#path", ".to:eq(1)", "a.element"] * * Test... :) console.group('Running single tests...'); var total = 0; var failed = 0; $("div, input, a, p, h1, h2, h3, h4, small, span").each(function () { paths = [$(this).getPathToElement(), $(this).getPathToElement(true)]; var i; for (i in paths) { if (paths.hasOwnProperty(i)) { if ($(paths[i]).get(0) !== $(this).get(0)) { failed++; console.error("Error with path '", paths[i], "' and element ", $(this).get(0)); } else { console.info('ok'); } total++; } } }); console.groupEnd(); if (failed) { console.error(total, ' tests completed and ', failed, ' failed'); } else { console.info(total, ' tests completed and ', failed, ' failed'); } */ (function($) { $.fn.getPathToElement = function (dontUseDirectDescendants, raw) { var current = $(this); var element = current; var isIdentified = false; var first = true; var path = []; // Returns the index of an element within its siblings (filtered by 'selector'). var getIndexString = function (elem, selector) { if (!dontUseDirectDescendants) { selector = '> ' + selector; } if (elem.parent().find(selector).length > 1) { return ':eq(' + elem.parent().find(selector).index(elem) + ')'; } else { return ''; } }; // Element is identified when we reach an element with ID or the document.body element. while (!isIdentified) { // ID if (element.attr('id')) { // If it is the first element, identify it with tagname + id. if (first) { path.push(element.get(0).nodeName.toLowerCase() + '#' + element.attr('id')); } else { path.push('#' + element.attr('id')); } // Found a valid path. isIdentified = true; // CLASSNAME } else if (element.attr('class')) { // handle multiple classnames var className = element.attr('class'); if (className.indexOf(" ") !== -1) { className = className.split(" ").join("."); } var classSelector = '.' + className; // If it is the first element, identify it with tagname + class. if (first) { path.push(element.get(0).nodeName.toLowerCase() + classSelector + getIndexString(element, classSelector)); } else { path.push(classSelector + getIndexString(element, classSelector)); } // TAGNAME } else { // Simply use tagname + index if nothing else is available path.push(element.get(0).nodeName.toLowerCase() + getIndexString(element, element.get(0).nodeName.toLowerCase())); } first = false; // climb the DOM tree element = element.parent(); // stops when required :) if (element.get(0) === document.body) { isIdentified = true; } } if (raw) { return path.reverse(); } if (dontUseDirectDescendants) { return path.reverse().join(" "); } return path.reverse().join(" > "); }; })(jQuery);
apache-2.0
osswangxining/dockerfoundry
cn.dockerfoundry.ide.eclipse.server.core/src/cn/dockerfoundry/ide/eclipse/server/core/internal/client/AbstractWaitWithProgressJob.java
4198
/******************************************************************************* * Copyright (c) 2012, 2015 Pivotal Software, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of 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. * * Contributors: * Pivotal Software, Inc. - initial API and implementation ********************************************************************************/ package cn.dockerfoundry.ide.eclipse.server.core.internal.client; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import cn.dockerfoundry.ide.eclipse.server.core.internal.CloudErrorUtil; /** * Performs an operation that is expect to return a result. The result is * validated, and if invalid, a waiting period occurs, and the operation * attempted again until a valid result is obtained, or the maximum number of * attempts is reached. If an invalid result is returned at the end of the * maximum attempt, and it's due to an error, a CoreException is thrown. * <p/> * A check is also performed on the progress monitor, if it is cancelled before * the maximum number of attempts is reached, the operation is cancelled, * regardless of whether a valid result was obtained or not. */ public abstract class AbstractWaitWithProgressJob<T> { private final int attempts; private final long sleepTime; private final boolean shouldRetryOnError; public AbstractWaitWithProgressJob(int attempts, long sleepTime) { this.attempts = attempts; this.sleepTime = sleepTime; this.shouldRetryOnError = false; } public AbstractWaitWithProgressJob(int attempts, long sleepTime, boolean shouldRetryOnError) { this.attempts = attempts; this.sleepTime = sleepTime; this.shouldRetryOnError = shouldRetryOnError; } /** * To continue waiting, return an invalid result that is checked as invalid * by the isValid(...) API * @param monitor may be null * @return */ abstract protected T runInWait(IProgressMonitor monitor) throws CoreException; protected boolean shouldRetryOnError(Throwable t) { return shouldRetryOnError; } protected boolean isValid(T result) { return result != null; } /** * Returns a result, or throws an exception ONLY if the result is invalid * AND an exception was thrown after all attempts have been exhausted. Will * only re-throw the last exception that was thrown. Note that the result * may still be null. * * @param monitor it may be null * @return * @throws CoreException */ public T run(IProgressMonitor monitor) throws CoreException { Throwable lastError = null; T result = null; int i = 0; while (i < attempts) { if (monitor != null && monitor.isCanceled()) { break; } boolean reattempt = false; // Two conditions which results in a reattempt: // 1. Result is not valid // 2. Exception is thrown and an exception handler decides that a // reattempt should happen based on the given error try { result = runInWait(monitor); reattempt = !isValid(result); } catch (Throwable th) { lastError = th; reattempt = shouldRetryOnError(lastError); } if (reattempt) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { // Ignore and proceed } } else { break; } i++; } // Only throw exception if an error was generated and an invalid result // was obtained. if (!isValid(result) && lastError != null) { CoreException coreError = lastError instanceof CoreException ? (CoreException) lastError : CloudErrorUtil .toCoreException(lastError); throw coreError; } return result; } }
apache-2.0
mlaursen/mathtabolism
src_old/main/java/com/mathtabolism/dto/MealDto.java
312
/** * */ package com.mathtabolism.dto; /** * @author mlaursen * */ public interface MealDto extends GeneratedIdDto { /** * Gets the Meal's name * @return the meal's name */ String getName(); /** * Sets the meal's name * @param name the name */ void setName(String name); }
apache-2.0
jasontangcn/JDKAPI
src/com/fruits/jdkapi/security/ClassInternal.java
2492
package com.fruits.jdkapi.security; import java.lang.reflect.Method; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; public class ClassInternal implements SecurityMisc.InterfaceA, SecurityMisc.InterfaceB { public static String getClassInfo(Class cls) { StringBuffer sb = new StringBuffer(); ClassLoader cl = cls.getClassLoader(); int count = 1; while (null != cl) { for(int i = 0; i < count; i++){ sb.append(" "); } sb.append(cl).append("\n"); URL[] urls = getClassLoaderURLs(cl); if(null != urls) { for(URL url : urls){ for(int i = 0; i < count; i++){ sb.append(" "); } sb.append(url).append("\n"); } } count++; cl = cl.getParent(); } sb.append("\n"); ProtectionDomain pd = cls.getProtectionDomain(); CodeSource cs = pd.getCodeSource(); sb.append("ProtectionDomain is : ").append(pd); if (null != cs) sb.append("CodeSource is : ").append(cs).append("\n"); else sb.append("CodeSource is NULL."); sb.append("Implemented interfaces:").append("\n"); Class[] is = cls.getInterfaces(); for (Class i : is) { sb.append(" " + i + "(" + Integer.toHexString(i.hashCode()) + ")"); ClassLoader loader = i.getClassLoader(); sb.append(" ClassLoader: " + loader); ProtectionDomain domain = i.getProtectionDomain(); CodeSource source = domain.getCodeSource(); if (null != source) sb.append(" CodeSource: " + source + "\n"); else sb.append(" CodeSource is NULL.\n"); } return sb.toString(); } /** * Use reflection to access a URL[] getURLs or ULR[] getAllURLs method so * that non-URLClassLoader class loaders, or class loaders that override * getURLs to return null or empty, can provide the true classpath info. */ public static URL[] getClassLoaderURLs(ClassLoader cl) { URL[] urls = {}; try { Class returnType = urls.getClass(); Class[] parameterTypes = {}; Method getURLs = cl.getClass().getMethod("getURLs", parameterTypes); if (returnType.isAssignableFrom(getURLs.getReturnType())) { Object[] args = {}; urls = (URL[]) getURLs.invoke(cl, args); } } catch (Exception exc) { exc.printStackTrace(); } return urls; } public static void main(String[] args) { System.out.println("ClassInternal :"); System.out.println(ClassInternal.getClassInfo(ClassInternal.class)); } }
apache-2.0
jk1/intellij-community
platform/smRunner/src/com/intellij/execution/testframework/sm/SMTestRunnerConnectionUtil.java
16480
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.testframework.sm; import com.intellij.execution.ExecutionException; import com.intellij.execution.Location; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.testframework.TestConsoleProperties; import com.intellij.execution.testframework.sm.runner.*; import com.intellij.execution.testframework.sm.runner.ui.AttachToProcessListener; import com.intellij.execution.testframework.sm.runner.ui.SMTRunnerConsoleView; import com.intellij.execution.testframework.sm.runner.ui.SMTRunnerUIActionsHandler; import com.intellij.execution.testframework.sm.runner.ui.SMTestRunnerResultsForm; import com.intellij.execution.testframework.ui.BaseTestsOutputConsoleView; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.testIntegration.TestLocationProvider; import com.intellij.util.io.URLUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; /** * @author Roman Chernyatchik */ public class SMTestRunnerConnectionUtil { private static final String TEST_RUNNER_DEBUG_MODE_PROPERTY = "idea.smrunner.debug"; private SMTestRunnerConnectionUtil() { } /** * Creates Test Runner console component with test tree, console, statistics tabs * and attaches it to given Process handler. * <p/> * You can use this method in run configuration's CommandLineState. You should * just override "execute" method of your custom command line state and return * test runner's console. * <p/> * E.g: <pre>{@code * public class MyCommandLineState extends CommandLineState { * * // ... * * @Override * public ExecutionResult execute(@NotNull Executor executor, @NotNull ProgramRunner runner) throws ExecutionException { * ProcessHandler processHandler = startProcess(); * RunConfiguration runConfiguration = getConfiguration(); * ExecutionEnvironment environment = getEnvironment(); * TestConsoleProperties properties = new SMTRunnerConsoleProperties(runConfiguration, "xUnit", executor) * ConsoleView console = SMTestRunnerConnectionUtil.createAndAttachConsole("xUnit", processHandler, properties, environment); * return new DefaultExecutionResult(console, processHandler, createActions(console, processHandler)); * } * } * }</pre> * <p/> * NB: For debug purposes please enable "debug mode". In this mode test runner will also validate * consistency of test events communication protocol and throw assertion errors. To enable debug mode * please set system property idea.smrunner.debug=true * * @param testFrameworkName Is used to store(project level) latest value of testTree/consoleTab splitter and other settings * and also will be mentioned in debug diagnostics * @param processHandler Process handler * @param consoleProperties Console properties for test console actions * @return Console view */ @NotNull public static BaseTestsOutputConsoleView createAndAttachConsole(@NotNull String testFrameworkName, @NotNull ProcessHandler processHandler, @NotNull TestConsoleProperties consoleProperties) throws ExecutionException { BaseTestsOutputConsoleView console = createConsole(testFrameworkName, consoleProperties); console.attachToProcess(processHandler); return console; } @NotNull public static BaseTestsOutputConsoleView createConsole(@NotNull String testFrameworkName, @NotNull TestConsoleProperties consoleProperties) { String splitterPropertyName = getSplitterPropertyName(testFrameworkName); SMTRunnerConsoleView consoleView = new SMTRunnerConsoleView(consoleProperties, splitterPropertyName); initConsoleView(consoleView, testFrameworkName); return consoleView; } @NotNull public static String getSplitterPropertyName(@NotNull String testFrameworkName) { return testFrameworkName + ".Splitter.Proportion"; } public static void initConsoleView(@NotNull final SMTRunnerConsoleView consoleView, @NotNull final String testFrameworkName) { consoleView.addAttachToProcessListener(new AttachToProcessListener() { @Override public void onAttachToProcess(@NotNull ProcessHandler processHandler) { TestConsoleProperties properties = consoleView.getProperties(); TestProxyPrinterProvider printerProvider = null; if (properties instanceof SMTRunnerConsoleProperties) { TestProxyFilterProvider filterProvider = ((SMTRunnerConsoleProperties)properties).getFilterProvider(); if (filterProvider != null) { printerProvider = new TestProxyPrinterProvider(consoleView, filterProvider); } } SMTestLocator testLocator = FileUrlProvider.INSTANCE; if (properties instanceof SMTRunnerConsoleProperties) { SMTestLocator customLocator = ((SMTRunnerConsoleProperties)properties).getTestLocator(); if (customLocator != null) { testLocator = new CombinedTestLocator(customLocator); } } boolean idBasedTestTree = false; if (properties instanceof SMTRunnerConsoleProperties) { idBasedTestTree = ((SMTRunnerConsoleProperties)properties).isIdBasedTestTree(); } SMTestRunnerResultsForm resultsForm = consoleView.getResultsViewer(); resultsForm.getTestsRootNode().setHandler(processHandler); attachEventsProcessors(properties, resultsForm, processHandler, testFrameworkName, testLocator, idBasedTestTree, printerProvider); } }); consoleView.setHelpId("reference.runToolWindow.testResultsTab"); consoleView.initUI(); } /** * In debug mode SM Runner will check events consistency. All errors will be reported using IDEA errors logger. * This mode must be disabled in production. The most widespread false positives were detected when you debug tests. * In such cases Test Framework may fire events several times, etc. * * @return true if in debug mode, otherwise false. */ public static boolean isInDebugMode() { return Boolean.valueOf(System.getProperty(TEST_RUNNER_DEBUG_MODE_PROPERTY)); } private static void attachEventsProcessors(TestConsoleProperties consoleProperties, SMTestRunnerResultsForm resultsViewer, ProcessHandler processHandler, String testFrameworkName, @Nullable SMTestLocator locator, boolean idBasedTestTree, @Nullable TestProxyPrinterProvider printerProvider) { // build messages consumer final OutputToGeneralTestEventsConverter outputConsumer; if (consoleProperties instanceof SMCustomMessagesParsing) { outputConsumer = ((SMCustomMessagesParsing)consoleProperties).createTestEventsConverter(testFrameworkName, consoleProperties); } else { outputConsumer = new OutputToGeneralTestEventsConverter(testFrameworkName, consoleProperties); } // UI actions SMTRunnerUIActionsHandler uiActionsHandler = new SMTRunnerUIActionsHandler(consoleProperties); // subscribes test runner's actions on results viewer events resultsViewer.addEventsListener(uiActionsHandler); outputConsumer.setTestingStartedHandler(() -> { // events processor GeneralTestEventsProcessor eventsProcessor; if (idBasedTestTree) { eventsProcessor = new GeneralIdBasedToSMTRunnerEventsConvertor(consoleProperties.getProject(), resultsViewer.getTestsRootNode(), testFrameworkName); } else { eventsProcessor = new GeneralToSMTRunnerEventsConvertor(consoleProperties.getProject(), resultsViewer.getTestsRootNode(), testFrameworkName); } if (locator != null) { eventsProcessor.setLocator(locator); } if (printerProvider != null) { eventsProcessor.setPrinterProvider(printerProvider); } // subscribes result viewer on event processor eventsProcessor.addEventsListener(resultsViewer); // subscribes event processor on output consumer events outputConsumer.setProcessor(eventsProcessor); }); outputConsumer.startTesting(); processHandler.addProcessListener(new ProcessAdapter() { @Override public void processTerminated(@NotNull final ProcessEvent event) { ApplicationManager.getApplication().executeOnPooledThread(() -> { outputConsumer.flushBufferOnProcessTermination(event.getExitCode()); outputConsumer.finishTesting(); Disposer.dispose(outputConsumer); }); } @Override public void onTextAvailable(@NotNull final ProcessEvent event, @NotNull final Key outputType) { outputConsumer.process(event.getText(), outputType); } }); } private static class CombinedTestLocator implements SMTestLocator, DumbAware { private final SMTestLocator myLocator; public CombinedTestLocator(SMTestLocator locator) { myLocator = locator; } @NotNull @Override public List<Location> getLocation(@NotNull String protocol, @NotNull String path, @NotNull Project project, @NotNull GlobalSearchScope scope) { return getLocation(protocol, path, null, project, scope); } @NotNull @Override public List<Location> getLocation(@NotNull String protocol, @NotNull String path, @Nullable String metainfo, @NotNull Project project, @NotNull GlobalSearchScope scope) { if (URLUtil.FILE_PROTOCOL.equals(protocol)) { return FileUrlProvider.INSTANCE.getLocation(protocol, path, project, scope); } else if (!DumbService.isDumb(project) || DumbService.isDumbAware(myLocator)) { return myLocator.getLocation(protocol, path, metainfo, project, scope); } else { return Collections.emptyList(); } } @NotNull @Override public List<Location> getLocation(@NotNull String stacktraceLine, @NotNull Project project, @NotNull GlobalSearchScope scope) { return myLocator.getLocation(stacktraceLine, project, scope); } } /** @deprecated use {@link #createConsole(String, TestConsoleProperties)} (to be removed in IDEA 17) */ @Deprecated @SuppressWarnings({"unused", "deprecation"}) public static BaseTestsOutputConsoleView createConsoleWithCustomLocator(@NotNull String testFrameworkName, @NotNull TestConsoleProperties consoleProperties, ExecutionEnvironment environment, @Nullable TestLocationProvider locator) { return createConsoleWithCustomLocator(testFrameworkName, consoleProperties, environment, locator, false, null); } /** @deprecated use {@link #createConsole(String, TestConsoleProperties)} (to be removed in IDEA 17) */ @Deprecated @SuppressWarnings({"unused", "deprecation"}) public static SMTRunnerConsoleView createConsoleWithCustomLocator(@NotNull String testFrameworkName, @NotNull TestConsoleProperties consoleProperties, ExecutionEnvironment environment, @Nullable TestLocationProvider locator, boolean idBasedTreeConstruction, @Nullable TestProxyFilterProvider filterProvider) { String splitterPropertyName = getSplitterPropertyName(testFrameworkName); SMTRunnerConsoleView consoleView = new SMTRunnerConsoleView(consoleProperties, splitterPropertyName); initConsoleView(consoleView, testFrameworkName, locator, idBasedTreeConstruction, filterProvider); return consoleView; } /** @deprecated use {@link #initConsoleView(SMTRunnerConsoleView, String)} (to be removed in IDEA 17) */ @Deprecated @SuppressWarnings({"unused", "deprecation"}) public static void initConsoleView(@NotNull final SMTRunnerConsoleView consoleView, @NotNull final String testFrameworkName, @Nullable final TestLocationProvider locator, final boolean idBasedTreeConstruction, @Nullable final TestProxyFilterProvider filterProvider) { consoleView.addAttachToProcessListener(new AttachToProcessListener() { @Override public void onAttachToProcess(@NotNull ProcessHandler processHandler) { TestConsoleProperties properties = consoleView.getProperties(); SMTestLocator testLocator = new CompositeTestLocationProvider(locator); TestProxyPrinterProvider printerProvider = null; if (filterProvider != null) { printerProvider = new TestProxyPrinterProvider(consoleView, filterProvider); } SMTestRunnerResultsForm resultsForm = consoleView.getResultsViewer(); attachEventsProcessors(properties, resultsForm, processHandler, testFrameworkName, testLocator, idBasedTreeConstruction, printerProvider); } }); consoleView.setHelpId("reference.runToolWindow.testResultsTab"); consoleView.initUI(); } @SuppressWarnings("deprecation") private static class CompositeTestLocationProvider implements SMTestLocator { private final TestLocationProvider myPrimaryLocator; private final TestLocationProvider[] myLocators; private CompositeTestLocationProvider(@Nullable TestLocationProvider primaryLocator) { myPrimaryLocator = primaryLocator; myLocators = Extensions.getExtensions(TestLocationProvider.EP_NAME); } @NotNull @Override public List<Location> getLocation(@NotNull String protocol, @NotNull String path, @NotNull Project project, @NotNull GlobalSearchScope scope) { boolean isDumbMode = DumbService.isDumb(project); if (myPrimaryLocator != null && (!isDumbMode || DumbService.isDumbAware(myPrimaryLocator))) { List<Location> locations = myPrimaryLocator.getLocation(protocol, path, project); if (!locations.isEmpty()) { return locations; } } if (URLUtil.FILE_PROTOCOL.equals(protocol)) { List<Location> locations = FileUrlProvider.INSTANCE.getLocation(protocol, path, project, scope); if (!locations.isEmpty()) { return locations; } } for (TestLocationProvider provider : myLocators) { if (!isDumbMode || DumbService.isDumbAware(provider)) { List<Location> locations = provider.getLocation(protocol, path, project); if (!locations.isEmpty()) { return locations; } } } return Collections.emptyList(); } } }
apache-2.0
google/gcnn-survey-paper
utils/train_utils.py
1447
#Copyright 2018 Google LLC # #Licensed under the Apache License, Version 2.0 (the "License"); #you may not use this file except in compliance with the License. #You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # #Unless required by applicable law or agreed to in writing, software #distributed under the License is distributed on an "AS IS" BASIS, #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #See the License for the specific language governing permissions and #limitations under the License. """Helper functions for training.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function def format_metrics(metrics, mode): """Format metrics for logging.""" result = '' for metric in metrics: result += '{}_{} = {:.4f} | '.format(mode, metric, float(metrics[metric])) return result def format_params(config): """Format training parameters for logging.""" result = '' for key, value in config.__dict__.items(): result += '{}={} \n '.format(key, str(value)) return result def check_improve(best_metrics, metrics, targets): """Checks if any of the target metrics improved.""" return [ compare(metrics[target], best_metrics[target], targets[target]) for target in targets ] def compare(x1, x2, increasing): if increasing == 1: return x1 >= x2 else: return x1 <= x2
apache-2.0
robert-bor/CSVeed
src/test/java/org/csveed/common/ColumnTest.java
2295
package org.csveed.common; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Map; import java.util.TreeMap; import org.csveed.api.Header; import org.csveed.report.CsvException; import org.csveed.row.HeaderImpl; import org.csveed.row.LineWithInfo; import org.junit.jupiter.api.Test; public class ColumnTest { @Test public void excelColumnToColumnIndex() { Column excel = new ColumnExcel("AH"); assertEquals(34, excel.getColumnIndex()); } @Test public void largestPossibleIndex() { Column excel = new ColumnExcel("ZZ"); assertEquals(702, excel.getColumnIndex()); } @Test public void columnIndexToExcelColumn() { Column excel = new Column(34); assertEquals("AH", excel.getExcelColumn()); } @Test public void wrongIndex() { assertThrows(CsvException.class, () -> { new Column(0); }); } @Test public void nextColumn() { Column column = new Column(3); assertEquals(4, column.nextColumn().getColumnIndex()); } @Test public void reset() { Column column = new Column(3); assertEquals(Column.FIRST_COLUMN_INDEX, column.nextLine().getColumnIndex()); } @Test public void equals() { assertEquals(new Column(3), new Column(3)); } @Test public void treeMap() { Map<Column, String> map = new TreeMap<>(); Column storeColumn = new Column("name"); map.put(storeColumn, "alpha"); LineWithInfo line = new LineWithInfo(); line.addCell("name"); Header header = new HeaderImpl(line); Column searchColumn = new Column().setHeader(header); assertNotNull(map.get(searchColumn)); } @Test public void treeMapWithColumnIndex() { Map<Column, String> map = new TreeMap<>(); map.put(new Column(1), "alpha"); map.put(new Column(2), "beta"); map.put(new Column(3), "gamma"); assertEquals("alpha", map.get(new Column(1))); assertEquals("beta", map.get(new Column(2))); assertEquals("gamma", map.get(new Column(3))); } }
apache-2.0
matt-royal/cf-acceptance-tests
assets/syslog-drain-listener/syslog_drain.go
842
package main import ( "fmt" "io" "net" "os" "time" ) func main() { go logIP() listenAddress := fmt.Sprintf(":%s", os.Getenv("PORT")) listener, err := net.Listen("tcp", listenAddress) if err != nil { panic(err) } fmt.Println("Listening for new connections") for { conn, err := listener.Accept() if err != nil { panic(err) } go handleConnection(conn) } } func handleConnection(conn net.Conn) { buffer := make([]byte, 65536) for { n, err := conn.Read(buffer) if err == io.EOF { fmt.Println("connection closed") return } else if err != nil { panic(err) } message := string(buffer[0:n]) fmt.Println(message) } } func logIP() { ip := os.Getenv("CF_INSTANCE_IP") port := os.Getenv("CF_INSTANCE_PORT") for { fmt.Printf("ADDRESS: |%s:%s|\n", ip, port) time.Sleep(5 * time.Second) } }
apache-2.0
criteo/zipkin4net
Src/zipkin4net/Tests/Utils/T_NumberUtils.cs
1848
using zipkin4net.Utils; using NUnit.Framework; namespace zipkin4net.UTest.Utils { [TestFixture] internal class T_NumberUtils { [Test] public void TransformationIsReversible() { const long longId = 150L; var guid = NumberUtils.LongToGuid(longId); var backToLongId = NumberUtils.GuidToLong(guid); Assert.AreEqual(longId, backToLongId); } [Test] public void LongIdLowerEncodingIsCorrect() { const long notEncodedLong = 170; const string expectedEncodedLong = "00000000000000aa"; var encodedLong = NumberUtils.EncodeLongToLowerHexString(notEncodedLong); Assert.AreEqual(expectedEncodedLong, encodedLong); } [Test] public void LongIdDecodingIsCorrect() { const string encodedLong = "00000000000000AA"; const long expectedLong = 170; var decodedLong = NumberUtils.DecodeHexString(encodedLong); Assert.AreEqual(expectedLong, decodedLong); } [Test] [Description("Check that encode is the inverse function of decode. In other words that x = encode(decode(x)) and y = decode(encode(y))")] public void IdEncodingDecodingGivesOriginalValues() { const long input = 10; var encoded = NumberUtils.EncodeLongToLowerHexString(input); var decoded = NumberUtils.DecodeHexString(encoded); Assert.AreEqual(input, decoded); const string encodedInput = "00000000000000aa"; var decodedInput = NumberUtils.DecodeHexString(encodedInput); var reEncodedInput = NumberUtils.EncodeLongToLowerHexString(decodedInput); Assert.AreEqual(encodedInput, reEncodedInput); } } }
apache-2.0
niks199/task1
Serialize and Deserialize Binary Tree Preorder.java
1876
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Codec { public void serializeImpl(TreeNode root, StringBuilder builder) { if (root == null) { builder.append("null"); builder.append(","); return; } builder.append(root.val); builder.append(","); serializeImpl(root.left, builder); serializeImpl(root.right, builder); } // Encodes a tree to a single string. public String serialize(TreeNode root) { StringBuilder builder = new StringBuilder(); serializeImpl(root, builder); if (builder.charAt(builder.length() - 1) == ',') { builder.deleteCharAt(builder.length() - 1); } return builder.toString(); } public TreeNode deserializeImpl(String[] tokens) { TreeNode root = null; if (readIndex < tokens.length) { int i = readIndex; ++readIndex; if (tokens[i].equals("null")) { return root; } root = new TreeNode( Integer.parseInt(tokens[i]) ); root.left = deserializeImpl(tokens); root.right = deserializeImpl(tokens); } return root; } int readIndex; // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if (data.isEmpty()) { return null; } final String[] tokens = data.split(","); readIndex = 0; return deserializeImpl(tokens); } }
apache-2.0
Mirieri/HelloGithub
app/src/ee/ioc/phon/android/speak/VoiceImeView.java
15072
package ee.ioc.phon.android.speak; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.speech.RecognitionListener; import android.speech.SpeechRecognizer; import android.util.AttributeSet; import android.util.Pair; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import ee.ioc.phon.android.speak.utils.PreferenceUtils; public class VoiceImeView extends LinearLayout { interface VoiceImeViewListener { void onPartialResult(String text); void onFinalResult(String text); void onSwitchIme(boolean isAskUser); void onGo(); void onDeleteLastWord(); void onAddNewline(); void onAddSpace(); } private MicButton mBImeStartStop; private ImageButton mBImeKeyboard; private ImageButton mBImeGo; private Button mBComboSelector; private TextView mTvInstruction; private TextView mTvMessage; private VoiceImeViewListener mListener; private SpeechRecognizer mRecognizer; private ServiceLanguageChooser mSlc; private Constants.State mState; public VoiceImeView(Context context, AttributeSet attrs) { super(context, attrs); } public void setListener(EditorInfo attribute, final VoiceImeViewListener listener) { mListener = listener; mBImeStartStop = (MicButton) findViewById(R.id.bImeStartStop); mBImeKeyboard = (ImageButton) findViewById(R.id.bImeKeyboard); mBImeGo = (ImageButton) findViewById(R.id.bImeGo); mBComboSelector = (Button) findViewById(R.id.tvComboSelector); mTvInstruction = (TextView) findViewById(R.id.tvInstruction); mTvMessage = (TextView) findViewById(R.id.tvMessage); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); // TODO: check for null? (test by deinstalling a recognizer but not changing K6nele settings) mSlc = new ServiceLanguageChooser(getContext(), prefs, attribute); if (mSlc.size() > 1) { mBComboSelector.setVisibility(View.VISIBLE); } else { mBComboSelector.setVisibility(View.GONE); } updateServiceLanguage(mSlc); setText(mTvMessage, ""); setGuiInitState(0); mBImeStartStop.setAudioCuesEnabled(PreferenceUtils.getPrefBoolean(prefs, getResources(), R.string.keyImeAudioCues, R.bool.defaultImeAudioCues)); if (PreferenceUtils.getPrefBoolean(prefs, getResources(), R.string.keyImeHelpText, R.bool.defaultImeHelpText)) { mTvInstruction.setVisibility(View.VISIBLE); } else { mTvInstruction.setVisibility(View.GONE); } // This button can be pressed in any state. mBImeStartStop.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.i("Microphone button pressed: state = " + mState); switch (mState) { case INIT: case ERROR: mRecognizer.startListening(mSlc.getIntent()); break; case RECORDING: mRecognizer.stopListening(); break; case LISTENING: case TRANSCRIBING: // We enter the INIT-state here, just in case cancel() does not take us there setGuiInitState(0); mRecognizer.cancel(); break; default: } } }); mBImeGo.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mListener.onGo(); } }); mBComboSelector.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mSlc.next(); updateServiceLanguage(mSlc); } }); mBComboSelector.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View view) { Context context = getContext(); Intent intent = new Intent(context, ComboSelectorActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Utils.startActivityIfAvailable(context, intent); return true; } }); mBImeKeyboard.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mListener.onSwitchIme(false); } }); mBImeKeyboard.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { mListener.onSwitchIme(true); return true; } }); setOnTouchListener(new OnSwipeTouchListener(getContext()) { @Override public void onSwipeLeft() { mListener.onDeleteLastWord(); } @Override public void onSwipeRight() { mListener.onAddNewline(); } @Override public void onDoubleTapMotion() { mListener.onAddSpace(); } }); } public void start() { if (mState == Constants.State.INIT || mState == Constants.State.ERROR) { // TODO: fix this //mRecognizer.startListening(mIntent); } } public void closeSession() { if (mRecognizer != null) { mRecognizer.cancel(); // TODO: maybe set to null } } private RecognitionListener getRecognizerListener() { return new RecognitionListener() { @Override public void onReadyForSpeech(Bundle params) { Log.i("onReadyForSpeech: state = " + mState); setGuiState(Constants.State.LISTENING); setText(mTvInstruction, R.string.buttonImeStop); setText(mTvMessage, ""); setVisibility(mBImeKeyboard, View.INVISIBLE); setVisibility(mBImeGo, View.INVISIBLE); setVisibility(mBComboSelector, View.INVISIBLE); } @Override public void onBeginningOfSpeech() { Log.i("onBeginningOfSpeech: state = " + mState); setGuiState(Constants.State.RECORDING); } @Override public void onEndOfSpeech() { Log.i("onEndOfSpeech: state = " + mState); // We go into the TRANSCRIBING-state only if we were in the RECORDING-state, // otherwise we ignore this event. This improves compatibility with // Google Voice Search, which calls EndOfSpeech after onResults. if (mState == Constants.State.RECORDING) { setGuiState(Constants.State.TRANSCRIBING); setText(mTvInstruction, R.string.statusImeTranscribing); } } /** * We process all possible SpeechRecognizer errors. Most of them * are generated by our implementation, others can be generated by the * framework, e.g. ERROR_CLIENT results from * "stopListening called with no preceding startListening". * * @param errorCode SpeechRecognizer error code */ @Override public void onError(final int errorCode) { Log.i("onError: " + errorCode); setGuiState(Constants.State.ERROR); switch (errorCode) { case SpeechRecognizer.ERROR_AUDIO: setGuiInitState(R.string.errorImeResultAudioError); break; case SpeechRecognizer.ERROR_RECOGNIZER_BUSY: setGuiInitState(R.string.errorImeResultRecognizerBusy); break; case SpeechRecognizer.ERROR_SERVER: setGuiInitState(R.string.errorImeResultServerError); break; case SpeechRecognizer.ERROR_NETWORK: setGuiInitState(R.string.errorImeResultNetworkError); break; case SpeechRecognizer.ERROR_NETWORK_TIMEOUT: setGuiInitState(R.string.errorImeResultNetworkTimeoutError); break; case SpeechRecognizer.ERROR_CLIENT: setGuiInitState(R.string.errorImeResultClientError); break; case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS: setGuiInitState(R.string.errorImeResultInsufficientPermissions); break; case SpeechRecognizer.ERROR_NO_MATCH: setGuiInitState(R.string.errorImeResultNoMatch); break; case SpeechRecognizer.ERROR_SPEECH_TIMEOUT: setGuiInitState(R.string.errorImeResultSpeechTimeout); break; default: Log.e("This might happen in future Android versions: code " + errorCode); setGuiInitState(R.string.errorImeResultClientError); } } @Override public void onPartialResults(final Bundle bundle) { Log.i("onPartialResults: state = " + mState); String text = selectSingleResult(bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)); if (text == null) { // This shouldn't really happen } else { // This can be true only with kaldi-gstreamer-server boolean isSemiFinal = bundle.getBoolean(Extras.EXTRA_SEMI_FINAL); if (isSemiFinal) { mListener.onFinalResult(text); } else { mListener.onPartialResult(text); } setText(mTvMessage, lastChars(text, isSemiFinal)); } } @Override public void onEvent(int eventType, Bundle params) { // TODO: future work: not sure how this can be generated by the service } @Override public void onResults(final Bundle bundle) { Log.i("onResults: state = " + mState); String text = selectSingleResult(bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)); if (text == null) { // If we got empty results then assume that the session ended, // e.g. cancel was called. mListener.onFinalResult(""); } else { mListener.onFinalResult(text); setText(mTvMessage, lastChars(text, true)); } setGuiInitState(0); } @Override public void onRmsChanged(float rmsdB) { //Log.i("onRmsChanged"); setMicButtonVolumeLevel(mBImeStartStop, rmsdB); } @Override public void onBufferReceived(byte[] buffer) { // TODO: future work } }; } private static String selectSingleResult(ArrayList<String> results) { if (results == null || results.size() < 1) { return null; } return results.get(0); } private void setGuiState(Constants.State state) { mState = state; setMicButtonState(mBImeStartStop, mState); } private void setGuiInitState(int message) { mState = Constants.State.INIT; setMicButtonState(mBImeStartStop, mState); setText(mTvInstruction, R.string.buttonImeSpeak); if (message == 0) { // Do not clear a possible error message //setText(mTvMessage, ""); } else { setText(mTvMessage, message); } setVisibility(mBImeKeyboard, View.VISIBLE); setVisibility(mBImeGo, View.VISIBLE); setVisibility(mBComboSelector, View.VISIBLE); } private static String lastChars(String str, boolean isFinal) { if (str == null) { str = ""; } else { str = str.replaceAll("\\n", "↲"); } if (isFinal) { return str + "▪"; } return str; } private static void setText(final TextView textView, final CharSequence text) { if (textView != null) { textView.post(new Runnable() { @Override public void run() { textView.setText(text); } }); } } private static void setText(final TextView textView, final int text) { if (textView != null) { textView.post(new Runnable() { @Override public void run() { textView.setText(text); } }); } } private static void setMicButtonVolumeLevel(final MicButton button, final float rmsdB) { if (button != null) { button.post(new Runnable() { @Override public void run() { button.setVolumeLevel(rmsdB); } }); } } private static void setMicButtonState(final MicButton button, final Constants.State state) { if (button != null) { button.post(new Runnable() { @Override public void run() { button.setState(state); } }); } } private static void setVisibility(final View view, final int visibility) { if (view != null && view.getVisibility() != View.GONE) { view.post(new Runnable() { @Override public void run() { view.setVisibility(visibility); } }); } } private void updateServiceLanguage(ServiceLanguageChooser slc) { // Cancel a possibly running service closeSession(); Pair<String, String> pair = Utils.getLabel(getContext(), slc.getCombo()); mBComboSelector.setText(pair.second + " @ " + pair.first); mRecognizer = slc.getSpeechRecognizer(); mRecognizer.setRecognitionListener(getRecognizerListener()); } }
apache-2.0
Vazkii/Emotes
MODSRC/vazkii/emotes/client/emote/base/EmoteState.java
840
package vazkii.emotes.client.emote.base; import net.minecraft.client.model.ModelBiped; public class EmoteState { float[] states = new float[0]; EmoteBase emote; public EmoteState(EmoteBase emote) { this.emote = emote; } public void save(ModelBiped model) { float[] values = new float[1]; for(int i = 0; i < ModelAccessor.STATE_COUNT; i++) { ModelAccessor.INSTANCE.getValues(model, i, values); states[i] = values[0]; } } public void load(ModelBiped model) { if(states.length == 0) { states = new float[ModelAccessor.STATE_COUNT]; return; } else { float[] values = new float[1]; for(int i = 0; i < ModelAccessor.STATE_COUNT; i++) { values[0] = states[i]; int part = i / 3 * 3; if(emote.usesBodyPart(part)) ModelAccessor.INSTANCE.setValues(model, i, values); } } } }
apache-2.0
SharedHealth/openmrs-module-bdshrclient
fhirmapper/src/main/java/org/openmrs/module/fhir/mapper/bundler/ProcedureFulfillmentMapper.java
3128
package org.openmrs.module.fhir.mapper.bundler; import org.hl7.fhir.dstu3.model.Identifier; import org.hl7.fhir.dstu3.model.Procedure; import org.hl7.fhir.dstu3.model.Resource; import org.openmrs.Obs; import org.openmrs.Order; import org.openmrs.module.fhir.mapper.model.*; import org.openmrs.module.shrclient.dao.IdMappingRepository; import org.openmrs.module.shrclient.model.IdMapping; import org.openmrs.module.shrclient.model.IdMappingType; import org.openmrs.module.shrclient.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Collections; import java.util.List; import static java.util.Arrays.asList; import static org.openmrs.module.fhir.MRSProperties.MRS_CONCEPT_PROCEDURES_TEMPLATE; @Component public class ProcedureFulfillmentMapper implements EmrObsResourceHandler { @Autowired private ProcedureMapper procedureMapper; @Autowired private IdMappingRepository idMappingRepository; @Override public boolean canHandle(Obs observation) { CompoundObservation procedureFulfillmentObs = new CompoundObservation(observation); if (!procedureFulfillmentObs.isOfType(ObservationType.PROCEDURE_FULFILLMENT)) return false; Obs procedureTemplate = procedureFulfillmentObs.getMemberObsForConceptName(MRS_CONCEPT_PROCEDURES_TEMPLATE); return (null != procedureTemplate); } @Override public List<FHIRResource> map(Obs obs, FHIREncounter fhirEncounter, SystemProperties systemProperties) { CompoundObservation procedureFulfillmentObs = new CompoundObservation(obs); Obs procedureTemplate = procedureFulfillmentObs.getMemberObsForConceptName(MRS_CONCEPT_PROCEDURES_TEMPLATE); List<FHIRResource> resources = procedureMapper.map(procedureTemplate, fhirEncounter, systemProperties); Procedure procedure = getProcedureForObs(resources); if (null == procedure) return Collections.emptyList(); setIdentifier(obs, systemProperties, procedure); setRequest(obs, procedure); return resources; } private Procedure getProcedureForObs(List<FHIRResource> resources) { for (FHIRResource iResource : resources) { Resource resource = iResource.getResource(); if (resource instanceof Procedure) return (Procedure) resource; } return null; } public void setRequest(Obs obs, Procedure procedure) { Order order = obs.getOrder(); IdMapping idMapping = idMappingRepository.findByInternalId(order.getUuid(), IdMappingType.PROCEDURE_REQUEST); if (idMapping != null) { procedure.addBasedOn().setReference(idMapping.getUri()); } } public void setIdentifier(Obs obs, SystemProperties systemProperties, Procedure procedure) { String id = new EntityReference().build(Obs.class, systemProperties, obs.getUuid()); Identifier identifierDt = procedure.addIdentifier(); identifierDt.setValue(id); procedure.setId(id); procedure.setIdentifier(asList(identifierDt)); } }
apache-2.0
torch2424/CrunchKey-Ionic
app/scripts/app.js
748
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' 'use strict'; angular.module('starter', ['ionic', 'starter.controllers', 'ngAnimate']) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if(window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if(window.StatusBar) { StatusBar.styleDefault(); } }); });
apache-2.0
ernestp/consulo
platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleDiffViewer.java
28887
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.tools.simple; import com.intellij.diff.DiffContext; import com.intellij.diff.actions.BufferedLineIterator; import com.intellij.diff.actions.NavigationContextChecker; import com.intellij.diff.comparison.DiffTooBigException; import com.intellij.diff.fragments.LineFragment; import com.intellij.diff.requests.ContentDiffRequest; import com.intellij.diff.requests.DiffRequest; import com.intellij.diff.tools.util.*; import com.intellij.diff.tools.util.base.HighlightPolicy; import com.intellij.diff.tools.util.base.TextDiffViewerUtil; import com.intellij.diff.tools.util.side.TwosideTextDiffViewer; import com.intellij.diff.util.*; import com.intellij.diff.util.DiffUserDataKeysEx.ScrollToPolicy; import com.intellij.diff.util.DiffUtil.DocumentData; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.diff.DiffNavigationContext; import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.UserDataHolder; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Function; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mustbe.consulo.RequiredDispatchThread; import org.mustbe.consulo.RequiredWriteAction; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.BitSet; import java.util.Iterator; import java.util.List; import static com.intellij.diff.util.DiffUtil.getLineCount; public class SimpleDiffViewer extends TwosideTextDiffViewer { public static final Logger LOG = Logger.getInstance(SimpleDiffViewer.class); @NotNull private final SyncScrollSupport.SyncScrollable mySyncScrollable; @NotNull private final PrevNextDifferenceIterable myPrevNextDifferenceIterable; @NotNull private final StatusPanel myStatusPanel; @NotNull private final List<SimpleDiffChange> myDiffChanges = new ArrayList<SimpleDiffChange>(); @NotNull private final List<SimpleDiffChange> myInvalidDiffChanges = new ArrayList<SimpleDiffChange>(); @NotNull private final MyFoldingModel myFoldingModel; @NotNull private final MyInitialScrollHelper myInitialScrollHelper = new MyInitialScrollHelper(); @NotNull private final ModifierProvider myModifierProvider; public SimpleDiffViewer(@NotNull DiffContext context, @NotNull DiffRequest request) { super(context, (ContentDiffRequest)request); mySyncScrollable = new MySyncScrollable(); myPrevNextDifferenceIterable = new MyPrevNextDifferenceIterable(); myStatusPanel = new MyStatusPanel(); myFoldingModel = new MyFoldingModel(getEditors(), this); myModifierProvider = new ModifierProvider(); } @Override @RequiredDispatchThread protected void onInit() { super.onInit(); myContentPanel.setPainter(new MyDividerPainter()); myModifierProvider.init(); } @Override @RequiredDispatchThread protected void onDispose() { destroyChangedBlocks(); super.onDispose(); } @NotNull @Override protected List<AnAction> createToolbarActions() { List<AnAction> group = new ArrayList<AnAction>(); group.add(new MyIgnorePolicySettingAction()); group.add(new MyHighlightPolicySettingAction()); group.add(new MyToggleExpandByDefaultAction()); group.add(new MyToggleAutoScrollAction()); group.add(new MyReadOnlyLockAction()); group.add(myEditorSettingsAction); return group; } @Nullable @Override protected List<AnAction> createPopupActions() { List<AnAction> group = new ArrayList<AnAction>(); group.add(AnSeparator.getInstance()); group.add(new MyIgnorePolicySettingAction().getPopupGroup()); group.add(AnSeparator.getInstance()); group.add(new MyHighlightPolicySettingAction().getPopupGroup()); group.add(AnSeparator.getInstance()); group.add(new MyToggleAutoScrollAction()); group.add(new MyToggleExpandByDefaultAction()); return group; } @NotNull @Override protected List<AnAction> createEditorPopupActions() { List<AnAction> group = new ArrayList<AnAction>(); group.add(new ReplaceSelectedChangesAction()); group.add(new AppendSelectedChangesAction()); group.add(new RevertSelectedChangesAction()); group.add(AnSeparator.getInstance()); group.addAll(super.createEditorPopupActions()); return group; } @Override @RequiredDispatchThread protected void processContextHints() { super.processContextHints(); myInitialScrollHelper.processContext(myRequest); } @Override @RequiredDispatchThread protected void updateContextHints() { super.updateContextHints(); myFoldingModel.updateContext(myRequest, getFoldingModelSettings()); myInitialScrollHelper.updateContext(myRequest); } // // Diff // @NotNull public FoldingModelSupport.Settings getFoldingModelSettings() { return TextDiffViewerUtil.getFoldingModelSettings(myContext); } @Override protected void onSlowRediff() { super.onSlowRediff(); myStatusPanel.setBusy(true); myInitialScrollHelper.onSlowRediff(); } @Override @NotNull protected Runnable performRediff(@NotNull final ProgressIndicator indicator) { try { indicator.checkCanceled(); final Document document1 = getContent1().getDocument(); final Document document2 = getContent2().getDocument(); DocumentData data = ApplicationManager.getApplication().runReadAction(new Computable<DocumentData>() { @Override public DocumentData compute() { return new DocumentData(document1.getImmutableCharSequence(), document2.getImmutableCharSequence(), document1.getModificationStamp(), document2.getModificationStamp()); } }); List<LineFragment> lineFragments = null; if (getHighlightPolicy().isShouldCompare()) { lineFragments = DiffUtil.compareWithCache(myRequest, data, getDiffConfig(), indicator); } boolean isEqualContents = (lineFragments == null || lineFragments.isEmpty()) && StringUtil.equals(document1.getCharsSequence(), document2.getCharsSequence()); return apply(new CompareData(lineFragments, isEqualContents)); } catch (DiffTooBigException e) { return applyNotification(DiffNotifications.DIFF_TOO_BIG); } catch (ProcessCanceledException e) { throw e; } catch (Throwable e) { LOG.error(e); return applyNotification(DiffNotifications.ERROR); } } @NotNull private Runnable apply(@NotNull final CompareData data) { return new Runnable() { @Override public void run() { myFoldingModel.updateContext(myRequest, getFoldingModelSettings()); clearDiffPresentation(); if (data.isEqualContent()) myPanel.addNotification(DiffNotifications.EQUAL_CONTENTS); if (data.getFragments() != null) { for (LineFragment fragment : data.getFragments()) { myDiffChanges.add(new SimpleDiffChange(SimpleDiffViewer.this, fragment, getHighlightPolicy().isFineFragments())); } } myFoldingModel.install(data.getFragments(), myRequest, getFoldingModelSettings()); myInitialScrollHelper.onRediff(); myContentPanel.repaintDivider(); myStatusPanel.update(); } }; } @NotNull private Runnable applyNotification(@Nullable final JComponent notification) { return new Runnable() { @Override public void run() { clearDiffPresentation(); if (notification != null) myPanel.addNotification(notification); } }; } private void clearDiffPresentation() { myStatusPanel.setBusy(false); myPanel.resetNotifications(); destroyChangedBlocks(); } @NotNull private DiffUtil.DiffConfig getDiffConfig() { return new DiffUtil.DiffConfig(getTextSettings().getIgnorePolicy(), getHighlightPolicy()); } @NotNull private HighlightPolicy getHighlightPolicy() { return getTextSettings().getHighlightPolicy(); } // // Impl // private void destroyChangedBlocks() { for (SimpleDiffChange change : myDiffChanges) { change.destroyHighlighter(); } myDiffChanges.clear(); for (SimpleDiffChange change : myInvalidDiffChanges) { change.destroyHighlighter(); } myInvalidDiffChanges.clear(); myFoldingModel.destroy(); myContentPanel.repaintDivider(); myStatusPanel.update(); } @Override @RequiredDispatchThread protected void onBeforeDocumentChange(@NotNull DocumentEvent e) { super.onBeforeDocumentChange(e); if (myDiffChanges.isEmpty()) return; Side side = null; if (e.getDocument() == getEditor(Side.LEFT).getDocument()) side = Side.LEFT; if (e.getDocument() == getEditor(Side.RIGHT).getDocument()) side = Side.RIGHT; if (side == null) { LOG.warn("Unknown document changed"); return; } int line1 = e.getDocument().getLineNumber(e.getOffset()); int line2 = e.getDocument().getLineNumber(e.getOffset() + e.getOldLength()) + 1; int shift = DiffUtil.countLinesShift(e); List<SimpleDiffChange> invalid = new ArrayList<SimpleDiffChange>(); for (SimpleDiffChange change : myDiffChanges) { if (change.processChange(line1, line2, shift, side)) { invalid.add(change); } } if (!invalid.isEmpty()) { myDiffChanges.removeAll(invalid); myInvalidDiffChanges.addAll(invalid); } } @Override protected void onDocumentChange(@NotNull DocumentEvent e) { super.onDocumentChange(e); myFoldingModel.onDocumentChanged(e); } @RequiredDispatchThread protected boolean doScrollToChange(@NotNull ScrollToPolicy scrollToPolicy) { SimpleDiffChange targetChange = scrollToPolicy.select(myDiffChanges); if (targetChange == null) return false; doScrollToChange(targetChange, false); return true; } private void doScrollToChange(@NotNull SimpleDiffChange change, final boolean animated) { final int line1 = change.getStartLine(Side.LEFT); final int line2 = change.getStartLine(Side.RIGHT); final int endLine1 = change.getEndLine(Side.LEFT); final int endLine2 = change.getEndLine(Side.RIGHT); DiffUtil.moveCaret(getEditor1(), line1); DiffUtil.moveCaret(getEditor2(), line2); getSyncScrollSupport().makeVisible(getCurrentSide(), line1, endLine1, line2, endLine2, animated); } protected boolean doScrollToContext(@NotNull DiffNavigationContext context) { ChangedLinesIterator changedLinesIterator = new ChangedLinesIterator(Side.RIGHT); NavigationContextChecker checker = new NavigationContextChecker(changedLinesIterator, context); int line = checker.contextMatchCheck(); if (line == -1) { // this will work for the case, when spaces changes are ignored, and corresponding fragments are not reported as changed // just try to find target line -> +- AllLinesIterator allLinesIterator = new AllLinesIterator(Side.RIGHT); NavigationContextChecker checker2 = new NavigationContextChecker(allLinesIterator, context); line = checker2.contextMatchCheck(); } if (line == -1) return false; scrollToLine(Side.RIGHT, line); return true; } // // Getters // @NotNull protected List<SimpleDiffChange> getDiffChanges() { return myDiffChanges; } @NotNull @Override protected SyncScrollSupport.SyncScrollable getSyncScrollable() { return mySyncScrollable; } @NotNull @Override protected JComponent getStatusPanel() { return myStatusPanel; } @NotNull public ModifierProvider getModifierProvider() { return myModifierProvider; } @NotNull @Override public SyncScrollSupport.TwosideSyncScrollSupport getSyncScrollSupport() { //noinspection ConstantConditions return super.getSyncScrollSupport(); } // // Misc // @SuppressWarnings("MethodOverridesStaticMethodOfSuperclass") public static boolean canShowRequest(@NotNull DiffContext context, @NotNull DiffRequest request) { return TwosideTextDiffViewer.canShowRequest(context, request); } @NotNull @RequiredDispatchThread private List<SimpleDiffChange> getSelectedChanges(@NotNull Side side) { final BitSet lines = DiffUtil.getSelectedLines(getEditor(side)); List<SimpleDiffChange> affectedChanges = new ArrayList<SimpleDiffChange>(); for (int i = myDiffChanges.size() - 1; i >= 0; i--) { SimpleDiffChange change = myDiffChanges.get(i); int line1 = change.getStartLine(side); int line2 = change.getEndLine(side); if (DiffUtil.isSelectedByLine(lines, line1, line2)) { affectedChanges.add(change); } } return affectedChanges; } @Nullable @RequiredDispatchThread private SimpleDiffChange getSelectedChange(@NotNull Side side) { int caretLine = getEditor(side).getCaretModel().getLogicalPosition().line; for (SimpleDiffChange change : myDiffChanges) { int line1 = change.getStartLine(side); int line2 = change.getEndLine(side); if (DiffUtil.isSelectedByLine(caretLine, line1, line2)) return change; } return null; } // // Actions // private class MyPrevNextDifferenceIterable extends PrevNextDifferenceIterableBase<SimpleDiffChange> { @NotNull @Override protected List<SimpleDiffChange> getChanges() { return myDiffChanges; } @NotNull @Override protected EditorEx getEditor() { return getCurrentEditor(); } @Override protected int getStartLine(@NotNull SimpleDiffChange change) { return change.getStartLine(getCurrentSide()); } @Override protected int getEndLine(@NotNull SimpleDiffChange change) { return change.getEndLine(getCurrentSide()); } @Override protected void scrollToChange(@NotNull SimpleDiffChange change) { doScrollToChange(change, true); } } private class MyReadOnlyLockAction extends TextDiffViewerUtil.EditorReadOnlyLockAction { public MyReadOnlyLockAction() { super(getContext(), getEditableEditors()); } @Override protected void doApply(boolean readOnly) { super.doApply(readOnly); for (SimpleDiffChange change : myDiffChanges) { change.updateGutterActions(true); } } } // // Modification operations // private abstract class ApplySelectedChangesActionBase extends AnAction implements DumbAware { private final boolean myModifyOpposite; public ApplySelectedChangesActionBase(@Nullable String text, @Nullable String description, @Nullable Icon icon, boolean modifyOpposite) { super(text, description, icon); myModifyOpposite = modifyOpposite; } @Override public void update(@NotNull AnActionEvent e) { Editor editor = e.getData(CommonDataKeys.EDITOR); if (editor != getEditor1() && editor != getEditor2()) { e.getPresentation().setEnabledAndVisible(false); return; } Side side = Side.fromLeft(editor == getEditor(Side.LEFT)); Editor modifiedEditor = getEditor(side.other(myModifyOpposite)); if (!DiffUtil.isEditable(modifiedEditor)) { e.getPresentation().setEnabledAndVisible(false); return; } e.getPresentation().setIcon(getIcon(side)); e.getPresentation().setVisible(true); e.getPresentation().setEnabled(isSomeChangeSelected(side)); } @Override public void actionPerformed(@NotNull final AnActionEvent e) { Editor editor = e.getRequiredData(CommonDataKeys.EDITOR); final Side side = Side.fromLeft(editor == getEditor(Side.LEFT)); final List<SimpleDiffChange> selectedChanges = getSelectedChanges(side); Editor modifiedEditor = getEditor(side.other(myModifyOpposite)); String title = e.getPresentation().getText() + " selected changes"; DiffUtil.executeWriteCommand(modifiedEditor.getDocument(), e.getProject(), title, new Runnable() { @Override public void run() { apply(side, selectedChanges); } }); } protected boolean isSomeChangeSelected(@NotNull Side side) { if (myDiffChanges.isEmpty()) return false; EditorEx editor = getEditor(side); List<Caret> carets = editor.getCaretModel().getAllCarets(); if (carets.size() != 1) return true; Caret caret = carets.get(0); if (caret.hasSelection()) return true; int line = editor.getDocument().getLineNumber(editor.getExpectedCaretOffset()); for (SimpleDiffChange change : myDiffChanges) { if (change.isSelectedByLine(line, side)) return true; } return false; } @NotNull protected abstract Icon getIcon(@NotNull Side side); @RequiredWriteAction protected abstract void apply(@NotNull Side side, @NotNull List<SimpleDiffChange> changes); } private class ReplaceSelectedChangesAction extends ApplySelectedChangesActionBase { public ReplaceSelectedChangesAction() { super("Replace", null, AllIcons.Diff.Arrow, true); } @NotNull @Override protected Icon getIcon(@NotNull Side side) { return side.isLeft() ? AllIcons.Diff.ArrowRight : AllIcons.Diff.Arrow; } @Override protected void apply(@NotNull Side side, @NotNull List<SimpleDiffChange> changes) { for (SimpleDiffChange change : changes) { replaceChange(change, side); } } } private class AppendSelectedChangesAction extends ApplySelectedChangesActionBase { public AppendSelectedChangesAction() { super("Insert", null, AllIcons.Diff.ArrowLeftDown, true); } @NotNull @Override protected Icon getIcon(@NotNull Side side) { return side.isLeft() ? AllIcons.Diff.ArrowRightDown : AllIcons.Diff.ArrowLeftDown; } @Override protected void apply(@NotNull Side side, @NotNull List<SimpleDiffChange> changes) { for (SimpleDiffChange change : changes) { appendChange(change, side); } } } private class RevertSelectedChangesAction extends ApplySelectedChangesActionBase { public RevertSelectedChangesAction() { super("Revert", null, AllIcons.Diff.Remove, false); } @NotNull @Override protected Icon getIcon(@NotNull Side side) { return AllIcons.Diff.Remove; } @Override protected void apply(@NotNull Side side, @NotNull List<SimpleDiffChange> changes) { for (SimpleDiffChange change : changes) { replaceChange(change, side.other()); } } } @RequiredWriteAction public void replaceChange(@NotNull SimpleDiffChange change, @NotNull final Side sourceSide) { if (!change.isValid()) return; Side outputSide = sourceSide.other(); DiffUtil.applyModification(getEditor(outputSide).getDocument(), change.getStartLine(outputSide), change.getEndLine(outputSide), getEditor(sourceSide).getDocument(), change.getStartLine(sourceSide), change.getEndLine(sourceSide)); change.destroyHighlighter(); myDiffChanges.remove(change); } @RequiredWriteAction public void appendChange(@NotNull SimpleDiffChange change, @NotNull final Side sourceSide) { if (!change.isValid()) return; if (change.getStartLine(sourceSide) == change.getEndLine(sourceSide)) return; Side outputSide = sourceSide.other(); DiffUtil.applyModification(getEditor(outputSide).getDocument(), change.getEndLine(outputSide), change.getEndLine(outputSide), getEditor(sourceSide).getDocument(), change.getStartLine(sourceSide), change.getEndLine(sourceSide)); change.destroyHighlighter(); myDiffChanges.remove(change); } private class MyHighlightPolicySettingAction extends TextDiffViewerUtil.HighlightPolicySettingAction { public MyHighlightPolicySettingAction() { super(getTextSettings()); } @Override protected void onSettingsChanged() { rediff(); } } private class MyIgnorePolicySettingAction extends TextDiffViewerUtil.IgnorePolicySettingAction { public MyIgnorePolicySettingAction() { super(getTextSettings()); } @Override protected void onSettingsChanged() { rediff(); } } private class MyToggleExpandByDefaultAction extends TextDiffViewerUtil.ToggleExpandByDefaultAction { public MyToggleExpandByDefaultAction() { super(getTextSettings()); } @Override protected void expandAll(boolean expand) { myFoldingModel.expandAll(expand); } } // // Scroll from annotate // private class AllLinesIterator implements Iterator<Pair<Integer, CharSequence>> { @NotNull private final Side mySide; @NotNull private final Document myDocument; private int myLine = 0; private AllLinesIterator(@NotNull Side side) { mySide = side; myDocument = getEditor(mySide).getDocument(); } @Override public boolean hasNext() { return myLine < getLineCount(myDocument); } @Override public Pair<Integer, CharSequence> next() { int offset1 = myDocument.getLineStartOffset(myLine); int offset2 = myDocument.getLineEndOffset(myLine); CharSequence text = myDocument.getImmutableCharSequence().subSequence(offset1, offset2); Pair<Integer, CharSequence> pair = new Pair<Integer, CharSequence>(myLine, text); myLine++; return pair; } @Override public void remove() { throw new UnsupportedOperationException(); } } private class ChangedLinesIterator extends BufferedLineIterator { @NotNull private final Side mySide; private int myIndex = 0; private ChangedLinesIterator(@NotNull Side side) { mySide = side; init(); } @Override public boolean hasNextBlock() { return myIndex < myDiffChanges.size(); } @Override public void loadNextBlock() { SimpleDiffChange change = myDiffChanges.get(myIndex); myIndex++; int line1 = change.getStartLine(mySide); int line2 = change.getEndLine(mySide); Document document = getEditor(mySide).getDocument(); for (int i = line1; i < line2; i++) { int offset1 = document.getLineStartOffset(i); int offset2 = document.getLineEndOffset(i); CharSequence text = document.getImmutableCharSequence().subSequence(offset1, offset2); addLine(i, text); } } } // // Helpers // @Nullable @Override public Object getData(@NonNls String dataId) { if (DiffDataKeys.PREV_NEXT_DIFFERENCE_ITERABLE.is(dataId)) { return myPrevNextDifferenceIterable; } else if (DiffDataKeys.CURRENT_CHANGE_RANGE.is(dataId)) { SimpleDiffChange change = getSelectedChange(getCurrentSide()); if (change != null) { return new LineRange(change.getStartLine(getCurrentSide()), change.getEndLine(getCurrentSide())); } } return super.getData(dataId); } private class MySyncScrollable extends BaseSyncScrollable { @Override public boolean isSyncScrollEnabled() { return getTextSettings().isEnableSyncScroll(); } public int transfer(@NotNull Side baseSide, int line) { if (myDiffChanges.isEmpty()) { return line; } return super.transfer(baseSide, line); } @Override protected void processHelper(@NotNull ScrollHelper helper) { if (!helper.process(0, 0)) return; for (SimpleDiffChange diffChange : myDiffChanges) { if (!helper.process(diffChange.getStartLine(Side.LEFT), diffChange.getStartLine(Side.RIGHT))) return; if (!helper.process(diffChange.getEndLine(Side.LEFT), diffChange.getEndLine(Side.RIGHT))) return; } helper.process(getEditor1().getDocument().getLineCount(), getEditor2().getDocument().getLineCount()); } } private class MyDividerPainter implements DiffSplitter.Painter, DiffDividerDrawUtil.DividerPaintable { @Override public void paint(@NotNull Graphics g, @NotNull JComponent divider) { Graphics2D gg = DiffDividerDrawUtil.getDividerGraphics(g, divider, getEditor1().getComponent()); gg.setColor(DiffDrawUtil.getDividerColor(getEditor1())); gg.fill(gg.getClipBounds()); //DividerPolygonUtil.paintSimplePolygons(gg, divider.getWidth(), getEditor1(), getEditor2(), this); DiffDividerDrawUtil.paintPolygons(gg, divider.getWidth(), getEditor1(), getEditor2(), this); myFoldingModel.paintOnDivider(gg, divider); gg.dispose(); } @Override public void process(@NotNull Handler handler) { for (SimpleDiffChange diffChange : myDiffChanges) { if (!handler.process(diffChange.getStartLine(Side.LEFT), diffChange.getEndLine(Side.LEFT), diffChange.getStartLine(Side.RIGHT), diffChange.getEndLine(Side.RIGHT), diffChange.getDiffType().getColor(getEditor1()))) { return; } } } } private class MyStatusPanel extends StatusPanel { @Override protected int getChangesCount() { return myDiffChanges.size() + myInvalidDiffChanges.size(); } } private static class CompareData { @Nullable private final List<LineFragment> myFragments; private final boolean myEqualContent; public CompareData(@Nullable List<LineFragment> fragments, boolean equalContent) { myFragments = fragments; myEqualContent = equalContent; } @Nullable public List<LineFragment> getFragments() { return myFragments; } public boolean isEqualContent() { return myEqualContent; } } public class ModifierProvider extends KeyboardModifierListener { public void init() { init(myPanel, SimpleDiffViewer.this); } @Override public void onModifiersChanged() { for (SimpleDiffChange change : myDiffChanges) { change.updateGutterActions(false); } } } private static class MyFoldingModel extends FoldingModelSupport { private final MyPaintable myPaintable = new MyPaintable(0, 1); public MyFoldingModel(@NotNull List<? extends EditorEx> editors, @NotNull Disposable disposable) { super(editors.toArray(new EditorEx[2]), disposable); } public void install(@Nullable final List<LineFragment> fragments, @NotNull UserDataHolder context, @NotNull FoldingModelSupport.Settings settings) { Iterator<int[]> it = map(fragments, new Function<LineFragment, int[]>() { @Override public int[] fun(LineFragment fragment) { return new int[]{ fragment.getStartLine1(), fragment.getEndLine1(), fragment.getStartLine2(), fragment.getEndLine2()}; } }); install(it, context, settings); } public void paintOnDivider(@NotNull Graphics2D gg, @NotNull Component divider) { myPaintable.paintOnDivider(gg, divider); } } private class MyInitialScrollHelper extends MyInitialScrollPositionHelper { @Override protected boolean doScrollToChange() { if (myScrollToChange == null) return false; return SimpleDiffViewer.this.doScrollToChange(myScrollToChange); } @Override protected boolean doScrollToFirstChange() { return SimpleDiffViewer.this.doScrollToChange(ScrollToPolicy.FIRST_CHANGE); } @Override protected boolean doScrollToContext() { if (myNavigationContext == null) return false; return SimpleDiffViewer.this.doScrollToContext(myNavigationContext); } } }
apache-2.0
sigitm/musichub
src/main/java/it/musichub/server/config/Required.java
300
package it.musichub.server.config; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(RUNTIME) @Target(FIELD) @interface Required { }
apache-2.0
XiaoMi/linden
linden-core/src/main/java/com/xiaomi/linden/core/search/query/QueryStringQueryConstructor.java
2371
// Copyright 2016 Xiaomi, 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. package com.xiaomi.linden.core.search.query; import java.io.IOException; import com.google.common.base.Throwables; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Query; import com.xiaomi.linden.core.LindenConfig; import com.xiaomi.linden.thrift.common.LindenQuery; import com.xiaomi.linden.thrift.common.LindenQueryStringQuery; import com.xiaomi.linden.thrift.common.Operator; public class QueryStringQueryConstructor extends QueryConstructor { @Override protected Query construct(LindenQuery lindenQuery, LindenConfig config) throws IOException { LindenQueryStringQuery stringQuery = lindenQuery.getQueryString(); QueryParser.Operator op = QueryParser.Operator.OR; if (stringQuery.isSetOperator() && stringQuery.getOperator() == Operator.AND) { op = QueryParser.Operator.AND; } QueryParser queryParser = new LindenQueryParser(config); String content = stringQuery.getQuery(); try { queryParser.setDefaultOperator(op); Query query = queryParser.parse(content); // disable coord if (query instanceof BooleanQuery) { BooleanQuery bQuery = (BooleanQuery) query; BooleanQuery booleanQuery = new BooleanQuery(stringQuery.isDisableCoord()); BooleanClause[] clauses = bQuery.getClauses(); for (BooleanClause clause : clauses) { booleanQuery.add(clause); } booleanQuery.setBoost(query.getBoost()); query = booleanQuery; } return query; } catch (ParseException e) { throw new IOException(Throwables.getStackTraceAsString(e)); } } }
apache-2.0
binout/pokemon-go
src/main/java/io/github/binout/pokemongo/domain/formula/LevelData.java
1996
/* * Copyright 2016 Benoît Prioux * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.binout.pokemongo.domain.formula; import io.github.binout.pokemongo.infrastructure.DataLoader; import java.util.Arrays; import java.util.Comparator; import java.util.stream.IntStream; public class LevelData { private static LevelData[] ALL; static LevelData[] all() { if (ALL == null) { ALL = DataLoader.fromFile("levelUpData.json").fromJson(LevelData[].class); } return ALL; } static double maxScalar() { return Arrays.stream(all()).max(Comparator.comparing(LevelData::getLevel)).map(LevelData::getCpScalar).orElseThrow(RuntimeException::new); } public static IntStream allDusts() { return Arrays.stream(all()).mapToInt(l -> l.dust).distinct(); } private double level; private int dust; private int candy; private double cpScalar; public double getLevel() { return level; } public void setLevel(double level) { this.level = level; } public int getDust() { return dust; } public void setDust(int dust) { this.dust = dust; } public int getCandy() { return candy; } public void setCandy(int candy) { this.candy = candy; } public double getCpScalar() { return cpScalar; } public void setCpScalar(double cpScalar) { this.cpScalar = cpScalar; } }
apache-2.0
stack-this/hunter-price
app/cache/prod/doctrine/orm/Proxies/__CG__HunterBundleEntityStoreProduct.php
6798
<?php namespace Proxies\__CG__\HunterBundle\Entity; /** * DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR */ class StoreProduct extends \HunterBundle\Entity\StoreProduct implements \Doctrine\ORM\Proxy\Proxy { /** * @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with * three parameters, being respectively the proxy object to be initialized, the method that triggered the * initialization process and an array of ordered parameters that were passed to that method. * * @see \Doctrine\Common\Persistence\Proxy::__setInitializer */ public $__initializer__; /** * @var \Closure the callback responsible of loading properties that need to be copied in the cloned object * * @see \Doctrine\Common\Persistence\Proxy::__setCloner */ public $__cloner__; /** * @var boolean flag indicating if this object was already initialized * * @see \Doctrine\Common\Persistence\Proxy::__isInitialized */ public $__isInitialized__ = false; /** * @var array properties to be lazy loaded, with keys being the property * names and values being their default values * * @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties */ public static $lazyPropertiesDefaults = []; /** * @param \Closure $initializer * @param \Closure $cloner */ public function __construct($initializer = null, $cloner = null) { $this->__initializer__ = $initializer; $this->__cloner__ = $cloner; } /** * * @return array */ public function __sleep() { if ($this->__isInitialized__) { return ['__isInitialized__', '' . "\0" . 'HunterBundle\\Entity\\StoreProduct' . "\0" . 'id', '' . "\0" . 'HunterBundle\\Entity\\StoreProduct' . "\0" . 'id_store', '' . "\0" . 'HunterBundle\\Entity\\StoreProduct' . "\0" . 'id_product', '' . "\0" . 'HunterBundle\\Entity\\StoreProduct' . "\0" . 'price']; } return ['__isInitialized__', '' . "\0" . 'HunterBundle\\Entity\\StoreProduct' . "\0" . 'id', '' . "\0" . 'HunterBundle\\Entity\\StoreProduct' . "\0" . 'id_store', '' . "\0" . 'HunterBundle\\Entity\\StoreProduct' . "\0" . 'id_product', '' . "\0" . 'HunterBundle\\Entity\\StoreProduct' . "\0" . 'price']; } /** * */ public function __wakeup() { if ( ! $this->__isInitialized__) { $this->__initializer__ = function (StoreProduct $proxy) { $proxy->__setInitializer(null); $proxy->__setCloner(null); $existingProperties = get_object_vars($proxy); foreach ($proxy->__getLazyProperties() as $property => $defaultValue) { if ( ! array_key_exists($property, $existingProperties)) { $proxy->$property = $defaultValue; } } }; } } /** * */ public function __clone() { $this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', []); } /** * Forces initialization of the proxy */ public function __load() { $this->__initializer__ && $this->__initializer__->__invoke($this, '__load', []); } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __isInitialized() { return $this->__isInitialized__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setInitialized($initialized) { $this->__isInitialized__ = $initialized; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setInitializer(\Closure $initializer = null) { $this->__initializer__ = $initializer; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __getInitializer() { return $this->__initializer__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setCloner(\Closure $cloner = null) { $this->__cloner__ = $cloner; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific cloning logic */ public function __getCloner() { return $this->__cloner__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic * @static */ public function __getLazyProperties() { return self::$lazyPropertiesDefaults; } /** * {@inheritDoc} */ public function getId() { if ($this->__isInitialized__ === false) { return (int) parent::getId(); } $this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', []); return parent::getId(); } /** * {@inheritDoc} */ public function setPrice($price) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setPrice', [$price]); return parent::setPrice($price); } /** * {@inheritDoc} */ public function getPrice() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getPrice', []); return parent::getPrice(); } /** * {@inheritDoc} */ public function setIdStore(\HunterBundle\Entity\Store $idStore = NULL) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setIdStore', [$idStore]); return parent::setIdStore($idStore); } /** * {@inheritDoc} */ public function getIdStore() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getIdStore', []); return parent::getIdStore(); } /** * {@inheritDoc} */ public function setIdProduct(\HunterBundle\Entity\Product $idProduct = NULL) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setIdProduct', [$idProduct]); return parent::setIdProduct($idProduct); } /** * {@inheritDoc} */ public function getIdProduct() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getIdProduct', []); return parent::getIdProduct(); } }
apache-2.0
KaduAmaral/Base
base/core/request/globals.class.php
265
<?php namespace Core\Request; class Globals extends Vars { public function __construct() { foreach ($GLOBALS as $key => $val) { $this->__set($key, $val); } } public function onSet($key, $val) { $GLOBALS[$key] = $val; } }
apache-2.0
timofeysie/catechis
test/org/catechis/file/FileWordCategoriesManagerTest.java
30112
package org.catechis.file; /* Copyright 2006 Timothy Curchod 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 java.io.File; import java.io.IOException; import java.util.Enumeration; import java.util.Properties; import java.util.Vector; import java.util.Hashtable; import java.util.ArrayList; import junit.framework.TestCase; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletContext; import org.catechis.dto.SimpleWord; import org.catechis.dto.WeeklyReport; import org.catechis.dto.Word; import org.catechis.dto.Test; import org.catechis.dto.WordCategory; import org.catechis.dto.WordTestDates; import org.catechis.dto.WordTestResult; import org.catechis.dto.WordLastTestDates; import org.catechis.file.WordNextTestDates; import org.catechis.juksong.TestDateEvaluator; import org.catechis.lists.Sarray; import org.catechis.lists.Sortable; import org.catechis.JDOMSolution; import org.catechis.Transformer; import org.catechis.WordTestDateUtility; import org.catechis.Domartin; import org.catechis.Storage; import org.catechis.FileStorage; import org.catechis.admin.JDOMFiles; import org.catechis.constants.Constants;; public class FileWordCategoriesManagerTest extends TestCase { public FileWordCategoriesManagerTest(String name) { super(name); } public void testAddWordCategory() { //System.out.println("FileWordCategoriesManagerTest.AddWordCategory"); String user_id = new String("new"); File path_file = new File(""); String current_dir = path_file.getAbsolutePath(); String action_time = Long.toString(new Date().getTime()); String subject = Constants.VOCAB; String encoding = "euc-kr"; WordCategory word_cat = new WordCategory(); word_cat.setCategoryType(Constants.EXCLUSIVE); word_cat.setName("Test"); FileWordCategoriesManager fwcm = new FileWordCategoriesManager(); long cat_id = fwcm.addWordCategory(word_cat, user_id, subject, current_dir, encoding); WordCategory cat = fwcm.getWordCategory(cat_id, user_id, subject, current_dir); long expected_id = cat_id; long actual_id = cat.getId(); boolean done = fwcm.deleteCategory(actual_id, user_id, subject, current_dir, encoding); //System.out.println("done? "+done); //printLog(fwcm.getLog()); assertEquals(expected_id, actual_id); } public void testAddWordCategoryWithWords() { //System.out.println("FileWordCategoriesManagerTest.testAddWordCategoryWithWords"); String user_id = new String("new"); File path_file = new File(""); String current_dir = path_file.getAbsolutePath(); String action_time = Long.toString(new Date().getTime()); String subject = Constants.VOCAB; String encoding = "euc-kr"; WordCategory word_cat = new WordCategory(); word_cat.setCategoryType(Constants.EXCLUSIVE); word_cat.setName("Test"); Vector category_words = new Vector(); SimpleWord simple_word1 = new SimpleWord(); simple_word1.setDefinition("def1"); simple_word1.setText("text1"); simple_word1.setWordId(1); simple_word1.setWordPath("test.xml"); category_words.add(simple_word1); // add word 1 SimpleWord simple_word2 = new SimpleWord(); simple_word2.setDefinition("def2"); simple_word2.setText("text2"); simple_word2.setWordId(2); simple_word2.setWordPath("test.xml"); category_words.add(simple_word2); // add word 2 word_cat.setCategoryWords(category_words); //System.out.println("calculated number of words: "+word_cat.calculateTotalWords()); FileWordCategoriesManager fwcm = new FileWordCategoriesManager(); long cat_id = fwcm.addWordCategory(word_cat, user_id, subject, current_dir, encoding); WordCategory returned_cat = fwcm.getWordCategory(cat_id, user_id, subject, current_dir); long expected_number_of_words = +word_cat.calculateTotalWords(); long actual_number_of_words = returned_cat.calculateTotalWords(); boolean done = fwcm.deleteCategory(cat_id, user_id, subject, current_dir, encoding); //System.out.println("done? "+done); //printLog(fwcm.getLog()); assertEquals(expected_number_of_words, actual_number_of_words); } public void testGetWordCategoryNames() { //System.out.println("FileWordCategoriesManagerTest.testGetWordCategoryNames"); String user_id = new String("new"); File path_file = new File(""); String current_dir = path_file.getAbsolutePath(); String action_time = Long.toString(new Date().getTime()); String subject = Constants.VOCAB; String encoding = "euc-kr"; FileWordCategoriesManager fwcm = new FileWordCategoriesManager(); Vector word_cats = fwcm.getWordCategoryNames(user_id, subject, current_dir); int expected_number_of_cats = 3; int actual_number_of_cats = word_cats.size(); //System.out.println("categories --------------------------"); //printCategories(word_cats); //System.out.println("log ---------------------------------"); //printLog(fwcm.getLog()); assertEquals(expected_number_of_cats, actual_number_of_cats); } public void testGetExclusiveWordCategoryNames() { //System.out.println("FileWordCategoriesManagerTest.testGetWordCategoryNames"); String user_id = new String("new"); File path_file = new File(""); String current_dir = path_file.getAbsolutePath(); String action_time = Long.toString(new Date().getTime()); String subject = Constants.VOCAB; String encoding = "euc-kr"; FileWordCategoriesManager fwcm = new FileWordCategoriesManager(); Vector word_cats = fwcm.getAllExclusiveCategories(user_id, subject, current_dir); int expected_number_of_cats = 2; int actual_number_of_cats = word_cats.size(); //System.out.println("categories --------------------------"); //printCategories(word_cats); //System.out.println("log ---------------------------------"); //printLog(fwcm.getLog()); assertEquals(expected_number_of_cats, actual_number_of_cats); } public void testGetExclusiveWordCategoryNames2() { //System.out.println("FileWordCategoriesManagerTest.testGetWordCategoryNames"); String user_id = new String("-5519451928541341469"); File path_file = new File(""); String current_dir = path_file.getAbsolutePath(); String action_time = Long.toString(new Date().getTime()); String subject = Constants.VOCAB; String encoding = "euc-kr"; FileWordCategoriesManager fwcm = new FileWordCategoriesManager(); Vector word_cats = fwcm.getAllExclusiveCategories(user_id, subject, current_dir); int expected_number_of_cats = 2; int actual_number_of_cats = word_cats.size(); //System.out.println("categories --------------------------"); //printCategories(word_cats); //System.out.println("log ---------------------------------"); printLog(fwcm.getLog()); assertEquals(expected_number_of_cats, actual_number_of_cats); } public void testGetWordCategory() { //System.out.println("FileWordCategoriesManagerTest.testGetWordCategory -=-=-"); String user_id = new String("-5519451928541341469"); File path_file = new File(""); String current_dir = path_file.getAbsolutePath(); String action_time = Long.toString(new Date().getTime()); String subject = Constants.VOCAB; String encoding = "euc-kr"; long cat_id = Long.parseLong("4716676107208947544"); FileWordCategoriesManager fwcm = new FileWordCategoriesManager(); WordCategory word_cat = fwcm.getWordCategory(cat_id, user_id, subject, current_dir); Vector words = word_cat.getCategoryWords(); //System.out.println("words -=-=-"); ////printWords(words); //System.out.println("words -=-=-"); int expected = 14; int actual = words.size(); printLog(fwcm.getLog()); assertEquals(expected, actual); } /** * Utility to generate category index file entries and WordCategory files from word files. * public void testGenerateCateogiresFromFilesUtility() { System.out.println("testGenerateCateogiresFromFilesUtility"); String user_id = new String("prime"); //String user_id = new String("new"); String subject = Constants.VOCAB; String encoding = "euc-kr"; File path_file = new File(""); String current_dir = path_file.getAbsolutePath(); FileCategories cats = new FileCategories(current_dir); //Hashtable files = cats.getSortedWordCategories(user_id); Hashtable files = cats.getSortedWordCategories2(user_id, encoding); System.out.println("cats log --- start"); printLog(cats.getLog()); System.out.println("cats log --- end"); FileStorage fs = new FileStorage(current_dir); for (Enumeration e = files.elements() ; e.hasMoreElements() ;) { String key = (String)e.nextElement(); String val = (String)files.get(key); // this is null and we couldn't even tell you what it should be, except maybe type... Vector words = fs.getWordObjects(key, user_id); WordCategory word_cat = new WordCategory(); word_cat.setCategoryType(Constants.EXCLUSIVE); word_cat.setName(key); Word first_word = null; try { first_word = (Word)words.get(0); long doe = first_word.getDateOfEntry(); if (doe==0) { TestDateEvaluator tde = new TestDateEvaluator(); FileJDOMWordLists fjdomwl = new FileJDOMWordLists(); String first_date = fjdomwl.getEarliestDate(first_word); doe = Domartin.getMilliseconds(first_date); } word_cat.setCreationTime(doe); word_cat.setCategoryWords(words); FileWordCategoriesManager fwcm = new FileWordCategoriesManager(); long cat_id = fwcm.addWordCategory(word_cat, user_id, subject, current_dir, encoding); System.out.println(key+" - "+words.size()+" doe "+Transformer.getDateFromMilliseconds(doe+"")); printLog(fwcm.getLog()); } catch (java.lang.ArrayIndexOutOfBoundsException aioobe) { System.out.println(key+" - "+words.size()+" doe iioobe"); } } int expected = 1; int actual = 0; assertEquals(expected, actual); } */ /** * Utility made 21013 to take all the word files in a folder and splice each word into it's own * file, and create a category entry for it. * There was a bug initially in ileCategories.getSortedWordCategories2 that was using a hash * and trying to put repeat keys into the list, so a series of files were being ignored. * That;s what the convertSkippedFiles methods below were all about. */ public void testGenerateSeparateWordFilesUtility() { System.out.println("testGenerateSeparateWordFilesUtility ======-======="); String user_id = new String("-5519451928541341469"); String subject = Constants.VOCAB; String encoding = "euc-kr"; //encoding = "UTF-8"; File path_file = new File(""); String current_dir = path_file.getAbsolutePath(); String files_path = current_dir+File.separator+"files"; FileCategories cats = new FileCategories(current_dir); Hashtable files = cats.getSortedWordCategories2(user_id, encoding); FileWordCategoriesManager fwcm = new FileWordCategoriesManager(); FileStorage fs = new FileStorage(current_dir); for (Enumeration e = files.elements() ; e.hasMoreElements() ;) { String key = (String)e.nextElement(); String val = (String)files.get(key); // this is null and we couldn't even tell you what it should be, except maybe type... //System.out.println("key "+key+" val "+val); Vector words = fs.getWordObjects(key, user_id); Vector simple_words = new Vector(); WordCategory exclusive_cat = new WordCategory(); exclusive_cat.setCategoryType(Constants.EXCLUSIVE); exclusive_cat.setName(key); for (int i = 0; i < words.size(); i++) { Word word = (Word)words.get(i); long doe = word.getDateOfEntry(); if (doe==0) { TestDateEvaluator tde = new TestDateEvaluator(); FileJDOMWordLists fjdomwl = new FileJDOMWordLists(); String first_date = fjdomwl.getEarliestDate(word); doe = Domartin.getMilliseconds(first_date); } exclusive_cat.setCreationTime(doe); Vector single_word = new Vector(); single_word.add(word); String word_id = Long.toString(word.getId()); if (Transformer.getDateFromMilliseconds(doe+"").equals("01/01/70")) { WordTestDateUtility wtdu = new WordTestDateUtility(); String result = wtdu.evaluateWordsFirstTestDate(word); if (result.equals("no tests")) { result = Long.toString(new Date().getTime()); } doe = Long.parseLong(result); } SimpleWord simple_word = new SimpleWord(word.getId(), word_id+".xml", word.getText(), word.getDefinition()); System.out.println(word.getId()+" "+word_id+".xml "+word.getText()+" "+word.getDefinition()); simple_words.add(simple_word); String new_file_path = files_path+File.separator+user_id+File.separator+word_id+".xml"; File file = new File(new_file_path); try { boolean created = file.createNewFile(); } catch (IOException e1) { // TODO Auto-generated catch block //System.out.println("ioe: File not created"); e1.printStackTrace(); } JDOMSolution jdom = new JDOMSolution(file); // the file is actually not used. try { jdom.addSingleWord(word, encoding, files_path, user_id); fs.addWord(word, word_id+".xml", user_id, encoding); } catch (Exception ex) { System.out.println("add word, add single word npe "+key+" - "+word.getDefinition()+" doe "+Transformer.getDateFromMilliseconds(doe+"")); printLog(jdom.getLog()); ex.printStackTrace(); break; } //System.out.println(key+" - "+word.getDefinition()+" doe "+Transformer.getDateFromMilliseconds(doe+"")); } exclusive_cat.setCategoryWords(simple_words); fwcm = new FileWordCategoriesManager(); long cat_id = fwcm.addWordCategory(exclusive_cat, user_id, subject, current_dir, encoding); if (cat_id == -1) { // cat exists, do nothing. } printLog(fwcm.getLog()); fwcm.resetLog(); String path_to_old_cat = files_path+File.separator+user_id+File.separator+key; File file_to = new File(path_to_old_cat); boolean exists = file_to.exists(); boolean deleted = file_to.delete(); if (!deleted||!exists) { System.out.println("not deleted or not exists: file "+path_to_old_cat+" deleted "+key+"? "+deleted+" exists? "+exists); } } // convert missed files convertSkippedFiles(); fwcm = new FileWordCategoriesManager(); Vector new_cats = fwcm.getAllExclusiveCategories(user_id, subject, current_dir); //System.out.println("new_cats --- start"); //printCategories(new_cats); //System.out.println("new_cats --- end"); //Sarray scats = fwcm.getSortedCategories(user_id, subject, current_dir, Constants.EXCLUSIVE); //System.out.println("new_cats --- start"); //printSarray(scats); //System.out.println("new_cats --- end"); int expected = 1; int actual = 0; assertEquals(expected, actual); } private Vector convertSkippedFiles() { Vector skipped_files = new Vector(); skipped_files.add("JanuaryB-7.xml"); skipped_files.add("JanuaryB-7.xml"); skipped_files.add("JanuaryB-17.xml"); skipped_files.add("JanuaryB-17.xml"); skipped_files.add("JanuaryB-30.xml "); skipped_files.add("JanuaryB-30.xml"); skipped_files.add("JanuaryB-3.xml"); skipped_files.add("JanuaryB-3.xml"); skipped_files.add("random words 2 I-29.xml"); skipped_files.add("random words 2 I-29.xml"); skipped_files.add("random words 2 I-27.xml"); skipped_files.add("random words 2 I-27.xml"); skipped_files.add("random words 2 II.xml"); skipped_files.add("random words 2 I-25.xml"); skipped_files.add("random words 2 I-25.xml"); skipped_files.add("random words 1.xml"); skipped_files.add("random words 2 II.xml"); skipped_files.add("random words 2 I-1.xml"); skipped_files.add("random words 2 I-1.xml"); skipped_files.add("random words 2 I-6.xml"); skipped_files.add("random words 2 I-6.xml"); skipped_files.add("random words 2 I-9.xml"); skipped_files.add("random words 2 I-9.xml"); skipped_files.add("random words 2 I-16.xml"); skipped_files.add("random words 2 I-16.xml"); skipped_files.add("random words 2 I-21.xml"); skipped_files.add("random words 2 I-21.xml"); skipped_files.add("random words 2 I-24.xml"); skipped_files.add("random words 2 I-24.xml"); return skipped_files; } private Hashtable convertSkippedFilesHash(Hashtable skipped_files) { String now = Long.toString(new Date().getTime()); skipped_files.put(now, "JanuaryB-7.xml"); skipped_files.put(now, "JanuaryB-7.xml"); skipped_files.put(now, "JanuaryB-17.xml"); skipped_files.put(now, "JanuaryB-17.xml"); skipped_files.put(now, "JanuaryB-30.xml"); skipped_files.put(now, "JanuaryB-30.xml"); skipped_files.put(now, "JanuaryB-3.xml"); skipped_files.put(now, "JanuaryB-3.xml"); skipped_files.put(now, "random words 2 I-29.xml"); skipped_files.put(now, "random words 2 I-29.xml"); skipped_files.put(now, "random words 2 I-27.xml"); skipped_files.put(now, "random words 2 I-27.xml"); skipped_files.put(now, "random words 2 II.xml"); skipped_files.put(now, "random words 2 I-25.xml"); skipped_files.put(now, "random words 2 I-25.xml"); skipped_files.put(now, "random words 1.xml"); skipped_files.put(now, "random words 2 II.xml"); skipped_files.put(now, "random words 2 I-1.xml"); skipped_files.put(now, "random words 2 I-1.xml"); skipped_files.put(now, "random words 2 I-6.xml"); skipped_files.put(now, "random words 2 I-6.xml"); skipped_files.put(now, "random words 2 I-9.xml"); skipped_files.put(now, "random words 2 I-9.xml"); skipped_files.put(now, "random words 2 I-16.xml"); skipped_files.put(now, "random words 2 I-16.xml"); skipped_files.put(now, "random words 2 I-21.xml"); skipped_files.put(now, "random words 2 I-21.xml"); skipped_files.put(now, "random words 2 I-24.xml"); skipped_files.put(now, "random words 2 I-24.xml"); return skipped_files; } public void testGetSortedCategoryNames() { //System.out.println("FileWordCategoriesManagerTest.testGetWordCategoryNames"); //String user_id = new String("-5519451928541341468"); String user_id = new String("prime"); File path_file = new File(""); String current_dir = path_file.getAbsolutePath(); String action_time = Long.toString(new Date().getTime()); String subject = Constants.VOCAB; String encoding = "euc-kr"; FileWordCategoriesManager fwcm = new FileWordCategoriesManager(); Sarray word_catsarray = new Sarray(); try { word_catsarray = fwcm.getSortedCategories(user_id, subject, current_dir, Constants.EXCLUSIVE); } catch (java.lang.NullPointerException npe) { //System.out.println("npe +++++++++++++++++"); //printLog(fwcm.getLog()); } int expected_number_of_cats = 117; int actual_number_of_cats = word_catsarray.size(); for (int i = 0; i < word_catsarray.size(); i++) { Sortable s = (Sortable)word_catsarray.elementAt(i); String object_key = (String)s.getKey(); WordCategory word_cat = (WordCategory)s.getObject(); // System.out.println(Transformer.getKoreanDateFromMilliseconds(Long.toString(word_cat.getCreationTime())) // +" "+word_cat.getName() // +" "+word_cat.getTotalWordCount()); } assertEquals(expected_number_of_cats, actual_number_of_cats); } /* public void testGallery() { //System.out.println("FileWordCategoriesManagerTest.testGetWordCategoryNames"); String user_id = new String("-5519451928541341468"); File path_file = new File(""); String current_dir = path_file.getAbsolutePath(); Hashtable eyem_files = getGraphicsFiles("oneminpasteight", "ompe-"); int expected_number_of_cats = 84; int actual_number_of_cats = eyem_files.size(); assertEquals(expected_number_of_cats, actual_number_of_cats); } */ /** * This is for the gallery app which has no tests. */ private Hashtable getGraphicsFiles(String file_name, String root_name) { String bin_path = System.getProperty("user.dir"); System.out.println("bin_path "+bin_path); Properties properties = System.getProperties(); String sep = new String(properties.getProperty("file.separator")); int last_slash = bin_path.lastIndexOf(sep); System.out.println("last_slash "+last_slash); String app_path = bin_path.substring(0, last_slash); System.out.println("app_path "+app_path); //String path = new String(app_path+sep+"webapps"+sep+"gallery"+sep+"sketch"+sep+file_name); String path = new String(app_path+sep+"catechis"+sep+"sketch"+sep+file_name); System.out.println("Gallery-"+file_name+".getGraphicsFiles: Looking in "+path); File user_files_dir = new File(path); String[] files = user_files_dir.list(); Hashtable user_files = new Hashtable(); //System.out.println("Gallery-"+file_name+".getGraphicsFiles: "+files.length+" files"); for (int i = 0; i < files.length; i++) { try { StringBuffer index_buffer = new StringBuffer(); String file = files[i]; int name_end = file.indexOf(root_name)+root_name.length(); file = Domartin.getFileWithoutExtension(file); // ompe-0lw int end_index = (file.length()-2); String substring = file.substring(name_end, end_index); String index_string = new String(index_buffer); user_files.put(substring, file); } catch (java.lang.StringIndexOutOfBoundsException sioobe) { //System.out.println("Gallery-aioob at "+i); break; } } return user_files; } public void testAddWordsToCategory() { //System.out.println("testAddWordsToCategory =-=-=-=-=-=-=-=-="); String user_id = new String("prime"); File path_file = new File(""); String current_dir = path_file.getAbsolutePath(); String action_time = Long.toString(new Date().getTime()); String subject = Constants.VOCAB; String encoding = "euc-kr"; FileWordCategoriesManager fwcm = new FileWordCategoriesManager(); Sarray word_catsarray = fwcm.getSortedCategories(user_id, subject, current_dir, Constants.EXCLUSIVE); Sortable s = (Sortable)word_catsarray.elementAt(0); String object_key = (String)s.getKey(); WordCategory word_cat = (WordCategory)s.getObject(); //System.out.println("name of cat to add word to: "+word_cat.getName()+" id "+word_cat.getId()); long cat_id = word_cat.getId(); int expected = word_cat.getTotalWordCount()+1; word_cat = fwcm.getWordCategory(cat_id, user_id, subject, current_dir); Vector words = word_cat.getCategoryWords(); int expected_words = words.size()+1; Date today = new Date(); String name = today.toString(); long word_id = today.getTime(); Vector category_words = new Vector(); Word simple_word1 = new Word(); simple_word1.setDefinition("def1"); simple_word1.setText("text1"); simple_word1.setId(word_id); simple_word1.setCategory(word_cat.getName()); category_words.add(simple_word1); fwcm.addWordsToCategory(user_id, word_cat.getId(), subject, current_dir, category_words, encoding); //printLog(fwcm.getLog()); word_cat = fwcm.getWordCategory(cat_id, user_id, subject, current_dir); words = word_cat.getCategoryWords(); int actual_words = words.size(); assertEquals(expected, actual_words); } public void testGetCategoryId() { //System.out.println("testGetCategoryId"); String user_id = new String("prime"); File path_file = new File(""); String current_dir = path_file.getAbsolutePath(); String action_time = Long.toString(new Date().getTime()); String subject = Constants.VOCAB; String encoding = "euc-kr"; String category_name = "october1-01.xml"; FileWordCategoriesManager fwcm = new FileWordCategoriesManager(); long actual = fwcm.getCategoryId(category_name, user_id, subject, current_dir); long expected = Long.parseLong("-5368021119795338553"); assertEquals(expected, actual); } /** * We had a problem getting a number format exception from this methods result. */ public void testGetCategoryId2() { //System.out.println("testGetCategoryId"); String user_id = new String("-5519451928541341469"); File path_file = new File(""); String current_dir = path_file.getAbsolutePath(); String action_time = Long.toString(new Date().getTime()); String subject = Constants.VOCAB; String encoding = "euc-kr"; String category_name = "seminar.xml"; FileWordCategoriesManager fwcm = new FileWordCategoriesManager(); long actual = fwcm.getCategoryId(category_name, user_id, subject, current_dir); //System.out.println("testGetCategoryId actual: "+actual); long expected = Long.parseLong("-5519451928541341469"); assertEquals(expected, actual); } public void testUpdateCategory() { System.out.println("FileWordCategoriesManagerTest.testUpdateCategory"); String user_id = new String("new"); user_id = "prime"; File path_file = new File(""); String current_dir = path_file.getAbsolutePath(); long now = new Date().getTime(); String action_time = Long.toString(now); String subject = Constants.VOCAB; String encoding = "euc-kr"; WordCategory word_cat1 = new WordCategory(); word_cat1.setCategoryType(Constants.EXCLUSIVE); word_cat1.setName("Test1 "+action_time); word_cat1.setCreationTime(now); Vector category_words = new Vector(); SimpleWord simple_word1 = new SimpleWord(); simple_word1.setDefinition("def1"); simple_word1.setText("text1"); simple_word1.setWordId(1); simple_word1.setWordPath("test.xml"); category_words.add(simple_word1); // add word 1 word_cat1.setCategoryWords(category_words); WordCategory word_cat2 = new WordCategory(); word_cat2.setCategoryType(Constants.EXCLUSIVE); word_cat2.setName("Test2 "+action_time); word_cat2.setCreationTime(now+1); SimpleWord simple_word2 = new SimpleWord(); simple_word2.setDefinition("def2"); simple_word2.setText("text2"); simple_word2.setWordId(2); simple_word2.setWordPath("test.xml"); category_words.add(simple_word2); // add word 2 word_cat2.setCategoryWords(category_words); //System.out.println("calculated number of words: "+word_cat.calculateTotalWords()); FileWordCategoriesManager fwcm = new FileWordCategoriesManager(); long cat_id1 = fwcm.addWordCategory(word_cat1, user_id, subject, current_dir, encoding); long cat_id2 = fwcm.addWordCategory(word_cat2, user_id, subject, current_dir, encoding); System.out.println("cat_id1 "+cat_id1); System.out.println("cat_id2 "+cat_id2); WordCategory returned_cat1 = fwcm.getWordCategory(cat_id1, user_id, subject, current_dir); WordCategory returned_cat2 = fwcm.getWordCategory(cat_id2, user_id, subject, current_dir); category_words.add(simple_word1); // add word 1 category_words.add(simple_word2); // add word 2 word_cat2.setCategoryWords(category_words); System.out.println("category_words "+category_words.size()); System.out.println("word_cat2.calculateTotalWords() "+word_cat2.calculateTotalWords()); fwcm.updateCategory(word_cat2, user_id, subject, current_dir, encoding); long expected_number_of_words = category_words.size(); WordCategory returned_cat2_after = fwcm.getWordCategory(cat_id2, user_id, subject, current_dir); System.out.println("fwcm log ----="); printLog(fwcm.getLog()); System.out.println("fwcm log ----="); // recalculate new number of words returned_cat2 = fwcm.getWordCategory(cat_id2, user_id, subject, current_dir); long actual_number_of_words = returned_cat2.calculateTotalWords(); category_words = returned_cat2.getCategoryWords(); //System.out.println("category_words after update "+category_words.size()); System.out.println("word_cat2.calculateTotalWords() "+word_cat2.calculateTotalWords()); boolean done1 = fwcm.deleteCategory(cat_id1, user_id, subject, current_dir, encoding); boolean done2 = fwcm.deleteCategory(cat_id2, user_id, subject, current_dir, encoding); //System.out.println("done? "+done); //printLog(fwcm.getLog()); assertEquals(expected_number_of_words, actual_number_of_words); } private void printCategories(Vector log) { System.out.println("name type date id words"); int total = log.size(); int i = 0; while (i<total) { WordCategory word_cat = (WordCategory)log.get(i); System.out.println(word_cat.getName() +" "+word_cat.getCategoryType() +Transformer.getDateFromMilliseconds(Long.toString(word_cat.getCreationTime())) +" "+word_cat.getId() +" "+word_cat.getTotalWordCount()); i++; } } private void printLog(Vector log) { int total = log.size(); int i = 0; while (i<total) { System.out.println("vector - "+log.get(i)); i++; } } private void printLog(ArrayList al) { int total = al.size(); int i = 0; while (i<total) { System.out.println("ArrayList - "+al.get(i)); i++; } } private void printLog(String loggy) { System.out.println("log- "+loggy); } private void printFiles(String [] files) { int i = 0; int l = files.length; while (i<l) { String file_w_ext = files [i]; String file = Transformer.getLongDateFromMilliseconds(Domartin.getFileWithoutExtension(file_w_ext)); System.out.println(i+" "+file); i++; } } private void printSarray(Sarray word_catsarray) { for (int i = 0; i < word_catsarray.size(); i++) { Sortable s = (Sortable)word_catsarray.elementAt(i); String object_key = (String)s.getKey(); WordCategory word_cat = (WordCategory)s.getObject(); System.out.println(i+" " +Transformer.getKoreanDateFromMilliseconds(Long.toString(word_cat.getCreationTime())) +" "+word_cat.getName()+" " +" "+word_cat.getTotalWordCount()); } } private void printWords(Vector log) { int total = log.size(); int i = 0; while (i<total) { SimpleWord word = (SimpleWord)log.get(i); System.out.println(word.getText()+" "+word.getDefinition()); i++; } } }
apache-2.0
SudhersonV/DotNetRoot
SampleCode/AdventureWorksEF/DatabaseLog.cs
929
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace AdventureWorksEF { using System; using System.Collections.Generic; public partial class DatabaseLog { public int DatabaseLogID { get; set; } public System.DateTime PostTime { get; set; } public string DatabaseUser { get; set; } public string Event { get; set; } public string Schema { get; set; } public string Object { get; set; } public string TSQL { get; set; } public string XmlEvent { get; set; } } }
apache-2.0
haf/NodaTime
src/NodaTime.Benchmarks/Extensions/Extensions.cs
1186
#region Copyright and license information // Copyright 2001-2009 Stephen Colebourne // Copyright 2009-2011 Jon Skeet // // 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. #endregion namespace NodaTime.Benchmarks.Extensions { internal static class BenchmarkingExtensions { /// <summary> /// This does absolutely nothing, but /// allows us to consume a property value without having /// a useless local variable. It should end up being JITted /// away completely, so have no effect on the results. /// </summary> internal static void Consume<T>(this T value) { } } }
apache-2.0
consulo/consulo-maven
plugin/src/main/java/org/jetbrains/idea/maven/services/artifactory/ArtifactoryRepositoryService.java
5655
/* * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.maven.services.artifactory; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.intellij.openapi.util.text.StringUtil; import javax.annotation.Nonnull; import org.jetbrains.idea.maven.model.MavenArtifactInfo; import org.jetbrains.idea.maven.model.MavenRepositoryInfo; import org.jetbrains.idea.maven.services.MavenRepositoryService; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * @author Gregory.Shrago */ public class ArtifactoryRepositoryService extends MavenRepositoryService { @Nonnull @Override public String getDisplayName() { return "Artifactory"; } @Nonnull @Override public List<MavenRepositoryInfo> getRepositories(@Nonnull String url) throws IOException { try { final Gson gson = new Gson(); final InputStreamReader stream = new InputStreamReader(new Endpoint.Repositories(url).getRepositoryDetailsListJson(null).getInputStream()); final ArtifactoryModel.RepositoryType[] repos = gson.fromJson(stream, ArtifactoryModel.RepositoryType[].class); final List<MavenRepositoryInfo> result = new ArrayList<MavenRepositoryInfo>(repos.length); for (ArtifactoryModel.RepositoryType repo : repos) { result.add(convert(repo)); } return result; } catch (JsonSyntaxException e) { return Collections.emptyList(); } catch (Exception e) { throw new IOException(e); } } private static MavenRepositoryInfo convert(ArtifactoryModel.RepositoryType repo) { return new MavenRepositoryInfo(repo.key, repo.description, repo.url); } @Nonnull @Override public List<MavenArtifactInfo> findArtifacts(@Nonnull String url, @Nonnull MavenArtifactInfo template) throws IOException { try { final String packaging = StringUtil.notNullize(template.getPackaging()); final ArrayList<MavenArtifactInfo> artifacts = new ArrayList<MavenArtifactInfo>(); final Gson gson = new Gson(); final String className = template.getClassNames(); if (className == null || className.length() == 0) { final String name = StringUtil.join(Arrays.asList(template.getGroupId(), template.getArtifactId(), template.getVersion()), ":"); final InputStream stream = new Endpoint.Search.Artifact(url).getArtifactSearchResultJson(name, null).getInputStream(); final ArtifactoryModel.GavcResults results = stream == null? null : gson.fromJson(new InputStreamReader(stream), ArtifactoryModel.GavcResults.class); if (results != null && results.results != null) { for (ArtifactoryModel.GavcResult result : results.results) { if (!result.uri.endsWith(packaging)) continue; artifacts.add(convertArtifactInfo(result.uri, url, null)); } } } else { // IDEA-58225 final String searchString = className.endsWith("*") || className.endsWith("?") ? className : className + ".class"; final InputStream stream = new Endpoint.Search.Archive(url).getArchiveSearchResultJson(searchString, null).getInputStream(); final ArtifactoryModel.ArchiveResults results = stream == null? null : gson.fromJson(new InputStreamReader(stream), ArtifactoryModel.ArchiveResults.class); if (results != null && results.results != null) { for (ArtifactoryModel.ArchiveResult result : results.results) { for (String uri : result.archiveUris) { if (!uri.endsWith(packaging)) continue; artifacts.add(convertArtifactInfo(uri, url, result.entry)); } } } } return artifacts; } catch (JsonSyntaxException e) { return Collections.emptyList(); } catch (Exception e) { throw new IOException(e); } } private static MavenArtifactInfo convertArtifactInfo(String uri, String baseUri, String className) throws IOException { final String repoPathFile = uri.substring((baseUri + "storage/").length()); final int repoIndex = repoPathFile.indexOf('/'); final String repoString = repoPathFile.substring(0, repoIndex); final String repo = repoString.endsWith("-cache") ? repoString.substring(0, repoString.lastIndexOf('-')) : repoString; final String filePath = repoPathFile.substring(repoIndex + 1, repoPathFile.lastIndexOf('/')); final int artIdIndex = filePath.lastIndexOf('/'); final String version = filePath.substring(artIdIndex + 1); final String groupArtifact = filePath.substring(0, artIdIndex); final int groupIndex = groupArtifact.lastIndexOf('/'); final String artifact = groupArtifact.substring(groupIndex + 1); final String group = groupArtifact.substring(0, groupIndex).replace('/', '.'); final String packaging = uri.substring(uri.lastIndexOf('.') + 1); return new MavenArtifactInfo(group, artifact, version, packaging, null, className, repo); } }
apache-2.0
crystalbyte/spectre
src/Crystalbyte.Spectre/CommandLineSwitchCollection.cs
225
using System; namespace Crystalbyte.Spectre { public sealed class CommandLineEntryCollection { public CommandLineEntryCollection (CommandLine commandLine) { } public object MyProperty { get; set; } } }
apache-2.0
altarit/cloudpolis-react
src/routes/AccessLog/index.js
219
export default (store) => ({ path: '/admin/access', name: 'accessLog', getComponent() { return Promise.all([ import('./containers/AccessLogContainer'), import('./modules/accessLog'), ]) } })
apache-2.0
che2/bde
groups/bsl/bsls/bsls_review_macroreset.cpp
986
// bsls_review_macroreset.cpp -*-C++-*- #include <bsls_review_macroreset.h> #include <bsls_ident.h> BSLS_IDENT("$Id$ $CSID$") namespace BloombergLP { } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2018 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
apache-2.0
Nankaiming/MobileSafe
src/com/example/mobilesafe/activity/CallSafeActivity.java
5196
package com.example.mobilesafe.activity; import java.util.List; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.example.mobilesafe.R; import com.example.mobilesafe.adapter.MyBaseAdapter; import com.example.mobilesafe.bean.BlackNumberInfo; import com.example.mobilesafe.db.dao.BlackNumberDao; import com.example.mobilesafe.utils.ToastUtils; public class CallSafeActivity extends Activity { private ListView list_view; private BlackNumberDao blackNumberDao; private List<BlackNumberInfo> blackNumberInfos; private int mPageSize = 20; private int mCurrentPageNum = 0; private int totalPageNumber; private Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { ll_pgs_bar.setVisibility(View.INVISIBLE); tv_page_number.setText((mCurrentPageNum+1)+"/"+totalPageNumber); adapter = new CallSafeAdapter(blackNumberInfos,CallSafeActivity.this); list_view.setAdapter(adapter); }; }; private CallSafeAdapter adapter; private LinearLayout ll_pgs_bar; private TextView tv_page_number; private EditText et_page_number; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_call_safe); initUI(); initData(); } private void initData() { blackNumberDao = new BlackNumberDao(this); new Thread(){ public void run() { blackNumberInfos = blackNumberDao.findPar(mCurrentPageNum, mPageSize); if(blackNumberDao.getTotalNumber() % mPageSize == 0){ totalPageNumber = blackNumberDao.getTotalNumber() / mPageSize; }else{ totalPageNumber = blackNumberDao.getTotalNumber() / mPageSize + 1; } // System.out.println("+++++"+totalPageNumber+"+++++"); handler.sendEmptyMessage(0); }; }.start(); } private void initUI() { list_view = (ListView) findViewById(R.id.list_view); ll_pgs_bar = (LinearLayout) findViewById(R.id.ll_pgs_bar); ll_pgs_bar.setVisibility(View.VISIBLE); et_page_number = (EditText) findViewById(R.id.et_page_number); tv_page_number = (TextView) findViewById(R.id.tv_page_number); } private class CallSafeAdapter extends MyBaseAdapter<BlackNumberInfo> { public CallSafeAdapter(List<BlackNumberInfo> list, Context context) { super(list, context); // TODO Auto-generated constructor stub } public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View view; ViewHolder viewHolder; if (convertView == null) { view = View.inflate(CallSafeActivity.this, R.layout.item_call_safe, null); viewHolder = new ViewHolder(); viewHolder.tv_number = (TextView) view.findViewById(R.id.tv_number); viewHolder.tv_mode = (TextView) view.findViewById(R.id.tv_mode); viewHolder.iv_delete = (ImageView) view.findViewById(R.id.iv_delete); view.setTag(viewHolder); } else { view = convertView; viewHolder = (ViewHolder) view.getTag(); } viewHolder.tv_number.setText(blackNumberInfos.get(position) .getNumber()); String mode = blackNumberInfos.get(position).getMode(); if (mode.equals("1")) { viewHolder.tv_mode.setText("À´µçÀ¹½Ø+¶ÌÐÅÀ¹½Ø"); } else if (mode.equals("2")) { viewHolder.tv_mode.setText("À´µçÀ¹½Ø"); } else if (mode.equals("3")) { viewHolder.tv_mode.setText("¶ÌÐÅÀ¹½Ø"); } viewHolder.iv_delete.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub BlackNumberInfo info = blackNumberInfos.get(position); boolean result = blackNumberDao.delete(info.getNumber()); if(result){ ToastUtils.showToast(CallSafeActivity.this, "ɾ³ý³É¹¦"); blackNumberInfos.remove(info); adapter.notifyDataSetChanged(); }else{ ToastUtils.showToast(CallSafeActivity.this, "ɾ³ýʧ°Ü"); } } }); return view; } } static class ViewHolder { TextView tv_number; TextView tv_mode; ImageView iv_delete; } public void prePage(View view){ if(mCurrentPageNum <= 0){ ToastUtils.showToast(this, "ÒѾ­ÊǵÚÒ»Ò³ÁË"); return; } mCurrentPageNum--; initData(); } public void nextPage(View view){ if(mCurrentPageNum >= totalPageNumber - 1){ ToastUtils.showToast(this, "ÒѾ­ÊÇ×îºóÒ»Ò³ÁË"); return; } mCurrentPageNum++; initData(); } public void jump(View view){ String str_page_number = et_page_number.getText().toString().trim(); if(TextUtils.isEmpty(str_page_number)){ ToastUtils.showToast(this, "ÇëÊäÈëÕýÈ·µÄÒ³Âë"); }else{ int number = Integer.parseInt(str_page_number) - 1; if(number >= 0 && number <= totalPageNumber - 1){ mCurrentPageNum = number; initData(); }else{ ToastUtils.showToast(this, "ÇëÊäÈëÕýÈ·µÄÒ³Âë"); } } } }
apache-2.0
cloudfoundry/php-buildpack
src/php/integration/composer_with_unicode_env_test.go
534
package integration_test import ( "github.com/cloudfoundry/libbuildpack/cutlass" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Composer with unicode env variables", func() { var app *cutlass.App AfterEach(func() { app = DestroyApp(app) }) It("", func() { app = cutlass.New(Fixtures("strangechars")) app.SetEnv("BP_DEBUG", "1") PushAppAndConfirm(app) Eventually(app.Stdout.String).Should(ContainSubstring(`[DEBUG] composer - ENV IS: CLUSTERS_INFO={"dev01":{"env":"開発環境"`)) }) })
apache-2.0
orientechnologies/orientdb
graphdb/src/main/java/com/tinkerpop/blueprints/impls/orient/OrientIndexManual.java
11401
/* * * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * For more information: http://orientdb.com * */ package com.tinkerpop.blueprints.impls.orient; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.index.OCompositeKey; import com.orientechnologies.orient.core.index.OIndex; import com.orientechnologies.orient.core.index.OIndexInternal; import com.orientechnologies.orient.core.index.OIndexTxAwareMultiValue; import com.orientechnologies.orient.core.index.OIndexTxAwareOneValue; import com.orientechnologies.orient.core.index.OSimpleKeyIndexDefinition; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.tinkerpop.blueprints.CloseableIterable; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.util.StringFactory; import com.tinkerpop.blueprints.util.WrappingCloseableIterable; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** @author Luca Garulli (l.garulli--(at)--orientdb.com) (http://orientdb.com) */ @SuppressWarnings("unchecked") public class OrientIndexManual<T extends OrientElement> implements OrientIndex<T> { public static final String CONFIG_CLASSNAME = "blueprintsIndexClass"; public static final String CONFIG_RECORD_MAP_NAME = "record_map_name"; protected static final String VERTEX = "Vertex"; protected static final String EDGE = "Edge"; protected static final String SEPARATOR = "!=!"; protected OrientBaseGraph graph; protected OIndex underlying; protected OIndex recordKeyValueIndex; protected Class<? extends Element> indexClass; protected OrientIndexManual( final OrientBaseGraph graph, final String indexName, final Class<? extends Element> indexClass, final OType iType) { this.graph = graph; this.indexClass = indexClass; create(indexName, this.indexClass, iType); } protected OrientIndexManual(final OrientBaseGraph orientGraph, final OIndex rawIndex) { this.graph = orientGraph; OIndexInternal rawIndexInternal = rawIndex.getInternal(); if (rawIndexInternal == null) { this.underlying = rawIndex; } else if (rawIndexInternal instanceof OIndexTxAwareMultiValue) { this.underlying = rawIndexInternal; } else { this.underlying = new OIndexTxAwareMultiValue(orientGraph.getRawGraph(), rawIndexInternal); } final ODocument metadata = rawIndex.getMetadata(); if (metadata == null) { load(rawIndex.getConfiguration()); } else load(metadata); } public String getIndexName() { return underlying.getName(); } public Class<T> getIndexClass() { return (Class<T>) this.indexClass; } public void put(final String key, final Object value, final T element) { final String keyTemp = key + SEPARATOR + value; final ODocument doc = element.getRecord(); if (!doc.getIdentity().isValid()) doc.save(); graph.setCurrentGraphInThreadLocal(); graph.autoStartTransaction(); underlying.put(keyTemp, doc); recordKeyValueIndex.put(new OCompositeKey(doc.getIdentity(), keyTemp), doc.getIdentity()); } @SuppressWarnings("rawtypes") public CloseableIterable<T> get(final String key, final Object iValue) { final String keyTemp = key + SEPARATOR + iValue; Collection<OIdentifiable> records; try (Stream<ORID> rids = underlying.getInternal().getRids(keyTemp)) { records = rids.collect(Collectors.toList()); } if (records == null || records.isEmpty()) return new WrappingCloseableIterable(Collections.emptySet()); return new OrientElementIterable<T>(graph, records); } public CloseableIterable<T> query(final String key, final Object query) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } public long count(final String key, final Object value) { final String keyTemp = key + SEPARATOR + value; try (Stream<ORID> rids = underlying.getInternal().getRids(keyTemp)) { return rids.count(); } } public void remove(final String key, final Object value, final T element) { final String keyTemp = key + SEPARATOR + value; graph.setCurrentGraphInThreadLocal(); graph.autoStartTransaction(); try { underlying.remove(keyTemp, element.getRecord()); recordKeyValueIndex.remove( new OCompositeKey(element.getIdentity(), keyTemp), element.getIdentity()); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } public String toString() { return StringFactory.indexString(this); } public OIndex getUnderlying() { return underlying; } public void close() { if (underlying != null) { underlying = null; } graph = null; } @Override public void removeElement(final T element) { graph.setCurrentGraphInThreadLocal(); graph.autoStartTransaction(); final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>( "select from index:" + recordKeyValueIndex.getName() + " where key between [" + element.getIdentity() + "] and [" + element.getIdentity() + "]"); final Collection<ODocument> entries = (Collection<ODocument>) graph.getRawGraph().query(query); for (ODocument entry : entries) { final OCompositeKey key = entry.field("key"); final List<Object> keys = key.getKeys(); underlying.remove(keys.get(1).toString(), element.getIdentity()); recordKeyValueIndex.remove(key, element.getIdentity()); } } private void create( final String indexName, final Class<? extends Element> indexClass, OType iKeyType) { this.indexClass = indexClass; if (iKeyType == null) iKeyType = OType.STRING; final ODatabaseDocumentInternal db = graph.getRawGraph(); this.recordKeyValueIndex = db.getMetadata() .getIndexManagerInternal() .createIndex( db, "__@recordmap@___" + indexName, OClass.INDEX_TYPE.DICTIONARY.toString(), new OSimpleKeyIndexDefinition(OType.LINK, OType.STRING), null, null, null); if (!db.isRemote()) { this.recordKeyValueIndex = new OIndexTxAwareOneValue(db, this.recordKeyValueIndex.getInternal()); } final String className; if (Vertex.class.isAssignableFrom(indexClass)) className = VERTEX; else if (Edge.class.isAssignableFrom(indexClass)) className = EDGE; else className = indexClass.getName(); final ODocument metadata = new ODocument(); metadata.field(CONFIG_CLASSNAME, className); metadata.field(CONFIG_RECORD_MAP_NAME, recordKeyValueIndex.getName()); // CREATE THE MAP if (!db.isRemote()) { this.underlying = new OIndexTxAwareMultiValue( db, db.getMetadata() .getIndexManagerInternal() .createIndex( db, indexName, OClass.INDEX_TYPE.NOTUNIQUE.toString(), new OSimpleKeyIndexDefinition(iKeyType), null, null, metadata) .getInternal()); } else { this.underlying = db.getMetadata() .getIndexManagerInternal() .createIndex( db, indexName, OClass.INDEX_TYPE.NOTUNIQUE.toString(), new OSimpleKeyIndexDefinition(iKeyType), null, null, metadata); } } private void load(final ODocument metadata) { // LOAD TREEMAP final String indexClassName = metadata.field(CONFIG_CLASSNAME); final String recordKeyValueMap = metadata.field(CONFIG_RECORD_MAP_NAME); if (VERTEX.equals(indexClassName)) this.indexClass = Vertex.class; else if (EDGE.equals(indexClassName)) this.indexClass = Edge.class; else try { this.indexClass = (Class<T>) Class.forName(indexClassName); } catch (ClassNotFoundException e) { throw new IllegalArgumentException( "Index class '" + indexClassName + "' is not registered. Supported ones: Vertex, Edge and custom class that extends them", e); } final ODatabaseDocumentInternal database = graph.getRawGraph(); if (recordKeyValueMap == null) recordKeyValueIndex = buildKeyValueIndex(metadata); else { final OIndex index = database.getMetadata().getIndexManagerInternal().getIndex(database, recordKeyValueMap); final OIndexInternal indexInternal = index.getInternal(); if (indexInternal != null) { recordKeyValueIndex = new OIndexTxAwareOneValue(database, indexInternal); } else { recordKeyValueIndex = index; } } } private OIndex buildKeyValueIndex(final ODocument metadata) { final ODatabaseDocumentInternal database = graph.getRawGraph(); final OIndex index = database .getMetadata() .getIndexManagerInternal() .createIndex( database, "__@recordmap@___" + underlying.getName(), OClass.INDEX_TYPE.DICTIONARY.toString(), new OSimpleKeyIndexDefinition(OType.LINK, OType.STRING), null, null, null); final OIndexInternal indexInternal = index.getInternal(); final OIndex recordKeyValueIndex; if (indexInternal != null) { recordKeyValueIndex = new OIndexTxAwareOneValue(graph.getRawGraph(), indexInternal); } else { recordKeyValueIndex = index; } final List<ODocument> entries = graph .getRawGraph() .query(new OSQLSynchQuery<Object>("select from index:" + underlying.getName())); for (ODocument entry : entries) { final OIdentifiable rid = entry.field("rid"); if (rid != null) recordKeyValueIndex.put(new OCompositeKey(rid, entry.field("key")), rid); } metadata.field(CONFIG_RECORD_MAP_NAME, recordKeyValueIndex.getName()); return recordKeyValueIndex; } }
apache-2.0
vmandic/dreamlet
dreamlet.server/dreamlet.Composition/DryIoc/FastExpressionCompiler.cs
91838
/* The MIT License (MIT) Copyright (c) 2016 Maksim Volkau 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 AddOrUpdateServiceFactory 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. */ namespace FastExpressionCompiler { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; /// <summary>Compiles expression to delegate by emitting the IL directly. /// The emitter is ~20 times faster than Expression.Compile.</summary> public static partial class ExpressionCompiler { /// <summary>First tries to compile fast and if failed (null result), then falls back to Expression.Compile.</summary> /// <typeparam name="T">Type of compiled delegate return result.</typeparam> /// <param name="lambdaExpr">Expr to compile.</param> /// <returns>Compiled delegate.</returns> public static Func<T> Compile<T>(Expression<Func<T>> lambdaExpr) { return TryCompile<Func<T>>(lambdaExpr.Body, lambdaExpr.Parameters, Empty<Type>(), typeof(T)) ?? lambdaExpr.Compile(); } /// <summary>Compiles lambda expression to <typeparamref name="TDelegate"/>.</summary> /// <typeparam name="TDelegate">The compatible delegate type, otherwise case will throw.</typeparam> /// <param name="lambdaExpr">Lambda expression to compile.</param> /// <returns>Compiled delegate.</returns> public static TDelegate Compile<TDelegate>(LambdaExpression lambdaExpr) where TDelegate : class { return TryCompile<TDelegate>(lambdaExpr) ?? (TDelegate)(object)lambdaExpr.Compile(); } /// <summary>Tries to compile lambda expression to <typeparamref name="TDelegate"/>.</summary> /// <typeparam name="TDelegate">The compatible delegate type, otherwise case will throw.</typeparam> /// <param name="lambdaExpr">Lambda expression to compile.</param> /// <returns>Compiled delegate.</returns> public static TDelegate TryCompile<TDelegate>(LambdaExpression lambdaExpr) where TDelegate : class { var paramExprs = lambdaExpr.Parameters; var paramTypes = GetParamExprTypes(paramExprs); var expr = lambdaExpr.Body; return TryCompile<TDelegate>(expr, paramExprs, paramTypes, expr.Type); } /// <summary>Performant method to get parameter types from parameter expressions.</summary> public static Type[] GetParamExprTypes(IList<ParameterExpression> paramExprs) { var paramsCount = paramExprs.Count; if (paramsCount == 0) return Empty<Type>(); if (paramsCount == 1) return new[] { paramExprs[0].Type }; var paramTypes = new Type[paramsCount]; for (var i = 0; i < paramTypes.Length; i++) paramTypes[i] = paramExprs[i].Type; return paramTypes; } /// <summary>Compiles expression to delegate by emitting the IL. /// If sub-expressions are not supported by emitter, then the method returns null. /// The usage should be calling the method, if result is null then calling the Expression.Compile.</summary> /// <param name="bodyExpr">Lambda body.</param> /// <param name="paramExprs">Lambda parameter expressions.</param> /// <param name="paramTypes">The types of parameters.</param> /// <param name="returnType">The return type.</param> /// <returns>Result delegate or null, if unable to compile.</returns> public static TDelegate TryCompile<TDelegate>( Expression bodyExpr, IList<ParameterExpression> paramExprs, Type[] paramTypes, Type returnType) where TDelegate : class { ClosureInfo ignored = null; return (TDelegate)TryCompile(ref ignored, typeof(TDelegate), paramTypes, returnType, bodyExpr, paramExprs); } /// <summary>Tries to compile lambda expression to <typeparamref name="TDelegate"/>.</summary> /// <typeparam name="TDelegate">The compatible delegate type, otherwise case will throw.</typeparam> /// <param name="lambdaExpr">Lambda expression to compile.</param> /// <returns>Compiled delegate.</returns> public static TDelegate TryCompile<TDelegate>(LambdaExpressionInfo lambdaExpr) where TDelegate : class { var paramExprs = lambdaExpr.Parameters; var paramTypes = GetParamExprTypes(paramExprs); var expr = lambdaExpr.Body; return TryCompile<TDelegate>(expr, paramExprs, paramTypes, expr.Type); } /// <summary>Compiles expression to delegate by emitting the IL. /// If sub-expressions are not supported by emitter, then the method returns null. /// The usage should be calling the method, if result is null then calling the Expression.Compile.</summary> /// <param name="bodyExpr">Lambda body.</param> /// <param name="paramExprs">Lambda parameter expressions.</param> /// <param name="paramTypes">The types of parameters.</param> /// <param name="returnType">The return type.</param> /// <returns>Result delegate or null, if unable to compile.</returns> public static TDelegate TryCompile<TDelegate>( ExpressionInfo bodyExpr, IList<ParameterExpression> paramExprs, Type[] paramTypes, Type returnType) where TDelegate : class { ClosureInfo ignored = null; return (TDelegate)TryCompile(ref ignored, typeof(TDelegate), paramTypes, returnType, bodyExpr, paramExprs); } private struct Expr { public static implicit operator Expr(Expression expr) { return expr == null ? default(Expr) : new Expr(expr, expr.NodeType, expr.Type); } public static implicit operator Expr(ExpressionInfo expr) { return expr == null ? default(Expr) : new Expr(expr, expr.NodeType, expr.Type); } public object Expression; public ExpressionType NodeType; public Type Type; private Expr(object expression, ExpressionType nodeType, Type type) { Expression = expression; NodeType = nodeType; Type = type; } } private static object TryCompile(ref ClosureInfo closureInfo, Type delegateType, Type[] paramTypes, Type returnType, Expr bodyExpr, IList<ParameterExpression> paramExprs, bool isNestedLambda = false) { if (!TryCollectBoundConstants(ref closureInfo, bodyExpr, paramExprs)) return null; if (closureInfo == null) { var method = new DynamicMethod(string.Empty, returnType, paramTypes, typeof(ExpressionCompiler), skipVisibility: true); if (!TryEmit(method, bodyExpr, paramExprs, closureInfo)) return null; return method.CreateDelegate(delegateType); } var closureObject = closureInfo.ConstructClosure(closureTypeOnly: isNestedLambda); var closureAndParamTypes = GetClosureAndParamTypes(paramTypes, closureInfo.ClosureType); var methodWithClosure = new DynamicMethod(string.Empty, returnType, closureAndParamTypes, typeof(ExpressionCompiler), skipVisibility: true); if (!TryEmit(methodWithClosure, bodyExpr, paramExprs, closureInfo)) return null; if (isNestedLambda) // include closure as the first parameter, BUT don't bound to it. It will be bound later in EmitNestedLambda. return methodWithClosure.CreateDelegate(GetFuncOrActionType(closureAndParamTypes, returnType)); return methodWithClosure.CreateDelegate(delegateType, closureObject); } private static bool TryEmit(DynamicMethod method, Expr bodyExpr, IList<ParameterExpression> paramExprs, ClosureInfo closureInfo) { var il = method.GetILGenerator(); if (!EmittingVisitor.TryEmit(bodyExpr, paramExprs, il, closureInfo)) return false; il.Emit(OpCodes.Ret); // emits return from generated method return true; } private static Type[] GetClosureAndParamTypes(Type[] paramTypes, Type closureType) { var paramCount = paramTypes.Length; if (paramCount == 0) return new[] { closureType }; if (paramCount == 1) return new[] { closureType, paramTypes[0] }; var closureAndParamTypes = new Type[paramCount + 1]; closureAndParamTypes[0] = closureType; Array.Copy(paramTypes, 0, closureAndParamTypes, 1, paramCount); return closureAndParamTypes; } private struct ConstantInfo { public object ConstantExpr; public Type Type; public object Value; public ConstantInfo(object constantExpr, object value, Type type) { ConstantExpr = constantExpr; Value = value; Type = type; } } private static class EmptyArray<T> { public static readonly T[] Value = new T[0]; } private static T[] Empty<T>() { return EmptyArray<T>.Value; } private static T[] Append<T>(this T[] source, T value) { if (source == null || source.Length == 0) return new[] { value }; if (source.Length == 1) return new[] { source[0], value }; if (source.Length == 2) return new[] { source[0], source[1], value }; var sourceLength = source.Length; var result = new T[sourceLength + 1]; Array.Copy(source, result, sourceLength); result[sourceLength] = value; return result; } private static int IndexOf<T>(this T[] source, Func<T, bool> predicate) { if (source == null || source.Length == 0) return -1; if (source.Length == 1) return predicate(source[0]) ? 0 : -1; for (var i = 0; i < source.Length; ++i) if (predicate(source[i])) return i; return -1; } private sealed class ClosureInfo { // Closed values used by expression and by its nested lambdas public ConstantInfo[] Constants = Empty<ConstantInfo>(); // Parameters not passed through lambda parameter list But used inside lambda body. // The top expression should not! contain non passed parameters. public ParameterExpression[] NonPassedParameters = Empty<ParameterExpression>(); // All nested lambdas recursively nested in expression public NestedLambdaInfo[] NestedLambdas = Empty<NestedLambdaInfo>(); // Field infos are needed to load field of closure object on stack in emitter // It is also an indicator that we use typed Closure object and not an array public FieldInfo[] Fields { get; private set; } // Type of constructed closure, is known after ConstructClosure call public Type ClosureType { get; private set; } // Known after ConstructClosure call public int ClosedItemCount { get; private set; } public void AddConstant(object expr, object value, Type type) { if (Constants.Length == 0 || Constants.IndexOf(it => it.ConstantExpr == expr) == -1) Constants = Constants.Append(new ConstantInfo(expr, value, type)); } public void AddConstant(ConstantInfo info) { if (Constants.Length == 0 || Constants.IndexOf(it => it.ConstantExpr == info.ConstantExpr) == -1) Constants = Constants.Append(info); } public void AddNonPassedParam(ParameterExpression expr) { if (NonPassedParameters.Length == 0 || NonPassedParameters.IndexOf(it => it == expr) == -1) NonPassedParameters = NonPassedParameters.Append(expr); } public void AddNestedLambda(object lambdaExpr, object lambda, ClosureInfo closureInfo, bool isAction) { if (NestedLambdas.Length == 0 || NestedLambdas.IndexOf(it => it.LambdaExpr == lambdaExpr) == -1) NestedLambdas = NestedLambdas.Append(new NestedLambdaInfo(closureInfo, lambdaExpr, lambda, isAction)); } public void AddNestedLambda(NestedLambdaInfo info) { if (NestedLambdas.Length == 0 || NestedLambdas.IndexOf(it => it.LambdaExpr == info.LambdaExpr) == -1) NestedLambdas = NestedLambdas.Append(info); } public object ConstructClosure(bool closureTypeOnly) { var constants = Constants; var nonPassedParams = NonPassedParameters; var nestedLambdas = NestedLambdas; var constPlusParamCount = constants.Length + nonPassedParams.Length; var totalItemCount = constPlusParamCount + nestedLambdas.Length; ClosedItemCount = totalItemCount; var closureCreateMethods = Closure.CreateMethods; // Construct the array based closure when number of values is bigger than // number of fields in biggest supported Closure class. if (totalItemCount > closureCreateMethods.Length) { ClosureType = typeof(ArrayClosure); if (closureTypeOnly) return null; var items = new object[totalItemCount]; if (constants.Length != 0) for (var i = 0; i < constants.Length; i++) items[i] = constants[i].Value; // skip non passed parameters as it is only for nested lambdas if (nestedLambdas.Length != 0) for (var i = 0; i < nestedLambdas.Length; i++) items[constPlusParamCount + i] = nestedLambdas[i].Lambda; return new ArrayClosure(items); } // Construct the Closure Type and optionally Closure object with closed values stored as fields: object[] fieldValues = null; var fieldTypes = new Type[totalItemCount]; if (closureTypeOnly) { if (constants.Length != 0) for (var i = 0; i < constants.Length; i++) fieldTypes[i] = constants[i].Type; if (nonPassedParams.Length != 0) for (var i = 0; i < nonPassedParams.Length; i++) fieldTypes[constants.Length + i] = nonPassedParams[i].Type; if (nestedLambdas.Length != 0) for (var i = 0; i < nestedLambdas.Length; i++) fieldTypes[constPlusParamCount + i] = nestedLambdas[i].Lambda.GetType(); } else { fieldValues = new object[totalItemCount]; if (constants.Length != 0) for (var i = 0; i < constants.Length; i++) { var constantExpr = constants[i]; fieldTypes[i] = constantExpr.Type; fieldValues[i] = constantExpr.Value; } if (nonPassedParams.Length != 0) for (var i = 0; i < nonPassedParams.Length; i++) fieldTypes[constants.Length + i] = nonPassedParams[i].Type; if (nestedLambdas.Length != 0) for (var i = 0; i < nestedLambdas.Length; i++) { var lambda = nestedLambdas[i].Lambda; fieldValues[constPlusParamCount + i] = lambda; fieldTypes[constPlusParamCount + i] = lambda.GetType(); } } var createClosureMethod = closureCreateMethods[totalItemCount - 1]; var createClosure = createClosureMethod.MakeGenericMethod(fieldTypes); ClosureType = createClosure.ReturnType; var fields = ClosureType.GetTypeInfo().DeclaredFields; Fields = fields as FieldInfo[] ?? fields.ToArray(); if (fieldValues == null) return null; return createClosure.Invoke(null, fieldValues); } } #region Closures internal static class Closure { private static readonly IEnumerable<MethodInfo> _methods = typeof(Closure).GetTypeInfo().DeclaredMethods; public static readonly MethodInfo[] CreateMethods = _methods as MethodInfo[] ?? _methods.ToArray(); public static Closure<T1> CreateClosure<T1>(T1 v1) { return new Closure<T1>(v1); } public static Closure<T1, T2> CreateClosure<T1, T2>(T1 v1, T2 v2) { return new Closure<T1, T2>(v1, v2); } public static Closure<T1, T2, T3> CreateClosure<T1, T2, T3>(T1 v1, T2 v2, T3 v3) { return new Closure<T1, T2, T3>(v1, v2, v3); } public static Closure<T1, T2, T3, T4> CreateClosure<T1, T2, T3, T4>(T1 v1, T2 v2, T3 v3, T4 v4) { return new Closure<T1, T2, T3, T4>(v1, v2, v3, v4); } public static Closure<T1, T2, T3, T4, T5> CreateClosure<T1, T2, T3, T4, T5>(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) { return new Closure<T1, T2, T3, T4, T5>(v1, v2, v3, v4, v5); } public static Closure<T1, T2, T3, T4, T5, T6> CreateClosure<T1, T2, T3, T4, T5, T6>(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) { return new Closure<T1, T2, T3, T4, T5, T6>(v1, v2, v3, v4, v5, v6); } public static Closure<T1, T2, T3, T4, T5, T6, T7> CreateClosure<T1, T2, T3, T4, T5, T6, T7>(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) { return new Closure<T1, T2, T3, T4, T5, T6, T7>(v1, v2, v3, v4, v5, v6, v7); } public static Closure<T1, T2, T3, T4, T5, T6, T7, T8> CreateClosure<T1, T2, T3, T4, T5, T6, T7, T8>( T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) { return new Closure<T1, T2, T3, T4, T5, T6, T7, T8>(v1, v2, v3, v4, v5, v6, v7, v8); } public static Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9> CreateClosure<T1, T2, T3, T4, T5, T6, T7, T8, T9>( T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) { return new Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9>(v1, v2, v3, v4, v5, v6, v7, v8, v9); } public static Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> CreateClosure<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) { return new Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10); } } internal sealed class Closure<T1> { public T1 V1; public Closure(T1 v1) { V1 = v1; } } internal sealed class Closure<T1, T2> { public T1 V1; public T2 V2; public Closure(T1 v1, T2 v2) { V1 = v1; V2 = v2; } } internal sealed class Closure<T1, T2, T3> { public T1 V1; public T2 V2; public T3 V3; public Closure(T1 v1, T2 v2, T3 v3) { V1 = v1; V2 = v2; V3 = v3; } } internal sealed class Closure<T1, T2, T3, T4> { public T1 V1; public T2 V2; public T3 V3; public T4 V4; public Closure(T1 v1, T2 v2, T3 v3, T4 v4) { V1 = v1; V2 = v2; V3 = v3; V4 = v4; } } internal sealed class Closure<T1, T2, T3, T4, T5> { public T1 V1; public T2 V2; public T3 V3; public T4 V4; public T5 V5; public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) { V1 = v1; V2 = v2; V3 = v3; V4 = v4; V5 = v5; } } internal sealed class Closure<T1, T2, T3, T4, T5, T6> { public T1 V1; public T2 V2; public T3 V3; public T4 V4; public T5 V5; public T6 V6; public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) { V1 = v1; V2 = v2; V3 = v3; V4 = v4; V5 = v5; V6 = v6; } } internal sealed class Closure<T1, T2, T3, T4, T5, T6, T7> { public T1 V1; public T2 V2; public T3 V3; public T4 V4; public T5 V5; public T6 V6; public T7 V7; public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) { V1 = v1; V2 = v2; V3 = v3; V4 = v4; V5 = v5; V6 = v6; V7 = v7; } } internal sealed class Closure<T1, T2, T3, T4, T5, T6, T7, T8> { public T1 V1; public T2 V2; public T3 V3; public T4 V4; public T5 V5; public T6 V6; public T7 V7; public T8 V8; public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) { V1 = v1; V2 = v2; V3 = v3; V4 = v4; V5 = v5; V6 = v6; V7 = v7; V8 = v8; } } internal sealed class Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9> { public T1 V1; public T2 V2; public T3 V3; public T4 V4; public T5 V5; public T6 V6; public T7 V7; public T8 V8; public T9 V9; public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) { V1 = v1; V2 = v2; V3 = v3; V4 = v4; V5 = v5; V6 = v6; V7 = v7; V8 = v8; V9 = v9; } } internal sealed class Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> { public T1 V1; public T2 V2; public T3 V3; public T4 V4; public T5 V5; public T6 V6; public T7 V7; public T8 V8; public T9 V9; public T10 V10; public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) { V1 = v1; V2 = v2; V3 = v3; V4 = v4; V5 = v5; V6 = v6; V7 = v7; V8 = v8; V9 = v9; V10 = v10; } } internal sealed class ArrayClosure { public readonly object[] Constants; public static FieldInfo ArrayField = typeof(ArrayClosure).GetTypeInfo().DeclaredFields.First(f => !f.IsStatic); public static ConstructorInfo Constructor = typeof(ArrayClosure).GetTypeInfo().DeclaredConstructors.First(); public ArrayClosure(object[] constants) { Constants = constants; } } #endregion #region Nested Lambdas private struct NestedLambdaInfo { public ClosureInfo ClosureInfo; public object LambdaExpr; // to find the lambda in bigger parent expression public object Lambda; public bool IsAction; public NestedLambdaInfo(ClosureInfo closureInfo, object lambdaExpr, object lambda, bool isAction) { ClosureInfo = closureInfo; Lambda = lambda; LambdaExpr = lambdaExpr; IsAction = isAction; } } internal static class CurryClosureFuncs { private static readonly IEnumerable<MethodInfo> _methods = typeof(CurryClosureFuncs).GetTypeInfo().DeclaredMethods; public static readonly MethodInfo[] Methods = _methods as MethodInfo[] ?? _methods.ToArray(); public static Func<R> Curry<C, R>(Func<C, R> f, C c) { return () => f(c); } public static Func<T1, R> Curry<C, T1, R>(Func<C, T1, R> f, C c) { return t1 => f(c, t1); } public static Func<T1, T2, R> Curry<C, T1, T2, R>(Func<C, T1, T2, R> f, C c) { return (t1, t2) => f(c, t1, t2); } public static Func<T1, T2, T3, R> Curry<C, T1, T2, T3, R>(Func<C, T1, T2, T3, R> f, C c) { return (t1, t2, t3) => f(c, t1, t2, t3); } public static Func<T1, T2, T3, T4, R> Curry<C, T1, T2, T3, T4, R>(Func<C, T1, T2, T3, T4, R> f, C c) { return (t1, t2, t3, t4) => f(c, t1, t2, t3, t4); } public static Func<T1, T2, T3, T4, T5, R> Curry<C, T1, T2, T3, T4, T5, R>(Func<C, T1, T2, T3, T4, T5, R> f, C c) { return (t1, t2, t3, t4, t5) => f(c, t1, t2, t3, t4, t5); } public static Func<T1, T2, T3, T4, T5, T6, R> Curry<C, T1, T2, T3, T4, T5, T6, R>(Func<C, T1, T2, T3, T4, T5, T6, R> f, C c) { return (t1, t2, t3, t4, t5, t6) => f(c, t1, t2, t3, t4, t5, t6); } } internal static class CurryClosureActions { private static readonly IEnumerable<MethodInfo> _methods = typeof(CurryClosureActions).GetTypeInfo().DeclaredMethods; public static readonly MethodInfo[] Methods = _methods as MethodInfo[] ?? _methods.ToArray(); internal static Action Curry<C>(Action<C> a, C c) { return () => a(c); } internal static Action<T1> Curry<C, T1>(Action<C, T1> f, C c) { return t1 => f(c, t1); } internal static Action<T1, T2> Curry<C, T1, T2>(Action<C, T1, T2> f, C c) { return (t1, t2) => f(c, t1, t2); } internal static Action<T1, T2, T3> Curry<C, T1, T2, T3>(Action<C, T1, T2, T3> f, C c) { return (t1, t2, t3) => f(c, t1, t2, t3); } internal static Action<T1, T2, T3, T4> Curry<C, T1, T2, T3, T4>(Action<C, T1, T2, T3, T4> f, C c) { return (t1, t2, t3, t4) => f(c, t1, t2, t3, t4); } internal static Action<T1, T2, T3, T4, T5> Curry<C, T1, T2, T3, T4, T5>(Action<C, T1, T2, T3, T4, T5> f, C c) { return (t1, t2, t3, t4, t5) => f(c, t1, t2, t3, t4, t5); } internal static Action<T1, T2, T3, T4, T5, T6> Curry<C, T1, T2, T3, T4, T5, T6>(Action<C, T1, T2, T3, T4, T5, T6> f, C c) { return (t1, t2, t3, t4, t5, t6) => f(c, t1, t2, t3, t4, t5, t6); } } #endregion #region Collect Bound Constants private static bool IsBoundConstant(object value) { if (value == null) return false; var typeInfo = value.GetType().GetTypeInfo(); return !typeInfo.IsPrimitive && !(value is string) && !(value is Type) && !typeInfo.IsEnum; } // @paramExprs is required for nested lambda compilation private static bool TryCollectBoundConstants( ref ClosureInfo closure, Expr e, IList<ParameterExpression> paramExprs) { var expr = e.Expression; if (expr == null) return false; switch (e.NodeType) { case ExpressionType.Constant: var constExprInfo = expr as ConstantExpressionInfo; var value = constExprInfo != null ? constExprInfo.Value : ((ConstantExpression)expr).Value; if (value is Delegate || IsBoundConstant(value)) (closure ?? (closure = new ClosureInfo())).AddConstant(expr, value, e.Type); break; case ExpressionType.Parameter: // if parameter is used But no passed (not in parameter expressions) // it means parameter is provided by outer lambda and should be put in closure for current lambda var exprInfo = expr as ParameterExpressionInfo; var paramExpr = exprInfo ?? (ParameterExpression)expr; if (paramExprs.IndexOf(paramExpr) == -1) (closure ?? (closure = new ClosureInfo())).AddNonPassedParam(paramExpr); break; case ExpressionType.Call: var callExprInfo = expr as MethodCallExpressionInfo; if (callExprInfo != null) return (callExprInfo.Object == null || TryCollectBoundConstants(ref closure, callExprInfo.Object, paramExprs)) && TryCollectBoundConstants(ref closure, callExprInfo.Arguments, paramExprs); var callExpr = (MethodCallExpression)expr; return (callExpr.Object == null || TryCollectBoundConstants(ref closure, callExpr.Object, paramExprs)) && TryCollectBoundConstants(ref closure, callExpr.Arguments, paramExprs); case ExpressionType.MemberAccess: var memberExprInfo = expr as MemberExpressionInfo; if (memberExprInfo != null) return memberExprInfo.Expression == null || TryCollectBoundConstants(ref closure, memberExprInfo.Expression, paramExprs); var memberExpr = ((MemberExpression)expr).Expression; return memberExpr == null || TryCollectBoundConstants(ref closure, memberExpr, paramExprs); case ExpressionType.New: var newExprInfo = expr as NewExpressionInfo; return newExprInfo != null ? TryCollectBoundConstants(ref closure, newExprInfo.Arguments, paramExprs) : TryCollectBoundConstants(ref closure, ((NewExpression)expr).Arguments, paramExprs); case ExpressionType.NewArrayInit: return TryCollectBoundConstants(ref closure, ((NewArrayExpression)expr).Expressions, paramExprs); // property initializer case ExpressionType.MemberInit: var memberInitExpr = (MemberInitExpression)expr; if (!TryCollectBoundConstants(ref closure, memberInitExpr.NewExpression, paramExprs)) return false; var memberBindings = memberInitExpr.Bindings; for (var i = 0; i < memberBindings.Count; ++i) { var memberBinding = memberBindings[i]; if (memberBinding.BindingType == MemberBindingType.Assignment && !TryCollectBoundConstants(ref closure, ((MemberAssignment)memberBinding).Expression, paramExprs)) return false; } break; // nested lambda expression case ExpressionType.Lambda: // 1. Try to compile nested lambda in place // 2. Check that parameters used in compiled lambda are passed or closed by outer lambda // 3. Add the compiled lambda to closure of outer lambda for later invocation object lambda; Type lambdaReturnType; ClosureInfo nestedClosure = null; var lambdaExprInfo = expr as LambdaExpressionInfo; if (lambdaExprInfo != null) { var lambdaParamExprs = lambdaExprInfo.Parameters; lambdaReturnType = lambdaExprInfo.Body.Type; lambda = TryCompile(ref nestedClosure, lambdaExprInfo.Type, GetParamExprTypes(lambdaParamExprs), lambdaReturnType, lambdaExprInfo.Body, lambdaParamExprs, isNestedLambda: true); } else { var lambdaExpr = (LambdaExpression)expr; var lambdaParamExprs = lambdaExpr.Parameters; lambdaReturnType = lambdaExpr.Body.Type; lambda = TryCompile(ref nestedClosure, lambdaExpr.Type, GetParamExprTypes(lambdaParamExprs), lambdaReturnType, lambdaExpr.Body, lambdaParamExprs, isNestedLambda: true); } if (lambda == null) return false; // add the nested lambda into closure (closure ?? (closure = new ClosureInfo())) .AddNestedLambda(expr, lambda, nestedClosure, isAction: lambdaReturnType == typeof(void)); if (nestedClosure == null) break; // if nested non passed parameter is no matched with any outer passed parameter, // then ensure it goes to outer non passed parameter. // But check that have non passed parameter in root expression is invalid. var nestedNonPassedParams = nestedClosure.NonPassedParameters; if (nestedNonPassedParams.Length != 0) for (var i = 0; i < nestedNonPassedParams.Length; i++) { var nestedNonPassedParam = nestedNonPassedParams[i]; if (paramExprs.Count == 0 || paramExprs.IndexOf(nestedNonPassedParam) == -1) closure.AddNonPassedParam(nestedNonPassedParam); } // Promote found constants and nested lambdas into outer closure var nestedConstants = nestedClosure.Constants; if (nestedConstants.Length != 0) for (var i = 0; i < nestedConstants.Length; i++) closure.AddConstant(nestedConstants[i]); var nestedNestedLambdas = nestedClosure.NestedLambdas; if (nestedNestedLambdas.Length != 0) for (var i = 0; i < nestedNestedLambdas.Length; i++) closure.AddNestedLambda(nestedNestedLambdas[i]); break; case ExpressionType.Invoke: var invocationExpr = (InvocationExpression)expr; return TryCollectBoundConstants(ref closure, invocationExpr.Expression, paramExprs) && TryCollectBoundConstants(ref closure, invocationExpr.Arguments, paramExprs); case ExpressionType.Conditional: var conditionalExpr = (ConditionalExpression)expr; return TryCollectBoundConstants(ref closure, conditionalExpr.Test, paramExprs) && TryCollectBoundConstants(ref closure, conditionalExpr.IfTrue, paramExprs) && TryCollectBoundConstants(ref closure, conditionalExpr.IfFalse, paramExprs); default: var unaryExpr = expr as UnaryExpression; if (unaryExpr != null) return TryCollectBoundConstants(ref closure, unaryExpr.Operand, paramExprs); var binaryExpr = expr as BinaryExpression; if (binaryExpr != null) return TryCollectBoundConstants(ref closure, binaryExpr.Left, paramExprs) && TryCollectBoundConstants(ref closure, binaryExpr.Right, paramExprs); break; } return true; } private static bool TryCollectBoundConstants(ref ClosureInfo closure, ExpressionInfo[] exprs, IList<ParameterExpression> paramExprs) { for (var i = 0; i < exprs.Length; i++) if (!TryCollectBoundConstants(ref closure, exprs[i], paramExprs)) return false; return true; } private static bool TryCollectBoundConstants(ref ClosureInfo closure, IList<Expression> exprs, IList<ParameterExpression> paramExprs) { for (var i = 0; i < exprs.Count; i++) if (!TryCollectBoundConstants(ref closure, exprs[i], paramExprs)) return false; return true; } /// <summary>Construct delegate type (Func or Action) from given input and return parameter types.</summary> public static Type GetFuncOrActionType(Type[] paramTypes, Type returnType) { if (returnType == typeof(void)) { switch (paramTypes.Length) { case 0: return typeof(Action); case 1: return typeof(Action<>).MakeGenericType(paramTypes); case 2: return typeof(Action<,>).MakeGenericType(paramTypes); case 3: return typeof(Action<,,>).MakeGenericType(paramTypes); case 4: return typeof(Action<,,,>).MakeGenericType(paramTypes); case 5: return typeof(Action<,,,,>).MakeGenericType(paramTypes); case 6: return typeof(Action<,,,,,>).MakeGenericType(paramTypes); case 7: return typeof(Action<,,,,,,>).MakeGenericType(paramTypes); default: throw new NotSupportedException( string.Format("Action with so many ({0}) parameters is not supported!", paramTypes.Length)); } } paramTypes = paramTypes.Append(returnType); switch (paramTypes.Length) { case 1: return typeof(Func<>).MakeGenericType(paramTypes); case 2: return typeof(Func<,>).MakeGenericType(paramTypes); case 3: return typeof(Func<,,>).MakeGenericType(paramTypes); case 4: return typeof(Func<,,,>).MakeGenericType(paramTypes); case 5: return typeof(Func<,,,,>).MakeGenericType(paramTypes); case 6: return typeof(Func<,,,,,>).MakeGenericType(paramTypes); case 7: return typeof(Func<,,,,,,>).MakeGenericType(paramTypes); case 8: return typeof(Func<,,,,,,,>).MakeGenericType(paramTypes); default: throw new NotSupportedException( string.Format("Func with so many ({0}) parameters is not supported!", paramTypes.Length)); } } #endregion /// <summary>Supports emitting of selected expressions, e.g. lambdaExpr are not supported yet. /// When emitter find not supported expression it will return false from <see cref="TryEmit"/>, so I could fallback /// to normal and slow Expression.Compile.</summary> private static class EmittingVisitor { private static readonly MethodInfo _getTypeFromHandleMethod = typeof(Type).GetTypeInfo() .DeclaredMethods.First(m => m.Name == "GetTypeFromHandle"); public static bool TryEmit(Expr e, IList<ParameterExpression> paramExprs, ILGenerator il, ClosureInfo closure) { var expr = e.Expression; var exprNodeType = e.NodeType; if ((int)exprNodeType == 46) // Support for ExpressionType.Assign in .NET < 4.0 return EmitAssignment(paramExprs, il, closure, expr); switch (exprNodeType) { case ExpressionType.Parameter: var pInfo = expr as ParameterExpressionInfo; return EmitParameter(pInfo != null ? pInfo.ParamExpr : (ParameterExpression)expr, paramExprs, il, closure); case ExpressionType.Convert: return EmitConvert((UnaryExpression)expr, paramExprs, il, closure); case ExpressionType.ArrayIndex: return EmitArrayIndex((BinaryExpression)expr, paramExprs, il, closure); case ExpressionType.Constant: return EmitConstant(e, il, closure); case ExpressionType.Call: return EmitMethodCall(e, paramExprs, il, closure); case ExpressionType.MemberAccess: return EmitMemberAccess(e, paramExprs, il, closure); case ExpressionType.New: return EmitNew(e, paramExprs, il, closure); case ExpressionType.NewArrayInit: return EmitNewArray((NewArrayExpression)expr, paramExprs, il, closure); case ExpressionType.MemberInit: return EmitMemberInit((MemberInitExpression)expr, paramExprs, il, closure); case ExpressionType.Lambda: return EmitNestedLambda(expr, paramExprs, il, closure); case ExpressionType.Invoke: return EmitInvokeLambda((InvocationExpression)expr, paramExprs, il, closure); case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: return EmitComparison((BinaryExpression)expr, paramExprs, il, closure); case ExpressionType.AndAlso: case ExpressionType.OrElse: return EmitLogicalOperator((BinaryExpression)expr, paramExprs, il, closure); case ExpressionType.Conditional: return EmitTernararyOperator((ConditionalExpression)expr, paramExprs, il, closure); //case ExpressionType.Coalesce: default: return false; } } // todo: review implementation for robustness private static bool EmitAssignment(IList<ParameterExpression> paramExprs, ILGenerator il, ClosureInfo closure, object expr) { var assignExpr = (BinaryExpression)expr; if (!TryEmit(assignExpr.Right, paramExprs, il, closure)) return false; var lValueExpr = assignExpr.Left; if (lValueExpr.NodeType == ExpressionType.MemberAccess) { ; // todo: OpCodes.Stfld } else if (lValueExpr.NodeType == ExpressionType.Parameter) { var paramExpr = (ParameterExpression)lValueExpr; var paramIndex = paramExprs.IndexOf(paramExpr); if (paramIndex != -1) { if (closure != null) paramIndex += 1; il.Emit(OpCodes.Starg, paramIndex); LoadParamArg(il, paramIndex); return true; } ; // todo: For parameter in closure, probably also a OpCodes.Stfld } return false; } private static bool EmitParameter(ParameterExpression p, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { var paramIndex = ps.IndexOf(p); // if parameter is passed, then just load it on stack if (paramIndex != -1) { if (closure != null) paramIndex += 1; // shift parameter indices by one, because the first one will be closure LoadParamArg(il, paramIndex); return true; } // if parameter isn't passed, then it is passed into some outer lambda, // so it should be loaded from closure. Then the closure is null will be an invalid case. if (closure == null) return false; var nonPassedParamIndex = closure.NonPassedParameters.IndexOf(it => it == p); if (nonPassedParamIndex == -1) return false; // what??? no chance var closureItemIndex = closure.Constants.Length + nonPassedParamIndex; il.Emit(OpCodes.Ldarg_0); // closure is always a first argument if (closure.Fields != null) il.Emit(OpCodes.Ldfld, closure.Fields[closureItemIndex]); else LoadArrayClosureItem(il, closureItemIndex, p.Type); return true; } private static void LoadParamArg(ILGenerator il, int paramIndex) { switch (paramIndex) { case 0: il.Emit(OpCodes.Ldarg_0); break; case 1: il.Emit(OpCodes.Ldarg_1); break; case 2: il.Emit(OpCodes.Ldarg_2); break; case 3: il.Emit(OpCodes.Ldarg_3); break; default: if (paramIndex <= byte.MaxValue) il.Emit(OpCodes.Ldarg_S, (byte)paramIndex); else il.Emit(OpCodes.Ldarg, paramIndex); break; } } private static bool EmitBinary(BinaryExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { return TryEmit(e.Left, ps, il, closure) && TryEmit(e.Right, ps, il, closure); } private static bool EmitMany(IList<Expression> es, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { for (int i = 0, n = es.Count; i < n; i++) if (!TryEmit(es[i], ps, il, closure)) return false; return true; } private static bool EmitMany(IList<ExpressionInfo> es, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { for (int i = 0, n = es.Count; i < n; i++) if (!TryEmit(es[i], ps, il, closure)) return false; return true; } private static bool EmitConvert(UnaryExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { if (!TryEmit(e.Operand, ps, il, closure)) return false; var targetType = e.Type; var sourceType = e.Operand.Type; if (targetType == sourceType) return true; // do nothing, no conversion is needed if (targetType == typeof(object)) { if (sourceType.GetTypeInfo().IsValueType) il.Emit(OpCodes.Box, sourceType); // for valuy type to object, just box a value return true; // for reference type we don't need to convert } // Just unbox type object to the target value type if (targetType.GetTypeInfo().IsValueType && sourceType == typeof(object)) { il.Emit(OpCodes.Unbox_Any, targetType); return true; } if (targetType == typeof(int)) il.Emit(OpCodes.Conv_I4); else if (targetType == typeof(float)) il.Emit(OpCodes.Conv_R4); else if (targetType == typeof(uint)) il.Emit(OpCodes.Conv_U4); else if (targetType == typeof(sbyte)) il.Emit(OpCodes.Conv_I1); else if (targetType == typeof(byte)) il.Emit(OpCodes.Conv_U1); else if (targetType == typeof(short)) il.Emit(OpCodes.Conv_I2); else if (targetType == typeof(ushort)) il.Emit(OpCodes.Conv_U2); else if (targetType == typeof(long)) il.Emit(OpCodes.Conv_I8); else if (targetType == typeof(ulong)) il.Emit(OpCodes.Conv_U8); else if (targetType == typeof(double)) il.Emit(OpCodes.Conv_R8); else il.Emit(OpCodes.Castclass, targetType); return true; } private static bool EmitConstant(Expr e, ILGenerator il, ClosureInfo closure) { var expr = e.Expression; var constExprInfo = expr as ConstantExpressionInfo; var constantValue = constExprInfo != null ? constExprInfo.Value : ((ConstantExpression)expr).Value; if (constantValue == null) { il.Emit(OpCodes.Ldnull); return true; } var constantActualType = constantValue.GetType(); if (constantActualType.GetTypeInfo().IsEnum) constantActualType = Enum.GetUnderlyingType(constantActualType); if (constantActualType == typeof(int)) { EmitLoadConstantInt(il, (int)constantValue); } else if (constantActualType == typeof(char)) { EmitLoadConstantInt(il, (char)constantValue); } else if (constantActualType == typeof(short)) { EmitLoadConstantInt(il, (short)constantValue); } else if (constantActualType == typeof(byte)) { EmitLoadConstantInt(il, (byte)constantValue); } else if (constantActualType == typeof(ushort)) { EmitLoadConstantInt(il, (ushort)constantValue); } else if (constantActualType == typeof(sbyte)) { EmitLoadConstantInt(il, (sbyte)constantValue); } else if (constantActualType == typeof(uint)) { unchecked { EmitLoadConstantInt(il, (int)(uint)constantValue); } } else if (constantActualType == typeof(long)) { il.Emit(OpCodes.Ldc_I8, (long)constantValue); } else if (constantActualType == typeof(ulong)) { unchecked { il.Emit(OpCodes.Ldc_I8, (long)(ulong)constantValue); } } else if (constantActualType == typeof(float)) { il.Emit(OpCodes.Ldc_R8, (float)constantValue); } else if (constantActualType == typeof(double)) { il.Emit(OpCodes.Ldc_R8, (double)constantValue); } else if (constantActualType == typeof(bool)) { il.Emit((bool)constantValue ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); } else if (constantValue is string) { il.Emit(OpCodes.Ldstr, (string)constantValue); } else if (constantValue is Type) { il.Emit(OpCodes.Ldtoken, (Type)constantValue); il.Emit(OpCodes.Call, _getTypeFromHandleMethod); } else if (closure != null) { var constantIndex = closure.Constants.IndexOf(it => it.ConstantExpr == expr); if (constantIndex == -1) return false; il.Emit(OpCodes.Ldarg_0); // closure is always a first argument if (closure.Fields != null) il.Emit(OpCodes.Ldfld, closure.Fields[constantIndex]); else LoadArrayClosureItem(il, constantIndex, e.Type); } else return false; // boxing the value type, otherwise we can get a strange result when 0 is treated as Null. if (e.Type == typeof(object) && constantActualType.GetTypeInfo().IsValueType) il.Emit(OpCodes.Box, constantValue.GetType()); // using normal type for Enum instead of underlying type return true; } // The @skipCastOrUnboxing option is for use-case when we loading and immediately storing the item, // it may happen when copying from one object array to another. private static void LoadArrayClosureItem(ILGenerator il, int closedItemIndex, Type closedItemType) { // load array field il.Emit(OpCodes.Ldfld, ArrayClosure.ArrayField); // load array item index EmitLoadConstantInt(il, closedItemIndex); // load item from index il.Emit(OpCodes.Ldelem_Ref); // Cast or unbox the object item depending if it is a class or value type if (closedItemType.GetTypeInfo().IsValueType) il.Emit(OpCodes.Unbox_Any, closedItemType); else il.Emit(OpCodes.Castclass, closedItemType); } private static bool EmitNew(Expr e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { var newExprInfo = e.Expression as NewExpressionInfo; if (newExprInfo != null) { if (!EmitMany(newExprInfo.Arguments, ps, il, closure)) return false; il.Emit(OpCodes.Newobj, newExprInfo.Constructor); } else { var newExpr = (NewExpression)e.Expression; if (!EmitMany(newExpr.Arguments, ps, il, closure)) return false; il.Emit(OpCodes.Newobj, newExpr.Constructor); } return true; } private static bool EmitNewArray(NewArrayExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { var elems = e.Expressions; var arrType = e.Type; var elemType = arrType.GetElementType(); if (elemType == null) return false; var isElemOfValueType = elemType.GetTypeInfo().IsValueType; var arrVar = il.DeclareLocal(arrType); EmitLoadConstantInt(il, elems.Count); il.Emit(OpCodes.Newarr, elemType); il.Emit(OpCodes.Stloc, arrVar); for (int i = 0, n = elems.Count; i < n; i++) { il.Emit(OpCodes.Ldloc, arrVar); EmitLoadConstantInt(il, i); // loading element address for later copying of value into it. if (isElemOfValueType) il.Emit(OpCodes.Ldelema, elemType); if (!TryEmit(elems[i], ps, il, closure)) return false; if (isElemOfValueType) il.Emit(OpCodes.Stobj, elemType); // store element of value type by array element address else il.Emit(OpCodes.Stelem_Ref); } il.Emit(OpCodes.Ldloc, arrVar); return true; } private static bool EmitArrayIndex(BinaryExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { if (!EmitBinary(e, ps, il, closure)) return false; il.Emit(OpCodes.Ldelem_Ref); return true; } private static bool EmitMemberInit(MemberInitExpression mi, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { if (!EmitNew(mi.NewExpression, ps, il, closure)) return false; var obj = il.DeclareLocal(mi.Type); il.Emit(OpCodes.Stloc, obj); var bindings = mi.Bindings; for (int i = 0, n = bindings.Count; i < n; i++) { var binding = bindings[i]; if (binding.BindingType != MemberBindingType.Assignment) return false; il.Emit(OpCodes.Ldloc, obj); if (!TryEmit(((MemberAssignment)binding).Expression, ps, il, closure)) return false; var prop = binding.Member as PropertyInfo; if (prop != null) { var propSetMethodName = "set_" + prop.Name; var setMethod = prop.DeclaringType.GetTypeInfo() .DeclaredMethods.FirstOrDefault(m => m.Name == propSetMethodName); if (setMethod == null) return false; EmitMethodCall(il, setMethod); } else { var field = binding.Member as FieldInfo; if (field == null) return false; il.Emit(OpCodes.Stfld, field); } } il.Emit(OpCodes.Ldloc, obj); return true; } private static bool EmitMethodCall(Expr e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { var exprObj = e.Expression; var exprInfo = exprObj as MethodCallExpressionInfo; if (exprInfo != null) { if (exprInfo.Object != null) { if (!TryEmit(exprInfo.Object, ps, il, closure)) return false; IfValueTypeStoreAndLoadValueAddress(il, exprInfo.Object.Type); } if (exprInfo.Arguments.Length != 0 && !EmitMany(exprInfo.Arguments, ps, il, closure)) return false; } else { var expr = (MethodCallExpression)exprObj; if (expr.Object != null) { if (!TryEmit(expr.Object, ps, il, closure)) return false; IfValueTypeStoreAndLoadValueAddress(il, expr.Object.Type); } if (expr.Arguments.Count != 0 && !EmitMany(expr.Arguments, ps, il, closure)) return false; } var method = exprInfo != null ? exprInfo.Method : ((MethodCallExpression)exprObj).Method; EmitMethodCall(il, method); return true; } private static void IfValueTypeStoreAndLoadValueAddress(ILGenerator il, Type ownerType) { if (ownerType.GetTypeInfo().IsValueType) { var valueVar = il.DeclareLocal(ownerType); il.Emit(OpCodes.Stloc, valueVar); il.Emit(OpCodes.Ldloca, valueVar); } } private static bool EmitMemberAccess(Expr e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { var exprObj = e.Expression; var exprInfo = exprObj as MemberExpressionInfo; if (exprInfo != null) { if (exprInfo.Expression != null) { if (!TryEmit(exprInfo.Expression, ps, il, closure)) return false; IfValueTypeStoreAndLoadValueAddress(il, exprInfo.Expression.Type); } } else { var instanceExpr = ((MemberExpression)exprObj).Expression; if (instanceExpr != null) { if (!TryEmit(instanceExpr, ps, il, closure)) return false; IfValueTypeStoreAndLoadValueAddress(il, instanceExpr.Type); } } var member = exprInfo != null ? exprInfo.Member : ((MemberExpression)exprObj).Member; var field = member as FieldInfo; if (field != null) { il.Emit(field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, field); return true; } var prop = member as PropertyInfo; if (prop != null) { var propGetMethodName = "get_" + prop.Name; var getMethod = prop.DeclaringType.GetTypeInfo() .DeclaredMethods.FirstOrDefault(m => m.Name == propGetMethodName); if (getMethod == null) return false; EmitMethodCall(il, getMethod); } return true; } private static bool EmitNestedLambda(object lambdaExpr, IList<ParameterExpression> paramExprs, ILGenerator il, ClosureInfo closure) { // First, find in closed compiled lambdas the one corresponding to the current lambda expression. // Situation with not found lambda is not possible/exceptional, // it means that we somehow skipped the lambda expression while collecting closure info. var outerNestedLambdas = closure.NestedLambdas; var outerNestedLambdaIndex = outerNestedLambdas.IndexOf(it => it.LambdaExpr == lambdaExpr); if (outerNestedLambdaIndex == -1) return false; var nestedLambdaInfo = outerNestedLambdas[outerNestedLambdaIndex]; var nestedLambda = nestedLambdaInfo.Lambda; var outerConstants = closure.Constants; var outerNonPassedParams = closure.NonPassedParameters; // Load compiled lambda on stack counting the offset outerNestedLambdaIndex += outerConstants.Length + outerNonPassedParams.Length; il.Emit(OpCodes.Ldarg_0); // closure is always a first argument if (closure.Fields != null) il.Emit(OpCodes.Ldfld, closure.Fields[outerNestedLambdaIndex]); else LoadArrayClosureItem(il, outerNestedLambdaIndex, nestedLambda.GetType()); // If lambda does not use any outer parameters to be set in closure, then we're done var nestedClosureInfo = nestedLambdaInfo.ClosureInfo; if (nestedClosureInfo == null) return true; // If closure is array-based, the create a new array to represent closure for the nested lambda var isNestedArrayClosure = nestedClosureInfo.Fields == null; if (isNestedArrayClosure) { EmitLoadConstantInt(il, nestedClosureInfo.ClosedItemCount); // size of array il.Emit(OpCodes.Newarr, typeof(object)); } // Load constants on stack var nestedConstants = nestedClosureInfo.Constants; if (nestedConstants.Length != 0) { for (var nestedConstIndex = 0; nestedConstIndex < nestedConstants.Length; nestedConstIndex++) { var nestedConstant = nestedConstants[nestedConstIndex]; // Find constant index in the outer closure var outerConstIndex = outerConstants.IndexOf(it => it.ConstantExpr == nestedConstant.ConstantExpr); if (outerConstIndex == -1) return false; // some error is here if (isNestedArrayClosure) { // Duplicate nested array on stack to store the item, and load index to where to store il.Emit(OpCodes.Dup); EmitLoadConstantInt(il, nestedConstIndex); } il.Emit(OpCodes.Ldarg_0); // closure is always a first argument if (closure.Fields != null) il.Emit(OpCodes.Ldfld, closure.Fields[outerConstIndex]); else LoadArrayClosureItem(il, outerConstIndex, nestedConstant.Type); if (isNestedArrayClosure) { if (nestedConstant.Type.GetTypeInfo().IsValueType) il.Emit(OpCodes.Box, nestedConstant.Type); il.Emit(OpCodes.Stelem_Ref); // store the item in array } } } // Load used and closed parameter values on stack var nestedNonPassedParams = nestedClosureInfo.NonPassedParameters; for (var nestedParamIndex = 0; nestedParamIndex < nestedNonPassedParams.Length; nestedParamIndex++) { var nestedUsedParam = nestedNonPassedParams[nestedParamIndex]; // Duplicate nested array on stack to store the item, and load index to where to store if (isNestedArrayClosure) { il.Emit(OpCodes.Dup); EmitLoadConstantInt(il, nestedConstants.Length + nestedParamIndex); } var paramIndex = paramExprs.IndexOf(nestedUsedParam); if (paramIndex != -1) // load param from input params { // +1 is set cause of added first closure argument LoadParamArg(il, 1 + paramIndex); } else // load parameter from outer closure { if (outerNonPassedParams.Length == 0) return false; // impossible, better to throw? var outerParamIndex = outerNonPassedParams.IndexOf(it => it == nestedUsedParam); if (outerParamIndex == -1) return false; // impossible, better to throw? il.Emit(OpCodes.Ldarg_0); // closure is always a first argument if (closure.Fields != null) il.Emit(OpCodes.Ldfld, closure.Fields[outerConstants.Length + outerParamIndex]); else LoadArrayClosureItem(il, outerConstants.Length + outerParamIndex, nestedUsedParam.Type); } if (isNestedArrayClosure) { if (nestedUsedParam.Type.GetTypeInfo().IsValueType) il.Emit(OpCodes.Box, nestedUsedParam.Type); il.Emit(OpCodes.Stelem_Ref); // store the item in array } } // Load nested lambdas on stack var nestedNestedLambdas = nestedClosureInfo.NestedLambdas; if (nestedNestedLambdas.Length != 0) { for (var nestedLambdaIndex = 0; nestedLambdaIndex < nestedNestedLambdas.Length; nestedLambdaIndex++) { var nestedNestedLambda = nestedNestedLambdas[nestedLambdaIndex]; // Find constant index in the outer closure var outerLambdaIndex = outerNestedLambdas.IndexOf(it => it.LambdaExpr == nestedNestedLambda.LambdaExpr); if (outerLambdaIndex == -1) return false; // some error is here // Duplicate nested array on stack to store the item, and load index to where to store if (isNestedArrayClosure) { il.Emit(OpCodes.Dup); EmitLoadConstantInt(il, nestedConstants.Length + nestedNonPassedParams.Length + nestedLambdaIndex); } outerLambdaIndex += outerConstants.Length + outerNonPassedParams.Length; il.Emit(OpCodes.Ldarg_0); // closure is always a first argument if (closure.Fields != null) il.Emit(OpCodes.Ldfld, closure.Fields[outerLambdaIndex]); else LoadArrayClosureItem(il, outerLambdaIndex, nestedNestedLambda.Lambda.GetType()); if (isNestedArrayClosure) il.Emit(OpCodes.Stelem_Ref); // store the item in array } } // Create nested closure object composed of all constants, params, lambdas loaded on stack if (isNestedArrayClosure) il.Emit(OpCodes.Newobj, ArrayClosure.Constructor); else il.Emit(OpCodes.Newobj, nestedClosureInfo.ClosureType.GetTypeInfo().DeclaredConstructors.First()); EmitMethodCall(il, GetCurryClosureMethod(nestedLambda, nestedLambdaInfo.IsAction)); return true; } private static MethodInfo GetCurryClosureMethod(object lambda, bool isAction) { var lambdaTypeArgs = lambda.GetType().GetTypeInfo().GenericTypeArguments; return isAction ? CurryClosureActions.Methods[lambdaTypeArgs.Length - 1].MakeGenericMethod(lambdaTypeArgs) : CurryClosureFuncs.Methods[lambdaTypeArgs.Length - 2].MakeGenericMethod(lambdaTypeArgs); } private static bool EmitInvokeLambda(InvocationExpression e, IList<ParameterExpression> paramExprs, ILGenerator il, ClosureInfo closure) { if (!TryEmit(e.Expression, paramExprs, il, closure) || !EmitMany(e.Arguments, paramExprs, il, closure)) return false; var invokeMethod = e.Expression.Type.GetTypeInfo().DeclaredMethods.First(m => m.Name == "Invoke"); EmitMethodCall(il, invokeMethod); return true; } private static bool EmitComparison(BinaryExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { if (!TryEmit(e.Left, ps, il, closure) || !TryEmit(e.Right, ps, il, closure)) return false; switch (e.NodeType) { case ExpressionType.Equal: il.Emit(OpCodes.Ceq); break; case ExpressionType.LessThan: il.Emit(OpCodes.Clt); break; case ExpressionType.GreaterThan: il.Emit(OpCodes.Cgt); break; case ExpressionType.NotEqual: il.Emit(OpCodes.Ceq); il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Ceq); break; case ExpressionType.LessThanOrEqual: il.Emit(OpCodes.Cgt); il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Ceq); break; case ExpressionType.GreaterThanOrEqual: il.Emit(OpCodes.Clt); il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Ceq); break; } return true; } private static bool EmitLogicalOperator(BinaryExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { if (!TryEmit(e.Left, ps, il, closure)) return false; var labelSkipRight = il.DefineLabel(); var isAnd = e.NodeType == ExpressionType.AndAlso; il.Emit(isAnd ? OpCodes.Brfalse : OpCodes.Brtrue, labelSkipRight); if (!TryEmit(e.Right, ps, il, closure)) return false; var labelDone = il.DefineLabel(); il.Emit(OpCodes.Br, labelDone); il.MarkLabel(labelSkipRight); // label the second branch il.Emit(isAnd ? OpCodes.Ldc_I4_0 : OpCodes.Ldc_I4_1); il.MarkLabel(labelDone); return true; } private static bool EmitTernararyOperator(ConditionalExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { if (!TryEmit(e.Test, ps, il, closure)) return false; var labelIfFalse = il.DefineLabel(); il.Emit(OpCodes.Brfalse, labelIfFalse); if (!TryEmit(e.IfTrue, ps, il, closure)) return false; var labelDone = il.DefineLabel(); il.Emit(OpCodes.Br, labelDone); il.MarkLabel(labelIfFalse); if (!TryEmit(e.IfFalse, ps, il, closure)) return false; il.MarkLabel(labelDone); return true; } private static void EmitMethodCall(ILGenerator il, MethodInfo method) { il.Emit(method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, method); } private static void EmitLoadConstantInt(ILGenerator il, int i) { switch (i) { case -1: il.Emit(OpCodes.Ldc_I4_M1); break; case 0: il.Emit(OpCodes.Ldc_I4_0); break; case 1: il.Emit(OpCodes.Ldc_I4_1); break; case 2: il.Emit(OpCodes.Ldc_I4_2); break; case 3: il.Emit(OpCodes.Ldc_I4_3); break; case 4: il.Emit(OpCodes.Ldc_I4_4); break; case 5: il.Emit(OpCodes.Ldc_I4_5); break; case 6: il.Emit(OpCodes.Ldc_I4_6); break; case 7: il.Emit(OpCodes.Ldc_I4_7); break; case 8: il.Emit(OpCodes.Ldc_I4_8); break; default: il.Emit(OpCodes.Ldc_I4, i); break; } } } } /// <summary>Base expression.</summary> public abstract class ExpressionInfo { /// <summary>Expression node type.</summary> public abstract ExpressionType NodeType { get; } /// <summary>All expressions should have a Type.</summary> public abstract Type Type { get; } /// <summary>Allow to change parameter expression as info interchangeable.</summary> public static implicit operator ExpressionInfo(ParameterExpression paramExpr) { return new ParameterExpressionInfo(paramExpr); } /// <summary>Analog of Expression.Constant</summary> public static ConstantExpressionInfo Constant(object value, Type type = null) { return new ConstantExpressionInfo(value, type); } /// <summary>Analog of Expression.Convert</summary> public static ConvertExpressionInfo Convert(ExpressionInfo operand, Type targetType) { return new ConvertExpressionInfo(operand, targetType); } /// <summary>Analog of Expression.New</summary> public static NewExpressionInfo New(ConstructorInfo ctor, params ExpressionInfo[] arguments) { return new NewExpressionInfo(ctor, arguments); } /// <summary>Static method call</summary> public static MethodCallExpressionInfo Call(MethodInfo method, params ExpressionInfo[] arguments) { return new MethodCallExpressionInfo(null, method, arguments); } /// <summary>Instance method call</summary> public static MethodCallExpressionInfo Call( ExpressionInfo instance, MethodInfo method, params ExpressionInfo[] arguments) { return new MethodCallExpressionInfo(instance, method, arguments); } /// <summary>Static property</summary> public static PropertyExpressionInfo Property(PropertyInfo property) { return new PropertyExpressionInfo(null, property); } /// <summary>Instance property</summary> public static PropertyExpressionInfo Property(ExpressionInfo instance, PropertyInfo property) { return new PropertyExpressionInfo(instance, property); } /// <summary>Static field</summary> public static FieldExpressionInfo Field(FieldInfo field) { return new FieldExpressionInfo(null, field); } /// <summary>Instance field</summary> public static FieldExpressionInfo Property(ExpressionInfo instance, FieldInfo field) { return new FieldExpressionInfo(instance, field); } /// <summary>Analog of Expression.Lambda</summary> public static LambdaExpressionInfo Lambda(ExpressionInfo body, params ParameterExpression[] parameters) { return new LambdaExpressionInfo(body, parameters); } } /// <summary>Wraps ParameterExpression and just it.</summary> public class ParameterExpressionInfo : ExpressionInfo { /// <summary>Wrapped parameter expression.</summary> public ParameterExpression ParamExpr { get; } /// <summary>Allow to change parameter expression as info interchangeable.</summary> public static implicit operator ParameterExpression(ParameterExpressionInfo info) { return info.ParamExpr; } /// <inheritdoc /> public override ExpressionType NodeType { get { return ExpressionType.Parameter; } } /// <inheritdoc /> public override Type Type { get { return ParamExpr.Type; } } /// <summary>Optional name.</summary> public string Name { get { return ParamExpr.Name; } } /// <summary>Constructor</summary> public ParameterExpressionInfo(ParameterExpression paramExpr) { ParamExpr = paramExpr; } } /// <summary>Analog of ConstantExpression.</summary> public class ConstantExpressionInfo : ExpressionInfo { /// <inheritdoc /> public override ExpressionType NodeType { get { return ExpressionType.Constant; } } /// <inheritdoc /> public override Type Type { get; } /// <summary>Value of constant.</summary> public readonly object Value; /// <summary>Constructor</summary> public ConstantExpressionInfo(object value, Type type = null) { Value = value; Type = type ?? (value == null ? typeof(object) : value.GetType()); } } /// <summary>Analog of Convert expression.</summary> public class ConvertExpressionInfo : ExpressionInfo { /// <inheritdoc /> public override ExpressionType NodeType { get { return ExpressionType.Convert; } } /// <summary>Target type.</summary> public override Type Type { get { return _targetType; } } private readonly Type _targetType; /// <summary>Operand to cast to a target type.</summary> public readonly ExpressionInfo Operand; /// <summary>Constructor</summary> public ConvertExpressionInfo(ExpressionInfo operand, Type targetType) { Operand = operand; _targetType = targetType; } } /// <summary>Base class for expressions with arguments.</summary> public abstract class ArgumentsExpressionInfo : ExpressionInfo { /// <summary>List of arguments</summary> public readonly ExpressionInfo[] Arguments; /// <summary>Constructor</summary> protected ArgumentsExpressionInfo(ExpressionInfo[] arguments) { Arguments = arguments; } } /// <summary>Analog of NewExpression</summary> public class NewExpressionInfo : ArgumentsExpressionInfo { /// <inheritdoc /> public override ExpressionType NodeType { get { return ExpressionType.New; } } /// <inheritdoc /> public override Type Type { get { return Constructor.DeclaringType; } } /// <summary>The constructor info.</summary> public readonly ConstructorInfo Constructor; /// <summary>Construct from constructor info and argument expressions</summary> public NewExpressionInfo(ConstructorInfo constructor, params ExpressionInfo[] arguments) : base(arguments) { Constructor = constructor; } } /// <summary>Analog of MethodCallExpression</summary> public class MethodCallExpressionInfo : ArgumentsExpressionInfo { /// <inheritdoc /> public override ExpressionType NodeType { get { return ExpressionType.Call; } } /// <inheritdoc /> public override Type Type { get { return Method.ReturnType; } } /// <summary>The method info.</summary> public readonly MethodInfo Method; /// <summary>Instance expression, null if static.</summary> public readonly ExpressionInfo Object; /// <summary>Construct from method info and argument expressions</summary> public MethodCallExpressionInfo( ExpressionInfo @object, MethodInfo method, params ExpressionInfo[] arguments) : base(arguments) { Object = @object; Method = method; } } /// <summary>Analog of MemberExpression</summary> public abstract class MemberExpressionInfo : ExpressionInfo { /// <inheritdoc /> public override ExpressionType NodeType { get { return ExpressionType.MemberAccess; } } /// <summary>Member info.</summary> public readonly MemberInfo Member; /// <summary>Instance expression, null if static.</summary> public readonly ExpressionInfo Expression; /// <summary>Constructs with</summary> protected MemberExpressionInfo(ExpressionInfo expression, MemberInfo member) { Expression = expression; Member = member; } } /// <summary>Analog of PropertyExpression</summary> public class PropertyExpressionInfo : MemberExpressionInfo { /// <inheritdoc /> public override Type Type { get { return ((PropertyInfo)Member).PropertyType; } } /// <summary>Construct from property info</summary> public PropertyExpressionInfo(ExpressionInfo instance, PropertyInfo property) : base(instance, property) { } } /// <summary>Analog of PropertyExpression</summary> public class FieldExpressionInfo : MemberExpressionInfo { /// <inheritdoc /> public override Type Type { get { return ((FieldInfo)Member).FieldType; } } /// <summary>Construct from field info</summary> public FieldExpressionInfo(ExpressionInfo instance, FieldInfo field) : base(instance, field) { } } /// <summary>LambdaExpression</summary> public class LambdaExpressionInfo : ExpressionInfo { /// <inheritdoc /> public override ExpressionType NodeType { get { return ExpressionType.Lambda; } } /// <inheritdoc /> public override Type Type { get { return _type; } } private readonly Type _type; /// <summary>Lambda body.</summary> public readonly ExpressionInfo Body; /// <summary>List of parameters.</summary> public readonly ParameterExpression[] Parameters; /// <summary>Constructor</summary> public LambdaExpressionInfo(ExpressionInfo body, ParameterExpression[] parameters) { Body = body; Parameters = parameters; _type = ExpressionCompiler.GetFuncOrActionType(ExpressionCompiler.GetParamExprTypes(parameters), Body.Type); } } /// <summary>Typed lambda expression.</summary> public sealed class ExpressionInfo<TDelegate> : LambdaExpressionInfo { /// <summary>Type of lambda</summary> public Type DelegateType { get { return typeof(TDelegate); } } /// <summary>Constructor</summary> public ExpressionInfo(ExpressionInfo body, ParameterExpression[] parameters) : base(body, parameters) { } } }
apache-2.0
sassoftware/mint
mint/rest/db/filemgr.py
2565
# # Copyright (c) SAS Institute 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 errno import os from conary.lib import util from restlib import response from mint.rest.db import manager class FileManager(manager.Manager): def _getImagePath(self, hostname, imageId, fileName=None, create=False): path = os.path.join(self.cfg.imagesPath, hostname, str(imageId)) if create and not os.path.isdir(path): util.mkdirChain(path) if fileName: path = os.path.join(path, fileName) return path def imageHasFile(self, hostname, imageId, fileName): return os.path.isfile(self._getImagePath(hostname, imageId, fileName)) def getImageFile(self, hostname, imageId, fileName, asResponse=False): path = self._getImagePath(hostname, imageId, fileName) if os.path.exists(path): if asResponse: return response.FileResponse(path, 'text/plain') else: return open(path).read() else: if asResponse: return response.Response('', 'text/plain') else: return '' def appendImageFile(self, hostname, imageId, fileName, data): path = self._getImagePath(hostname, imageId, fileName, create=True) fObj = open(path, 'a') fObj.write(data) fObj.close() def deleteImageFile(self, hostname, imageId, fileName): path = self._getImagePath(hostname, imageId, fileName) try: os.unlink(path) except OSError, err: if err.args[0] != errno.ENOENT: raise # Try to delete the parent directory try: os.rmdir(os.path.dirname(path)) except OSError, err: if err.args[0] not in (errno.ENOENT, errno.ENOTEMPTY): raise def openImageFile(self, hostname, imageId, fileName, mode): create = mode[0] in 'aw' path = self._getImagePath(hostname, imageId, fileName, create) return open(path, mode)
apache-2.0
ImLiar/finch
core/src/main/scala/io/finch/endpoint/body.scala
4655
package io.finch.endpoint import cats.effect.Sync import com.twitter.io.{Buf, Reader} import io.finch._ import io.finch.internal._ import io.finch.items._ import java.nio.charset.{Charset, StandardCharsets} import scala.reflect.ClassTag private[finch] abstract class FullBody[F[_], A] extends Endpoint[F, A] { protected def F: Sync[F] protected def missing: F[Output[A]] protected def present(contentType: String, content: Buf, cs: Charset): F[Output[A]] final def apply(input: Input): EndpointResult[F, A] = if (input.request.isChunked) EndpointResult.NotMatched[F] else { val output = F.suspend { val contentLength = input.request.contentLengthOrNull if (contentLength == null || contentLength == "0") missing else present( input.request.mediaTypeOrEmpty, input.request.content, input.request.charsetOrUtf8 ) } EndpointResult.Matched(input, Trace.empty, output) } final override def item: RequestItem = items.BodyItem } private[finch] object FullBody { trait PreparedBody[F[_], A, B] { _: FullBody[F, B] => protected def prepare(a: A): B } trait Required[F[_], A] extends PreparedBody[F, A, A] { _: FullBody[F, A] => protected def prepare(a: A): A = a protected def missing: F[Output[A]] = F.raiseError(Error.NotPresent(items.BodyItem)) } trait Optional[F[_], A] extends PreparedBody[F, A, Option[A]] { _: FullBody[F, Option[A]] => protected def prepare(a: A): Option[A] = Some(a) protected def missing: F[Output[Option[A]]] = F.pure(Output.None) } } private[finch] abstract class Body[F[_], A, B, CT](implicit dd: Decode.Dispatchable[A, CT], ct: ClassTag[A], protected val F: Sync[F] ) extends FullBody[F, B] with FullBody.PreparedBody[F, A, B] { protected def present(contentType: String, content: Buf, cs: Charset): F[Output[B]] = dd(contentType, content, cs) match { case Right(s) => F.pure(Output.payload(prepare(s))) case Left(e) => F.raiseError(Error.NotParsed(items.BodyItem, ct, e)) } final override def toString: String = "body" } private[finch] abstract class BinaryBody[F[_], A](implicit protected val F: Sync[F]) extends FullBody[F, A] with FullBody.PreparedBody[F, Array[Byte], A] { protected def present(contentType: String, content: Buf, cs: Charset): F[Output[A]] = F.pure(Output.payload(prepare(content.asByteArray))) final override def toString: String = "binaryBody" } private[finch] abstract class StringBody[F[_], A](implicit protected val F: Sync[F]) extends FullBody[F, A] with FullBody.PreparedBody[F, String, A] { protected def present(contentType: String, content: Buf, cs: Charset): F[Output[A]] = F.pure(Output.payload(prepare(content.asString(cs)))) final override def toString: String = "stringBody" } private[finch] abstract class ChunkedBody[F[_], S[_[_], _], A] extends Endpoint[F, S[F, A]] { protected def F: Sync[F] protected def prepare(r: Reader[Buf], cs: Charset): Output[S[F, A]] final def apply(input: Input): EndpointResult[F, S[F, A]] = if (!input.request.isChunked) EndpointResult.NotMatched[F] else EndpointResult.Matched( input, Trace.empty, F.delay(prepare(input.request.reader, input.request.charsetOrUtf8)) ) final override def item: RequestItem = items.BodyItem } private[finch] final class BinaryBodyStream[F[_], S[_[_], _]](implicit LR: LiftReader[S, F], protected val F: Sync[F] ) extends ChunkedBody[F, S, Array[Byte]] with (Buf => Array[Byte]) { def apply(buf: Buf): Array[Byte] = buf.asByteArray protected def prepare(r: Reader[Buf], cs: Charset): Output[S[F, Array[Byte]]] = Output.payload(LR(r, this)) override def toString: String = "binaryBodyStream" } private[finch] final class StringBodyStream[F[_], S[_[_], _]](implicit LR: LiftReader[S, F], protected val F: Sync[F] ) extends ChunkedBody[F, S, String] with (Buf => String) { def apply(buf: Buf): String = buf.asString(StandardCharsets.UTF_8) protected def prepare(r: Reader[Buf], cs: Charset): Output[S[F, String]] = cs match { case StandardCharsets.UTF_8 => Output.payload(LR(r, this)) case _ => Output.payload(LR(r, _.asString(cs))) } override def toString: String = "stringBodyStream" } private[finch] final class BodyStream[F[_], S[_[_], _], A, CT <: String](implicit protected val F: Sync[F], LR: LiftReader[S, F], A: DecodeStream.Aux[S, F, A, CT] ) extends ChunkedBody[F, S, A] { protected def prepare(r: Reader[Buf], cs: Charset): Output[S[F, A]] = Output.payload(A(LR(r), cs)) override def toString: String = "bodyStream" }
apache-2.0
NationalSecurityAgency/ghidra
Ghidra/Debug/Debugger-agent-lldb/src/main/java/agent/lldb/model/iface2/LldbModelTargetBreakpointSpec.java
3126
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package agent.lldb.model.iface2; import java.util.concurrent.CompletableFuture; import agent.lldb.lldb.DebugClient; import ghidra.dbg.target.TargetBreakpointSpec; import ghidra.dbg.target.TargetBreakpointSpecContainer.TargetBreakpointKindSet; import ghidra.dbg.target.TargetDeletable; import ghidra.util.datastruct.ListenerSet; public interface LldbModelTargetBreakpointSpec extends // LldbModelTargetObject, // TargetBreakpointSpec, // TargetDeletable { String BPT_ACCESS_ATTRIBUTE_NAME = "Access"; String BPT_DISP_ATTRIBUTE_NAME = "Enabled"; String BPT_VALID_ATTRIBUTE_NAME = "Valid"; String BPT_TIMES_ATTRIBUTE_NAME = "Count"; String BPT_TYPE_ATTRIBUTE_NAME = "Type"; String BPT_INDEX_ATTRIBUTE_NAME = "Id"; @Override public default CompletableFuture<Void> delete() { return getModel().gateFuture(getManager().deleteBreakpoints(getId())); } @Override public default CompletableFuture<Void> disable() { setEnabled(false, "Disabled"); return getModel().gateFuture(getManager().disableBreakpoints(getId())); } @Override public default CompletableFuture<Void> enable() { setEnabled(true, "Enabled"); return getModel().gateFuture(getManager().enableBreakpoints(getId())); } public default String getId() { return DebugClient.getId(getModelObject()); } @Override public TargetBreakpointKindSet getKinds(); public void updateInfo(Object info, String reason); /** * Update the enabled field * * This does not actually toggle the breakpoint. It just updates the field and calls the proper * listeners. To actually toggle the breakpoint, use {@link #toggle(boolean)} instead, which if * effective, should eventually cause this method to be called. * * @param enabled true if enabled, false if disabled * @param reason a description of the cause (not really used, yet) */ public void setEnabled(boolean enabled, String reason); public ListenerSet<TargetBreakpointAction> getActions(); @Override public default void addAction(TargetBreakpointAction action) { getActions().add(action); } @Override public default void removeAction(TargetBreakpointAction action) { getActions().remove(action); } public default void breakpointHit() { LldbModelTargetThread targetThread = getParentProcess().getThreads().getTargetThread(getManager().getEventThread()); getActions().fire.breakpointHit((LldbModelTargetBreakpointSpec) getProxy(), targetThread, null, findLocation(targetThread)); } public LldbModelTargetBreakpointLocation findLocation(Object object); }
apache-2.0
lilpaw/thwack
app/models/end.rb
73
class End < ActiveRecord::Base belongs_to :round has_many :arrows end
apache-2.0
dans123456/pnc
ui/app/import/product/ProductImportCtrl.js
14263
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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. */ 'use strict'; (function () { var module = angular.module('pnc.import'); module.controller('ProductImportCtrl', [ '$log', 'productImport', 'TreeFactory', '$scope', '$timeout', 'pncNotify', '$state', 'ProductVersionDAO', function ($log, productImport, TreeFactory, scope, $timeout, pncNotify, $state, ProductVersionDAO) { scope.started = false; scope.display = 'start'; scope.$watch('display', function(newval) { scope.$root.importProductState = newval; }); var data = {}; // data loaded from analyzer endpoints scope.startData = {}; scope.startSubmitDisabled = false; scope.startTooltipIsOpen = false; scope.finishSubmitDisabled = false; scope.finishTooltipIsOpen = false; scope.bcData = {}; // data for the left-side form var tree = TreeFactory.build(); scope.tree = tree; scope.validateFormCaller = {call: _.noop()}; /** * Given node, return string label to use in the tree. */ var getNodeText = function (node) { var nodeClass = 'text-'; var nodeTitle = ''; if (!node.getParent().nodeData) { nodeClass = ''; } else if (node.nodeData.internallyBuilt) { nodeClass += 'success'; nodeTitle = 'The artifact was already built.'; } else if (node.nodeData.availableVersions && node.nodeData.availableVersions.length) { nodeClass += 'warning'; nodeTitle = 'Another version of the artifact was already built.'; } else { nodeClass += 'danger'; nodeTitle = 'The artifact hasn\'t been built yet.'; } return '<span class="' + nodeClass + '" title="' + nodeTitle + '">' + node.nodeData.gav.groupId + ':<strong>' + node.nodeData.gav.artifactId + '</strong>:' + node.nodeData.gav.version + (nodeIsValid(node) ? '' : '<span class="fa fa-exclamation-triangle" style="color: #ec7a08;"></span>') + '<span>'; }; var getNodeGavString = function (node) { return node.nodeData.gav.groupId + ':' + node.nodeData.gav.artifactId + ':' + node.nodeData.gav.version; }; var nodeIsValid = function (node) { if (!_(node).has('valid')) { node.valid = true; } return node.valid; }; /** * Handle clicking on a BC in the tree. */ var nodeSelect = function (node) { $timeout(function () { scope.bcData = node; }); }; /** * Handle toggling a checkbox in the tree. * Does not check the parent boxes, but uncheckes recursively. */ var nodeToggle = function (node) { $timeout(function () { if (_.isUndefined(node.state)) { node.state = {}; } node.state.checked = node.state.checked !== true; if (node.state.checked) { var n = node.getParent(); while (n !== null) { if (_.isUndefined(n.state)) { n.state = {}; } //n.state.checked = true; n = n.getParent(); } } else { var recursiveUncheck = function (n) { if (_.isUndefined(n.state)) { n.state = {}; } //n.state.checked = false; _.forEach(n.nodes, function (e) { recursiveUncheck(e); }); }; recursiveUncheck(node); } tree._refresh(); }); }; /** * Handle clicking on the arrow for expanding/collapsing a subtree. */ var nodeExpand = function (node) { $timeout(function () { if (_.isUndefined(node.state)) { node.state = {}; } node.state.expanded = node.state.expanded !== true; tree._refresh(); }); }; var isStrNonEmpty = function (str) { return _.isString(str) && str.length > 0; }; var isValidBCName = function (name) { var BC_NAME_REGEXP = /^[a-zA-Z0-9_.][a-zA-Z0-9_.-]*(?!\.git)+$/; return BC_NAME_REGEXP.test(name); }; var isValidURL = function (url) { var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@\-\/]))?$/; return URL_REGEXP.test(url); }; var nodeValidate = function (node) { node.valid = isStrNonEmpty(node.nodeData.name) && (!isStrNonEmpty(node.nodeData.scmUrl) || isValidURL(node.nodeData.scmUrl)) && (!isStrNonEmpty(node.nodeData.name) || isValidBCName(node.nodeData.name)) && (node.nodeData.environmentId !== null) && (node.nodeData.projectId !== null); return node.valid; }; /** * Stick the above handlers on each tree node * when it is being parsed from received data. */ var processNode = function (node) { node.select = _.partial(nodeSelect, node); node.text = getNodeText(node); node.gavString = getNodeGavString(node); node.toggle = _.partial(nodeToggle, node); node.analyze = _.partial(analyzeNextLevel, node); node.expand = _.partial(nodeExpand, node); node.validate = _.partial(nodeValidate, node); }; /** * Set checkbox state depending on the REST data */ var processCheckbox = function (node) { if (_.isUndefined(node.state)) { node.state = {}; } node.state.checked = node.nodeData.selected; }; /** * Given a tree and the JSON data structure from the analyzer REST endpoint, * parse the structure to add nodes on the tree as needed. * @return true on success * * @param tree * Tree representation which is displayed * * @param data * Tree data coming from REST * */ var parseData = function (tree, data) { /** * Check if the node contains child representing the given dependency, * so there are no duplicates in the tree. */ var find = function (node, dependency) { return _(node.nodes).find(function (e) { return _.isEqual(e.nodeData.gav, dependency.gav); }); }; var recursiveParse = function (node, dataNode) { var subNode = find(node, dataNode); var subNodeData = _.omit(dataNode, 'dependencies'); if (_.isUndefined(subNode)) { subNode = node.append(subNodeData); processNode(subNode); } else { subNode.nodeData = subNodeData; } processCheckbox(subNode); if (_.isArray(dataNode.dependencies)) { var res = true; _.forEach(dataNode.dependencies, function (dependency) { res = recursiveParse(subNode, dependency) && res; }); return res; } else { return false; } }; return recursiveParse(tree, data.topLevelBc); }; /** * Parse the tree to get the required JSON data structure, * basically the reverse of {@link parseData}. * @param tree * @param update function that allows to use this function in a more general way. * Is called for each node parsed and returns 'BC object' for that node, which is the included * in the resulting JSON data. */ var parseTree0 = function (tree, update) { var res = _.chain(data).clone().omit('scmUrl', 'scmRevision', 'topLevelBc').value(); res.bcSetName = scope.bcSetName; var recursiveParse = function (node) { var n = update(node); n.dependencies = _(node.nodes).map(function (e) { return recursiveParse(e); }); return n; }; res.topLevelBc = recursiveParse(tree.nodes[0]); return res; }; /** * Parse tree for analyzing next level. */ var parseTree = function (tree) { return parseTree0(tree, function (node) { node.nodeData.cloneRepo = false; return _.clone(node.nodeData); }); }; /** * Parse tree for finishing process. * Takes checkboxes into account. */ var parseTreeFinish = function (tree) { return parseTree0(tree, function (node) { node.nodeData.cloneRepo = false; var n = _.clone(node.nodeData); n.selected = !_.isUndefined(node.state) && node.state.checked; return n; }); }; var validateTree = function (tree) { var recursiveParse = function (node) { var valid = true; node.selected = !_.isUndefined(node.state) && node.state.checked; //var isValid = node.validate(); if (node.selected && !node.nodeData.useExistingBc) { valid = node.validate();//isValid; } if (_(node).has('nodes')) { _.forEach(node.nodes, function (n) { valid = recursiveParse(n) && valid; }); } node.text = getNodeText(node); return valid; }; return recursiveParse(tree.nodes[0]); }; scope.startProcess = function () { scope.startSubmitDisabled = true; scope.startTooltipIsOpen = false; pncNotify.info('Preparing analysis. This may take a minute, please be patient.'); productImport.start(scope.startData).then(function (r) { if (_(r).has('id')) { data = r; scope.id = data.id; scope.bcSetName = data.bcSetName; parseData(tree, data); tree.nodes[0].nlaSuccessful = true; tree.nodes[0].select(); scope.display = 'bc'; tree._refresh(); } else { pncNotify.error('Something went wrong. Make sure that you entered correct data.'); } }, function(error) { $log.error('Error starting import process: %s', JSON.stringify(error, null, 2)); pncNotify.error('RPC Server Error ' + error.code + ': ' + error.message); scope.startTooltipIsOpen = true; }).finally(function() { scope.startSubmitDisabled = false; }); }; var analyzeNextLevel = function (node) { node.nlaSuccessful = true; tree.nodes[0].select(); node.select(); node.nodeData.selected = true; data = parseTree(tree); pncNotify.info('Analyzing \'' + node.gavString + '\'. This may take a minute, please be patient.'); productImport.nextLevel(data).then(function (r) { if (_(r).has('id')) { data = r; if (parseData(tree, data)) { node.nlaSuccessful = true; tree.nodes[0].select(); node.select(); node.expand(); pncNotify.success('Successfully analyzed ' + (_.isUndefined(node.nodes) ? 0 : node.nodes.length) + ' dependencies for \'' + node.gavString + '\'.'); } else { pncNotify.warn('Could not find dependencies of \'' + node.gavString + '\' in a repository.'); } } else { node.nlaSuccessful = false; tree.nodes[0].select(); node.select(); pncNotify.error('Could not analyze \'' + node.gavString + '\'. Check that the information in the form is correct.'); } }, function(error) { $log.error('Remote error analyzing next level: ' + JSON.stringify(error, null, 2)); pncNotify.error('Error analyzing next level: ' + error.message); }); }; var goToProductVersion = function(id) { // TODO unnecessary rest call ProductVersionDAO.get({versionId:id}).$promise.then(function(r) { $state.go('product.detail.version', {productId: r.productId,versionId: r.id}); }); }; scope.finishProcess = function () { if(_.isUndefined(tree.nodes[0].state) || tree.nodes[0].state.checked !== true) { pncNotify.warn('You have to select at least one BC.'); return; } data = parseTreeFinish(tree); if (validateTree(tree)) { scope.finishSubmitDisabled = true; scope.finishTooltipIsOpen = false; pncNotify.info('Product is being imported. This may take a minute, please be patient.'); productImport.finish(data).then(function (r) { if(r.success) { pncNotify.success('Product import completed!'); scope.reset(); goToProductVersion(r.productVersionId); } else { pncNotify.error('Product import failed. ' + r.message); } }, function(error) { $log.error('Remote error finishing import process: ' + JSON.stringify(error, null, 2)); pncNotify.error('Product import failed: ' + error.message); scope.finishTooltipIsOpen = true; }).finally(function() { scope.finishSubmitDisabled = false; }); } else { tree._refresh(); pncNotify.warn('Some data is invalid or missing. Verify all checked BCs.'); } }; scope.reset = function () { data = {}; tree.clear(); scope.display = 'start'; }; } ]); }) ();
apache-2.0
azurenightwalker/MyFinances
MyFinances/src/main/java/com/androidproductions/myfinances/data/FinancesDB.java
1067
package com.androidproductions.myfinances.data; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class FinancesDB extends SQLiteOpenHelper { public static final String TABLE_ACCOUNTS = "accounts"; private static final String DATABASE_NAME = "Finances"; private static final String DATABASE_CREATE_ACCOUNTS = "create table "+ TABLE_ACCOUNTS +" (" + AccountContract._ID + " integer primary key autoincrement, " + AccountContract.Name + " text not null, " + AccountContract.Balance + " int not null, " + AccountContract.Overdraft + " int null)"; public FinancesDB(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(DATABASE_CREATE_ACCOUNTS); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) { } }
apache-2.0
God2016/poster_1472181226002
src/main/java/cn/dmesoft/haibao/modules/test/entity/Test.java
2951
/** * Copyright &copy; 2012-2016 <a href="http://dmesoft.cn">dmesoft</a> All rights reserved. */ package cn.dmesoft.haibao.modules.test.entity; import java.util.Date; import cn.dmesoft.haibao.common.persistence.DataEntity; import cn.dmesoft.haibao.common.supcan.annotation.treelist.SupTreeList; import cn.dmesoft.haibao.common.supcan.annotation.treelist.cols.SupCol; import cn.dmesoft.haibao.common.supcan.annotation.treelist.cols.SupGroup; import org.hibernate.validator.constraints.Length; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import cn.dmesoft.haibao.modules.sys.entity.Office; /** * 测试Entity * @author dmesoft * @version 2013-10-17 */ @SupTreeList( groups={ @SupGroup(id="date", name="日期", sort=50), @SupGroup(id="date2", name="日期2", sort=60, parentId="date"), @SupGroup(id="date3", name="日期3", sort=70, parentId="date") }) public class Test extends DataEntity<Test> { private static final long serialVersionUID = 1L; private Office office; // 归属部门 private String loginName;// 登录名 private String name; // 名称 public Test() { super(); } public Test(String id){ super(id); } @SupCol(text="归属公司", sort = 10, minWidth="125px") @JsonSerialize(using = ToStringSerializer.class) public Office getOffice() { return office; } public void setOffice(Office office) { this.office = office; } @SupCol(text="登录名", sort = 20, minWidth="125px") public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } @SupCol(text="姓名", sort = 30, minWidth="125px") @Length(min=1, max=200) public String getName() { return name; } public void setName(String name) { this.name = name; } @SupCol(text="创建时间", sort = 1, groupId="date", width="125px") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getCreateDate() { return createDate; } @SupCol(text="修改时间", sort = 2, groupId="date", width="125px") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getUpdateDate() { return updateDate; } @SupCol(text="创建时间2", sort = 2, groupId="date2", width="125px") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getCreateDate2() { return createDate; } @SupCol(text="修改时间2", sort = 1, groupId="date2", width="125px") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getUpdateDate2() { return updateDate; } @SupCol(text="创建时间3", sort = 200, groupId="date3", width="125px") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getCreateDate3() { return createDate; } @SupCol(text="修改时间3", sort = 1, groupId="date3", width="125px") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getUpdateDate3() { return updateDate; } }
apache-2.0
tolbertam/java-driver
driver-core/src/test/java/com/datastax/driver/core/DseCCMClusterTest.java
2772
/* * Copyright (C) 2012-2017 DataStax 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. */ package com.datastax.driver.core; import org.testng.annotations.Test; import static com.datastax.driver.core.CCMAccess.Workload.*; /** * A simple test to validate DSE setups. * <p/> * <h3>Running all tests against DSE</h3> * <p/> * To run tests globally against DSE, set the system property {@code dse} * to {@code true}. * <p/> * When this flag is provided, it is assumed a DSE version is passed under * the system property {@code cassandra.version}. * A mapping for determining C* version from DSE version is described in {@link CCMBridge}. * <p/> * Example usages: * <p/> * DSE 4.8.3: * <pre> * -Ddse -Dcassandra.version=4.8.3 * -Ddse=true -Dcassandra.version=4.8.3 * </pre> * <p/> * Custom local install of DSE 5.0 (using {@code cassandra.directory} instead of {@code cassandra.version}): * <pre> * -Dcassandra.version=5.0 -Ddse -Dcassandra.directory=/path/to/dse * </pre> * <p/> * <h3>Running a specific test against DSE</h3> * <p/> * Set the following properties on the test: * <pre>{@code @CCMConfig(dse = true, version = "4.8.3")}</pre> * * <h3>Supplying DSE credentials</h3> * * Rather than adding system properties for DSE credentials, * DSE tests rely on a recent change in CCM to support providing * credentials via {@code $HOME/.ccm/.dse.ini}. * * The contents of this file need to be formed in this way: * <pre> * [dse_credentials] * dse_username = myusername * dse_password = mypassword * </pre> * <p/> * <h3>Other requirements</h3> * <p/> * DSE requires your {@code PATH} variable to provide access * to super-user executables in {@code /usr/sbin}. * <p/> * A correct example is as follows: {@code /usr/bin:/usr/local/bin:/bin:/usr/sbin:$JAVA_HOME/bin:$PATH}. */ @Test(enabled = false) @CCMConfig( dse = true, numberOfNodes = 3, version = "4.8.3", workloads = { @CCMWorkload(solr), @CCMWorkload({spark, solr}), @CCMWorkload({cassandra, spark}) } ) public class DseCCMClusterTest extends CCMTestsSupport { @Test(groups = "short") public void should_conenct_to_dse() throws InterruptedException { } }
apache-2.0
kolstae/openpipe
solr-producer/src/main/java/no/trank/openpipe/solr/producer/SolrDocumentProducer.java
2615
/* * Copyright 2007 T-Rank AS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package no.trank.openpipe.solr.producer; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.ServletHandler; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.jetty.servlet.ServletMapping; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Adds the update servlet and fires up jetty. * * @version $Revision$ */ public class SolrDocumentProducer implements Runnable { private static final Logger log = LoggerFactory.getLogger(SolrDocumentProducer.class); private Server server; private SolrUpdateServlet solrUpdateServlet; private String updatePath; /** * Initialization - adds the update servlet */ public void init() { ServletHandler servletHandler = new ServletHandler(); ServletHolder updateHolder = new ServletHolder(solrUpdateServlet); updateHolder.setName("updateServlet"); servletHandler.addServlet(updateHolder); ServletMapping updateMapping = new ServletMapping(); updateMapping.setPathSpec(updatePath); updateMapping.setServletName("updateServlet"); servletHandler.addServletMapping(updateMapping); server.addHandler(servletHandler); } /** * Fires up jetty. */ @Override public void run() { log.info("Starting Solr producer"); startJetty(); } private void startJetty() { try { if(!server.isRunning()) { server.start(); log.info("Successfully started jetty"); } else { log.info("Jetty is already running."); } } catch (Exception e) { log.error("Error starting jetty", e); } } // spring setters public void setServer(Server server) { this.server = server; } public void setSolrUpdateServlet(SolrUpdateServlet solrUpdateServlet) { this.solrUpdateServlet = solrUpdateServlet; } public void setUpdatePath(String updatePath) { this.updatePath = updatePath; } }
apache-2.0
GoogleCloudPlatform/ml-pipeline-generator-python
ml_pipeline_gen/templates/xgboost_model.py
779
# Copyright 2020 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ML model definition.""" from {{model_path}} import get_model def get_estimator(params): """Returns a SKLearn model.""" estimator = get_model(params) return estimator
apache-2.0
inkstand-io/halite
halite-core/src/main/java/io/inkstand/halite/HAL.java
2182
package io.inkstand.halite; import javax.xml.bind.annotation.XmlTransient; /** * The class contains factory methods to create simple Resources and Links and provides a set of standard link * relations. * * @author <a href="mailto:gerald.muecke@gmail.com">Gerald M&uuml;cke</a> */ @XmlTransient public final class HAL { /** * Relation identifier for a self reference */ public static final String SELF = "self"; /** * Relation identifier for a next page */ public static final String NEXT = "next"; /** * Relation identifier for a previous page */ public static final String PREV = "prev"; /** * Relation identifier for a first page */ public static final String FIRST = "first"; /** * Relation identifier for a last page */ public static final String LAST = "last"; private static final ObjectFactory FACTORY = new ObjectFactory(); private HAL() { } /** * Creates a new Link that can be added to a resource. The method requires the mandatory attributes for a link. * * @param rel * the relation that the link denotes * @param href * the hyper-reference, the target, of the link * @return the new link link */ public static Link newLink(final String rel, final String href) { return FACTORY.createLink(rel, href); } /** * Creates a Link that is added to the specified resource. The method requires the mandatory attributes for a link. * * @param resource * the resource to which the link is added * @param rel * the relation that the link denotes * @param href * the hyper-reference, the target, of the link * @return a link */ public static Link newLink(final Resource resource, final String rel, final String href) { return resource.addLink(rel, href); } /** * Creates a new Resource for the specified uri * * @return the created resource */ public static Resource newResource(final String uri) { return FACTORY.createResource(uri); } }
apache-2.0
NLeSC/Platinum
ptk-vbrowser-vrs/src/main/java/nl/esciencecenter/vbrowser/vrs/localfs/LocalFileAttributes.java
2257
/* * Copyright 2012-2014 Netherlands eScience Center. * * 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 the following location: * * 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. * * For the full license, see: LICENSE.txt (located in the root folder of this distribution). * --- */ // source: package nl.esciencecenter.vbrowser.vrs.localfs; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import nl.esciencecenter.vbrowser.vrs.io.VFSFileAttributes; public class LocalFileAttributes implements VFSFileAttributes { protected BasicFileAttributes attrs; public LocalFileAttributes(BasicFileAttributes attrs) { this.attrs = attrs; } public boolean isSymbolicLink() { return attrs.isSymbolicLink(); } public String getSymbolicLinkTarget() { return null; } public boolean isHidden() { return false; } @Override public FileTime lastModifiedTime() { return attrs.lastModifiedTime(); } @Override public FileTime lastAccessTime() { return attrs.lastAccessTime(); } @Override public FileTime creationTime() { return attrs.creationTime(); } @Override public boolean isRegularFile() { return attrs.isRegularFile(); } @Override public boolean isDirectory() { return attrs.isDirectory(); } @Override public boolean isOther() { return attrs.isOther(); } @Override public long size() { return attrs.size(); } @Override public Object fileKey() { return attrs.fileKey(); } @Override public boolean isLocal() { return true; } @Override public boolean isRemote() { return false; } }
apache-2.0
twilmes/sql-gremlin
src/main/java/org/twilmes/sql/gremlin/adapter/converter/ast/nodes/operator/GremlinSqlBasicCall.java
4845
/* * 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.twilmes.sql.gremlin.adapter.converter.ast.nodes.operator; import lombok.Getter; import org.apache.calcite.sql.SqlBasicCall; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.twilmes.sql.gremlin.adapter.converter.SqlMetadata; import org.twilmes.sql.gremlin.adapter.converter.ast.nodes.GremlinSqlFactory; import org.twilmes.sql.gremlin.adapter.converter.ast.nodes.GremlinSqlNode; import org.twilmes.sql.gremlin.adapter.converter.ast.nodes.operands.GremlinSqlIdentifier; import org.twilmes.sql.gremlin.adapter.converter.ast.nodes.operator.aggregate.GremlinSqlAggFunction; import org.twilmes.sql.gremlin.adapter.converter.ast.nodes.operator.logic.GremlinSqlNumericLiteral; import java.sql.SQLException; import java.util.List; /** * This module is a GremlinSql equivalent of Calcite's SqlBasicCall. * * @author Lyndon Bauto (lyndonb@bitquilltech.com) */ @Getter public class GremlinSqlBasicCall extends GremlinSqlNode { private static final Logger LOGGER = LoggerFactory.getLogger(GremlinSqlBasicCall.class); private final SqlBasicCall sqlBasicCall; private final GremlinSqlOperator gremlinSqlOperator; private final List<GremlinSqlNode> gremlinSqlNodes; public GremlinSqlBasicCall(final SqlBasicCall sqlBasicCall, final SqlMetadata sqlMetadata) throws SQLException { super(sqlBasicCall, sqlMetadata); this.sqlBasicCall = sqlBasicCall; gremlinSqlOperator = GremlinSqlFactory.createOperator(sqlBasicCall.getOperator(), sqlBasicCall.getOperandList()); gremlinSqlNodes = GremlinSqlFactory.createNodeList(sqlBasicCall.getOperandList()); } void validate() throws SQLException { if (gremlinSqlOperator instanceof GremlinSqlAsOperator) { if (gremlinSqlNodes.size() != 2) { throw new SQLException("Error, expected only two sub nodes for GremlinSqlBasicCall."); } } else if (gremlinSqlOperator instanceof GremlinSqlAggFunction) { if (gremlinSqlNodes.size() != 1) { throw new SQLException("Error, expected only one sub node for GremlinSqlAggFunction."); } } } public void generateTraversal(final GraphTraversal<?, ?> graphTraversal) throws SQLException { validate(); gremlinSqlOperator.appendOperatorTraversal(graphTraversal); } public String getRename() throws SQLException { if (gremlinSqlOperator instanceof GremlinSqlAsOperator) { return ((GremlinSqlAsOperator) gremlinSqlOperator).getRename(); } else if (gremlinSqlOperator instanceof GremlinSqlAggFunction) { if (gremlinSqlNodes.size() == 1 && gremlinSqlNodes.get(0) instanceof GremlinSqlIdentifier) { // returns the formatted column name for aggregations return ((GremlinSqlAggFunction) gremlinSqlOperator).getNewName(); } } throw new SQLException("Unable to determine column rename."); } public String getActual() throws SQLException { if (gremlinSqlOperator instanceof GremlinSqlAsOperator) { return ((GremlinSqlAsOperator) gremlinSqlOperator).getActual(); } else if (gremlinSqlOperator instanceof GremlinSqlAggFunction) { if (gremlinSqlNodes.size() == 1 && gremlinSqlNodes.get(0) instanceof GremlinSqlIdentifier) { return ((GremlinSqlIdentifier) gremlinSqlNodes.get(0)).getColumn(); } else if (gremlinSqlNodes.size() == 2 && gremlinSqlNodes.get(1) instanceof GremlinSqlIdentifier) { return ((GremlinSqlIdentifier) gremlinSqlNodes.get(1)).getColumn(); } else if (gremlinSqlNodes.size() == 1 && gremlinSqlNodes.get(0) instanceof GremlinSqlNumericLiteral) { return ((GremlinSqlAggFunction) gremlinSqlOperator).getNewName(); } } throw new SQLException("Unable to determine actual column name."); } }
apache-2.0
TAnsz/HKWeb
Solution.DataAccess/SubSonic/employeedetTable.cs
2350
using System; namespace Solution.DataAccess.DataModel { /// <summary> /// Table: employeedet /// Primary Key: no /// </summary> public class employeedetTable { /// <summary> /// 表名 /// </summary> public static string TableName { get{ return "employeedet"; } } /// <summary> /// /// </summary> public static string employeeid{ get{ return "employeeid"; } } /// <summary> /// /// </summary> public static string comingtime{ get{ return "comingtime"; } } /// <summary> /// /// </summary> public static string overtime{ get{ return "overtime"; } } /// <summary> /// /// </summary> public static string date1{ get{ return "date1"; } } /// <summary> /// /// </summary> public static string month1{ get{ return "month1"; } } /// <summary> /// /// </summary> public static string year1{ get{ return "year1"; } } /// <summary> /// /// </summary> public static string week1{ get{ return "week1"; } } /// <summary> /// /// </summary> public static string remark{ get{ return "remark"; } } /// <summary> /// /// </summary> public static string no{ get{ return "no"; } } /// <summary> /// /// </summary> public static string empid{ get{ return "empid"; } } /// <summary> /// /// </summary> public static string comingtype{ get{ return "comingtype"; } } /// <summary> /// /// </summary> public static string overtype{ get{ return "overtype"; } } /// <summary> /// /// </summary> public static string ComingMac{ get{ return "ComingMac"; } } /// <summary> /// /// </summary> public static string OverMac{ get{ return "OverMac"; } } } }
apache-2.0
huggingface/transformers
src/transformers/models/luke/configuration_luke.py
6161
# coding=utf-8 # Copyright Studio Ousia and The HuggingFace Inc. team. # # 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. """ LUKE configuration""" from ...configuration_utils import PretrainedConfig from ...utils import logging logger = logging.get_logger(__name__) LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP = { "studio-ousia/luke-base": "https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json", "studio-ousia/luke-large": "https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json", } class LukeConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`LukeModel`]. It is used to instantiate a LUKE model according to the specified arguments, defining the model architecture. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 30522): Vocabulary size of the LUKE model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`LukeModel`]. entity_vocab_size (`int`, *optional*, defaults to 500000): Entity vocabulary size of the LUKE model. Defines the number of different entities that can be represented by the `entity_ids` passed when calling [`LukeModel`]. hidden_size (`int`, *optional*, defaults to 768): Dimensionality of the encoder layers and the pooler layer. entity_emb_size (`int`, *optional*, defaults to 256): The number of dimensions of the entity embedding. num_hidden_layers (`int`, *optional*, defaults to 12): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 12): Number of attention heads for each attention layer in the Transformer encoder. intermediate_size (`int`, *optional*, defaults to 3072): Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder. hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported. hidden_dropout_prob (`float`, *optional*, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1): The dropout ratio for the attention probabilities. max_position_embeddings (`int`, *optional*, defaults to 512): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). type_vocab_size (`int`, *optional*, defaults to 2): The vocabulary size of the `token_type_ids` passed when calling [`LukeModel`]. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. layer_norm_eps (`float`, *optional*, defaults to 1e-12): The epsilon used by the layer normalization layers. use_entity_aware_attention (`bool`, defaults to `True`): Whether or not the model should use the entity-aware self-attention mechanism proposed in [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention (Yamada et al.)](https://arxiv.org/abs/2010.01057). Examples: ```python >>> from transformers import LukeConfig, LukeModel >>> # Initializing a LUKE configuration >>> configuration = LukeConfig() >>> # Initializing a model from the configuration >>> model = LukeModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "luke" def __init__( self, vocab_size=50267, entity_vocab_size=500000, hidden_size=768, entity_emb_size=256, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, layer_norm_eps=1e-12, use_entity_aware_attention=True, pad_token_id=1, bos_token_id=0, eos_token_id=2, **kwargs ): """Constructs LukeConfig.""" super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs) self.vocab_size = vocab_size self.entity_vocab_size = entity_vocab_size self.hidden_size = hidden_size self.entity_emb_size = entity_emb_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.initializer_range = initializer_range self.layer_norm_eps = layer_norm_eps self.use_entity_aware_attention = use_entity_aware_attention
apache-2.0
1ukash/horizon
horizon/dashboards/project/volumes/tests.py
14507
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, 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. from django import http from django.conf import settings from django.core.urlresolvers import reverse from django.forms import widgets from mox import IsA from horizon import api from horizon import test class VolumeViewTests(test.TestCase): @test.create_stubs({api: ('tenant_quota_usages', 'volume_create', 'volume_snapshot_list')}) def test_create_volume(self): volume = self.volumes.first() usage = {'gigabytes': {'available': 250}, 'volumes': {'available': 6}} formData = {'name': u'A Volume I Am Making', 'description': u'This is a volume I am making for a test.', 'method': u'CreateForm', 'size': 50, 'snapshot_source': ''} api.tenant_quota_usages(IsA(http.HttpRequest)).AndReturn(usage) api.volume_snapshot_list(IsA(http.HttpRequest)).\ AndReturn(self.volume_snapshots.list()) api.volume_create(IsA(http.HttpRequest), formData['size'], formData['name'], formData['description'], snapshot_id=None).AndReturn(volume) self.mox.ReplayAll() url = reverse('horizon:project:volumes:create') res = self.client.post(url, formData) redirect_url = reverse('horizon:project:volumes:index') self.assertRedirectsNoFollow(res, redirect_url) @test.create_stubs({api: ('tenant_quota_usages', 'volume_create', 'volume_snapshot_list'), api.nova: ('volume_snapshot_get',)}) def test_create_volume_from_snapshot(self): volume = self.volumes.first() usage = {'gigabytes': {'available': 250}, 'volumes': {'available': 6}} snapshot = self.volume_snapshots.first() formData = {'name': u'A Volume I Am Making', 'description': u'This is a volume I am making for a test.', 'method': u'CreateForm', 'size': 50, 'snapshot_source': snapshot.id} # first call- with url param api.tenant_quota_usages(IsA(http.HttpRequest)).AndReturn(usage) api.nova.volume_snapshot_get(IsA(http.HttpRequest), str(snapshot.id)).AndReturn(snapshot) api.volume_create(IsA(http.HttpRequest), formData['size'], formData['name'], formData['description'], snapshot_id=snapshot.id).\ AndReturn(volume) # second call- with dropdown api.tenant_quota_usages(IsA(http.HttpRequest)).AndReturn(usage) api.volume_snapshot_list(IsA(http.HttpRequest)).\ AndReturn(self.volume_snapshots.list()) api.nova.volume_snapshot_get(IsA(http.HttpRequest), str(snapshot.id)).AndReturn(snapshot) api.volume_create(IsA(http.HttpRequest), formData['size'], formData['name'], formData['description'], snapshot_id=snapshot.id).\ AndReturn(volume) self.mox.ReplayAll() # get snapshot from url url = reverse('horizon:project:volumes:create') res = self.client.post("?".join([url, "snapshot_id=" + str(snapshot.id)]), formData) redirect_url = reverse('horizon:project:volumes:index') self.assertRedirectsNoFollow(res, redirect_url) # get snapshot from dropdown list url = reverse('horizon:project:volumes:create') res = self.client.post(url, formData) redirect_url = reverse('horizon:project:volumes:index') self.assertRedirectsNoFollow(res, redirect_url) @test.create_stubs({api: ('tenant_quota_usages',), api.nova: ('volume_snapshot_get',)}) def test_create_volume_from_snapshot_invalid_size(self): usage = {'gigabytes': {'available': 250}, 'volumes': {'available': 6}} snapshot = self.volume_snapshots.first() formData = {'name': u'A Volume I Am Making', 'description': u'This is a volume I am making for a test.', 'method': u'CreateForm', 'size': 20, 'snapshot_source': snapshot.id} api.tenant_quota_usages(IsA(http.HttpRequest)).AndReturn(usage) api.nova.volume_snapshot_get(IsA(http.HttpRequest), str(snapshot.id)).AndReturn(snapshot) api.tenant_quota_usages(IsA(http.HttpRequest)).AndReturn(usage) self.mox.ReplayAll() url = reverse('horizon:project:volumes:create') res = self.client.post("?".join([url, "snapshot_id=" + str(snapshot.id)]), formData, follow=True) self.assertEqual(res.redirect_chain, []) self.assertFormError(res, 'form', None, "The volume size cannot be less than the " "snapshot size (40GB)") @test.create_stubs({api: ('tenant_quota_usages', 'volume_snapshot_list')}) def test_create_volume_gb_used_over_alloted_quota(self): usage = {'gigabytes': {'available': 100, 'used': 20}} formData = {'name': u'This Volume Is Huge!', 'description': u'This is a volume that is just too big!', 'method': u'CreateForm', 'size': 5000} api.tenant_quota_usages(IsA(http.HttpRequest)).AndReturn(usage) api.volume_snapshot_list(IsA(http.HttpRequest)).\ AndReturn(self.volume_snapshots.list()) api.tenant_quota_usages(IsA(http.HttpRequest)).AndReturn(usage) self.mox.ReplayAll() url = reverse('horizon:project:volumes:create') res = self.client.post(url, formData) expected_error = [u'A volume of 5000GB cannot be created as you only' ' have 100GB of your quota available.'] self.assertEqual(res.context['form'].errors['__all__'], expected_error) @test.create_stubs({api: ('tenant_quota_usages', 'volume_snapshot_list')}) def test_create_volume_number_over_alloted_quota(self): usage = {'gigabytes': {'available': 100, 'used': 20}, 'volumes': {'available': 0}} formData = {'name': u'Too Many...', 'description': u'We have no volumes left!', 'method': u'CreateForm', 'size': 10} api.tenant_quota_usages(IsA(http.HttpRequest)).AndReturn(usage) api.volume_snapshot_list(IsA(http.HttpRequest)).\ AndReturn(self.volume_snapshots.list()) api.tenant_quota_usages(IsA(http.HttpRequest)).AndReturn(usage) self.mox.ReplayAll() url = reverse('horizon:project:volumes:create') res = self.client.post(url, formData) expected_error = [u'You are already using all of your available' ' volumes.'] self.assertEqual(res.context['form'].errors['__all__'], expected_error) @test.create_stubs({api: ('volume_list', 'volume_delete', 'server_list')}) def test_delete_volume(self): volume = self.volumes.first() formData = {'action': 'volumes__delete__%s' % volume.id} api.volume_list(IsA(http.HttpRequest), search_opts=None).\ AndReturn(self.volumes.list()) api.volume_delete(IsA(http.HttpRequest), volume.id) api.server_list(IsA(http.HttpRequest)).AndReturn(self.servers.list()) api.volume_list(IsA(http.HttpRequest), search_opts=None).\ AndReturn(self.volumes.list()) api.server_list(IsA(http.HttpRequest)).AndReturn(self.servers.list()) self.mox.ReplayAll() url = reverse('horizon:project:volumes:index') res = self.client.post(url, formData, follow=True) self.assertMessageCount(res, count=0) @test.create_stubs({api: ('volume_list', 'volume_delete', 'server_list')}) def test_delete_volume_error_existing_snapshot(self): volume = self.volumes.first() formData = {'action': 'volumes__delete__%s' % volume.id} exc = self.exceptions.cinder.__class__(400, "error: dependent snapshots") api.volume_list(IsA(http.HttpRequest), search_opts=None).\ AndReturn(self.volumes.list()) api.volume_delete(IsA(http.HttpRequest), volume.id). \ AndRaise(exc) api.server_list(IsA(http.HttpRequest)).AndReturn(self.servers.list()) api.volume_list(IsA(http.HttpRequest), search_opts=None).\ AndReturn(self.volumes.list()) api.server_list(IsA(http.HttpRequest)).AndReturn(self.servers.list()) self.mox.ReplayAll() url = reverse('horizon:project:volumes:index') res = self.client.post(url, formData, follow=True) self.assertMessageCount(res, error=1) self.assertEqual(list(res.context['messages'])[0].message, u'Unable to delete volume "%s". ' u'One or more snapshots depend on it.' % volume.display_name) @test.create_stubs({api: ('volume_get',), api.nova: ('server_list',)}) def test_edit_attachments(self): volume = self.volumes.first() servers = self.servers.list() api.volume_get(IsA(http.HttpRequest), volume.id).AndReturn(volume) api.nova.server_list(IsA(http.HttpRequest)).AndReturn(servers) self.mox.ReplayAll() url = reverse('horizon:project:volumes:attach', args=[volume.id]) res = self.client.get(url) # Asserting length of 2 accounts for the one instance option, # and the one 'Choose Instance' option. form = res.context['form'] self.assertEqual(len(form.fields['instance']._choices), 2) self.assertEqual(res.status_code, 200) self.assertTrue(isinstance(form.fields['device'].widget, widgets.TextInput)) @test.create_stubs({api: ('volume_get',), api.nova: ('server_list',)}) def test_edit_attachments_cannot_set_mount_point(self): PREV = settings.OPENSTACK_HYPERVISOR_FEATURES['can_set_mount_point'] settings.OPENSTACK_HYPERVISOR_FEATURES['can_set_mount_point'] = False volume = self.volumes.first() servers = self.servers.list() api.volume_get(IsA(http.HttpRequest), volume.id).AndReturn(volume) api.nova.server_list(IsA(http.HttpRequest)).AndReturn(servers) self.mox.ReplayAll() url = reverse('horizon:project:volumes:attach', args=[volume.id]) res = self.client.get(url) # Assert the device field is hidden. form = res.context['form'] self.assertTrue(isinstance(form.fields['device'].widget, widgets.HiddenInput)) settings.OPENSTACK_HYPERVISOR_FEATURES['can_set_mount_point'] = PREV @test.create_stubs({api: ('volume_get',), api.nova: ('server_get', 'server_list',)}) def test_edit_attachments_attached_volume(self): server = self.servers.first() volume = self.volumes.list()[0] api.volume_get(IsA(http.HttpRequest), volume.id) \ .AndReturn(volume) api.nova.server_list(IsA(http.HttpRequest)) \ .AndReturn(self.servers.list()) self.mox.ReplayAll() url = reverse('horizon:project:volumes:attach', args=[volume.id]) res = self.client.get(url) self.assertEqual(res.context['form'].fields['instance']._choices[0][1], "Select an instance") self.assertEqual(len(res.context['form'].fields['instance'].choices), 2) self.assertEqual(res.context['form'].fields['instance']._choices[1][0], server.id) self.assertEqual(res.status_code, 200) @test.create_stubs({api.nova: ('volume_get', 'server_get',)}) def test_detail_view(self): volume = self.volumes.first() server = self.servers.first() volume.attachments = [{"server_id": server.id}] api.nova.volume_get(IsA(http.HttpRequest), volume.id).AndReturn(volume) api.nova.server_get(IsA(http.HttpRequest), server.id).AndReturn(server) self.mox.ReplayAll() url = reverse('horizon:project:volumes:detail', args=[volume.id]) res = self.client.get(url) self.assertContains(res, "<dd>Volume name</dd>", 1, 200) self.assertContains(res, "<dd>41023e92-8008-4c8b-8059-7f2293ff3775</dd>", 1, 200) self.assertContains(res, "<dd>Available</dd>", 1, 200) self.assertContains(res, "<dd>40 GB</dd>", 1, 200) self.assertContains(res, ("<a href=\"/project/instances/1/\">%s</a>" % server.name), 1, 200) self.assertNoMessages()
apache-2.0
vengefuldrx/rekt-googlecore
rekt_googlecore/client.py
4758
import types import time from itertools import chain from functools import partial from pathlib import Path, PurePath from pkg_resources import resource_filename import rekt from rekt.service import RestClient from rekt.utils import load_config, api_method_names, _ASYNC_METHOD_PREFIX from .errors import Status, exceptions_by_status from .errors import InvalidRequestError __all__ = ['GoogleAPIClient'] _API_KEY_ARG_NAME = 'key' _PAGETOKEN_ARG_NAME = 'pagetoken' _MAX_PAGES = 3 _MILLIS_PER_SEC = 1000 class GoogleAPIClient(RestClient): """ Base for google api clients that is primed with the api key so you do not have to specify it with each request like a raw rekt rest client. Further, the google status responses that are not 'OK' raise an error with the same name of the status code that share the exception class GoogleAPIError for a catch all. """ def __init__(self, rekt_google_module, api_key): RestClient.__init__(self) self._api_key = api_key self._rekt_client = rekt_google_module.Client() api_methods = api_method_names(rekt_google_module.resources) def build_wrapped_api_method(method_name): raw_api_method = getattr(self._rekt_client, method_name) def api_call_func(self, **kwargs): kwargs[_API_KEY_ARG_NAME] = self._api_key response = raw_api_method(**kwargs) try: status = Status[response.status.lower()] except (AttributeError, KeyError) as e: status = Status.ok if status in exceptions_by_status: kwargs.pop(_API_KEY_ARG_NAME, None) raise exceptions_by_status[status](raw_api_method.__name__, kwargs.items(), response.error_message, response) return response api_call_func.__name__ = raw_api_method.__name__ api_call_func.__doc__ = raw_api_method.__doc__ return api_call_func def build_wrapped_async_api_method(method_name): raw_api_method_name = method_name.replace(_ASYNC_METHOD_PREFIX, '') def api_call_func(self, **kwargs): raw_api_method = getattr(self, raw_api_method_name) def _async_call_handler(): return raw_api_method(**kwargs) return self._rekt_client._executor.submit(_async_call_handler) api_call_func.__name__ = method_name api_call_func.__doc__ = getattr(self._rekt_client, raw_api_method_name).__doc__ return api_call_func for method_name in api_methods: if method_name.startswith(_ASYNC_METHOD_PREFIX): new_method = build_wrapped_async_api_method(method_name) else: new_method = build_wrapped_api_method(method_name) setattr(self, method_name, types.MethodType(new_method, self)) #TODO: Genericize time parameters and errors. def exponential_retry(call): """ Retry on an InvalidRequestError which will happen if a pagetoken is used before that pagetoken becomes valid. """ base_wait = 333 # ms max_wait = 2000 # ms last_exception = None for attempt in range(5): try: return call() except InvalidRequestError as e: last_exception = e wait_time = (1 << attempt) * base_wait wait_time = min(wait_time, max_wait) # box wait time by the max wait wait_time /= _MILLIS_PER_SEC time.sleep(wait_time) raise last_exception def paginate_responses(call, max_pages=_MAX_PAGES): """ Assumes that call is the curried api method with the initial arguments. This will make a generator based on the api calls that require a page token to paginate results. This returned generator will yeild a response for each call it is on the caller to do the appropriate chaining of results. """ next_page_token = None for _ in range(max_pages): if next_page_token is None: # Do not retry the initial call incase the intial args are bogus response = call() else: # Args are ignored when the pagetoken is given so we have # a guarantee that the InvalidRequestError is because the # pagetoken is not yet active versus just run of the mill # bad params. call_with_pagetoken = partial(call, **{_PAGETOKEN_ARG_NAME : next_page_token}) response = exponential_retry(call_with_pagetoken) yield response next_page_token = response.next_page_token if next_page_token is None: break
apache-2.0
utgenome/utgb
utgb-core/src/main/java/org/utgenome/format/egt/Gene.java
2015
/*-------------------------------------------------------------------------- * Copyright 2007 utgenome.org * * 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. *--------------------------------------------------------------------------*/ //-------------------------------------- // utgb-core Project // // Gene.java // Since: Dec 21, 2007 // // $URL$ // $Author$ //-------------------------------------- package org.utgenome.format.egt; import java.util.ArrayList; import java.util.List; public class Gene { private String target; private long start; private long end; private String strand; private String name; private String url; private ArrayList<Exon> exonList = new ArrayList<Exon>(); public Gene() {} public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public long getStart() { return start; } public void setStart(long start) { this.start = start; } public long getEnd() { return end; } public void setEnd(long end) { this.end = end; } public String getStrand() { return strand; } public void setStrand(String strand) { this.strand = strand; } public void addExon(Exon exon) { exonList.add(exon); } public List<Exon> getExon() { return exonList; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
apache-2.0
okankurtulus/droidparts
droidparts/src/org/droidparts/activity/legacy/ListActivity.java
1288
/** * Copyright 2015 Alex Yanchenko * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.droidparts.activity.legacy; import org.droidparts.Injector; import org.droidparts.bus.EventBus; import org.droidparts.contract.Injectable; import android.os.Bundle; public abstract class ListActivity extends android.app.ListActivity implements Injectable { @Override public void onPreInject() { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); onPreInject(); Injector.inject(this); } @Override protected void onResume() { super.onResume(); EventBus.registerAnnotatedReceiver(this); } @Override protected void onPause() { super.onPause(); EventBus.unregisterAnnotatedReceiver(this); } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-fsx/src/main/java/com/amazonaws/services/fsx/model/ServiceLimit.java
2223
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.fsx.model; import javax.annotation.Generated; /** * <p> * The types of limits on your service utilization. Limits include file system count, total throughput capacity, total * storage, and total user-initiated backups. These limits apply for a specific account in a specific AWS Region. You * can increase some of them by contacting AWS Support. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum ServiceLimit { FILE_SYSTEM_COUNT("FILE_SYSTEM_COUNT"), TOTAL_THROUGHPUT_CAPACITY("TOTAL_THROUGHPUT_CAPACITY"), TOTAL_STORAGE("TOTAL_STORAGE"), TOTAL_USER_INITIATED_BACKUPS("TOTAL_USER_INITIATED_BACKUPS"); private String value; private ServiceLimit(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return ServiceLimit corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static ServiceLimit fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (ServiceLimit enumEntry : ServiceLimit.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
apache-2.0
nblair/bw-util
bw-util-deployment/src/main/java/org/bedework/util/deployment/WebXml.java
4557
package org.bedework.util.deployment; import org.bedework.util.xml.XmlUtil; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.File; /** Represent a web.xml file. * * @author douglm */ public class WebXml extends XmlFile { private final PropertiesChain props; public WebXml(final File webInf, final PropertiesChain props) throws Throwable { super(webInf, "web.xml", false); this.props = props; } public void update() throws Throwable { setConfigName(); setTransportGuarantee(); setSecurityDomain(); addFilter(); addFilterMapping(); addListener(); } public void setConfigName() throws Throwable { findBwappname: for (final Element el : XmlUtil.getElementsArray(root)) { if (!"context-param".equals(el.getNodeName())) { continue findBwappname; } final Node pn = XmlUtil.getOneTaggedNode(el, "param-name"); if (pn == null) { continue findBwappname; } final String pname = XmlUtil.getElementContent((Element)pn); if (!"bwappname".equals(pname)) { continue findBwappname; } propsReplaceContent(el, "param-value", props); } } public void setTransportGuarantee() throws Throwable { final NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { final Node n = children.item(i); if (!"security-constraint".equals(n.getNodeName())) { continue; } final Node udc = XmlUtil.getOneTaggedNode(n, "user-data-constraint"); if (udc == null) { continue; } propsReplaceContent((Element)udc, "transport-guarantee", props); } } public void setSecurityDomain() throws Throwable { final Node n = XmlUtil.getOneTaggedNode(root, "login-config"); if (n == null) { return; } propsReplaceContent((Element)n, "realm-name", props); } public void addFilter() throws Throwable { final String fltr = props.get("app.filter"); if (fltr == null) { return; } try { final XmlFile fltrDefs = new XmlFile(fltr, false); final Element filtersEl = fltrDefs.root; /* if we already have a filter def insert in front */ Node insertAt = XmlUtil.getOneTaggedNode(root, "filter"); if (insertAt == null) { // then try for listener insertAt = XmlUtil.getOneTaggedNode(root, "listener"); } if (insertAt == null) { // Bad web.xml? throw new Exception("Cannot locate place to insert filter"); } for (final Element el: XmlUtil.getElements(filtersEl)) { root.insertBefore(doc.importNode(el, true), insertAt); } } catch (final Throwable t) { Utils.error("Unable to open/process file " + fltr); throw t; } } public void addFilterMapping() throws Throwable { final String fltr = props.get("app.filter-mapping"); if (fltr == null) { return; } try { final XmlFile fltrDefs = new XmlFile(fltr, false); final Element filtersEl = fltrDefs.root; /* if we already have a filter def insert in front */ Node insertAt = XmlUtil.getOneTaggedNode(root, "filter-mapping"); if (insertAt == null) { // then try for listener insertAt = XmlUtil.getOneTaggedNode(root, "listener"); } if (insertAt == null) { // Bad web.xml? throw new Exception("Cannot locate place to insert filter-mapping"); } for (final Element el: XmlUtil.getElements(filtersEl)) { root.insertBefore(doc.importNode(el, true), insertAt); } } catch (final Throwable t) { Utils.error("Unable to open/process file " + fltr); throw t; } } public void addListener() throws Throwable { final String fltr = props.get("app.listener"); if (fltr == null) { return; } try { final XmlFile fltrDefs = new XmlFile(fltr, false); final Element filtersEl = fltrDefs.root; /* Insert in front current listener */ final Node insertAt = XmlUtil.getOneTaggedNode(root, "listener"); if (insertAt == null) { // Bad web.xml? throw new Exception("Cannot locate place to insert listener"); } for (final Element el: XmlUtil.getElements(filtersEl)) { root.insertBefore(doc.importNode(el, true), insertAt); } } catch (final Throwable t) { Utils.error("Unable to open/process file " + fltr); throw t; } } }
apache-2.0
yahyaharif/impexformatter
src/main/webapp/resources/js/custom.js
105
$(document).ready(function() { $('#result').DataTable(); $('[data-toggle="tooltip"]').tooltip(); });
apache-2.0
qmx/aerogear-unifiedpush-server
jaxrs/src/test/java/org/jboss/aerogear/unifiedpush/rest/util/HttpRequestHelperTest.java
4724
/** * JBoss, Home of Professional Open Source * Copyright Red Hat, Inc., and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.aerogear.unifiedpush.rest.util; import org.junit.Test; import org.mockito.Mockito; import javax.servlet.http.HttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; public class HttpRequestHelperTest { @Test public void extractRemoteAddress() { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getHeader("x-forwarded-for")).thenReturn(null); Mockito.when(request.getHeader("Proxy-Client-IP")).thenReturn(null); Mockito.when(request.getHeader("WL-Proxy-Client-IP")).thenReturn(null); Mockito.when(request.getRemoteAddr()).thenReturn("127.0.0.1"); final String remoteAddress = HttpRequestUtil.extractIPAddress(request); assertThat(remoteAddress).isNotNull(); assertThat(remoteAddress).isEqualTo("127.0.0.1"); } @Test public void extractWLProxyClientIPHeader() { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getHeader("x-forwarded-for")).thenReturn(null); Mockito.when(request.getHeader("Proxy-Client-IP")).thenReturn(null); Mockito.when(request.getHeader("WL-Proxy-Client-IP")).thenReturn("127.0.0.1"); final String remoteAddress = HttpRequestUtil.extractIPAddress(request); assertThat(remoteAddress).isNotNull(); assertThat(remoteAddress).isEqualTo("127.0.0.1"); } @Test public void extractProxyClientIPHeader() { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getHeader("x-forwarded-for")).thenReturn(null); Mockito.when(request.getHeader("Proxy-Client-IP")).thenReturn("127.0.0.1"); final String remoteAddress = HttpRequestUtil.extractIPAddress(request); assertThat(remoteAddress).isNotNull(); assertThat(remoteAddress).isEqualTo("127.0.0.1"); } @Test public void extractXForwardForHeader() { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getHeader("x-forwarded-for")).thenReturn("127.0.0.1"); final String remoteAddress = HttpRequestUtil.extractIPAddress(request); assertThat(remoteAddress).isNotNull(); assertThat(remoteAddress).isEqualTo("127.0.0.1"); } @Test public void extractAeroGearSenderHeader() { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getHeader("aerogear-sender")).thenReturn("Java Sender"); final String client = HttpRequestUtil.extractAeroGearSenderInformation(request); assertThat(client).isNotNull(); assertThat(client).isEqualTo("Java Sender"); } @Test public void extractAeroGearSenderHeaderViaUserAgent() { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getHeader("aerogear-sender")).thenReturn(null); Mockito.when(request.getHeader("user-agent")).thenReturn("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2)"); final String client = HttpRequestUtil.extractAeroGearSenderInformation(request); assertThat(client).isNotNull(); assertThat(client).isEqualTo("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2)"); } @Test public void extactNullSortingParamValue() { assertThat(HttpRequestUtil.extractSortingQueryParamValue(null)).isTrue(); } @Test public void extactDescSortingParamValue() { assertThat(HttpRequestUtil.extractSortingQueryParamValue("deSc")).isFalse(); assertThat(HttpRequestUtil.extractSortingQueryParamValue("desc")).isFalse(); assertThat(HttpRequestUtil.extractSortingQueryParamValue("DESC")).isFalse(); } @Test public void extactAscSortingParamValue() { assertThat(HttpRequestUtil.extractSortingQueryParamValue("foo")).isTrue(); assertThat(HttpRequestUtil.extractSortingQueryParamValue("AsC")).isTrue(); } }
apache-2.0
pengzhiming/AndroidApp
app/src/main/java/com/yl/merchat/component/net/YLRxSubscriberHelper.java
3867
package com.yl.merchat.component.net; import android.content.Context; import com.yl.merchat.base.data.BaseResponse; import com.yl.merchat.util.ThrowableUtil; import com.yl.core.component.log.DLog; import com.yl.core.component.net.JHttpLoggingInterceptor; import com.yl.core.component.net.RxSubscriberHelper; import com.yl.core.component.net.exception.ApiException; import com.yl.core.component.net.exception.ExceptionEngine; import java.io.IOException; import java.util.List; import io.reactivex.exceptions.CompositeException; import retrofit2.HttpException; /** * Created by zm on 2018/9/9. */ public abstract class YLRxSubscriberHelper<T> extends RxSubscriberHelper<T> { public YLRxSubscriberHelper() { super(); } public YLRxSubscriberHelper(Context context, boolean isShowLoad) { super(context, isShowLoad); } /** * @param context * @param builder 配置builder */ public YLRxSubscriberHelper(Context context, Builder builder) { super(context, builder); } @Override public final void onNext(T t) { super.onNext(t); } private void autoThrowable(Throwable throwable) { /** * 输出错误日志 */ if (throwable != null) { if (throwable instanceof CompositeException) { List<Throwable> throwables = ((CompositeException) throwable).getExceptions(); if (throwables != null) { for (Throwable throwableTemp : throwables) { parseThrowable(throwableTemp); } } } else { parseThrowable(throwable); } } } private void parseThrowable(Throwable throwable) { if (throwable instanceof HttpException) { HttpException httpException = (HttpException) throwable; try { String[] datas = JHttpLoggingInterceptor.getHttpLog( httpException.response().raw().request(), httpException.response().raw(), 0 ); log(datas); } catch (IOException e) { DLog.e(ThrowableUtil.getMessage(e)); } } else { DLog.e(ThrowableUtil.getMessage(throwable)); } } void log(String... messages) { DLog.e(messages); } @Override public void onError(Throwable throwable) { autoThrowable(throwable); ApiException apiException = ExceptionEngine.handleException(throwable); if (isShowMessage) { onShowMessage(apiException); } if (isShowLoad) { onDissLoad(); } /** * 升级检查 */ if (apiException.object != null && (BaseResponse.SUCCESS_CODE_UPGRADE.equals("" + apiException.status) || BaseResponse.SUCCESS_CODE_UPGRADE_FOUCE.equals("" + apiException.status))) { if (onUpgradeError(apiException)) { // TODO 更新逻辑 } return; } /** * 其他错误 */ else { _onError(apiException); } } protected boolean onUpgradeError(ApiException apiException) { return true; } protected boolean onSSOError(ApiException apiException) { return true; } /** * 权限失效会自动登出, V1版本权限失效主要依据为 401 {@link ExceptionEngine#handleException(Throwable)} * 所有需要验证权限的接口,Authorization token 缺失或校验失败都将触发401 {@link } * * @param apiException */ @Override protected void onPermissionError(ApiException apiException) { // TODO 退出登录 } }
apache-2.0
postfix/csfw
utils/crypto/crytpo.go
1429
// Copyright 2015, Cyrill @ Schumacher.fm and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License") // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package crypto // @see lib/internal/Magento/Framework/Encryption type Encrypter interface { // Encrypt a string Encrypt(data []byte) []byte // Decrypt a string Decrypt(data []byte) []byte // Return crypt model, instantiate if it is empty // @return \Magento\Framework\Encryption\Crypt ValidateKey(key string) } type Hasher interface { // Generate a [salted] hash. // $salt can be: // false - salt is not used // true - random salt of the default length will be generated // integer - random salt of specified length will be generated // string - actual salt value to be used GenerateHash(password string, salt bool) string // Hash a string Hash(data string) string // Validate hash against hashing method (with or without salt) ValidateHash(password, hash string) error }
apache-2.0
lightenna/structuredfun-core
web/app.php
840
<?php use Symfony\Component\ClassLoader\ApcClassLoader; use Symfony\Component\HttpFoundation\Request; $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; // Use APC for autoloading to improve performance. // Change 'sf2' to a unique prefix in order to prevent cache key conflicts // with other applications also using APC. /* $loader = new ApcClassLoader('sf2', $loader); $loader->register(true); */ require_once __DIR__.'/../app/AppKernel.php'; //require_once __DIR__.'/../app/AppCache.php'; // disable zray if installed if (function_exists('zray_disable')) { zray_disable(); } $kernel = new AppKernel('prod', true); $kernel->loadClassCache(); //$kernel = new AppCache($kernel); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
apache-2.0
xschildw/Synapse-Repository-Services
lib/jdomodels/src/main/java/org/sagebionetworks/repo/model/dbo/file/DBOMultipartUpload.java
12278
package org.sagebionetworks.repo.model.dbo.file; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_BUCKET; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_DDL; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_FILE_HANDLE_ID; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_KEY; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_NUMBER_OF_PARTS; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_REQUEST_HASH; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_STARTED_BY; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_STARTED_ON; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_STATE; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_UPDATED_ON; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_UPLOAD_ETAG; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_UPLOAD_ID; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_UPLOAD_REQUEST; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_UPLOAD_TOKEN; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_MULTIPART_UPLOAD_TYPE; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_MULTIPART_UPLOAD; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.sagebionetworks.repo.model.dbo.FieldColumn; import org.sagebionetworks.repo.model.dbo.MigratableDatabaseObject; import org.sagebionetworks.repo.model.dbo.TableMapping; import org.sagebionetworks.repo.model.dbo.migration.MigratableTableTranslation; import org.sagebionetworks.repo.model.file.UploadType; import org.sagebionetworks.repo.model.migration.MigrationType; /** * The master table used to track the state of multi-part uploads. * */ public class DBOMultipartUpload implements MigratableDatabaseObject<DBOMultipartUpload, DBOMultipartUpload>{ private static FieldColumn[] FIELDS = new FieldColumn[] { new FieldColumn("id", COL_MULTIPART_UPLOAD_ID, true).withIsBackupId(true), new FieldColumn("requestHash", COL_MULTIPART_REQUEST_HASH), new FieldColumn("etag", COL_MULTIPART_UPLOAD_ETAG).withIsEtag(true), new FieldColumn("requestBlob", COL_MULTIPART_UPLOAD_REQUEST), new FieldColumn("startedBy", COL_MULTIPART_STARTED_BY), new FieldColumn("startedOn", COL_MULTIPART_STARTED_ON), new FieldColumn("updatedOn", COL_MULTIPART_UPDATED_ON), new FieldColumn("fileHandleId", COL_MULTIPART_FILE_HANDLE_ID), new FieldColumn("state", COL_MULTIPART_STATE), new FieldColumn("uploadToken", COL_MULTIPART_UPLOAD_TOKEN), new FieldColumn("uploadType", COL_MULTIPART_UPLOAD_TYPE), new FieldColumn("bucket", COL_MULTIPART_BUCKET), new FieldColumn("key", COL_MULTIPART_KEY), new FieldColumn("numberOfParts", COL_MULTIPART_NUMBER_OF_PARTS) }; Long id; String requestHash; String etag; byte[] requestBlob; Long startedBy; Date startedOn; Date updatedOn; Long fileHandleId; String state; String uploadToken; String bucket; String key; Integer numberOfParts; String uploadType; @Override public TableMapping<DBOMultipartUpload> getTableMapping() { return new TableMapping<DBOMultipartUpload>(){ @Override public DBOMultipartUpload mapRow(ResultSet rs, int rowNum) throws SQLException { DBOMultipartUpload dbo = new DBOMultipartUpload(); dbo.setId(rs.getLong(COL_MULTIPART_UPLOAD_ID)); dbo.setRequestHash(rs.getString(COL_MULTIPART_REQUEST_HASH)); dbo.setEtag(rs.getString(COL_MULTIPART_UPLOAD_ETAG)); dbo.setStartedBy(rs.getLong(COL_MULTIPART_STARTED_BY)); dbo.setStartedOn(new Date(rs.getTimestamp(COL_MULTIPART_STARTED_ON).getTime())); dbo.setUpdatedOn(new Date(rs.getTimestamp(COL_MULTIPART_UPDATED_ON).getTime())); dbo.setFileHandleId(rs.getLong(COL_MULTIPART_FILE_HANDLE_ID)); if(rs.wasNull()){ dbo.setFileHandleId(null); } dbo.setState(rs.getString(COL_MULTIPART_STATE)); dbo.setRequestBlob(rs.getBytes(COL_MULTIPART_UPLOAD_REQUEST)); dbo.setUploadToken(rs.getString(COL_MULTIPART_UPLOAD_TOKEN)); dbo.setUploadType(rs.getString(COL_MULTIPART_UPLOAD_TYPE)); dbo.setBucket(rs.getString(COL_MULTIPART_BUCKET)); dbo.setKey(rs.getString(COL_MULTIPART_KEY)); dbo.setNumberOfParts(rs.getInt(COL_MULTIPART_NUMBER_OF_PARTS)); return dbo; } @Override public String getTableName() { return TABLE_MULTIPART_UPLOAD; } @Override public String getDDLFileName() { return COL_MULTIPART_DDL; } @Override public FieldColumn[] getFieldColumns() { return FIELDS; } @Override public Class<? extends DBOMultipartUpload> getDBOClass() { return DBOMultipartUpload.class; }}; } @Override public MigrationType getMigratableTableType() { return MigrationType.MULTIPART_UPLOAD; } @Override public MigratableTableTranslation<DBOMultipartUpload, DBOMultipartUpload> getTranslator() { return new MigratableTableTranslation<DBOMultipartUpload, DBOMultipartUpload>() { @Override public DBOMultipartUpload createDatabaseObjectFromBackup(DBOMultipartUpload backup) { if (backup.getUploadType() == null) { backup.setUploadType(UploadType.S3.toString()); } return backup; } @Override public DBOMultipartUpload createBackupFromDatabaseObject(DBOMultipartUpload dbo) { return dbo; } }; } @Override public Class<? extends DBOMultipartUpload> getBackupClass() { return DBOMultipartUpload.class; } @Override public Class<? extends DBOMultipartUpload> getDatabaseObjectClass() { return DBOMultipartUpload.class; } @Override public List<MigratableDatabaseObject<?, ?>> getSecondaryTypes() { List<MigratableDatabaseObject<?,?>> list = new LinkedList<>(); list.add(new DBOMultipartUploadPartState()); list.add(new DBOMultipartUploadComposerPartState()); return list; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getEtag() { return etag; } public void setEtag(String etag) { this.etag = etag; } public String getRequestHash() { return requestHash; } public void setRequestHash(String requestHash) { this.requestHash = requestHash; } public Date getUpdatedOn() { return updatedOn; } public void setUpdatedOn(Date updatedOn) { this.updatedOn = updatedOn; } public Long getStartedBy() { return startedBy; } public void setStartedBy(Long startedBy) { this.startedBy = startedBy; } public Date getStartedOn() { return startedOn; } public void setStartedOn(Date startedOn) { this.startedOn = startedOn; } public Long getFileHandleId() { return fileHandleId; } public byte[] getRequestBlob() { return requestBlob; } public void setRequestBlob(byte[] requestBlob) { this.requestBlob = requestBlob; } public void setFileHandleId(Long fileHandleId) { this.fileHandleId = fileHandleId; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getUploadToken() { return uploadToken; } public void setUploadToken(String uploadToken) { this.uploadToken = uploadToken; } public String getUploadType() { return uploadType; } public void setUploadType(String uploadType) { this.uploadType = uploadType; } public String getBucket() { return bucket; } public void setBucket(String bucket) { this.bucket = bucket; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Integer getNumberOfParts() { return numberOfParts; } public void setNumberOfParts(Integer numberOfParts) { this.numberOfParts = numberOfParts; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((uploadType == null) ? 0 : uploadType.hashCode()); result = prime * result + ((bucket == null) ? 0 : bucket.hashCode()); result = prime * result + ((etag == null) ? 0 : etag.hashCode()); result = prime * result + ((fileHandleId == null) ? 0 : fileHandleId.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((numberOfParts == null) ? 0 : numberOfParts.hashCode()); result = prime * result + Arrays.hashCode(requestBlob); result = prime * result + ((requestHash == null) ? 0 : requestHash.hashCode()); result = prime * result + ((startedBy == null) ? 0 : startedBy.hashCode()); result = prime * result + ((startedOn == null) ? 0 : startedOn.hashCode()); result = prime * result + ((state == null) ? 0 : state.hashCode()); result = prime * result + ((updatedOn == null) ? 0 : updatedOn.hashCode()); result = prime * result + ((uploadToken == null) ? 0 : uploadToken.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DBOMultipartUpload other = (DBOMultipartUpload) obj; if (uploadType == null) { if (other.uploadType != null) return false; } else if (!uploadType.equals(other.uploadType)) return false; if (bucket == null) { if (other.bucket != null) return false; } else if (!bucket.equals(other.bucket)) return false; if (etag == null) { if (other.etag != null) return false; } else if (!etag.equals(other.etag)) return false; if (fileHandleId == null) { if (other.fileHandleId != null) return false; } else if (!fileHandleId.equals(other.fileHandleId)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (numberOfParts == null) { if (other.numberOfParts != null) return false; } else if (!numberOfParts.equals(other.numberOfParts)) return false; if (!Arrays.equals(requestBlob, other.requestBlob)) return false; if (requestHash == null) { if (other.requestHash != null) return false; } else if (!requestHash.equals(other.requestHash)) return false; if (startedBy == null) { if (other.startedBy != null) return false; } else if (!startedBy.equals(other.startedBy)) return false; if (startedOn == null) { if (other.startedOn != null) return false; } else if (!startedOn.equals(other.startedOn)) return false; if (state == null) { if (other.state != null) return false; } else if (!state.equals(other.state)) return false; if (updatedOn == null) { if (other.updatedOn != null) return false; } else if (!updatedOn.equals(other.updatedOn)) return false; if (uploadToken == null) { if (other.uploadToken != null) return false; } else if (!uploadToken.equals(other.uploadToken)) return false; return true; } @Override public String toString() { return "DBOMultipartUpload [" + "id=" + id + ", requestHash=" + requestHash + ", etag=" + etag + ", requestBlob=" + Arrays.toString(requestBlob) + ", startedBy=" + startedBy + ", startedOn=" + startedOn + ", updatedOn=" + updatedOn + ", fileHandleId=" + fileHandleId + ", state=" + state + ", uploadToken=" + uploadToken + ", uploadType=" + uploadType + ", bucket=" + bucket + ", key=" + key + ", numberOfParts=" + numberOfParts + "]"; } }
apache-2.0