repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
lam1607/FLOPopupPrototypes
FLOPopupPrototypes/Sevices/Google/GTMAuthentication/GTMAuthenticationInfo.h
<filename>FLOPopupPrototypes/Sevices/Google/GTMAuthentication/GTMAuthenticationInfo.h // // GTMAuthenticationInfo.h // SharedSources // // Created by lamnguyen on 7/16/20. // Copyright © 2020 Floware. All rights reserved. // #import <Foundation/Foundation.h> @interface GTMAuthenticationInfo : NSObject <GTMFetcherAuthorizationProtocol> /// @property /// @property (nonatomic, strong) NSString *accessToken; @property (nonatomic, strong) NSString *refreshToken; @property (nonatomic, strong) NSString *tokenType; @property (nonatomic, strong) NSString *idToken; @property (nonatomic, strong) NSString *scope; @property (nonatomic, assign) NSTimeInterval expiredTime; @property (nonatomic, strong) NSDate *expiredDate; @property (nonatomic, strong) NSString *authorizationCode; @property (nonatomic, strong) NSString *userID; @property (nonatomic, strong) NSString *serviceProvider; @property (nonatomic, strong) NSString *authorizationQueryParams; // These fields are only included when the user has granted the "profile" and // "email" OAuth scopes to the application. @property (nonatomic, assign) NSInteger isVerified; @property (nonatomic, strong) NSString *userFamilyName; @property (nonatomic, strong) NSString *userGivenName; @property (nonatomic, strong) NSString *userName; @property (nonatomic, strong) NSString *userPicture; /// Initialize /// - (instancetype)initWithAuthenticationInfo:(NSDictionary *)authenticationInfo; - (instancetype)initWithTokenInfo:(NSDictionary *)tokenInfo; /// Methods /// - (void)updateByObject:(GTMAuthenticationInfo *)authenticationInfo; @end
ghsecuritylab/EasyTomato
release/src/router/httpd/traceping.c
<reponame>ghsecuritylab/EasyTomato /* Tomato Firmware Copyright (C) 2006-2009 <NAME> */ #include "tomato.h" #include <ctype.h> static int check_addr(const char *addr, int max) { const char *p; char c; if ((addr == NULL) || (addr[0] == 0)) return 0; p = addr; while (*p) { c = *p; if ((!isalnum(c)) && (c != '.') && (c != '-') && (c != ':')) return 0; //Give IPv6 addresses a chance ++p; } return((p - addr) <= max); } void wo_trace(char *url) { char cmd[256]; const char *addr; addr = webcgi_get("addr"); if (!check_addr(addr, 64)) return; killall("traceroute", SIGTERM); web_puts("\ntracedata = '"); sprintf(cmd, "traceroute -I -m %u -w %u %s", atoi(webcgi_safeget("hops", "0")), atoi(webcgi_safeget("wait", "0")), addr); web_pipecmd(cmd, WOF_JAVASCRIPT); web_puts("';"); } void wo_ping(char *url) { char cmd[256]; const char *addr; addr = webcgi_get("addr"); if (!check_addr(addr, 64)) return; killall("ping", SIGTERM); web_puts("\npingdata = '"); sprintf(cmd, "ping -c %d -s %d %s", atoi(webcgi_safeget("count", "0")), atoi(webcgi_safeget("size", "0")), addr); web_pipecmd(cmd, WOF_JAVASCRIPT); web_puts("';"); } /* #include <regex.h> int main(int argc, char **argv) { FILE *f; char s[1024]; int n; char domain[512]; char ip[32]; char min[32]; regex_t re; regmatch_t rm[10]; int i; if ((f = popen("traceroute -I 192.168.0.1", "r")) == NULL) { perror("popen"); return 1; } // 2 192.168.0.1 (192.168.0.1) 1.908 ms 1.812 ms 1.688 ms while (fgets(s, sizeof(s), f)) { // if (regcomp(&re, "^ +[0-9]+ +(.+?) +\\((.+?)\\) +(.+?) ms +(.+?) ms +(.+?) ms", REG_EXTENDED) != 0) { printf("error: regcomp\n"); return 1; } if ((regexec(&re, s, sizeof(rm) / sizeof(rm[0]), rm, 0) == 0) && (re.re_nsub == 5)) { printf("["); for (i = 1; i < 6; ++i) { s[rm[i].rm_eo] = 0; printf("'%s'%c", s + rm[i].rm_so, (i == 5) ? ' ' : ','); } printf("]\n"); // printf("%d = %d = [%s]\n", i, rm[i].rm_so, s + rm[i].rm_so); } regfree(&re); // sscanf(s, "%d %s (%s) %s ms", &n, domain, ip, min); // printf("[%s] %s %s\n", ip, domain, min); } pclose(f); return 0; } */
utilitywarehouse/poc-pg-mirror
billmodel/pbatch.xo.go
<gh_stars>0 // Package billmodel contains the types for schema 'equinox'. package billmodel // GENERATED BY XO. DO NOT EDIT. import ( "database/sql" "github.com/lib/pq" ) // Pbatch represents a row from 'equinox.pbatches'. type Pbatch struct { Pbbatchnumber sql.NullString `json:"pbbatchnumber"` // pbbatchnumber Pbbatchdate pq.NullTime `json:"pbbatchdate"` // pbbatchdate Pbbatchcode sql.NullString `json:"pbbatchcode"` // pbbatchcode Pbcommitdate pq.NullTime `json:"pbcommitdate"` // pbcommitdate Pbcommittime pq.NullTime `json:"pbcommittime"` // pbcommittime Pbbatchtotal sql.NullFloat64 `json:"pbbatchtotal"` // pbbatchtotal Pbinputtotal sql.NullFloat64 `json:"pbinputtotal"` // pbinputtotal Pbinputrecords sql.NullInt64 `json:"pbinputrecords"` // pbinputrecords Pbnotes sql.NullString `json:"pbnotes"` // pbnotes Pbpaymentdate pq.NullTime `json:"pbpaymentdate"` // pbpaymentdate Pbbatchgroup sql.NullString `json:"pbbatchgroup"` // pbbatchgroup EquinoxLrn int64 `json:"equinox_lrn"` // equinox_lrn EquinoxSec sql.NullInt64 `json:"equinox_sec"` // equinox_sec } func AllPbatch(db XODB, callback func(x Pbatch) bool) error { // sql query const sqlstr = `SELECT ` + `pbbatchnumber, pbbatchdate, pbbatchcode, pbcommitdate, pbcommittime, pbbatchtotal, pbinputtotal, pbinputrecords, pbnotes, pbpaymentdate, pbbatchgroup, equinox_lrn, equinox_sec ` + `FROM equinox.pbatches ` q, err := db.Query(sqlstr) if err != nil { return err } defer q.Close() // load results for q.Next() { p := Pbatch{} // scan err = q.Scan(&p.Pbbatchnumber, &p.Pbbatchdate, &p.Pbbatchcode, &p.Pbcommitdate, &p.Pbcommittime, &p.Pbbatchtotal, &p.Pbinputtotal, &p.Pbinputrecords, &p.Pbnotes, &p.Pbpaymentdate, &p.Pbbatchgroup, &p.EquinoxLrn, &p.EquinoxSec) if err != nil { return err } if !callback(p) { return nil } } return nil } // PbatchByEquinoxLrn retrieves a row from 'equinox.pbatches' as a Pbatch. // // Generated from index 'pbatches_pkey'. func PbatchByEquinoxLrn(db XODB, equinoxLrn int64) (*Pbatch, error) { var err error // sql query const sqlstr = `SELECT ` + `pbbatchnumber, pbbatchdate, pbbatchcode, pbcommitdate, pbcommittime, pbbatchtotal, pbinputtotal, pbinputrecords, pbnotes, pbpaymentdate, pbbatchgroup, equinox_lrn, equinox_sec ` + `FROM equinox.pbatches ` + `WHERE equinox_lrn = $1` // run query XOLog(sqlstr, equinoxLrn) p := Pbatch{} err = db.QueryRow(sqlstr, equinoxLrn).Scan(&p.Pbbatchnumber, &p.Pbbatchdate, &p.Pbbatchcode, &p.Pbcommitdate, &p.Pbcommittime, &p.Pbbatchtotal, &p.Pbinputtotal, &p.Pbinputrecords, &p.Pbnotes, &p.Pbpaymentdate, &p.Pbbatchgroup, &p.EquinoxLrn, &p.EquinoxSec) if err != nil { return nil, err } return &p, nil }
rajeev02101987/arangodb
3rdParty/V8/v7.9.317/src/interpreter/interpreter-generator.h
<filename>3rdParty/V8/v7.9.317/src/interpreter/interpreter-generator.h // Copyright 2017 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_INTERPRETER_INTERPRETER_GENERATOR_H_ #define V8_INTERPRETER_INTERPRETER_GENERATOR_H_ #include "src/interpreter/bytecode-operands.h" #include "src/interpreter/bytecodes.h" namespace v8 { namespace internal { struct AssemblerOptions; namespace interpreter { extern Handle<Code> GenerateBytecodeHandler(Isolate* isolate, const char* debug_name, Bytecode bytecode, OperandScale operand_scale, int builtin_index, const AssemblerOptions& options); extern Handle<Code> GenerateDeserializeLazyHandler( Isolate* isolate, OperandScale operand_scale, int builtin_index, const AssemblerOptions& options); } // namespace interpreter } // namespace internal } // namespace v8 #endif // V8_INTERPRETER_INTERPRETER_GENERATOR_H_
nongdenchet/Samgu
app/src/main/java/apidez/com/samgu/adapter/FriendListAdapter.java
package apidez.com.samgu.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.bumptech.glide.Glide; import java.util.ArrayList; import java.util.List; import apidez.com.samgu.R; import butterknife.Bind; import butterknife.ButterKnife; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by nongdenchet on 6/5/16. */ public class FriendListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.friend_item, parent, false); return new FriendItemViewHolder(rootView); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ((FriendItemViewHolder) holder).bind(friends().get(position)); } @Override public int getItemCount() { return friends().size(); } public static class Friend { public String url, name, message; public Friend(String url, String name, String message) { this.url = url; this.name = name; this.message = message; } } public class FriendItemViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.cvAvatar) CircleImageView cvAvatar; @Bind(R.id.tvName) TextView tvName; @Bind(R.id.tvMessage) TextView tvMessage; public FriendItemViewHolder(View rootView) { super(rootView); ButterKnife.bind(this, rootView); } public void bind(Friend friend) { tvName.setText(friend.name); tvMessage.setText(friend.message); Glide.with(itemView.getContext()) .load(friend.url) .centerCrop() .into(cvAvatar); itemView.setOnClickListener(v -> { }); } } public List<FriendListAdapter.Friend> friends() { List<FriendListAdapter.Friend> friends = new ArrayList<>(); friends.add(new Friend("http://scontent-hkg3-1.xx.fbcdn.net/t31.0-8/13072819_1133555470022181_5019669804777413920_o.jpg", "<NAME>", "Thấy ghét hà <3")); friends.add(new Friend("https://scontent.fsgn2-2.fna.fbcdn.net/v/t1.0-9/15253571_1255569104513806_1694383344236438323_n.jpg?oh=c674b4a786507584893ad5e165ec5571&oe=58F1A03E", "<NAME>", "Anh ơi")); friends.add(new Friend("http://scontent-hkg3-1.xx.fbcdn.net/t31.0-8/12998383_1127949393916122_3155205815095903997_o.jpg", "<NAME>", "<3 <3 <3")); friends.add(new Friend("https://scontent.fsgn2-2.fna.fbcdn.net/v/t1.0-9/12038031_1504317549860999_6722477539523468950_n.jpg?oh=90bc47661df8d88ccc8e685b8ba446a0&oe=58C0A17F", "Sếp Tùng", "Sky eiiiii!!!")); friends.add(new Friend("http://scontent-hkg3-1.xx.fbcdn.net/t31.0-8/13062973_463324620540694_6650778368538652819_o.jpg", "Sammy", "Ck có nhớ vk ko???")); friends.add(new Friend("https://scontent.fsgn2-2.fna.fbcdn.net/t31.0-8/15325195_348739635493100_2324514124436964483_o.jpg", "Trinh", "Giận rùi")); friends.add(new Friend("https://scontent.fsgn2-2.fna.fbcdn.net/t31.0-8/14102954_655203127977711_346605723006854355_o.jpg", "Trang", "Thích nhạc Maroon 5 nhứt")); friends.add(new Friend("http://scontent-hkg3-1.xx.fbcdn.net/t31.0-8/11000654_469380153209783_6363118670586989285_o.jpg", "<NAME>", "Nhạc Jazz khó nghe lắm")); return friends; } }
git-wwts/pysyte
pysyte/bash/test/test_shell.py
<gh_stars>1-10 """Test the term module""" import unittest from pysyte.bash import shell class TestShell(unittest.TestCase): def test_double_cd(self): """This test is purely for sake of coverage The second cd (to same dir) should have no effect """ shell.cd("/usr/local") expected = shell.run("basename $PWD") shell.cd("/usr/local") actual = shell.run("basename $PWD") self.assertEqual(actual, expected)
uk-gov-mirror/hmcts.ia-case-api
src/main/java/uk/gov/hmcts/reform/iacaseapi/domain/entities/ccd/callback/PostSubmitCallbackResponse.java
package uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.callback; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.annotation.JsonNaming; import java.util.Optional; @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) public class PostSubmitCallbackResponse { private Optional<String> confirmationHeader = Optional.empty(); private Optional<String> confirmationBody = Optional.empty(); public Optional<String> getConfirmationHeader() { return confirmationHeader; } public Optional<String> getConfirmationBody() { return confirmationBody; } public void setConfirmationHeader(String confirmationHeader) { this.confirmationHeader = Optional.ofNullable(confirmationHeader); } public void setConfirmationBody(String confirmationBody) { this.confirmationBody = Optional.ofNullable(confirmationBody); } }
NotDiscordOfficial/Fortnite_SDK
Enum_MANG_Security_ID_struct.h
<filename>Enum_MANG_Security_ID_struct.h<gh_stars>0 // UserDefinedEnum Enum_MANG_Security_ID.Enum_MANG_Security_ID enum class Enum_MANG_Security_ID : uint8 { NewEnumerator0, NewEnumerator1, NewEnumerator2, NewEnumerator3, NewEnumerator4, NewEnumerator5, NewEnumerator6, NewEnumerator7, NewEnumerator8, NewEnumerator9, NewEnumerator10, Enum_MANG_Security_MAX, };
zaaksam/dproxy
go/services/proxyService.go
<gh_stars>10-100 package services import ( "errors" "fmt" "io" "net" "strings" "sync" "time" "github.com/zaaksam/dproxy/go/logger" "github.com/zaaksam/dproxy/go/model" ) // Proxy 代理服务对象 var Proxy proxyService func init() { Proxy.proxys = make(map[int64]*proxy) } type proxyService struct { proxys map[int64]*proxy mx sync.Mutex } func (s *proxyService) addProxy(id int64, p *proxy) { s.mx.Lock() defer s.mx.Unlock() s.proxys[id] = p } func (s *proxyService) delProxy(id int64) { s.mx.Lock() defer s.mx.Unlock() delete(s.proxys, id) } func (s *proxyService) StartAll() error { list, err := PortMap.Find(1, 500, "", "", "") if err != nil { return err } if list.Total <= 0 { return nil } var mds []*model.PortMapModel if items, ok := list.Items.(*[]*model.PortMapModel); ok { mds = *items } else { return nil } for i, l := 0, len(mds); i < l; i++ { if !mds[i].IsStart { err = s.Start(mds[i].ID) if err != nil { return err } } } return nil } func (s *proxyService) StopAll() { list, err := PortMap.Find(1, 500, "", "", "") if err != nil { return } if list.Total <= 0 { return } for partMapID := range Proxy.proxys { s.Stop(partMapID) } } // Start 启动代理请求服务 func (s *proxyService) Start(portMapID int64) error { if _, ok := s.proxys[portMapID]; !ok { //检查是否存在该配置 md, err := PortMap.Get(portMapID) if err != nil { return err } //开启代理请求协程 sourceAddr := fmt.Sprintf("%s:%d", md.SourceIP, md.SourcePort) targetAddr := fmt.Sprintf("%s:%d", md.TargetIP, md.TargetPort) listener, err := net.Listen("tcp", sourceAddr) if err != nil { return errors.New("代理启动失败:" + err.Error()) } p := &proxy{ listener: listener, stopChan: make(chan bool), clients: make(map[string]chan bool), } s.addProxy(portMapID, p) go func() { for { //监听请求 clientConn, err := p.listener.Accept() if err != nil { logger.Error("客户端请求响应失败:", err) break } go s.Serve(p, clientConn, sourceAddr, targetAddr) } }() } return nil } func (s *proxyService) Serve(p *proxy, clientConn net.Conn, sourceAddr, targetAddr string) { defer clientConn.Close() //白名单检查 clientAddr := strings.ToLower(clientConn.RemoteAddr().String()) ip := strings.Split(clientAddr, ":")[0] if !WhiteList.Check(ip) { logger.Warning("非法请求:", clientAddr, "->", sourceAddr, "(", targetAddr, ")") return } //创建 server serverConn, err := net.DialTimeout("tcp", targetAddr, 30*time.Second) if err != nil { logger.Error("服务端请求响应失败:", err) return } defer serverConn.Close() //注册客户端 invalidChan := p.addClient(ip) //代理停止命令监测 endChan := make(chan bool) go func() { select { case <-p.stopChan: //代理停止命令 serverConn.Close() case <-invalidChan: //白名单失效通知,可能删除,可能过期 serverConn.Close() case <-endChan: //单次请求连接结束通知 } }() defer close(endChan) errc := make(chan error, 2) cp := func(dst io.Writer, src io.Reader, info string) { _, err := io.Copy(dst, src) if err != nil { if err == io.EOF || strings.Contains(err.Error(), "use of closed network connection") { err = nil } else { err = errors.New(info + "失败:" + err.Error()) } } errc <- err } go cp(serverConn, clientConn, "代理请求发送") go cp(clientConn, serverConn, "服务响应接收") err = <-errc if err != nil { logger.Error(err) } } func (s *proxyService) Stop(portMapID int64) { if p, ok := s.proxys[portMapID]; ok { p.listener.Close() close(p.stopChan) s.delProxy(portMapID) } } func (s *proxyService) setClientInvalid(ip string) { for _, p := range s.proxys { p.setClientInvalid(ip) } } // ================ proxy 定义 ======================== type proxy struct { listener net.Listener stopChan chan bool clients map[string]chan bool // map[ip]invalidChan mx sync.Mutex // clients map[string]map[string]net.Conn // map[ip]map[port]net.Conn // ipMutex sync.RWMutex // portMutex sync.RWMutex } func (p *proxy) addClient(ip string) <-chan bool { p.mx.Lock() defer p.mx.Unlock() invalidChan, ok := p.clients[ip] if !ok { invalidChan = make(chan bool) p.clients[ip] = invalidChan } return invalidChan } func (p *proxy) removeClient(ip string) { p.mx.Lock() defer p.mx.Unlock() delete(p.clients, ip) } func (p *proxy) setClientInvalid(ip string) { if invalidChan, ok := p.clients[ip]; ok { close(invalidChan) p.removeClient(ip) } }
cuilan/ssmp-framework
ssmp-admin/src/main/java/cn/cuilan/ssmp/admin/security/handler/LoginFailureHandler.java
<reponame>cuilan/ssmp-framework package cn.cuilan.ssmp.admin.security.handler; import cn.cuilan.ssmp.utils.result.Result; import cn.cuilan.ssmp.utils.result.ResultUtil; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 用户登录失败处理 * * @author zhang.yan */ @Component public class LoginFailureHandler implements AuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { ResultUtil.responseJson(response, Result.fail(exception.getMessage())); } }
sahirsharma/Martian
NASA SPACEAPPS CHALLENGE/Solution/Software part/Astronomical Data and Python Libraries/Astropy/astropy-1.1.2/astropy/units/tests/test_quantity_ufuncs.py
# The purpose of these tests are to ensure that calling ufuncs with quantities # returns quantities with the right units, or raises exceptions. import numpy as np from numpy.testing.utils import assert_allclose from ... import units as u from ...tests.helper import pytest, raises class TestUfuncCoverage(object): """Test that we cover all ufunc's""" def test_coverage(self): all_np_ufuncs = set([ufunc for ufunc in np.core.umath.__dict__.values() if type(ufunc) == np.ufunc]) from .. import quantity_helper as qh all_q_ufuncs = (qh.UNSUPPORTED_UFUNCS | set(qh.UFUNC_HELPERS.keys())) assert all_np_ufuncs - all_q_ufuncs == set([]) assert all_q_ufuncs - all_np_ufuncs == set([]) class TestQuantityTrigonometricFuncs(object): """ Test trigonometric functions """ def test_sin_scalar(self): q = np.sin(30. * u.degree) assert q.unit == u.dimensionless_unscaled assert_allclose(q.value, 0.5) def test_sin_array(self): q = np.sin(np.array([0., np.pi / 4., np.pi / 2.]) * u.radian) assert q.unit == u.dimensionless_unscaled assert_allclose(q.value, np.array([0., 1. / np.sqrt(2.), 1.]), atol=1.e-15) def test_arcsin_scalar(self): q1 = 30. * u.degree q2 = np.arcsin(np.sin(q1)).to(q1.unit) assert_allclose(q1.value, q2.value) def test_arcsin_array(self): q1 = np.array([0., np.pi / 4., np.pi / 2.]) * u.radian q2 = np.arcsin(np.sin(q1)).to(q1.unit) assert_allclose(q1.value, q2.value) def test_sin_invalid_units(self): with pytest.raises(TypeError) as exc: np.sin(3. * u.m) assert exc.value.args[0] == ("Can only apply 'sin' function " "to quantities with angle units") def test_arcsin_invalid_units(self): with pytest.raises(TypeError) as exc: np.arcsin(3. * u.m) assert exc.value.args[0] == ("Can only apply 'arcsin' function to " "dimensionless quantities") def test_cos_scalar(self): q = np.cos(np.pi / 3. * u.radian) assert q.unit == u.dimensionless_unscaled assert_allclose(q.value, 0.5) def test_cos_array(self): q = np.cos(np.array([0., np.pi / 4., np.pi / 2.]) * u.radian) assert q.unit == u.dimensionless_unscaled assert_allclose(q.value, np.array([1., 1. / np.sqrt(2.), 0.]), atol=1.e-15) def test_arccos_scalar(self): q1 = np.pi / 3. * u.radian q2 = np.arccos(np.cos(q1)).to(q1.unit) assert_allclose(q1.value, q2.value) def test_arccos_array(self): q1 = np.array([0., np.pi / 4., np.pi / 2.]) * u.radian q2 = np.arccos(np.cos(q1)).to(q1.unit) assert_allclose(q1.value, q2.value) def test_cos_invalid_units(self): with pytest.raises(TypeError) as exc: np.cos(3. * u.s) assert exc.value.args[0] == ("Can only apply 'cos' function " "to quantities with angle units") def test_arccos_invalid_units(self): with pytest.raises(TypeError) as exc: np.arccos(3. * u.s) assert exc.value.args[0] == ("Can only apply 'arccos' function to " "dimensionless quantities") def test_tan_scalar(self): q = np.tan(np.pi / 3. * u.radian) assert q.unit == u.dimensionless_unscaled assert_allclose(q.value, np.sqrt(3.)) def test_tan_array(self): q = np.tan(np.array([0., 45., 135., 180.]) * u.degree) assert q.unit == u.dimensionless_unscaled assert_allclose(q.value, np.array([0., 1., -1., 0.]), atol=1.e-15) def test_arctan_scalar(self): q = np.pi / 3. * u.radian assert np.arctan(np.tan(q)) def test_arctan_array(self): q = np.array([10., 30., 70., 80.]) * u.degree assert_allclose(np.arctan(np.tan(q)).to(q.unit).value, q.value) def test_tan_invalid_units(self): with pytest.raises(TypeError) as exc: np.tan(np.array([1, 2, 3]) * u.N) assert exc.value.args[0] == ("Can only apply 'tan' function " "to quantities with angle units") def test_arctan_invalid_units(self): with pytest.raises(TypeError) as exc: np.arctan(np.array([1, 2, 3]) * u.N) assert exc.value.args[0] == ("Can only apply 'arctan' function to " "dimensionless quantities") def test_arctan2_valid(self): q1 = np.array([10., 30., 70., 80.]) * u.m q2 = 2.0 * u.km assert np.arctan2(q1, q2).unit == u.radian assert_allclose(np.arctan2(q1, q2).value, np.arctan2(q1.value, q2.to(q1.unit).value)) q3 = q1 / q2 q4 = 1. at2 = np.arctan2(q3, q4) assert_allclose(at2.value, np.arctan2(q3.to(1).value, q4)) def test_arctan2_invalid(self): with pytest.raises(u.UnitsError) as exc: np.arctan2(np.array([1, 2, 3]) * u.N, 1. * u.s) assert "compatible dimensions" in exc.value.args[0] with pytest.raises(u.UnitsError) as exc: np.arctan2(np.array([1, 2, 3]) * u.N, 1.) assert "dimensionless quantities when other arg" in exc.value.args[0] def test_radians(self): q1 = np.deg2rad(180. * u.degree) assert_allclose(q1.value, np.pi) assert q1.unit == u.radian q2 = np.radians(180. * u.degree) assert_allclose(q2.value, np.pi) assert q2.unit == u.radian # the following doesn't make much sense in terms of the name of the # routine, but we check it gives the correct result. q3 = np.deg2rad(3. * u.radian) assert_allclose(q3.value, 3.) assert q3.unit == u.radian q4 = np.radians(3. * u.radian) assert_allclose(q4.value, 3.) assert q4.unit == u.radian with pytest.raises(TypeError): np.deg2rad(3. * u.m) with pytest.raises(TypeError): np.radians(3. * u.m) def test_degrees(self): # the following doesn't make much sense in terms of the name of the # routine, but we check it gives the correct result. q1 = np.rad2deg(60. * u.degree) assert_allclose(q1.value, 60.) assert q1.unit == u.degree q2 = np.degrees(60. * u.degree) assert_allclose(q2.value, 60.) assert q2.unit == u.degree q3 = np.rad2deg(np.pi * u.radian) assert_allclose(q3.value, 180.) assert q3.unit == u.degree q4 = np.degrees(np.pi * u.radian) assert_allclose(q4.value, 180.) assert q4.unit == u.degree with pytest.raises(TypeError): np.rad2deg(3. * u.m) with pytest.raises(TypeError): np.degrees(3. * u.m) class TestQuantityMathFuncs(object): """ Test other mathematical functions """ def test_multiply_scalar(self): assert np.multiply(4. * u.m, 2. / u.s) == 8. * u.m / u.s assert np.multiply(4. * u.m, 2.) == 8. * u.m assert np.multiply(4., 2. / u.s) == 8. / u.s def test_multiply_array(self): assert np.all(np.multiply(np.arange(3.) * u.m, 2. / u.s) == np.arange(0, 6., 2.) * u.m / u.s) @pytest.mark.parametrize('function', (np.divide, np.true_divide)) def test_divide_scalar(self, function): assert function(4. * u.m, 2. * u.s) == function(4., 2.) * u.m / u.s assert function(4. * u.m, 2.) == function(4., 2.) * u.m assert function(4., 2. * u.s) == function(4., 2.) / u.s @pytest.mark.parametrize('function', (np.divide, np.true_divide)) def test_divide_array(self, function): assert np.all(function(np.arange(3.) * u.m, 2. * u.s) == function(np.arange(3.), 2.) * u.m / u.s) def test_divmod_and_floor_divide(self): inch = u.Unit(0.0254 * u.m) dividend = np.array([1., 2., 3.]) * u.m divisor = np.array([3., 4., 5.]) * inch quotient = dividend // divisor assert_allclose(quotient.value, [13., 19., 23.]) assert quotient.unit == u.dimensionless_unscaled quotient2, remainder = divmod(dividend, divisor) assert np.all(quotient2 == quotient) assert_allclose(remainder.value, [0.0094, 0.0696, 0.079]) assert remainder.unit == dividend.unit with pytest.raises(TypeError): divmod(dividend, u.km) with pytest.raises(TypeError): dividend // u.km def test_sqrt_scalar(self): assert np.sqrt(4. * u.m) == 2. * u.m ** 0.5 def test_sqrt_array(self): assert np.all(np.sqrt(np.array([1., 4., 9.]) * u.m) == np.array([1., 2., 3.]) * u.m ** 0.5) def test_square_scalar(self): assert np.square(4. * u.m) == 16. * u.m ** 2 def test_square_array(self): assert np.all(np.square(np.array([1., 2., 3.]) * u.m) == np.array([1., 4., 9.]) * u.m ** 2) def test_reciprocal_scalar(self): assert np.reciprocal(4. * u.m) == 0.25 / u.m def test_reciprocal_array(self): assert np.all(np.reciprocal(np.array([1., 2., 4.]) * u.m) == np.array([1., 0.5, 0.25]) / u.m) # cbrt only introduced in numpy 1.10 @pytest.mark.skipif("not hasattr(np, 'cbrt')") def test_cbrt_scalar(self): assert np.cbrt(8. * u.m**3) == 2. * u.m @pytest.mark.skipif("not hasattr(np, 'cbrt')") def test_cbrt_array(self): # Calculate cbrt on both sides since on Windows the cube root of 64 # does not exactly equal 4. See 4388. values = np.array([1., 8., 64.]) assert np.all(np.cbrt(values * u.m**3) == np.cbrt(values) * u.m) def test_power_scalar(self): assert np.power(4. * u.m, 2.) == 16. * u.m ** 2 assert np.power(4., 200. * u.cm / u.m) == \ u.Quantity(16., u.dimensionless_unscaled) # regression check on #1696 assert np.power(4. * u.m, 0.) == 1. * u.dimensionless_unscaled def test_power_array(self): assert np.all(np.power(np.array([1., 2., 3.]) * u.m, 3.) == np.array([1., 8., 27.]) * u.m ** 3) # regression check on #1696 assert np.all(np.power(np.arange(4.) * u.m, 0.) == 1. * u.dimensionless_unscaled) @raises(ValueError) def test_power_array_array(self): np.power(4. * u.m, [2., 4.]) @raises(ValueError) def test_power_array_array2(self): np.power([2., 4.] * u.m, [2., 4.]) def test_power_invalid(self): with pytest.raises(TypeError) as exc: np.power(3., 4. * u.m) assert "raise something to a dimensionless" in exc.value.args[0] def test_copysign_scalar(self): assert np.copysign(3 * u.m, 1.) == 3. * u.m assert np.copysign(3 * u.m, 1. * u.s) == 3. * u.m assert np.copysign(3 * u.m, -1.) == -3. * u.m assert np.copysign(3 * u.m, -1. * u.s) == -3. * u.m def test_copysign_array(self): assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, -1.) == -np.array([1., 2., 3.]) * u.s) assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, -1. * u.m) == -np.array([1., 2., 3.]) * u.s) assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, np.array([-2.,2.,-4.]) * u.m) == np.array([-1., 2., -3.]) * u.s) q = np.copysign(np.array([1., 2., 3.]), -3 * u.m) assert np.all(q == np.array([-1., -2., -3.])) assert not isinstance(q, u.Quantity) def test_ldexp_scalar(self): assert np.ldexp(4. * u.m, 2) == 16. * u.m def test_ldexp_array(self): assert np.all(np.ldexp(np.array([1., 2., 3.]) * u.m, [3, 2, 1]) == np.array([8., 8., 6.]) * u.m) def test_ldexp_invalid(self): with pytest.raises(TypeError): np.ldexp(3. * u.m, 4.) with pytest.raises(TypeError): np.ldexp(3., u.Quantity(4, u.m, dtype=int)) @pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2, np.log, np.log2, np.log10, np.log1p)) def test_exp_scalar(self, function): q = function(3. * u.m / (6. * u.m)) assert q.unit == u.dimensionless_unscaled assert q.value == function(0.5) @pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2, np.log, np.log2, np.log10, np.log1p)) def test_exp_array(self, function): q = function(np.array([2., 3., 6.]) * u.m / (6. * u.m)) assert q.unit == u.dimensionless_unscaled assert np.all(q.value == function(np.array([1. / 3., 1. / 2., 1.]))) # should also work on quantities that can be made dimensionless q2 = function(np.array([2., 3., 6.]) * u.m / (6. * u.cm)) assert q2.unit == u.dimensionless_unscaled assert_allclose(q2.value, function(np.array([100. / 3., 100. / 2., 100.]))) @pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2, np.log, np.log2, np.log10, np.log1p)) def test_exp_invalid_units(self, function): # Can't use exp() with non-dimensionless quantities with pytest.raises(TypeError) as exc: function(3. * u.m / u.s) assert exc.value.args[0] == ("Can only apply '{0}' function to " "dimensionless quantities" .format(function.__name__)) def test_modf_scalar(self): q = np.modf(9. * u.m / (600. * u.cm)) assert q == (0.5 * u.dimensionless_unscaled, 1. * u.dimensionless_unscaled) def test_modf_array(self): v = np.arange(10.) * u.m / (500. * u.cm) q = np.modf(v) n = np.modf(v.to(1).value) assert q[0].unit == u.dimensionless_unscaled assert q[1].unit == u.dimensionless_unscaled assert all(q[0].value == n[0]) assert all(q[1].value == n[1]) def test_frexp_scalar(self): q = np.frexp(3. * u.m / (6. * u.m)) assert q == (np.array(0.5), np.array(0.0)) def test_frexp_array(self): q = np.frexp(np.array([2., 3., 6.]) * u.m / (6. * u.m)) assert all((_q0, _q1) == np.frexp(_d) for _q0, _q1, _d in zip(q[0], q[1], [1. / 3., 1. / 2., 1.])) def test_frexp_invalid_units(self): # Can't use prod() with non-dimensionless quantities with pytest.raises(TypeError) as exc: np.frexp(3. * u.m / u.s) assert exc.value.args[0] == ("Can only apply 'frexp' function to " "unscaled dimensionless quantities") # also does not work on quantities that can be made dimensionless with pytest.raises(TypeError) as exc: np.frexp(np.array([2., 3., 6.]) * u.m / (6. * u.cm)) assert exc.value.args[0] == ("Can only apply 'frexp' function to " "unscaled dimensionless quantities") @pytest.mark.parametrize('function', (np.logaddexp, np.logaddexp2)) def test_dimensionless_twoarg_array(self, function): q = function(np.array([2., 3., 6.]) * u.m / (6. * u.cm), 1.) assert q.unit == u.dimensionless_unscaled assert_allclose(q.value, function(np.array([100. / 3., 100. / 2., 100.]), 1.)) @pytest.mark.parametrize('function', (np.logaddexp, np.logaddexp2)) def test_dimensionless_twoarg_invalid_units(self, function): with pytest.raises(TypeError) as exc: function(1. * u.km / u.s, 3. * u.m / u.s) assert exc.value.args[0] == ("Can only apply '{0}' function to " "dimensionless quantities" .format(function.__name__)) class TestInvariantUfuncs(object): @pytest.mark.parametrize(('ufunc'), [np.absolute, np.fabs, np.conj, np.conjugate, np.negative, np.spacing, np.rint, np.floor, np.ceil]) def test_invariant_scalar(self, ufunc): q_i = 4.7 * u.m q_o = ufunc(q_i) assert isinstance(q_o, u.Quantity) assert q_o.unit == q_i.unit assert q_o.value == ufunc(q_i.value) @pytest.mark.parametrize(('ufunc'), [np.absolute, np.conjugate, np.negative, np.rint, np.floor, np.ceil]) def test_invariant_array(self, ufunc): q_i = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s q_o = ufunc(q_i) assert isinstance(q_o, u.Quantity) assert q_o.unit == q_i.unit assert np.all(q_o.value == ufunc(q_i.value)) @pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot, np.maximum, np.minimum, np.nextafter, np.remainder, np.mod, np.fmod]) def test_invariant_twoarg_scalar(self, ufunc): q_i1 = 4.7 * u.m q_i2 = 9.4 * u.km q_o = ufunc(q_i1, q_i2) assert isinstance(q_o, u.Quantity) assert q_o.unit == q_i1.unit assert_allclose(q_o.value, ufunc(q_i1.value, q_i2.to(q_i1.unit).value)) @pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot, np.maximum, np.minimum, np.nextafter, np.remainder, np.mod, np.fmod]) def test_invariant_twoarg_array(self, ufunc): q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s q_i2 = np.array([10., -5., 1.e6]) * u.g / u.us q_o = ufunc(q_i1, q_i2) assert isinstance(q_o, u.Quantity) assert q_o.unit == q_i1.unit assert_allclose(q_o.value, ufunc(q_i1.value, q_i2.to(q_i1.unit).value)) @pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot, np.maximum, np.minimum, np.nextafter, np.remainder, np.mod, np.fmod]) def test_invariant_twoarg_one_arbitrary(self, ufunc): q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s arbitrary_unit_value = np.array([0.]) q_o = ufunc(q_i1, arbitrary_unit_value) assert isinstance(q_o, u.Quantity) assert q_o.unit == q_i1.unit assert_allclose(q_o.value, ufunc(q_i1.value, arbitrary_unit_value)) @pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot, np.maximum, np.minimum, np.nextafter, np.remainder, np.mod, np.fmod]) def test_invariant_twoarg_invalid_units(self, ufunc): q_i1 = 4.7 * u.m q_i2 = 9.4 * u.s with pytest.raises(u.UnitsError) as exc: ufunc(q_i1, q_i2) assert "compatible dimensions" in exc.value.args[0] class TestComparisonUfuncs(object): @pytest.mark.parametrize(('ufunc'), [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal, np.equal]) def test_comparison_valid_units(self, ufunc): q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s q_i2 = np.array([10., -5., 1.e6]) * u.g / u.Ms q_o = ufunc(q_i1, q_i2) assert not isinstance(q_o, u.Quantity) assert q_o.dtype == np.bool assert np.all(q_o == ufunc(q_i1.value, q_i2.to(q_i1.unit).value)) q_o2 = ufunc(q_i1 / q_i2, 2.) assert not isinstance(q_o2, u.Quantity) assert q_o2.dtype == np.bool assert np.all(q_o2 == ufunc((q_i1 / q_i2).to(1).value, 2.)) # comparison with 0., inf, nan is OK even for dimensional quantities for arbitrary_unit_value in (0., np.inf, np.nan): ufunc(q_i1, arbitrary_unit_value) ufunc(q_i1, arbitrary_unit_value*np.ones(len(q_i1))) # and just for completeness ufunc(q_i1, np.array([0., np.inf, np.nan])) @pytest.mark.parametrize(('ufunc'), [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal, np.equal]) def test_comparison_invalid_units(self, ufunc): q_i1 = 4.7 * u.m q_i2 = 9.4 * u.s with pytest.raises(u.UnitsError) as exc: ufunc(q_i1, q_i2) assert "compatible dimensions" in exc.value.args[0] class TestInplaceUfuncs(object): @pytest.mark.parametrize(('value'), [1., np.arange(10.)]) def test_one_argument_ufunc_inplace(self, value): # without scaling s = value * u.rad check = s np.sin(s, out=s) assert check is s assert check.unit == u.dimensionless_unscaled # with scaling s2 = (value * u.rad).to(u.deg) check2 = s2 np.sin(s2, out=s2) assert check2 is s2 assert check2.unit == u.dimensionless_unscaled assert_allclose(s.value, s2.value) @pytest.mark.parametrize(('value'), [1., np.arange(10.)]) def test_one_argument_ufunc_inplace_2(self, value): """Check inplace works with non-quantity input and quantity output""" s = value * u.m check = s np.absolute(value, out=s) assert check is s assert np.all(check.value == np.absolute(value)) assert check.unit is u.dimensionless_unscaled np.sqrt(value, out=s) assert check is s assert np.all(check.value == np.sqrt(value)) assert check.unit is u.dimensionless_unscaled np.exp(value, out=s) assert check is s assert np.all(check.value == np.exp(value)) assert check.unit is u.dimensionless_unscaled np.arcsin(value/10., out=s) assert check is s assert np.all(check.value == np.arcsin(value/10.)) assert check.unit is u.radian @pytest.mark.parametrize(('value'), [1., np.arange(10.)]) def test_one_argument_two_output_ufunc_inplace(self, value): v = 100. * value * u.cm / u.m v_copy = v.copy() tmp = v.copy() check = v np.modf(v, tmp, v) # cannot use out1,out2 keywords with numpy 1.7 assert check is v assert check.unit == u.dimensionless_unscaled v2 = v_copy.to(1) check2 = v2 np.modf(v2, tmp, v2) assert check2 is v2 assert check2.unit == u.dimensionless_unscaled # can also replace in last position if no scaling is needed v3 = v_copy.to(1) check3 = v3 np.modf(v3, v3, tmp) assert check3 is v3 assert check3.unit == u.dimensionless_unscaled # but cannot replace input with first output if scaling is needed with pytest.raises(TypeError): np.modf(v_copy, v_copy, tmp) @pytest.mark.parametrize(('value'), [1., np.arange(10.)]) def test_two_argument_ufunc_inplace_1(self, value): s = value * u.cycle check = s s /= 2. assert check is s assert np.all(check.value == value / 2.) s /= u.s assert check is s assert check.unit == u.cycle / u.s s *= 2. * u.s assert check is s assert np.all(check == value * u.cycle) @pytest.mark.parametrize(('value'), [1., np.arange(10.)]) def test_two_argument_ufunc_inplace_2(self, value): s = value * u.cycle check = s np.arctan2(s, s, out=s) assert check is s assert check.unit == u.radian with pytest.raises(u.UnitsError): s += 1. * u.m assert check is s assert check.unit == u.radian np.arctan2(1. * u.deg, s, out=s) assert check is s assert check.unit == u.radian np.add(1. * u.deg, s, out=s) assert check is s assert check.unit == u.deg np.multiply(2. / u.s, s, out=s) assert check is s assert check.unit == u.deg / u.s def test_two_argument_ufunc_inplace_3(self): s = np.array([1., 2., 3.]) * u.dimensionless_unscaled np.add(np.array([1., 2., 3.]), np.array([1., 2., 3.]) * 2., out=s) assert np.all(s.value == np.array([3., 6., 9.])) assert s.unit is u.dimensionless_unscaled np.arctan2(np.array([1., 2., 3.]), np.array([1., 2., 3.]) * 2., out=s) assert_allclose(s.value, np.arctan2(1., 2.)) assert s.unit is u.radian def test_ufunc_inplace_non_contiguous_data(self): # ensure inplace works also for non-contiguous data (closes #1834) s = np.arange(10.) * u.m s_copy = s.copy() s2 = s[::2] s2 += 1. * u.cm assert np.all(s[::2] > s_copy[::2]) assert np.all(s[1::2] == s_copy[1::2]) def test_ufunc_inplace_non_standard_dtype(self): """Check that inplace operations check properly for casting. First two tests that check that float32 is kept close #3976. """ a1 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.float32) a1 *= np.float32(10) assert a1.unit is u.m assert a1.dtype == np.float32 a2 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.float32) a2 += (20.*u.km) assert a2.unit is u.m assert a2.dtype == np.float32 # For integer, in-place only works if no conversion is done. a3 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.int32) a3 += u.Quantity(10, u.m, dtype=np.int64) assert a3.unit is u.m assert a3.dtype == np.int32 a4 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.int32) with pytest.raises(TypeError): a4 += u.Quantity(10, u.mm, dtype=np.int64)
rizhenkov/feedbin
test/controllers/updated_entries_controller_test.rb
<gh_stars>1000+ require "test_helper" class UpdatedEntriesControllerTest < ActionController::TestCase setup do @user = users(:new) @feeds = create_feeds(@user) @entries = @user.entries @updated = @entries.each do |entry| UpdatedEntry.create_from_owners(@user.id, entry) end end test "should get index" do login_as @user get :index, xhr: true assert_response :success assert_equal @updated.length, assigns(:entries).length end end
thl-mot/mbed-os
connectivity/nanostack/sal-stack-nanostack/source/Security/protocols/tls_sec_prot/tls_sec_prot_lib.c
<reponame>thl-mot/mbed-os /* * Copyright (c) 2019-2020, Pelion and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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 "nsconfig.h" #ifdef HAVE_WS #include "mbedtls/version.h" #if defined(MBEDTLS_SSL_TLS_C) && defined(MBEDTLS_X509_CRT_PARSE_C) && defined(MBEDTLS_SSL_EXPORT_KEYS) /* EXPORT_KEYS not supported by mbedtls baremetal yet */ #define WS_MBEDTLS_SECURITY_ENABLED #endif #include <string.h> #include <randLIB.h> #include "ns_types.h" #include "ns_list.h" #include "ns_trace.h" #include "nsdynmemLIB.h" #include "common_functions.h" #include "Service_Libs/Trickle/trickle.h" #include "Security/protocols/sec_prot_cfg.h" #include "Security/protocols/sec_prot_certs.h" #include "Security/protocols/tls_sec_prot/tls_sec_prot_lib.h" #if defined(MBEDTLS_SSL_TLS_C) && defined(MBEDTLS_X509_CRT_PARSE_C) && defined(MBEDTLS_SSL_EXPORT_KEYS) /* EXPORT_KEYS not supported by mbedtls baremetal yet */ #ifdef WS_MBEDTLS_SECURITY_ENABLED #endif #include "mbedtls/sha256.h" #include "mbedtls/error.h" #include "mbedtls/platform.h" #include "mbedtls/ssl_cookie.h" #include "mbedtls/entropy.h" #include "mbedtls/ctr_drbg.h" #include "mbedtls/ssl_ciphersuites.h" #include "mbedtls/debug.h" #include "mbedtls/oid.h" #define TRACE_GROUP "tlsl" #define TLS_HANDSHAKE_TIMEOUT_MIN 25000 #define TLS_HANDSHAKE_TIMEOUT_MAX 201000 //#define TLS_SEC_PROT_LIB_TLS_DEBUG // Enable mbed TLS debug traces typedef int tls_sec_prot_lib_crt_verify_cb(tls_security_t *sec, mbedtls_x509_crt *crt, uint32_t *flags); struct tls_security_s { mbedtls_ssl_config conf; /**< mbed TLS SSL configuration */ mbedtls_ssl_context ssl; /**< mbed TLS SSL context */ mbedtls_ctr_drbg_context ctr_drbg; /**< mbed TLS pseudo random number generator context */ mbedtls_entropy_context entropy; /**< mbed TLS entropy context */ mbedtls_x509_crt cacert; /**< CA certificate(s) */ mbedtls_x509_crl *crl; /**< Certificate Revocation List */ mbedtls_x509_crt owncert; /**< Own certificate(s) */ mbedtls_pk_context pkey; /**< Private key for own certificate */ void *handle; /**< Handle provided in callbacks (defined by library user) */ bool ext_cert_valid : 1; /**< Extended certificate validation enabled */ #if (MBEDTLS_VERSION_MAJOR < 3) tls_sec_prot_lib_crt_verify_cb *crt_verify; /**< Verify function for client/server certificate */ #endif tls_sec_prot_lib_send *send; /**< Send callback */ tls_sec_prot_lib_receive *receive; /**< Receive callback */ tls_sec_prot_lib_export_keys *export_keys; /**< Export keys callback */ tls_sec_prot_lib_set_timer *set_timer; /**< Set timer callback */ tls_sec_prot_lib_get_timer *get_timer; /**< Get timer callback */ }; static void tls_sec_prot_lib_ssl_set_timer(void *ctx, uint32_t int_ms, uint32_t fin_ms); static int tls_sec_prot_lib_ssl_get_timer(void *ctx); static int tls_sec_lib_entropy_poll(void *data, unsigned char *output, size_t len, size_t *olen); static int tls_sec_prot_lib_ssl_send(void *ctx, const unsigned char *buf, size_t len); static int tls_sec_prot_lib_ssl_recv(void *ctx, unsigned char *buf, size_t len); #if (MBEDTLS_VERSION_MAJOR >= 3) static void tls_sec_prot_lib_ssl_export_keys(void *p_expkey, mbedtls_ssl_key_export_type type, const unsigned char *secret, size_t secret_len, const unsigned char client_random[32], const unsigned char server_random[32], mbedtls_tls_prf_types tls_prf_type); #else static int tls_sec_prot_lib_ssl_export_keys(void *p_expkey, const unsigned char *secret, const unsigned char *kb, size_t maclen, size_t keylen, size_t ivlen, const unsigned char client_random[32], const unsigned char server_random[32], mbedtls_tls_prf_types tls_prf_type); #endif #if (MBEDTLS_VERSION_MAJOR < 3) static int tls_sec_prot_lib_x509_crt_verify(void *ctx, mbedtls_x509_crt *crt, int certificate_depth, uint32_t *flags); static int8_t tls_sec_prot_lib_subject_alternative_name_validate(mbedtls_x509_crt *crt); static int8_t tls_sec_prot_lib_extended_key_usage_validate(mbedtls_x509_crt *crt); #ifdef HAVE_PAE_AUTH static int tls_sec_prot_lib_x509_crt_idevid_ldevid_verify(tls_security_t *sec, mbedtls_x509_crt *crt, uint32_t *flags); #endif #ifdef HAVE_PAE_SUPP static int tls_sec_prot_lib_x509_crt_server_verify(tls_security_t *sec, mbedtls_x509_crt *crt, uint32_t *flags); #endif #endif #ifdef TLS_SEC_PROT_LIB_TLS_DEBUG static void tls_sec_prot_lib_debug(void *ctx, int level, const char *file, int line, const char *string); #endif #ifdef MBEDTLS_PLATFORM_MEMORY // Disable for now //#define TLS_SEC_PROT_LIB_USE_MBEDTLS_PLATFORM_MEMORY #endif #ifdef TLS_SEC_PROT_LIB_USE_MBEDTLS_PLATFORM_MEMORY static void *tls_sec_prot_lib_mem_calloc(size_t count, size_t size); static void tls_sec_prot_lib_mem_free(void *ptr); #endif #if defined(HAVE_PAE_AUTH) && defined(HAVE_PAE_SUPP) #define is_server_is_set (is_server == true) #define is_server_is_not_set (is_server == false) #elif defined(HAVE_PAE_AUTH) #define is_server_is_set true #define is_server_is_not_set false #elif defined(HAVE_PAE_SUPP) #define is_server_is_set false #define is_server_is_not_set true #endif int8_t tls_sec_prot_lib_init(tls_security_t *sec) { const char *pers = "ws_tls"; #ifdef TLS_SEC_PROT_LIB_USE_MBEDTLS_PLATFORM_MEMORY mbedtls_platform_set_calloc_free(tls_sec_prot_lib_mem_calloc, tls_sec_prot_lib_mem_free); #endif mbedtls_ssl_init(&sec->ssl); mbedtls_ssl_config_init(&sec->conf); mbedtls_ctr_drbg_init(&sec->ctr_drbg); mbedtls_entropy_init(&sec->entropy); mbedtls_x509_crt_init(&sec->cacert); mbedtls_x509_crt_init(&sec->owncert); mbedtls_pk_init(&sec->pkey); sec->crl = NULL; if (mbedtls_entropy_add_source(&sec->entropy, tls_sec_lib_entropy_poll, NULL, 128, MBEDTLS_ENTROPY_SOURCE_WEAK) < 0) { tr_error("Entropy add fail"); return -1; } if ((mbedtls_ctr_drbg_seed(&sec->ctr_drbg, mbedtls_entropy_func, &sec->entropy, (const unsigned char *) pers, strlen(pers))) != 0) { tr_error("drbg seed fail"); return -1; } return 0; } uint16_t tls_sec_prot_lib_size(void) { return sizeof(tls_security_t); } void tls_sec_prot_lib_set_cb_register(tls_security_t *sec, void *handle, tls_sec_prot_lib_send *send, tls_sec_prot_lib_receive *receive, tls_sec_prot_lib_export_keys *export_keys, tls_sec_prot_lib_set_timer *set_timer, tls_sec_prot_lib_get_timer *get_timer) { if (!sec) { return; } sec->handle = handle; sec->send = send; sec->receive = receive; sec->export_keys = export_keys; sec->set_timer = set_timer; sec->get_timer = get_timer; } void tls_sec_prot_lib_free(tls_security_t *sec) { mbedtls_x509_crt_free(&sec->cacert); if (sec->crl) { mbedtls_x509_crl_free(sec->crl); ns_dyn_mem_free(sec->crl); } mbedtls_x509_crt_free(&sec->owncert); mbedtls_pk_free(&sec->pkey); mbedtls_entropy_free(&sec->entropy); mbedtls_ctr_drbg_free(&sec->ctr_drbg); mbedtls_ssl_config_free(&sec->conf); mbedtls_ssl_free(&sec->ssl); } static int tls_sec_prot_lib_configure_certificates(tls_security_t *sec, const sec_prot_certs_t *certs) { if (!certs->own_cert_chain.cert[0]) { tr_error("no own cert"); return -1; } // Parse own certificate chain uint8_t index = 0; while (true) { uint16_t cert_len; uint8_t *cert = sec_prot_certs_cert_get(&certs->own_cert_chain, index, &cert_len); if (!cert) { if (index == 0) { tr_error("No own cert"); return -1; } break; } if (mbedtls_x509_crt_parse(&sec->owncert, cert, cert_len) < 0) { tr_error("Own cert parse eror"); return -1; } index++; } // Parse private key uint8_t key_len; uint8_t *key = sec_prot_certs_priv_key_get(&certs->own_cert_chain, &key_len); if (!key) { tr_error("No private key"); return -1; } #if (MBEDTLS_VERSION_MAJOR >= 3) if (mbedtls_pk_parse_key(&sec->pkey, key, key_len, NULL, 0, mbedtls_ctr_drbg_random, &sec->ctr_drbg) < 0) { #else if (mbedtls_pk_parse_key(&sec->pkey, key, key_len, NULL, 0) < 0) { #endif tr_error("Private key parse error"); return -1; } // Configure own certificate chain and private key if (mbedtls_ssl_conf_own_cert(&sec->conf, &sec->owncert, &sec->pkey) != 0) { tr_error("Own cert and private key conf error"); return -1; } // Parse trusted certificate chains ns_list_foreach(cert_chain_entry_t, entry, &certs->trusted_cert_chain_list) { index = 0; while (true) { uint16_t cert_len; uint8_t *cert = sec_prot_certs_cert_get(entry, index, &cert_len); if (!cert) { if (index == 0) { tr_error("No trusted cert"); return -1; } break; } if (mbedtls_x509_crt_parse(&sec->cacert, cert, cert_len) < 0) { tr_error("Trusted cert parse error"); return -1; } index++; } } // Parse certificate revocation lists ns_list_foreach(cert_revocat_list_entry_t, entry, &certs->cert_revocat_lists) { uint16_t crl_len; const uint8_t *crl = sec_prot_certs_revocat_list_get(entry, &crl_len); if (!crl) { break; } if (!sec->crl) { sec->crl = ns_dyn_mem_temporary_alloc(sizeof(mbedtls_x509_crl)); if (!sec->crl) { tr_error("No memory for CRL"); return -1; } mbedtls_x509_crl_init(sec->crl); } if (mbedtls_x509_crl_parse(sec->crl, crl, crl_len) < 0) { tr_error("CRL parse error"); return -1; } } // Configure trusted certificates and certificate revocation lists mbedtls_ssl_conf_ca_chain(&sec->conf, &sec->cacert, sec->crl); // Certificate verify required on both client and server mbedtls_ssl_conf_authmode(&sec->conf, MBEDTLS_SSL_VERIFY_REQUIRED); // Get extended certificate validation setting sec->ext_cert_valid = sec_prot_certs_ext_certificate_validation_get(certs); return 0; } int8_t tls_sec_prot_lib_connect(tls_security_t *sec, bool is_server, const sec_prot_certs_t *certs) { #if !defined(HAVE_PAE_SUPP) || !defined(HAVE_PAE_AUTH) (void) is_server; #endif if (!sec) { return -1; } #if (MBEDTLS_VERSION_MAJOR < 3) #ifdef HAVE_PAE_SUPP if (is_server_is_not_set) { sec->crt_verify = tls_sec_prot_lib_x509_crt_server_verify; } #endif #ifdef HAVE_PAE_AUTH if (is_server_is_set) { sec->crt_verify = tls_sec_prot_lib_x509_crt_idevid_ldevid_verify; } #endif #endif if ((mbedtls_ssl_config_defaults(&sec->conf, is_server_is_set ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, 0)) != 0) { tr_error("config defaults fail"); return -1; } #if !defined(MBEDTLS_SSL_CONF_RNG) // Configure random number generator mbedtls_ssl_conf_rng(&sec->conf, mbedtls_ctr_drbg_random, &sec->ctr_drbg); #endif #ifdef MBEDTLS_ECP_RESTARTABLE // Set ECC calculation maximum operations (affects only client) mbedtls_ecp_set_max_ops(ECC_CALCULATION_MAX_OPS); #endif if ((mbedtls_ssl_setup(&sec->ssl, &sec->conf)) != 0) { tr_error("ssl setup fail"); return -1; } // Defines MBEDTLS_SSL_CONF_RECV/SEND/RECV_TIMEOUT define global functions which should be the same for all // callers of mbedtls_ssl_set_bio_ctx and there should be only one ssl context. If these rules don't apply, // these defines can't be used. #if !defined(MBEDTLS_SSL_CONF_RECV) && !defined(MBEDTLS_SSL_CONF_SEND) && !defined(MBEDTLS_SSL_CONF_RECV_TIMEOUT) // Set calbacks mbedtls_ssl_set_bio(&sec->ssl, sec, tls_sec_prot_lib_ssl_send, tls_sec_prot_lib_ssl_recv, NULL); #else mbedtls_ssl_set_bio_ctx(&sec->ssl, sec); #endif /* !defined(MBEDTLS_SSL_CONF_RECV) && !defined(MBEDTLS_SSL_CONF_SEND) && !defined(MBEDTLS_SSL_CONF_RECV_TIMEOUT) */ // Defines MBEDTLS_SSL_CONF_SET_TIMER/GET_TIMER define global functions which should be the same for all // callers of mbedtls_ssl_set_timer_cb and there should be only one ssl context. If these rules don't apply, // these defines can't be used. #if !defined(MBEDTLS_SSL_CONF_SET_TIMER) && !defined(MBEDTLS_SSL_CONF_GET_TIMER) mbedtls_ssl_set_timer_cb(&sec->ssl, sec, tls_sec_prot_lib_ssl_set_timer, tls_sec_prot_lib_ssl_get_timer); #endif /* !defined(MBEDTLS_SSL_CONF_SET_TIMER) && !defined(MBEDTLS_SSL_CONF_GET_TIMER) */ // Configure certificates, keys and certificate revocation list if (tls_sec_prot_lib_configure_certificates(sec, certs) != 0) { tr_error("cert conf fail"); return -1; } #if !defined(MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE) // Configure ciphersuites static const int sec_suites[] = { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, 0, 0, 0 }; mbedtls_ssl_conf_ciphersuites(&sec->conf, sec_suites); #endif /* !defined(MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE) */ #ifdef TLS_SEC_PROT_LIB_TLS_DEBUG mbedtls_ssl_conf_dbg(&sec->conf, tls_sec_prot_lib_debug, sec); mbedtls_debug_set_threshold(5); #endif // Export keys callback #if (MBEDTLS_VERSION_MAJOR >= 3) mbedtls_ssl_set_export_keys_cb(&sec->ssl, tls_sec_prot_lib_ssl_export_keys, sec); #else mbedtls_ssl_conf_export_keys_ext_cb(&sec->conf, tls_sec_prot_lib_ssl_export_keys, sec); #endif #if !defined(MBEDTLS_SSL_CONF_MIN_MINOR_VER) || !defined(MBEDTLS_SSL_CONF_MIN_MAJOR_VER) mbedtls_ssl_conf_min_version(&sec->conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3); #endif /* !defined(MBEDTLS_SSL_CONF_MIN_MINOR_VER) || !defined(MBEDTLS_SSL_CONF_MIN_MAJOR_VER) */ #if !defined(MBEDTLS_SSL_CONF_MAX_MINOR_VER) || !defined(MBEDTLS_SSL_CONF_MAX_MAJOR_VER) mbedtls_ssl_conf_max_version(&sec->conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MAJOR_VERSION_3); #endif /* !defined(MBEDTLS_SSL_CONF_MAX_MINOR_VER) || !defined(MBEDTLS_SSL_CONF_MAX_MAJOR_VER) */ // Set certificate verify callback #if (MBEDTLS_VERSION_MAJOR < 3) mbedtls_ssl_set_verify(&sec->ssl, tls_sec_prot_lib_x509_crt_verify, sec); #endif /* Currently assuming we are running fast enough HW that ECC calculations are not blocking any normal operation. * * If there is a problem with ECC calculations and those are taking too long in border router * MBEDTLS_ECP_RESTARTABLE feature needs to be enabled and public API is needed to allow it in border router * enabling should be done here. */ return 0; } #ifdef TLS_SEC_PROT_LIB_TLS_DEBUG static void tls_sec_prot_lib_debug(void *ctx, int level, const char *file, int line, const char *string) { (void) ctx; tr_debug("%i %s %i %s", level, file, line, string); } #endif int8_t tls_sec_prot_lib_process(tls_security_t *sec) { int32_t ret = -1; while (ret != MBEDTLS_ERR_SSL_WANT_READ) { ret = mbedtls_ssl_handshake_step(&sec->ssl); #if defined(MBEDTLS_ECP_RESTARTABLE) && defined(MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) if (ret == MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS /* || ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS */) { return TLS_SEC_PROT_LIB_CALCULATING; } #endif if (ret && (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE)) { tr_error("TLS error: %" PRId32, ret); return TLS_SEC_PROT_LIB_ERROR; } #if (MBEDTLS_VERSION_MAJOR >= 3) if (sec->ssl.private_state == MBEDTLS_SSL_HANDSHAKE_OVER) { #else if (sec->ssl.state == MBEDTLS_SSL_HANDSHAKE_OVER) { #endif return TLS_SEC_PROT_LIB_HANDSHAKE_OVER; } } return TLS_SEC_PROT_LIB_CONTINUE; } static void tls_sec_prot_lib_ssl_set_timer(void *ctx, uint32_t int_ms, uint32_t fin_ms) { tls_security_t *sec = (tls_security_t *)ctx; sec->set_timer(sec->handle, int_ms, fin_ms); } static int tls_sec_prot_lib_ssl_get_timer(void *ctx) { tls_security_t *sec = (tls_security_t *)ctx; return sec->get_timer(sec->handle); } static int tls_sec_prot_lib_ssl_send(void *ctx, const unsigned char *buf, size_t len) { tls_security_t *sec = (tls_security_t *)ctx; return sec->send(sec->handle, buf, len); } static int tls_sec_prot_lib_ssl_recv(void *ctx, unsigned char *buf, size_t len) { tls_security_t *sec = (tls_security_t *)ctx; int16_t ret = sec->receive(sec->handle, buf, len); if (ret == TLS_SEC_PROT_LIB_NO_DATA) { return MBEDTLS_ERR_SSL_WANT_READ; } return ret; } #if (MBEDTLS_VERSION_MAJOR >= 3) static void tls_sec_prot_lib_ssl_export_keys(void *p_expkey, mbedtls_ssl_key_export_type type, const unsigned char *secret, size_t secret_len, const unsigned char client_random[32], const unsigned char server_random[32], mbedtls_tls_prf_types tls_prf_type) #else static int tls_sec_prot_lib_ssl_export_keys(void *p_expkey, const unsigned char *secret, const unsigned char *kb, size_t maclen, size_t keylen, size_t ivlen, const unsigned char client_random[32], const unsigned char server_random[32], mbedtls_tls_prf_types tls_prf_type) #endif { #if (MBEDTLS_VERSION_MAJOR >= 3) if (type != MBEDTLS_SSL_KEY_EXPORT_TLS12_MASTER_SECRET || secret_len < 48) { return; } #else (void) kb; (void) maclen; (void) keylen; (void) ivlen; #endif tls_security_t *sec = (tls_security_t *)p_expkey; uint8_t eap_tls_key_material[128]; uint8_t random[64]; memcpy(random, client_random, 32); memcpy(&random[32], server_random, 32); int ret = mbedtls_ssl_tls_prf(tls_prf_type, secret, 48, "client EAP encryption", random, 64, eap_tls_key_material, 128); if (ret != 0) { tr_error("key material PRF error"); #if (MBEDTLS_VERSION_MAJOR < 3) return 0; #endif } sec->export_keys(sec->handle, secret, eap_tls_key_material); #if (MBEDTLS_VERSION_MAJOR < 3) return 0; #endif } #if (MBEDTLS_VERSION_MAJOR < 3) static int tls_sec_prot_lib_x509_crt_verify(void *ctx, mbedtls_x509_crt *crt, int certificate_depth, uint32_t *flags) { tls_security_t *sec = (tls_security_t *) ctx; /* MD/PK forced by configuration flags and dynamic settings but traced also here to prevent invalid configurations/certificates */ if (crt->sig_md != MBEDTLS_MD_SHA256) { tr_error("Invalid signature md algorithm"); } if (crt->sig_pk != MBEDTLS_PK_ECDSA) { tr_error("Invalid signature pk algorithm"); } if (*flags & MBEDTLS_X509_BADCERT_FUTURE) { tr_info("Certificate time future"); *flags &= ~MBEDTLS_X509_BADCERT_FUTURE; } // Verify client/server certificate of the chain if (certificate_depth == 0) { return sec->crt_verify(sec, crt, flags); } // No further checks for intermediate and root certificates at the moment return 0; } static int8_t tls_sec_prot_lib_subject_alternative_name_validate(mbedtls_x509_crt *crt) { mbedtls_asn1_sequence *seq = &crt->subject_alt_names; int8_t result = -1; while (seq) { mbedtls_x509_subject_alternative_name san; int ret_value = mbedtls_x509_parse_subject_alt_name((mbedtls_x509_buf *)&seq->buf, &san); if (ret_value == 0 && san.type == MBEDTLS_X509_SAN_OTHER_NAME) { // id-on-hardwareModuleName must be present (1.3.6.1.5.5.7.8.4) if (MBEDTLS_OID_CMP(MBEDTLS_OID_ON_HW_MODULE_NAME, &san.san.other_name.value.hardware_module_name.oid)) { // Traces hardwareModuleName (1.3.6.1.4.1.<enteprise number>.<model,version,etc.>) char buffer[30]; ret_value = mbedtls_oid_get_numeric_string(buffer, sizeof(buffer), &san.san.other_name.value.hardware_module_name.oid); if (ret_value != MBEDTLS_ERR_OID_BUF_TOO_SMALL) { tr_info("id-on-hardwareModuleName %s", buffer); } // Traces serial number as hex string mbedtls_x509_buf *val = &san.san.other_name.value.hardware_module_name.val; if (val->p) { tr_info("id-on-hardwareModuleName hwSerialNum %s", trace_array(val->p, val->len)); } result = 0; } } else { tr_debug("Ignored subject alt name: %i", san.type); } seq = seq->next; } return result; } static int8_t tls_sec_prot_lib_extended_key_usage_validate(mbedtls_x509_crt *crt) { #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) // Extended key usage must be present if (mbedtls_x509_crt_check_extended_key_usage(crt, MBEDTLS_OID_WISUN_FAN, sizeof(MBEDTLS_OID_WISUN_FAN) - 1) != 0) { tr_error("invalid extended key usage"); return -1; // FAIL } #endif return 0; } #ifdef HAVE_PAE_AUTH static int tls_sec_prot_lib_x509_crt_idevid_ldevid_verify(tls_security_t *sec, mbedtls_x509_crt *crt, uint32_t *flags) { // For both IDevID and LDevId both subject alternative name or extended key usage must be valid if (tls_sec_prot_lib_subject_alternative_name_validate(crt) < 0 || tls_sec_prot_lib_extended_key_usage_validate(crt) < 0) { tr_info("no wisun fields on cert"); if (sec->ext_cert_valid) { *flags |= MBEDTLS_X509_BADCERT_OTHER; return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED; } } return 0; } #endif #ifdef HAVE_PAE_SUPP static int tls_sec_prot_lib_x509_crt_server_verify(tls_security_t *sec, mbedtls_x509_crt *crt, uint32_t *flags) { int8_t sane_res = tls_sec_prot_lib_subject_alternative_name_validate(crt); int8_t ext_key_res = tls_sec_prot_lib_extended_key_usage_validate(crt); // If either subject alternative name or extended key usage is present if (sane_res >= 0 || ext_key_res >= 0) { // Then both subject alternative name and extended key usage must be valid if (sane_res < 0 || ext_key_res < 0) { tr_info("no wisun fields on cert"); if (sec->ext_cert_valid) { *flags |= MBEDTLS_X509_BADCERT_OTHER; return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED; } } } return 0; } #endif #endif static int tls_sec_lib_entropy_poll(void *ctx, unsigned char *output, size_t len, size_t *olen) { (void)ctx; char *c = (char *)ns_dyn_mem_temporary_alloc(len); if (!c) { tr_error("entropy alloca fail"); return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED; } memset(c, 0, len); for (uint16_t i = 0; i < len; i++) { *(c + i) = (char)randLIB_get_8bit(); } memmove(output, c, len); *olen = len; ns_dyn_mem_free(c); return (0); } #ifdef TLS_SEC_PROT_LIB_USE_MBEDTLS_PLATFORM_MEMORY static void *tls_sec_prot_lib_mem_calloc(size_t count, size_t size) { void *mem_ptr = ns_dyn_mem_temporary_alloc(count * size); if (mem_ptr) { // Calloc should initialize with zero memset(mem_ptr, 0, count * size); } return mem_ptr; } static void tls_sec_prot_lib_mem_free(void *ptr) { ns_dyn_mem_free(ptr); } #endif #else /* WS_MBEDTLS_SECURITY_ENABLED */ int8_t tls_sec_prot_lib_connect(tls_security_t *sec, bool is_server, const sec_prot_certs_t *certs) { (void)sec; (void)is_server; (void)certs; return 0; } void tls_sec_prot_lib_free(tls_security_t *sec) { (void)sec; } int8_t tls_sec_prot_lib_init(tls_security_t *sec) { (void)sec; return 0; } int8_t tls_sec_prot_lib_process(tls_security_t *sec) { (void)sec; return 0; } void tls_sec_prot_lib_set_cb_register(tls_security_t *sec, void *handle, tls_sec_prot_lib_send *send, tls_sec_prot_lib_receive *receive, tls_sec_prot_lib_export_keys *export_keys, tls_sec_prot_lib_set_timer *set_timer, tls_sec_prot_lib_get_timer *get_timer) { (void)sec; (void)handle; (void)send; (void)receive; (void)export_keys; (void)set_timer; (void)get_timer; } uint16_t tls_sec_prot_lib_size(void) { return 0; } #endif /* WS_MBEDTLS_SECURITY_ENABLED */ #endif /* HAVE_WS */
CorbinFoucart/FEMexperiment
codes/src/fem_base/master/master_1D.py
<filename>codes/src/fem_base/master/master_1D.py #!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from src.fem_base.master.nodal_basis_1D import NodalBasis1D from src.fem_base.master.nodal_basis_1D import LegendreGaussLobatto, GaussLegendre class Master1D(object): """ minimalist 1D master object, for use in purely 1D problems detailed explanation in tutorial/1D_basis_and_master_element.ipynb """ def __init__(self, p, nquad_pts=None, *args, **kwargs): self.p, self.nb = p, p+1 self.basis = NodalBasis1D(p=p, **kwargs) self.nodal_pts = self.basis.nodal_pts self.nq = 2*self.p + 2 if nquad_pts is None else nquad_pts self.quad_pts, self.wghts = GaussLegendre(self.nq) # shape functions at nodal and quadrature points self.shap_quad, self.dshap_quad = self.mk_shap_and_dshap_at_pts(self.quad_pts) _, self.dshap_nodal = self.mk_shap_and_dshap_at_pts(self.nodal_pts) # mass, stiffness matrices self.M, self.S, self.K = self.mk_M(), self.mk_S(), self.mk_K() self.Minv = np.linalg.inv(self.M) # lifting permuatation matrix L (0s, 1s) self.L = self.mk_L() def mk_shap_and_dshap_at_pts(self, pts): shap = self.basis.shape_functions_at_pts(pts) dshap = self.basis.shape_function_derivatives_at_pts(pts) return shap, dshap def mk_M(self): """ the mass matrix, M_ij = (phi_i, phi_j) """ shapw = np.dot(np.diag(self.wghts), self.shap_quad) M = np.dot(self.shap_quad.T, shapw) return M def mk_S(self): """ the stiffness matrix, S_ij = (phi_i, \frac{d\phi_j}{dx}) """ dshapw = np.dot(np.diag(self.wghts), self.dshap_quad) S = np.dot(self.shap_quad.T, dshapw) return S def mk_K(self): """ the stiffness matrix, K_ij = (\frac{d\phi_i}{dx}, \frac{d\phi_j}{dx}) """ dshapw = np.dot(np.diag(self.wghts), self.dshap_quad) K = np.dot(self.dshap_quad.T, dshapw) return K def mk_L(self): L = np.zeros((self.nb, 2)) L[0, 0] = 1 L[-1, 1] = 1 return L def map_to_physical_edge(self): """ creates a transformation matrix which can map a list of 2D edge vertices to their physical space locations. @retval T transformation matrix """ vertices = self.basis.vol_verts T = np.ones((len(self.nodal_pts), 2)) for node in range(self.nb): T[node, 0] = (1. + np.sign(vertices[0]) * self.nodal_pts[node]) / 2. T[node, 1] = (1. + np.sign(vertices[1]) * self.nodal_pts[node]) / 2. return T @property def nodal_shap_der(self): """ return the shape derivatives for apps expecting 2, 3D""" return [self.dshap_nodal]
sormo/simpleSDL
source/legacy/Text2D.cpp
<filename>source/legacy/Text2D.cpp #include "Text2D.h" #include <vector> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "utils/Shader.h" #include "utils/Texture.h" #include "Common.h" #include <sstream> GLuint g_texture; GLuint g_bufferVertex; GLuint g_bufferUV; GLuint g_program; GLuint g_locationVertex; GLuint g_locationUV; GLuint g_locationTexture; std::vector<float> g_widths; static const int32_t FIRST_CHAR_ASCII = 32; static const int32_t CHARS_IN_ROW = 16; static const int32_t CHAR_SIZE_PIXELS = 32; // expect only consecutive character widths as numbers void Text2DReadWidthFactors(const char * path) { std::vector<uint8_t> data = Common::ReadFile(path); data.push_back('\0'); std::stringstream stream((char*)data.data()); while (stream) { uint32_t width; stream >> width; g_widths.push_back((float)width / (float)CHAR_SIZE_PIXELS); } } bool Text2DInitFont() { // Initialize texture auto texture = Texture::Load("text2d/text2d-32bpp.bmp"); if (!texture) return false; g_texture = *texture; // Initialize VBO glGenBuffers(1, &g_bufferVertex); glGenBuffers(1, &g_bufferUV); // Initialize Shader auto program = CreateAndLinkProgramFile("shaders/vertText.glsl", nullptr, "shaders/fragText.glsl"); if (!program) return false; g_program = *program; // Get a handle for our buffers g_locationVertex = glGetAttribLocation(g_program, "positionScreenSpace"); g_locationUV = glGetAttribLocation(g_program, "vertexUV"); // Initialize uniforms' IDs g_locationTexture = glGetUniformLocation(g_program, "textureValue"); Text2DReadWidthFactors("text2d/text2d-widths.txt"); return true; } void Text2DPrint(const char * text, int32_t x, int32_t y, int32_t size) { static const float UV_CELL_SIZE = 1.0f / (float)CHARS_IN_ROW; // Fill buffers std::vector<glm::vec2> vertices; std::vector<glm::vec2> UVs; float widthCursor = 0.0f; for (size_t i = 0; i < strlen(text); i++) { int32_t characterIndex = (int32_t)text[i] - FIRST_CHAR_ASCII; float nextWidthCursor = widthCursor + g_widths[characterIndex] * (float)size; glm::vec2 upLeft = glm::vec2(x + widthCursor , y + size); glm::vec2 upRight = glm::vec2(x + nextWidthCursor, y + size); glm::vec2 downRight = glm::vec2(x + nextWidthCursor, y ); glm::vec2 downLeft = glm::vec2(x + widthCursor , y ); widthCursor = nextWidthCursor; vertices.push_back(upLeft); vertices.push_back(downLeft); vertices.push_back(upRight); vertices.push_back(downRight); vertices.push_back(upRight); vertices.push_back(downLeft); float uvx = (characterIndex % CHARS_IN_ROW) / (float)CHARS_IN_ROW; float uvy = (characterIndex / CHARS_IN_ROW) / (float)CHARS_IN_ROW; // uvy is from upper left but uv coordinates are from bottom right uvy = 1.0f - uvy - UV_CELL_SIZE; float uvWidthSize = UV_CELL_SIZE *g_widths[characterIndex]; glm::vec2 uvUpLeft = glm::vec2(uvx , uvy + UV_CELL_SIZE); glm::vec2 uvUpRight = glm::vec2(uvx + uvWidthSize, uvy + UV_CELL_SIZE); glm::vec2 uvDownRight = glm::vec2(uvx + uvWidthSize, uvy); glm::vec2 uvDownLeft = glm::vec2(uvx , uvy); UVs.push_back(uvUpLeft); UVs.push_back(uvDownLeft); UVs.push_back(uvUpRight); UVs.push_back(uvDownRight); UVs.push_back(uvUpRight); UVs.push_back(uvDownLeft); } glBindBuffer(GL_ARRAY_BUFFER, g_bufferVertex); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec2), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, g_bufferUV); glBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(glm::vec2), &UVs[0], GL_STATIC_DRAW); // Bind shader glUseProgram(g_program); // Bind texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, g_texture); // Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(g_locationTexture, 0); // 1rst attribute buffer : vertices glEnableVertexAttribArray(g_locationVertex); glBindBuffer(GL_ARRAY_BUFFER, g_bufferVertex); glVertexAttribPointer(g_locationVertex, 2, GL_FLOAT, GL_FALSE, 0, (void*)0 ); // 2nd attribute buffer : UVs glEnableVertexAttribArray(g_locationUV); glBindBuffer(GL_ARRAY_BUFFER, g_bufferUV); glVertexAttribPointer(g_locationUV, 2, GL_FLOAT, GL_FALSE, 0, (void*)0 ); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Draw call glDrawArrays(GL_TRIANGLES, 0, vertices.size() ); glDisable(GL_BLEND); glDisableVertexAttribArray(g_locationVertex); glDisableVertexAttribArray(g_locationUV); } void Text2DCleanup(){ // Delete buffers glDeleteBuffers(1, &g_bufferVertex); glDeleteBuffers(1, &g_bufferUV); // Delete texture glDeleteTextures(1, &g_texture); // Delete shader glDeleteProgram(g_program); }
jspare-projects/jsdb
jsdb-server/lib/workers/removeDomain.js
<gh_stars>1-10 const /*--- Declaring imports ---*/ _ = require('underscore'), _error = require('./../application/error'), _io = require('./../storage/io'), _path = require('./../storage/path'); module.exports = { roles : [ 'grantAll', 'grantMngDomain', 'grantRemoveDomain', 'grantRemoveDomain::instance' ], validateRequest : function(data){ return !_.isEmpty(data); }, execute : function(transaction, callback) { var data = transaction.getData(); if(!_io.exist(_path.buildInstanceDomainsDir(data.instance))){ callback(new _error.BusinessError('INSTNFD')); return; } if(!_io.exist(_path.buildDomainDataDir(data.instance, data.domain))){ callback(new _error.BusinessError('DMNNFD')); return; } _io.removeDir(_path.buildDomainDir(data.instance, data.domain)); callback(); }, rollback : function(transaction, error) { } }
SleepyRae/IntelligenceCoding
hoj-springboot/DataBackup/src/main/java/top/hcode/hoj/service/group/training/GroupTrainingProblemService.java
<reponame>SleepyRae/IntelligenceCoding package top.hcode.hoj.service.group.training; import top.hcode.hoj.common.result.CommonResult; import top.hcode.hoj.pojo.dto.TrainingDto; import top.hcode.hoj.pojo.dto.TrainingProblemDto; import top.hcode.hoj.pojo.entity.training.Training; import top.hcode.hoj.pojo.entity.training.TrainingProblem; import top.hcode.hoj.pojo.vo.TrainingVo; import com.baomidou.mybatisplus.core.metadata.IPage; import java.util.HashMap; /** * @Author: LengYun * @Date: 2022/3/11 13:36 * @Description: */ public interface GroupTrainingProblemService { public CommonResult<HashMap<String, Object>> getTrainingProblemList(Integer limit, Integer currentPage, String keyword, Boolean queryExisted, Long tid); public CommonResult<Void> updateTrainingProblem(TrainingProblem trainingProblem); public CommonResult<Void> deleteTrainingProblem(Long pid, Long tid); public CommonResult<Void> addProblemFromPublic(TrainingProblemDto trainingProblemDto); public CommonResult<Void> addProblemFromGroup(String problemId, Long tid); }
cxcruz/math-facts-play
app/controllers/Application.scala
package controllers import play.api._ import play.api.mvc._ import play.api.libs.json.Json import play.api.libs.ws._ import play.api.Play.current import scala.concurrent.ExecutionContext.Implicits.global import scalikejdbc._ import models.Fact object Application extends Controller { def index = Action { Ok(views.html.index("Your new application is ready.")) } def facts(id: Long) = Action { implicit val session = AutoSession sql""" select 1; """.execute.apply() val facts: List[Fact] = sql"select * from facts".map(rs => Fact(rs)).list.apply() println(facts) val user = models.User(id) Ok(views.html.facts(user)) } def details(userid: Long, levelid: Long) = Action { val user = models.User(userid) val level = user.getLevels().filter(level => level.id == levelid).head //val level = new models.Level(levelid, "plant", "title") Ok(views.html.details(user, level)) } def difficult(userid: Long, levelid: Long) = Action { implicit request => val searchType = request.getQueryString("searchType"); // null if not in URL val tmcUrl = s"http://www.nba.com" WS.url(tmcUrl).withQueryString("k1" -> "v1") Ok(views.html.index("Your new application is ready.")) } /* def test() = Action { implicit request => Async { val searchType = request.getQueryString("searchType"); // null if not in URL val tmcUrl = s"http://www.nba.com" val mu = WS.url(tmcUrl).withQueryString("k1" -> "v1", "k2" -> "v2").get().map { response => Ok(response.json) } mu } // mu.value.get.toOption.getOrElse(Ok("failure")) } */ def sayHello = Action(parse.json) { implicit request => (request.body \ "name").asOpt[String].map { name => Ok(Json.toJson( Map("status" -> "OK", "message" -> ("Hello " + name)))) }.getOrElse { BadRequest(Json.toJson( Map("status" -> "KO", "message" -> "Missing parameter [name]"))) } } }
hdm/mac-tracker
data/js/b4/c6/2e/00/00/00.24.js
macDetailCallback("b4c62e000000/24",[{"a":"2222 Wellington Court Lisle IL US 60532","o":"Molex CMS","d":"2018-08-12","t":"add","s":"ieee","c":"US"}]);
SpeedJack/lsmsd1
Ristogo/src/ristogo/ui/menus/forms/ChoiceFormField.java
package ristogo.ui.menus.forms; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.function.Predicate; public class ChoiceFormField<T extends Enum<T>> extends FormField { protected LinkedHashMap<Integer, String> values = new LinkedHashMap<>(); protected int defaultSelection; protected Class<T> enumClass; protected Predicate<T> validator; public ChoiceFormField(String name, Class<T> e) { super(name); enumClass = e; int i = 1; String[] values = getEnumNames(e); for (String value: values) { this.values.put(i, value); i++; } } public ChoiceFormField(String name, Class<T> e, Predicate<T> validator) { this(name, e); this.validator = validator; } public ChoiceFormField(String name, T defaultValue, Class<T> e) { super(name, defaultValue.toString()); enumClass = e; int i = 1; String[] values = getEnumNames(e); for (String value: values) { this.values.put(i, value); if (value.equals(defaultValue.name())) defaultSelection = i; i++; } } public ChoiceFormField(String name, T defaultValue, Class<T> e, Predicate<T> validator) { this(name, defaultValue, e); this.validator = validator; } @Override protected boolean isValid() { if (!values.containsValue(value)) return false; if (validator == null) return true; return validator.test(Enum.valueOf(enumClass, value)); } @Override public void setValue(String value) { if (value == null || value.isBlank()) value = Integer.toString(defaultSelection); this.value = values.get(Integer.parseInt(value)); } @Override public String toString() { StringBuilder sb = new StringBuilder(name + ":\n"); values.forEach((key, value) -> { sb.append("\t" + key + ") " + Enum.valueOf(enumClass, value).toString() + "\n"); }); sb.append("Enter selection" + (defaultSelection > 0 ? " [" + defaultSelection + "]" : "")); return sb.toString(); } protected static String[] getEnumNames(Class<? extends Enum<?>> e) { return Arrays.stream(e.getEnumConstants()).map(Enum::name).toArray(String[]::new); } }
myCustomDemo/kaa_demo
server/appenders/file-appender/src/test/java/org/kaaproject/kaa/server/appenders/file/appender/FileSystemLogAppenderTest.java
/* * Copyright 2014-2016 CyberVision, 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 org.kaaproject.kaa.server.appenders.file.appender; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import org.junit.Assert; import org.junit.Test; import org.kaaproject.kaa.common.avro.AvroByteArrayConverter; import org.kaaproject.kaa.common.avro.AvroJsonConverter; import org.kaaproject.kaa.common.avro.GenericAvroConverter; import org.kaaproject.kaa.common.dto.EndpointProfileDataDto; import org.kaaproject.kaa.common.dto.logs.LogAppenderDto; import org.kaaproject.kaa.common.dto.logs.LogHeaderStructureDto; import org.kaaproject.kaa.common.dto.logs.LogSchemaDto; import org.kaaproject.kaa.common.endpoint.gen.BasicEndpointProfile; import org.kaaproject.kaa.server.appenders.file.config.gen.FileConfig; import org.kaaproject.kaa.server.common.core.algorithms.generation.DefaultRecordGenerationAlgorithm; import org.kaaproject.kaa.server.common.core.algorithms.generation.DefaultRecordGenerationAlgorithmImpl; import org.kaaproject.kaa.server.common.core.configuration.RawData; import org.kaaproject.kaa.server.common.core.configuration.RawDataFactory; import org.kaaproject.kaa.server.common.core.schema.RawSchema; import org.kaaproject.kaa.server.common.log.shared.appender.LogDeliveryCallback; import org.kaaproject.kaa.server.common.log.shared.appender.LogEvent; import org.kaaproject.kaa.server.common.log.shared.appender.LogSchema; import org.kaaproject.kaa.server.common.log.shared.appender.data.BaseLogEventPack; import org.mockito.Mockito; import org.springframework.test.util.ReflectionTestUtils; import java.io.File; import java.util.Arrays; import java.util.Collections; public class FileSystemLogAppenderTest { private static final String APPENDER_ID = "appender_id"; private static final String APPLICATION_ID = "application_id"; private static final String TENANT_ID = "tenant_id"; private static final String APPENDER_NAME = "test"; private FileSystemLogEventService fileSystemLogEventService; @Test public void testAppend() throws Exception { FileSystemLogAppender appender = new FileSystemLogAppender(); appender.setName("test"); FileSystemLogEventService service = Mockito.mock(FileSystemLogEventService.class); ReflectionTestUtils.setField(appender, "fileSystemLogEventService", service); appender.setName(APPENDER_NAME); appender.setAppenderId(APPENDER_ID); LogAppenderDto logAppenderDto = prepareConfig(); logAppenderDto.setApplicationId(APPLICATION_ID); logAppenderDto.setName("test"); logAppenderDto.setTenantId(TENANT_ID); try { appender.init(logAppenderDto); ReflectionTestUtils.setField(appender, "header", Arrays.asList(LogHeaderStructureDto.values())); GenericAvroConverter<BasicEndpointProfile> converter = new GenericAvroConverter<BasicEndpointProfile>( BasicEndpointProfile.SCHEMA$); BasicEndpointProfile theLog = new BasicEndpointProfile("test"); LogSchemaDto schemaDto = new LogSchemaDto(); LogSchema schema = new LogSchema(schemaDto, BasicEndpointProfile.SCHEMA$.toString()); LogEvent logEvent = new LogEvent(); logEvent.setLogData(converter.encode(theLog)); EndpointProfileDataDto profileDto = new EndpointProfileDataDto("1", "endpointKey", 1, "", 0, null); BaseLogEventPack logEventPack = new BaseLogEventPack(profileDto, 1234567l, schema.getVersion(), Collections.singletonList(logEvent)); logEventPack.setLogSchema(schema); TestLogDeliveryCallback callback = new TestLogDeliveryCallback(); appender.doAppend(logEventPack, callback); Assert.assertTrue(callback.success); } finally { appender.close(); } } @Test public void appendToClosedAppenderTest() { FileSystemLogAppender appender = new FileSystemLogAppender(); LogDeliveryCallback listener = mock(LogDeliveryCallback.class); ReflectionTestUtils.setField(appender, "closed", true); appender.doAppend(null, null, listener); verify(listener).onInternalError(); } @Test public void testAppendWithInternalError() throws Exception { FileSystemLogAppender appender = new FileSystemLogAppender(); appender.setName("test"); FileSystemLogEventService service = Mockito.mock(FileSystemLogEventService.class); ReflectionTestUtils.setField(appender, "fileSystemLogEventService", service); appender.setName(APPENDER_NAME); appender.setAppenderId(APPENDER_ID); LogAppenderDto logAppenderDto = prepareConfig(); logAppenderDto.setApplicationId(APPLICATION_ID); logAppenderDto.setName("test"); logAppenderDto.setTenantId(TENANT_ID); try { appender.init(logAppenderDto); ReflectionTestUtils.setField(appender, "header", Arrays.asList(LogHeaderStructureDto.values())); LogSchemaDto schemaDto = new LogSchemaDto(); LogSchema schema = new LogSchema(schemaDto, BasicEndpointProfile.SCHEMA$.toString()); LogEvent logEvent = new LogEvent(); logEvent.setLogData(new byte[0]); EndpointProfileDataDto profileDto = new EndpointProfileDataDto("1", "endpointKey", 1, "", 0, null); BaseLogEventPack logEventPack = new BaseLogEventPack(profileDto, 1234567l, schema.getVersion(), Collections.singletonList(logEvent)); logEventPack.setLogSchema(schema); TestLogDeliveryCallback callback = new TestLogDeliveryCallback(); appender.doAppend(logEventPack, callback); Assert.assertTrue(callback.internallError); } finally { appender.close(); } } @Test public void initTest() throws Exception { FileSystemLogAppender appender = new FileSystemLogAppender(); fileSystemLogEventService = mock(FileSystemLogEventService.class); FileSystemLogger logger = Mockito.mock(FileSystemLogger.class); ReflectionTestUtils.setField(appender, "fileSystemLogEventService", fileSystemLogEventService); ReflectionTestUtils.setField(appender, "logger", logger); appender.setName(APPENDER_NAME); appender.setAppenderId(APPENDER_ID); LogAppenderDto logAppenderDto = prepareConfig(); logAppenderDto.setApplicationId(APPLICATION_ID); logAppenderDto.setName("test"); logAppenderDto.setTenantId(TENANT_ID); try { appender.init(logAppenderDto); Assert.assertEquals(APPENDER_NAME, appender.getName()); Assert.assertEquals(APPENDER_ID, appender.getAppenderId()); } finally { appender.close(); } } private LogAppenderDto prepareConfig() throws Exception { LogAppenderDto logAppenderDto = new LogAppenderDto(); logAppenderDto.setApplicationId(APPLICATION_ID); logAppenderDto.setName("test"); logAppenderDto.setTenantId(TENANT_ID); RawSchema rawSchema = new RawSchema(FileConfig.getClassSchema().toString()); DefaultRecordGenerationAlgorithm<RawData> algotithm = new DefaultRecordGenerationAlgorithmImpl<>(rawSchema, new RawDataFactory()); RawData rawData = algotithm.getRootData(); AvroJsonConverter<FileConfig> converter = new AvroJsonConverter<>(FileConfig.getClassSchema(), FileConfig.class); FileConfig fileConfig = converter.decodeJson(rawData.getRawData()); fileConfig.setLogsRootPath(System.getProperty("java.io.tmpdir") + File.separator + "tmp_logs_" + System.currentTimeMillis()); AvroByteArrayConverter<FileConfig> byteConverter = new AvroByteArrayConverter<>(FileConfig.class); byte[] rawConfiguration = byteConverter.toByteArray(fileConfig); logAppenderDto.setRawConfiguration(rawConfiguration); return logAppenderDto; } private static class TestLogDeliveryCallback implements LogDeliveryCallback { private volatile boolean success; private volatile boolean internallError; @Override public void onSuccess() { success = true; } @Override public void onInternalError() { internallError = true; } @Override public void onConnectionError() { } @Override public void onRemoteError() { } } }
robsonsopran/incubator-nuttx
drivers/bch/bchlib_read.c
<reponame>robsonsopran/incubator-nuttx /**************************************************************************** * drivers/bch/bchlib_read.c * * 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <stdint.h> #include <string.h> #include <errno.h> #include <assert.h> #include <debug.h> #include "bch.h" /**************************************************************************** * Private Types ****************************************************************************/ /**************************************************************************** * Private Function Prototypes ****************************************************************************/ /**************************************************************************** * Private Data ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: bchlib_read * * Description: * Read from the block device set-up by bchlib_setup as if it were a * character device. * ****************************************************************************/ ssize_t bchlib_read(FAR void *handle, FAR char *buffer, size_t offset, size_t len) { FAR struct bchlib_s *bch = (FAR struct bchlib_s *)handle; size_t nsectors; size_t sector; uint16_t sectoffset; size_t nbytes; size_t bytesread; int ret; /* Get rid of this special case right away */ if (len < 1) { return 0; } /* Convert the file position into a sector number an offset. */ sector = offset / bch->sectsize; sectoffset = offset - sector * bch->sectsize; if (sector >= bch->nsectors) { /* Return end-of-file */ return 0; } /* Read the initial partial sector */ bytesread = 0; if (sectoffset > 0) { /* Read the sector into the sector buffer */ bchlib_readsector(bch, sector); /* Copy the tail end of the sector to the user buffer */ if (sectoffset + len > bch->sectsize) { nbytes = bch->sectsize - sectoffset; } else { nbytes = len; } memcpy(buffer, &bch->buffer[sectoffset], nbytes); /* Adjust pointers and counts */ sector++; if (sector >= bch->nsectors) { return nbytes; } bytesread = nbytes; buffer += nbytes; len -= nbytes; } /* Then read all of the full sectors following the partial sector directly * into the user buffer. */ if (len >= bch->sectsize) { nsectors = len / bch->sectsize; if (sector + nsectors > bch->nsectors) { nsectors = bch->nsectors - sector; } ret = bch->inode->u.i_bops->read(bch->inode, (FAR uint8_t *)buffer, sector, nsectors); if (ret < 0) { ferr("ERROR: Read failed: %d\n", ret); return ret; } /* Adjust pointers and counts */ sector += nsectors; nbytes = nsectors * bch->sectsize; bytesread += nbytes; if (sector >= bch->nsectors) { return bytesread; } buffer += nbytes; len -= nbytes; } /* Then read any partial final sector */ if (len > 0) { /* Read the sector into the sector buffer */ bchlib_readsector(bch, sector); /* Copy the head end of the sector to the user buffer */ memcpy(buffer, bch->buffer, len); /* Adjust counts */ bytesread += len; } return bytesread; }
dos1/card10-firmware
lib/sdk/Libraries/BTLE/documentation/html/Cordio_Stack_Cordio_Profiles/search/typedefs_8.js
<reponame>dos1/card10-firmware<filename>lib/sdk/Libraries/BTLE/documentation/html/Cordio_Stack_Cordio_Profiles/search/typedefs_8.js var searchData= [ ['terminalhandler_5ft',['terminalHandler_t',['../group___w_s_f___u_t_i_l___a_p_i.html#ga87bf3c9e9ad209a2f2b93c5e96a9c925',1,'terminal.h']]], ['terminaluarttx_5ft',['terminalUartTx_t',['../group___w_s_f___u_t_i_l___a_p_i.html#ga09677791f060831e5a56f9c76137ea1d',1,'terminal.h']]] ];
wchen1990/Mekanism
src/main/java/mekanism/common/item/block/machine/ItemBlockLogisticalSorter.java
package mekanism.common.item.block.machine; import java.util.List; import javax.annotation.Nonnull; import mekanism.common.block.basic.BlockLogisticalSorter; import mekanism.common.item.block.ItemBlockTooltip; import mekanism.common.item.interfaces.IItemSustainedInventory; import mekanism.common.lib.security.ISecurityItem; import mekanism.common.registration.impl.ItemDeferredRegister; import mekanism.common.util.MekanismUtils; import mekanism.common.util.SecurityUtils; import net.minecraft.item.ItemStack; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.World; public class ItemBlockLogisticalSorter extends ItemBlockTooltip<BlockLogisticalSorter> implements IItemSustainedInventory, ISecurityItem { public ItemBlockLogisticalSorter(BlockLogisticalSorter block) { super(block, true, ItemDeferredRegister.getMekBaseProperties().maxStackSize(1)); } @Override public void addDetails(@Nonnull ItemStack stack, World world, @Nonnull List<ITextComponent> tooltip, boolean advanced) { SecurityUtils.addSecurityTooltip(stack, tooltip); MekanismUtils.addUpgradesToTooltip(stack, tooltip); } }
nasa/SCRD
Code/SCRD_BRE/src/java/ejb/gov/opm/scrd/services/impl/BatchPrintoutArchiveServiceImpl.java
<reponame>nasa/SCRD /* Copyright 2014 OPM.gov 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 gov.opm.scrd.services.impl; import gov.opm.scrd.LoggingHelper; import gov.opm.scrd.entities.application.Printout; import gov.opm.scrd.entities.common.Helper; import gov.opm.scrd.services.BatchPrintoutArchiveService; import gov.opm.scrd.services.OPMException; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.ejb.Local; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.persistence.PersistenceException; import org.jboss.logging.Logger; /** * <p> * This class is the implementation of the BatchPrintoutArchiveService. It utilizes JPA EntityManager for necessary * operations. * </p> * * <p> * <em>Changes in OPM - SCRD - Frontend Initial Module Assembly 1.0:</em> * <ul> * <li>Changed to use LoggingHelper instead for logging</li> * </ul> * </p> * * <p> * <strong>Thread Safety: </strong> This class is effectively thread safe after configuration, the configuration is done * in a thread safe manner. * </p> * * @author faeton, sparemax * @version 1.0 */ @Stateless @Local(BatchPrintoutArchiveService.class) @LocalBean @TransactionManagement(TransactionManagementType.CONTAINER) public class BatchPrintoutArchiveServiceImpl extends BaseService implements BatchPrintoutArchiveService { /** * <p> * Represents the class name. * </p> */ private static final String CLASS_NAME = BatchPrintoutArchiveServiceImpl.class.getName(); /** * <p> * Represents the JPQL to query Printout. * </p> */ private static final String JPQL_QUERY_PRINTOUT = "SELECT e.id, e.name, e.printDate FROM Printout e" + " WHERE e.deleted = false"; /** * <p> * Represents the JPQL to query printout data. * </p> */ private static final String JPQL_QUERY_PRINTOUT_DATA = "SELECT e.content FROM Printout e" + " WHERE e.deleted = false AND e.name = :name"; /** * Creates an instance of BatchPrintoutArchiveServiceImpl. */ public BatchPrintoutArchiveServiceImpl() { // Empty } /** * Returns the list of available printouts in the application. * * @return List of available printouts, can not be null * * @throws OPMException * if there is any problem when executing the method. */ @SuppressWarnings("unchecked") @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<Printout> getAvailablePrintouts() throws OPMException { String signature = CLASS_NAME + "#getAvailablePrintouts()"; Logger logger = getLogger(); LoggingHelper.logEntrance(logger, signature, null, null); try { // Printout.content should not be retrieved List<Object[]> data = getEntityManager().createQuery(JPQL_QUERY_PRINTOUT).getResultList(); List<Printout> result = new ArrayList<Printout>(); for (Object[] row : data) { Printout printout = new Printout(); printout.setId((Long) row[0]); printout.setName((String) row[1]); printout.setPrintDate((Date) row[2]); result.add(printout); } LoggingHelper.logExit(logger, signature, new Object[] {result}); return result; } catch (IllegalStateException e) { throw LoggingHelper.logException(logger, signature, new OPMException("The entity manager has been closed.", e)); } catch (PersistenceException e) { throw LoggingHelper.logException(logger, signature, new OPMException( "An error has occurred when accessing persistence.", e)); } } /** * Return the content of the printout by name. * * @param name * the printout name. * * @return Printout contents as byte array, can be null. * * @throws IllegalArgumentException * if name is null/empty. * @throws OPMException * if there is any problem when executing the method. */ @TransactionAttribute(TransactionAttributeType.SUPPORTS) public byte[] getPrintout(String name) throws OPMException { String signature = CLASS_NAME + "#getPrintout(String name)"; Logger logger = getLogger(); LoggingHelper.logEntrance(logger, signature, new String[] {"name"}, new Object[] {name}); Helper.checkNullOrEmpty(logger, signature, name, "name"); try { byte[] content = (byte[]) getEntityManager().createQuery(JPQL_QUERY_PRINTOUT_DATA) .setParameter("name", name) .getSingleResult(); LoggingHelper.logExit(logger, signature, new Object[] {content}); return content; } catch (IllegalStateException e) { throw LoggingHelper.logException(logger, signature, new OPMException("The entity manager has been closed.", e)); } catch (PersistenceException e) { throw LoggingHelper.logException(logger, signature, new OPMException( "An error has occurred when accessing persistence.", e)); } } }
Criss-Wang/tp
src/main/java/seedu/clinic/model/macro/UniqueMacroList.java
<reponame>Criss-Wang/tp package seedu.clinic.model.macro; import static java.util.Objects.requireNonNull; import static seedu.clinic.commons.util.CollectionUtil.requireAllNonNull; import java.util.Iterator; import java.util.List; import java.util.Optional; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import seedu.clinic.model.macro.exceptions.DuplicateMacroException; import seedu.clinic.model.macro.exceptions.MacroNotFoundException; /** * A list of macros that enforces uniqueness between its elements and does not allow nulls. A macro is considered * unique by comparing using {@code Macro#isSameMacro(Macro)}. As such, adding and updating of macros uses * Macro#isSameMacro(Macro) for equality so as to ensure that the macro being added or updated is unique in * terms of identity in the UniqueMacroList. However, the removal of a macro uses Macro#equals(Object) so as to * ensure that the macro with exactly the same fields will be removed. * <p> * Supports a minimal set of list operations. * * @see Macro#isSameMacro(Macro) */ public class UniqueMacroList implements Iterable<Macro> { private final ObservableList<Macro> internalList = FXCollections.observableArrayList(); private final ObservableList<Macro> internalUnmodifiableList = FXCollections.unmodifiableObservableList(internalList); /** * Returns true if the macro list contains an equivalent macro as the given macro argument. */ public boolean contains(Macro toCheck) { requireNonNull(toCheck); return internalList.stream().anyMatch(toCheck::isSameMacro); } /** * Returns the macro corresponding to the alias string in an optional wrapper if it exists, * and an empty optional otherwise. */ public Optional<Macro> getMacro(String aliasString) { requireNonNull(aliasString); Alias alias; try { alias = new Alias(aliasString); } catch (IllegalArgumentException e) { // Invalid Alias return Optional.empty(); } return getMacro(alias); } /** * Returns the macro corresponding to the alias in an optional wrapper if it exists, * and an empty optional otherwise. */ public Optional<Macro> getMacro(Alias alias) { requireNonNull(alias); return internalList.stream().filter((Macro macro) -> macro.getAlias().equals(alias)).findFirst(); } /** * Adds a macro to the list. * The macro must not already exist in the list. */ public void add(Macro toAdd) { requireNonNull(toAdd); if (contains(toAdd)) { throw new DuplicateMacroException(); } internalList.add(toAdd); } /** * Replaces the macro {@code target} in the list with {@code editedMacro}. * {@code target} must exist in the list. * The macro identity of {@code editedMacro} must not be the same as another existing macro in the list. */ public void setMacro(Macro target, Macro editedMacro) { requireAllNonNull(target, editedMacro); int index = internalList.indexOf(target); if (index == -1) { throw new MacroNotFoundException(); } if (!target.isSameMacro(editedMacro) && contains(editedMacro)) { throw new DuplicateMacroException(); } internalList.set(index, editedMacro); } /** * Removes the equivalent macro from the list. * The macro must exist in the list. */ public void remove(Macro toRemove) { requireNonNull(toRemove); if (!internalList.remove(toRemove)) { throw new MacroNotFoundException(); } } public void setMacros(UniqueMacroList replacement) { requireNonNull(replacement); internalList.setAll(replacement.internalList); } /** * Replaces the contents of this list with {@code macros}. * {@code macros} must not contain duplicate macros. */ public void setMacros(List<Macro> macros) { requireAllNonNull(macros); if (!macrosAreUnique(macros)) { throw new DuplicateMacroException(); } internalList.setAll(macros); } /** * Returns the backing list as an unmodifiable {@code ObservableList}. */ public ObservableList<Macro> asUnmodifiableObservableList() { return internalUnmodifiableList; } @Override public Iterator<Macro> iterator() { return internalList.iterator(); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof UniqueMacroList // instanceof handles nulls && internalList.equals(((UniqueMacroList) other).internalList)); } @Override public int hashCode() { return internalList.hashCode(); } /** * Returns true if {@code macros} contains only unique macros. */ private boolean macrosAreUnique(List<Macro> macros) { for (int i = 0; i < macros.size() - 1; i++) { for (int j = i + 1; j < macros.size(); j++) { if (macros.get(i).isSameMacro(macros.get(j))) { return false; } } } return true; } }
cxj16888/FreeECAT
software/FreeECAT-Master/IgH/IgH-API/html/structec__slave.js
<reponame>cxj16888/FreeECAT<filename>software/FreeECAT-Master/IgH/IgH-API/html/structec__slave.js<gh_stars>10-100 var structec__slave = [ [ "master", "structec__slave.html#ae3ca485627d212610814bf4e0130eddd", null ], [ "device_index", "structec__slave.html#adc17b41384e235c98b39f4ac49319d68", null ], [ "ring_position", "structec__slave.html#a337a538c53fb9ac8bcfb951fd445e0a1", null ], [ "station_address", "structec__slave.html#ae4c26b32979bcb21cf391ca3b170d701", null ], [ "effective_alias", "structec__slave.html#a954d95e8464b5dcb7084463d00760291", null ], [ "ports", "structec__slave.html#a0dc49f089a749f49fcce90007063ed85", null ], [ "config", "structec__slave.html#a35616766fc7afbd4fc0b8a5d5a652bf7", null ], [ "requested_state", "structec__slave.html#af81c1abd2ac2b8a5a5bfbbfe7d79ce70", null ], [ "current_state", "structec__slave.html#a6214f41ec1dce05b67b298b89a49e1f8", null ], [ "error_flag", "structec__slave.html#aef33c89d3974546f5aed153b379d0d24", null ], [ "force_config", "structec__slave.html#a0baba2f1593708191871119e3570655f", null ], [ "configured_rx_mailbox_offset", "structec__slave.html#a885011c3377eacc3513c7806db9ea4d4", null ], [ "configured_rx_mailbox_size", "structec__slave.html#a0310afbbf38da2a92cdbe3911a46535c", null ], [ "configured_tx_mailbox_offset", "structec__slave.html#a365e2116bd54803112c56cb3a98970cb", null ], [ "configured_tx_mailbox_size", "structec__slave.html#a79ecaa06844f2b8bf2d1b4d9bfae9207", null ], [ "base_type", "structec__slave.html#a942db00c8dc12ba78cd124b353945301", null ], [ "base_revision", "structec__slave.html#a5346100cbd1fa0187ae3074d4a75d3cc", null ], [ "base_build", "structec__slave.html#afd680b0cb700169c2a97aa38c0fd0552", null ], [ "base_fmmu_count", "structec__slave.html#a45adb760f44d08fcab9c81d6022e0bad", null ], [ "base_sync_count", "structec__slave.html#aa4d67d55717398c4f25d379ede390d5d", null ], [ "base_fmmu_bit_operation", "structec__slave.html#a39d39fe2e87602de4629cfbdb0106929", null ], [ "base_dc_supported", "structec__slave.html#a2b02f5e40a79f9b6213dde898a10b873", null ], [ "base_dc_range", "structec__slave.html#a8bc5c82a2467c31b4c427fe4c56cb544", null ], [ "has_dc_system_time", "structec__slave.html#a65fba9aad1f196c6c43ba7dceecc15dd", null ], [ "transmission_delay", "structec__slave.html#a0e5d719413436f927eba7320ee565125", null ], [ "sii_words", "structec__slave.html#a3886920f38a9b5a97c1d50f3c08e989a", null ], [ "sii_nwords", "structec__slave.html#a9b6ee3261f586d6c30647b1494da0f57", null ], [ "sii", "structec__slave.html#a081433f5a30f9352fbc4363093ae1e16", null ], [ "sdo_dictionary", "structec__slave.html#a2754265971634ba5f97ce28fc1029d58", null ], [ "sdo_dictionary_fetched", "structec__slave.html#a94732ef500405ce3afa15f6aeef4918d", null ], [ "jiffies_preop", "structec__slave.html#af177795f6287be576f617772d18e3dee", null ], [ "sdo_requests", "structec__slave.html#a6cbec4e34923f5b25fecdbd166a8328a", null ], [ "reg_requests", "structec__slave.html#a614562e4df0afc3707515ae9f1df0ffc", null ], [ "foe_requests", "structec__slave.html#a374ce6a1879d81ca54496be994b9e46e", null ], [ "soe_requests", "structec__slave.html#a85daad41c4862aa0de137a3c927abac8", null ], [ "eoe_requests", "structec__slave.html#a6bbdde3fdf12674be7afe01bfddb3f55", null ], [ "fsm", "structec__slave.html#aecb677b730d579c8eeeaa83a432a74a8", null ] ];
braymar/afl
qemu_mode/qemu-2.10.0/roms/u-boot/arch/arm/mach-exynos/include/mach/system.h
/* * (C) Copyright 2012 Samsung Electronics * <NAME> <<EMAIL>> * * SPDX-License-Identifier: GPL-2.0+ */ #ifndef __ASM_ARM_ARCH_SYSTEM_H_ #define __ASM_ARM_ARCH_SYSTEM_H_ #ifndef __ASSEMBLY__ struct exynos4_sysreg { unsigned char res1[0x210]; unsigned int display_ctrl; unsigned int display_ctrl2; unsigned int camera_control; unsigned int audio_endian; unsigned int jtag_con; }; struct exynos5_sysreg { unsigned char res1[0x214]; unsigned int disp1blk_cfg; unsigned int disp2blk_cfg; unsigned int hdcp_e_fuse; unsigned int gsclblk_cfg0; unsigned int gsclblk_cfg1; unsigned int reserved; unsigned int ispblk_cfg; unsigned int usb20phy_cfg; unsigned char res2[0x29c]; unsigned int mipi_dphy; unsigned int dptx_dphy; unsigned int phyclk_sel; }; #endif #define USB20_PHY_CFG_HOST_LINK_EN (1 << 0) /* * This instruction causes an event to be signaled to all cores * within a multiprocessor system. If SEV is implemented, * WFE must also be implemented. */ #define sev() __asm__ __volatile__ ("sev\n\t" : : ); /* * If the Event Register is not set, WFE suspends execution until * one of the following events occurs: * - an IRQ interrupt, unless masked by the CPSR I-bit * - an FIQ interrupt, unless masked by the CPSR F-bit * - an Imprecise Data abort, unless masked by the CPSR A-bit * - a Debug Entry request, if Debug is enabled * - an Event signaled by another processor using the SEV instruction. * If the Event Register is set, WFE clears it and returns immediately. * If WFE is implemented, SEV must also be implemented. */ #define wfe() __asm__ __volatile__ ("wfe\n\t" : : ); /* Move 0xd3 value to CPSR register to enable SVC mode */ #define svc32_mode_en() __asm__ __volatile__ \ ("@ I&F disable, Mode: 0x13 - SVC\n\t" \ "msr cpsr_c, #0x13|0xC0\n\t" : : ) /* Set program counter with the given value */ #define set_pc(x) __asm__ __volatile__ ("mov pc, %0\n\t" : : "r"(x)) /* Branch to the given location */ #define branch_bx(x) __asm__ __volatile__ ("bx %0\n\t" : : "r"(x)) /* Read Main Id register */ #define mrc_midr(x) __asm__ __volatile__ \ ("mrc p15, 0, %0, c0, c0, 0\n\t" : "=r"(x) : ) /* Read Multiprocessor Affinity Register */ #define mrc_mpafr(x) __asm__ __volatile__ \ ("mrc p15, 0, %0, c0, c0, 5\n\t" : "=r"(x) : ) /* Read System Control Register */ #define mrc_sctlr(x) __asm__ __volatile__ \ ("mrc p15, 0, %0, c1, c0, 0\n\t" : "=r"(x) : ) /* Read Auxiliary Control Register */ #define mrc_auxr(x) __asm__ __volatile__ \ ("mrc p15, 0, %0, c1, c0, 1\n\t" : "=r"(x) : ) /* Read L2 Control register */ #define mrc_l2_ctlr(x) __asm__ __volatile__ \ ("mrc p15, 1, %0, c9, c0, 2\n\t" : "=r"(x) : ) /* Read L2 Auxilliary Control register */ #define mrc_l2_aux_ctlr(x) __asm__ __volatile__ \ ("mrc p15, 1, %0, c15, c0, 0\n\t" : "=r"(x) : ) /* Write System Control Register */ #define mcr_sctlr(x) __asm__ __volatile__ \ ("mcr p15, 0, %0, c1, c0, 0\n\t" : : "r"(x)) /* Write Auxiliary Control Register */ #define mcr_auxr(x) __asm__ __volatile__ \ ("mcr p15, 0, %0, c1, c0, 1\n\t" : : "r"(x)) /* Invalidate all instruction caches to PoU */ #define mcr_icache(x) __asm__ __volatile__ \ ("mcr p15, 0, %0, c7, c5, 0\n\t" : : "r"(x)) /* Invalidate unified TLB */ #define mcr_tlb(x) __asm__ __volatile__ \ ("mcr p15, 0, %0, c8, c7, 0\n\t" : : "r"(x)) /* Write L2 Control register */ #define mcr_l2_ctlr(x) __asm__ __volatile__ \ ("mcr p15, 1, %0, c9, c0, 2\n\t" : : "r"(x)) /* Write L2 Auxilliary Control register */ #define mcr_l2_aux_ctlr(x) __asm__ __volatile__ \ ("mcr p15, 1, %0, c15, c0, 0\n\t" : : "r"(x)) void set_usbhost_mode(unsigned int mode); void set_system_display_ctrl(void); int exynos_lcd_early_init(const void *blob); #endif /* _EXYNOS4_SYSTEM_H */
bcvsolutions/CzechIdMng
Realization/backend/acc/src/main/java/eu/bcvsolutions/idm/acc/service/api/SysProvisioningArchiveService.java
package eu.bcvsolutions.idm.acc.service.api; import java.util.List; import eu.bcvsolutions.idm.acc.dto.SysAttributeDifferenceDto; import eu.bcvsolutions.idm.acc.dto.SysProvisioningArchiveDto; import eu.bcvsolutions.idm.acc.dto.SysProvisioningOperationDto; import eu.bcvsolutions.idm.acc.dto.SysSystemDto; import eu.bcvsolutions.idm.acc.dto.filter.SysProvisioningOperationFilter; import eu.bcvsolutions.idm.core.api.script.ScriptEnabled; import eu.bcvsolutions.idm.core.api.service.ReadWriteDtoService; import eu.bcvsolutions.idm.core.security.api.service.AuthorizableService; import eu.bcvsolutions.idm.ic.api.IcConnectorObject; /** * Archived provisioning operation. * * @author <NAME> * */ public interface SysProvisioningArchiveService extends ReadWriteDtoService<SysProvisioningArchiveDto, SysProvisioningOperationFilter>, AuthorizableService<SysProvisioningArchiveDto>, ScriptEnabled { /** * Archives provisioning operation * * @param provisioningOperation * @return */ SysProvisioningArchiveDto archive(SysProvisioningOperationDto provisioningOperation); /** * Optimize - system can be pre-loaded in DTO. * * @param archive * @return */ SysSystemDto getSystem(SysProvisioningArchiveDto archive); /** * Creates differences of attributes with evaluated type of change. * * @param currentObject * @param changedObject * @return */ List<SysAttributeDifferenceDto> evaluateProvisioningDifferences(IcConnectorObject currentObject, IcConnectorObject changedObject); }
rinat-nezametdinov/deckhouse
docs/site/backend/main.go
<filename>docs/site/backend/main.go package main import ( "context" "fmt" "github.com/gorilla/mux" log "github.com/sirupsen/logrus" "net/http" "os" "os/signal" "strings" "time" ) func newRouter() *mux.Router { r := mux.NewRouter() staticFileDirectory := http.Dir("./root") r.PathPrefix("/status").HandlerFunc(statusHandler) r.PathPrefix("/{lang:ru|en}/documentation/{group:v[0-9]+.[0-9]+}-{channel:alpha|beta|ea|stable|rock-solid}").HandlerFunc(groupChannelHandler) r.PathPrefix("/{lang:ru|en}/documentation/{group:v[0-9]+}").HandlerFunc(groupHandler) r.PathPrefix("/{lang:ru|en}/documentation").HandlerFunc(rootDocHandler) r.PathPrefix("/health").HandlerFunc(healthCheckHandler) r.Path("/{lang:ru|en}/includes/header.html").HandlerFunc(headerHandler) r.Path("/includes/version-menu.html").HandlerFunc(headerHandler) r.Path("/includes/group-menu.html").HandlerFunc(groupMenuHandler) r.Path("/includes/channel-menu.html").HandlerFunc(channelMenuHandler) r.Path("/404.html").HandlerFunc(notFoundHandler) // Other (En) static r.PathPrefix("/").Handler(serveFilesHandler(staticFileDirectory)) r.Use(LoggingMiddleware) r.NotFoundHandler = r.NewRoute().HandlerFunc(notFoundHandler).GetHandler() return r } func main() { logLevel := strings.ToLower(os.Getenv("LOG_LEVEL")) switch logLevel { case "debug": log.SetLevel(log.DebugLevel) case "trace": log.SetLevel(log.TraceLevel) default: log.SetLevel(log.InfoLevel) } log.SetFormatter(&log.TextFormatter{ DisableColors: true, FullTimestamp: true, }) log.Infoln(fmt.Sprintf("Started with LOG_LEVEL %s", logLevel)) r := newRouter() srv := &http.Server{ Handler: r, Addr: "0.0.0.0:8080", WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, } go func() { err := srv.ListenAndServe() if err == http.ErrServerClosed { err = nil } if err != nil { log.Errorln(err) } }() c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) <-c ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := srv.Shutdown(ctx); err != nil { log.Fatalf("shutdown failed:%+s", err) } log.Infoln("Shutting down...") }
zann1x/FrameGraph
framegraph/Shared/PipelineResourcesHelper.h
// Copyright (c) 2018-2019, <NAME>. For more information see 'LICENSE' #pragma once #include "framegraph/Public/PipelineResources.h" #include "stl/Memory/MemWriter.h" namespace FG { // // Pipeline Resources Helper // class PipelineResourcesHelper { public: using DynamicData = PipelineResources::DynamicData; using DynamicDataPtr = PipelineResources::DynamicDataPtr; ND_ static DynamicDataPtr CreateDynamicData (const PipelineDescription::UniformMapPtr &uniforms, uint resourceCount, uint arrayElemCount, uint bufferDynamicOffsetCount); ND_ static DynamicDataPtr CloneDynamicData (const PipelineResources &); ND_ static DynamicDataPtr RemoveDynamicData (INOUT PipelineResources &); static bool Initialize (OUT PipelineResources &, RawDescriptorSetLayoutID layoutId, const DynamicDataPtr &); ND_ static RawPipelineResourcesID GetCached (const PipelineResources &res) { return res._GetCachedID(); } static void SetCache (const PipelineResources &res, const RawPipelineResourcesID &id) { res._SetCachedID( id ); } }; } // FG
LaudateCorpus1/squest
monitoring/views.py
<gh_stars>0 import base64 import logging import prometheus_client from django.http import HttpResponse from django.conf import settings logger = logging.getLogger(__name__) def metrics(request): """ Exports /metrics as a Django view. """ metrics_password_protected = getattr( settings, "METRICS_PASSWORD_PROTECTED", False) if metrics_password_protected: expected_username = getattr( settings, "METRICS_AUTHORIZATION_USERNAME", None) expected_password = getattr( settings, "METRICS_AUTHORIZATION_PASSWORD", None) auth_header = request.META.get("HTTP_AUTHORIZATION", "") token_type, _, credentials = auth_header.partition(" ") if credentials == '': logger.debug(f"[metrics] credentials not provided") response = HttpResponse('Authorization Required', status=401) response['WWW-Authenticate'] = 'Basic realm="Login Required"' return response received_auth_string = base64.b64decode(credentials).decode() if ':' not in received_auth_string: logger.debug(f"[metrics] Invalid credentials format") response = HttpResponse('Authorization Required', status=400) response['WWW-Authenticate'] = 'Basic realm="Login Required"' return response received_username = received_auth_string.split(':')[0] received_password = received_auth_string.split(':')[1] valid_username = received_username == expected_username valid_password = received_password == <PASSWORD> if token_type != 'Basic' or not valid_username or not valid_password: logger.debug(f"[metrics] invalid credentials") response = HttpResponse('Invalid credentials', status=401) response['WWW-Authenticate'] = 'Basic realm="Login Required"' return response registry = prometheus_client.REGISTRY metrics_page = prometheus_client.generate_latest(registry) return HttpResponse( metrics_page, content_type=prometheus_client.CONTENT_TYPE_LATEST )
fjvigil89/worldprofe
src/main/webapp/client/app/services/language.service.js
<filename>src/main/webapp/client/app/services/language.service.js (function (angular) { 'use strict'; angular.module('app').factory('Language', factory); /* @ngInject */ function factory($translate) { return { getCurrent: getCurrent }; function getCurrent() { if ($translate.use()) return $translate.use(); return $translate.preferredLanguage(); } } })(angular);
stewartschillingsdi/reactor-extension-core
src/lib/actions/helpers/decorateCode.js
/*************************************************************************************** * Copyright 2019 Adobe. All rights reserved. * This file is licensed 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 REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. ****************************************************************************************/ 'use strict'; var id = 0; var isSourceLoadedFromFile = function(action) { return action.settings.isExternal; }; var decorateGlobalJavaScriptCode = function(action, source) { // The line break after the source is important in case their last line of code is a comment. return '<scr' + 'ipt>\n' + source + '\n</scr' + 'ipt>'; }; var decorateNonGlobalJavaScriptCode = function(action, source) { var runScriptFnName = '__runScript' + ++id; _satellite[runScriptFnName] = function(fn) { fn.call(action.event.element, action.event, action.event.target); delete _satellite[runScriptFnName]; }; // The line break after the source is important in case their last line of code is a comment. return '<scr' + 'ipt>_satellite["' + runScriptFnName + '"](function(event, target) {\n' + source + '\n});</scr' + 'ipt>'; }; var decorators = { javascript: function(action, source) { return action.settings.global ? decorateGlobalJavaScriptCode(action, source) : decorateNonGlobalJavaScriptCode(action, source); }, html: function(action, source) { // We need to replace tokens only for sources loaded from external files. The sources from // inside the container are automatically taken care by Turbine. if (isSourceLoadedFromFile(action)) { return turbine.replaceTokens(source, action.event); } return source; } }; module.exports = function(action, source) { return decorators[action.settings.language](action, source); };
emafazillah/FHIR
cql/operation/fhir-operation-cqf/src/main/java/com/ibm/fhir/operation/cqf/OperationHelper.java
/* * (C) Copyright IBM Corp. 2022 * * SPDX-License-Identifier: Apache-2.0 */ package com.ibm.fhir.operation.cqf; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.opencds.cqf.cql.engine.execution.InMemoryLibraryLoader; import org.opencds.cqf.cql.engine.execution.LibraryLoader; import com.ibm.fhir.cql.helpers.LibraryHelper; import com.ibm.fhir.cql.translator.CqlTranslationProvider; import com.ibm.fhir.cql.translator.FHIRLibraryLibrarySourceProvider; import com.ibm.fhir.cql.translator.impl.InJVMCqlTranslationProvider; import com.ibm.fhir.exception.FHIROperationException; import com.ibm.fhir.model.resource.Library; import com.ibm.fhir.model.resource.Measure; import com.ibm.fhir.model.resource.Resource; import com.ibm.fhir.model.type.code.ResourceType; import com.ibm.fhir.persistence.SingleResourceResult; import com.ibm.fhir.registry.FHIRRegistry; import com.ibm.fhir.server.spi.operation.FHIRResourceHelpers; public class OperationHelper { /** * Create a library loader that will server up the CQL library content of the * provided list of FHIR Library resources. * * @param libraries * FHIR library resources * @return LibraryLoader that will serve the CQL Libraries for the provided FHIR resources */ public static LibraryLoader createLibraryLoader(List<Library> libraries) { List<org.cqframework.cql.elm.execution.Library> result = loadCqlLibraries(libraries); return new InMemoryLibraryLoader(result); } /** * Load the CQL Library content for each of the provided FHIR Library resources with * translation as needed for Libraries with CQL attachments and no corresponding * ELM attachment. * * @param libraries * FHIR Libraries * @return CQL Libraries */ public static List<org.cqframework.cql.elm.execution.Library> loadCqlLibraries(List<Library> libraries) { FHIRLibraryLibrarySourceProvider sourceProvider = new FHIRLibraryLibrarySourceProvider(libraries); CqlTranslationProvider translator = new InJVMCqlTranslationProvider(sourceProvider); List<org.cqframework.cql.elm.execution.Library> result = libraries.stream().flatMap(fl -> LibraryHelper.loadLibrary(translator, fl).stream()).filter(Objects::nonNull).collect(Collectors.toList()); return result; } /** * Load a Measure resource by reference. * @see loadResourceByReference * @param resourceHelper FHIRResourceHelpers for resource reads * @param reference Resource reference either in ResourceType/ID or canonical URL format * @return loaded resource * @throws FHIROperationException when resource is not found */ public static Measure loadMeasureByReference(FHIRResourceHelpers resourceHelper, String reference) throws FHIROperationException { return loadResourceByReference(resourceHelper, ResourceType.MEASURE, Measure.class, reference); } /** * Load a Measure resource by ID. * * @see loadResourceById * @param resourceHelper FHIRResourceHelpers for resource reads * @param resourceId Resource ID * @return loaded resource * @throws FHIROperationException when resource is not found */ public static Measure loadMeasureById(FHIRResourceHelpers resourceHelper, String resourceId) throws FHIROperationException { return loadResourceById(resourceHelper, ResourceType.MEASURE, resourceId); } /** * Load a Library resource by reference. * @see loadResourceByReference * @param resourceHelper FHIRResourceHelpers for resource reads * @param reference Resource reference either in ResourceType/ID or canonical URL format * @return loaded resource * @throws FHIROperationException when resource is not found */ public static Library loadLibraryByReference(FHIRResourceHelpers resourceHelper, String reference) throws FHIROperationException { return loadResourceByReference(resourceHelper, ResourceType.LIBRARY, Library.class, reference); } /** * Load a Library resource by ID. * * @see loadResourceById * @param resourceHelper FHIRResourceHelpers for resource reads * @param resourceId Resource ID * @return loaded resource * @throws FHIROperationException when resource is not found */ public static Library loadLibraryById(FHIRResourceHelpers resourceHelper, String resourceId) throws FHIROperationException { return loadResourceById(resourceHelper, ResourceType.LIBRARY, resourceId); } /** * Load a resource by reference. If the reference is of the format, ResourceType/ID or * does not contain any forward slash characters, it will be loaded directly. Otherwise, * the reference will be treated as a canonical URL and resolved from the FHIR registry. * * @param resourceHelper FHIRResourceHelpers for resource reads * @param reference Resource reference either in ResourceType/ID or canonical URL format * @return loaded resource * @throws FHIROperationException when resource is not found */ @SuppressWarnings("unchecked") public static <T extends Resource> T loadResourceByReference(FHIRResourceHelpers resourceHelper, ResourceType resourceType, Class<T> resourceClass, String reference) throws FHIROperationException { T resource; int pos = reference.indexOf('/'); if( pos == -1 || reference.startsWith(resourceType.getValue() + "/") ) { String resourceId = reference; if( pos > -1 ) { resourceId = reference.substring(pos + 1); } resource = (T) loadResourceById(resourceHelper, resourceType, resourceId); } else { resource = FHIRRegistry.getInstance().getResource(reference, resourceClass); if( resource == null ) { throw new FHIROperationException(String.format("Failed to resolve %s resource \"%s\"", resourceType.getValue(), reference)); } } return resource; } /** * Load a resource by ID. ID values are expected to already be separated * from the ResourceType in a reference. * * @param <T> Resource class to load * @param resourceHelper FHIRResourceHelpers for resource reads * @param resourceType ResourceType of the resource to load * @param resourceId ID * @return * @throws FHIROperationException */ @SuppressWarnings("unchecked") public static <T extends Resource> T loadResourceById(FHIRResourceHelpers resourceHelper, ResourceType resourceType, String resourceId) throws FHIROperationException { T resource; try { SingleResourceResult<?> readResult = resourceHelper.doRead(resourceType.getValue(), resourceId); resource = (T) readResult.getResource(); if (resource == null) { throw new FHIROperationException(String.format("Failed to resolve %s resource \"%s\"", resourceType.getValue(), resourceId)); } } catch (FHIROperationException fex) { throw fex; } catch (Exception ex) { throw new FHIROperationException("Unexpected error while reading " + resourceType.getValue() + "/" + resourceId, ex); } return resource; } }
mb-syss/ruby-serialize
jrmp.rb
#!/usr/bin/env ruby require 'set' require 'socket' require 'base64' require 'timeout' require 'stringio' require 'openssl' require_relative 'deserialize' require_relative 'serialize' require_relative 'config' require_relative 'data' module Java module JRMP class JRMPError < StandardError attr_accessor :ex def initialize(ex) @ex = ex end end class InvalidResponseError < StandardError end def unwrap_exception(r) return if r.nil? desc = r[0] type = desc[0] fields = r[1] if !fields['cause'].nil? && fields['cause'] != r unwrap_exception(fields['cause']) end return unwrap_exception(fields['detail']) unless fields['detail'].nil? r end module_function :unwrap_exception def unwrap_ref(r) return if r.nil? || r[1].nil? r = r[1]['h'] if r[1].key?('h') r[1] end module_function :unwrap_ref class MarshalOutputStream < Java::Serialize::ObjectOutputStream def initialize(client, registry, location: nil) super(client, registry) @annotateClass = true @annotateProxyClass = true @location = location end def annotateClass(_cl) writeObject(@location) end def annotateProxyClass(cl) annotateClass(cl) end end class JRMPClient def initialize(host, port, registry, location: nil, ssl: false) @location = location @registry = registry @ssl = ssl if ssl sockcl = TCPSocket.new host, port sslctx = OpenSSL::SSL::SSLContext.new('SSLv23_client') sslctx.verify_mode = OpenSSL::SSL::VERIFY_NONE @client = OpenSSL::SSL::SSLSocket.new(sockcl, sslctx) @client.connect else @client = TCPSocket.new host, port end @client.write('JRMI') @client.write([2].pack('S>')) @client.write([0x4c].pack('C')) # TransportConstants.SingleOpProtocol @client.flush end def sendLegacy(objId, methodId, methodhash, args, uid: nil) @client.write([0x50].pack('C')) # TransportConstants.Call oos = MarshalOutputStream.new(@client, @registry, location: @location) @client.write([0x77, 34].pack('CC')) # Blockdata if !uid.nil? @client.write([objId, uid[0], uid[1], uid[2], methodId, methodhash].pack('q>l>q>s>I>Q>')) else @client.write([objId, 0, 0, 0, methodId, methodhash].pack('q>l>q>s>I>Q>')) end for arg in args begin if arg.is_a? Java::Serialize::Data::JavaPrimitive bd = '' if arg.instance_of? Java::Serialize::Data::JavaBoolean bd = [arg.value ? 1 : 0].pack('C') elsif arg.instance_of? Java::Serialize::Data::JavaByte bd = [arg.value].pack('C') elsif arg.instance_of? Java::Serialize::Data::JavaShort bd = [arg.value].pack('s>') elsif arg.instance_of? Java::Serialize::Data::JavaChar bd = [arg.value].pack('S>') elsif arg.instance_of? Java::Serialize::Data::JavaInteger bd = [arg.value].pack('i>') elsif arg.instance_of? Java::Serialize::Data::JavaLong bd = [arg.value].pack('q>') elsif arg.instance_of? Java::Serialize::Data::JavaFloat bd = [arg.value].pack('g>') elsif arg.instance_of? Java::Serialize::Data::JavaDouble bd = [arg.value].pack('G>') else raise 'Unimplemented' end @client.write([0x77, bd.length].pack('CC')) @client.write(bd) else oos.writeObject(arg) end # server may send error and close connection before consuming all arguments rescue Errno::ECONNRESET econn = true break rescue Errno::EPIPE econn = true break end end @client.flush rtype = nil Timeout.timeout(10) do rtype = @client.read(1).unpack('C')[0] end raise InvalidResponseError if rtype != 0x51 smagic, sversion = @client.read(4).unpack('S>S>') raise 'Invalid stream magic' if smagic != 0xaced || sversion != 5 ois = Java::Deserialize::ObjectInputStream.new(@client, @registry) bs = ois.read_blockdata (resptype, uid1, uid2, uid3) = bs.unpack('CI>Q>S>') obj = ois.read_object if resptype == 2 raise JRMPError, obj elsif econn raise 'Connection error' end obj end end class JRMPServer def initialize(port, registry, bind: true) @server = TCPServer.new port if bind @registry = registry end def run loop do client = @server.accept handle_connection(client) end end def handle_stream_proto(client, ois) if client.respond_to?('peeraddr') sock_domain, remote_port, remote_hostname, remote_ip = client.peeraddr else remote_port = client.peerport remote_hostname = client.peerhost end client.write([0x4e].pack('C')) # ACK client.write([remote_hostname.length].pack('S>')) client.write(remote_hostname) client.write([remote_port].pack('I>')) client.flush name = ois.read_utf port = client.read(4).unpack('I>')[0] end def handle_legacy_call(client, ois, objnum, opnum, hash); end def handle_call(client, ois) smagic, sversion = client.read(4).unpack('S>S>') if smagic != 0xaced || sversion != 5 puts 'Invalid stream magic' return end # read object id bdata = ois.read_blockdata # read raw objID objnum, suinque, stime, scount, opnum = bdata.unpack('Q>I>Q>S>I>') if objnum >= 0 && bdata.length == 34 # DGC hash = bdata[26, 34].unpack('Q>')[0] handle_legacy_call(client, ois, objnum, opnum, hash) else puts 'Unsupported call ' + onum.to_s(16) end # RETURN + MAGIC/VERSION client.write([0x51, 0xaced, 5].pack('CS>S>')) # UID client.write([0x77, 15].pack('CS>')) # Blockdata client.write([2].pack('C')) client.write([0, 0, 0].pack('I>Q>S>')) client.write([0x70].pack('C')) # NULL for now, object requires class sannotation end def handle_request(client, ois) op = client.read(1).unpack('C')[0] if op == 0x50 # Call handle_call(client, ois) elsif op == 0x52 # Ping client.write([0x53].pack('C')) # ack elsif op == 0x54 # DGCAck # ignore else puts 'Unknown operation ' + op.to_s(16) end client.flush end def handle_connection(client) magic = client.recv(4) if magic != 'JRMI' puts 'Invalid magic ' + magic.each_byte.map { |byte| format('%02x', byte) }.join return end ver = client.recv(2).unpack('S>')[0] if ver != 2 puts 'Invalid version ' + ver.to_s(16) return end ois = Java::Deserialize::ObjectInputStream.new(client, @registry) proto = client.recv(1).unpack('C')[0] handle_stream_proto(client, ois) if proto == 0x4b # STREAM if proto != 0x4c && proto != 0x4b puts 'Invalid protocol' return end handle_request(client, ois) ensure client.close end end class DGCServer < JRMPServer def initialize(port, registry) super(port, registry) @seen = Set.new @handlers = {} end def handle_dirty(objId) if @seen.add?(objId) if @handlers.key?(objId) h = @handlers[key] h(objId) else puts 'DGC dirty for object ' + objId.to_s end end end def handle_legacy_call(_client, ois, objnum, opnum, _hash) return if objnum != 2 || opnum != 1 rv = ois.read_object # rv is array of ObjID for id in rv objId = id[1]['objNum'].unpack('q>')[0] handle_dirty(objId) end end end class ExceptionJRMPServer < JRMPServer def initialize(port, registry, obj, bind: false) super(port, registry, bind: bind) @seen = Set.new @handlers = {} @obj = obj end def handle_call(client, ois) smagic, sversion = client.read(4).unpack('S>S>') if smagic != 0xaced || sversion != 5 puts 'Invalid stream magic' return end # read object id bdata = ois.read_blockdata # read raw objID objnum, suinque, stime, scount, opnum = bdata.unpack('Q>I>Q>S>I>') oid = [objnum, suinque, stime, scount] return if @seen.include?(oid) @seen.add(oid) # buffer, subtle differences between native and metasploit IO out = StringIO.new # RETURN + MAGIC/VERSION out.write([0x51].pack('C')) # Return oos = MarshalOutputStream.new(out, @registry) oos.setBlockMode(true) oos.writeBytes([2].pack('C')) # ExceptionalReturn oos.writeBytes([0, 0, 0].pack('I>Q>S>')) # UID oos.writeObject(@obj) oos.flush client.write out.string client.flush end end def make_marshalledobject(obj, reg) h = 0 buf = StringIO.new(''.force_encoding('BINARY')) oos = Java::Serialize::ObjectOutputStream.new(buf, reg) oos.writeObject(obj) oos.flush buf.rewind bytes = Array(buf.each_byte) Java::Serialize::JavaObject.new('Ljava/rmi/MarshalledObject;', 'hash' => h, 'objBytes' => Java::Serialize::JavaArray.new('B', bytes)) end module_function :make_marshalledobject def test_remoteclassloading(host, port, reg, objid, uid, methodid, methodhash, ssl: false) args = [Java::Serialize::JavaCustomObject.new('Ldoesnotexist;', {}, 'typeString' => 'Ldoesnotexist;')] client = Java::JRMP::JRMPClient.new(host, port, reg, location: 'invalid', ssl: ssl) client.sendLegacy(objid, methodid, methodhash, args, uid: uid) raise 'Should not succeed' rescue Java::JRMP::JRMPError => e root = unwrap_exception(e.ex) type = root[0][0] if type == 'java.net.MalformedURLException' vuln 'Endpoint appears to allow remote classloading' return true elsif type == 'java.lang.ClassNotFoundException' return false else raise end end module_function :test_remoteclassloading class ReferenceProber def initialize(name, ref, reg, connhost, rc: Java::Config::RunConfig.new) @name = name @reg = reg @ref = ref @host = ref['host'] @port = ref['port'] @objid = ref['objid'] @uid = ref['uid'] @ssl = false @legacy = false @rc = rc if !ref['factory'].nil? && ref['factory'][0][0] == 'javax.rmi.ssl.SslRMIClientSocketFactory' info 'Exported on a SSL endpoint' @ssl = true end begin client = Java::JRMP::JRMPClient.new(@host, @port, @reg, ssl: @ssl) r = client.sendLegacy(@objid, 0, 0, [], uid: @uid) info 'Is a legacy-style object ' + name @legacy = true rescue Java::JRMP::JRMPError => e root = Java::JRMP.unwrap_exception(e.ex) type = root[0][0] if root[1]['detailMessage'] == 'skeleton class not found but required for client version' info 'Is a new-style object ' + name else raise end rescue Exception => e if @host != connhost @host = connhost info 'Trying with original host ' + @host + ' port ' + @port.to_s client = Java::JRMP::JRMPClient.new(@host, @port, @reg, ssl: @ssl) begin r = client.sendLegacy(@objid, 0, 0, [], uid: @uid) rescue Java::JRMP::JRMPError => e rescue Exception => e error 'Failed to connect: ' + e.to_s raise end end end end def generate_method_hash(sig) sha1 = Digest::SHA1.new sha1.update [sig.length].pack('s>') + sig.encode(Encoding::UTF_8) dgst = sha1.digest dgst[0..8].unpack('q<')[0] end def read_argtype(argsig, p) type = '' l = 0 if argsig[p] == 'L' s = p p += 1 while p < argsig.length && argsig[p] != ';' type = argsig[s..p + 1] l = p - s + 1 elsif argsig[p] == '[' atype, al = read_argtype(argsig[p]) type = '[' + atype l = al + 1 else type = argsig[p] l = 1 end [type, l] end def generate_base_args(sig) args = [] argidx = -1 s = sig.index('(') e = sig.index(')', s + 1) argsig = sig[s + 1..e - 1] p = 0 a = 0 while p < argsig.length type, l = read_argtype(argsig, p) if argidx < 0 && (type[0] == 'L' || type['0'] == '[') argidx = a args.push(nil) elsif type[0] == 'Z' args.push(Java::Serialize::Data::JavaBoolean.new(false)) elsif type[0] == 'B' args.push(Java::Serialize::Data::JavaByte.new(0)) elsif type[0] == 'S' args.push(Java::Serialize::Data::JavaShort.new(0)) elsif type[0] == 'C' args.push(Java::Serialize::Data::JavaChar.new(0)) elsif type[0] == 'I' args.push(Java::Serialize::Data::JavaInteger.new(0)) elsif type[0] == 'J' args.push(Java::Serialize::Data::JavaLong.new(0)) elsif type[0] == 'F' args.push(Java::Serialize::Data::JavaFloat.new(0)) elsif type[0] == 'D' args.push(Java::Serialize::Data::JavaDouble.new(0)) else raise 'Unsupported' end p += l a += 1 end [args, argidx] end def run vectors = [] if !@rc.methodHash.nil? methodhash = @rc.methodHash methodid = @rc.methodId args = @rc.methodBaseArgs argidx = @rc.methodArgIdx elsif !@rc.methodSignature.nil? methodid = -1 methodhash = generate_method_hash(@rc.methodSignature) args, argidx = generate_base_args(@rc.methodSignature) if argidx < 0 error 'Method without a object-valued parameter' return vectors end info 'Computed method hash ' + methodhash.to_s + ' for ' + @rc.methodSignature info 'Injecting argument ' + argidx.to_s else error 'Further testing requires method details...' return vectors end begin send(methodid, methodhash, args) rescue Java::JRMP::JRMPError => e root = Java::JRMP.unwrap_exception(e.ex) type = root[0][0] if type == 'java.rmi.UnmarshalException' error root[1]['detailMessage'] return vectors elsif type == 'java.lang.NullPointerException' else raise end end return vectors unless @rc.tryDeser? ctx = Java::Prober::BuiltinProbes.new.create_context(@reg, params: { 'methodid' => methodid, 'methodhash' => methodhash, 'args' => args, 'argidx' => argidx }) strategy = Java::Prober::ExceptionProbeStrategy.new(method(:test_call)) strategy.init(ctx) if ctx.run(strategy) vectors.push(Java::RMI::RMICallDeserVector.new(@host, @port, @objid, ssl: @ssl, ctx: ctx, uid: @uid, methodId: methodid, methodHash: methodhash, baseargs: args, argidx: argidx)) end vectors end def send(methodid, methodhash, args, location: nil, customreg: nil) reg = @reg reg = customreg unless customreg.nil? client = Java::JRMP::JRMPClient.new(@host, @port, reg, location: location, ssl: @ssl) client.sendLegacy(@objid, methodid, methodhash, args, uid: @uid) end def test_call(payl, reg, params) args = params['args'] args[params['argidx']] = payl send(params['methodid'], params['methodhash'], args, customreg: reg) rescue Java::JRMP::JRMPError => e root = Java::JRMP.unwrap_exception(e.ex) type = root[0][0] if type == 'java.lang.IllegalArgumentException' return else return type end end def close; end end end end
johnarn/price_observer_bot
venv/Lib/site-packages/PyInstaller/hooks/pre_find_module_path/hook-distutils.py
<reponame>johnarn/price_observer_bot<filename>venv/Lib/site-packages/PyInstaller/hooks/pre_find_module_path/hook-distutils.py<gh_stars>1-10 #----------------------------------------------------------------------------- # Copyright (c) 2005-2019, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- """ `distutils`-specific pre-find module path hook. When run from within a venv (virtual environment), this hook changes the `__path__` of the `distutils` package to that of the system-wide rather than venv-specific `distutils` package. While the former is suitable for freezing, the latter is intended for use _only_ from within venvs. """ import distutils import os from PyInstaller.utils.hooks import logger def pre_find_module_path(api): # Absolute path of the system-wide "distutils" package when run from within # a venv or None otherwise. distutils_dir = getattr(distutils, 'distutils_path', None) if distutils_dir is not None: # Find this package in its parent directory. api.search_dirs = [os.path.dirname(distutils_dir)] logger.info('distutils: retargeting to non-venv dir %r' % distutils_dir)
ay1741/ay1741.github.io
owncloud/apps/files/l10n/az.js
OC.L10N.register( "files", { "Storage not available" : "İnformasiya daşıyıcısı mövcud deyil", "Storage invalid" : "İnformasiya daşıyıcısı yalnışdır", "Unknown error" : "Bəlli olmayan səhv baş verdi", "Could not move %s - File with this name already exists" : "Köçürmə mümkün deyil %s - Bu adla fayl artıq mövcuddur", "Could not move %s" : "Yerdəyişmə mükün olmadı %s", "Permission denied" : "Yetki qadağandır", "File name cannot be empty." : "Faylın adı boş ola bilməz.", "\"%s\" is an invalid file name." : "\"%s\" yalnış fayl adıdır.", "Invalid name, '\\', '/', '<', '>', ':', '\"', '|', '?' and '*' are not allowed." : "Yalnış ad, '\\', '/', '<', '>', ':', '\"', '|', '?' və '*' qəbul edilmir.", "The target folder has been moved or deleted." : "Mənsəbdə olan qovluqun ünvanı dəyişib yada silinib.", "The name %s is already used in the folder %s. Please choose a different name." : "Bu ad %s artıq %s qovluğunda istifadə edilir. Xahiş olunur fərqli ad istifadə edəsiniz.", "Not a valid source" : "Düzgün mənbə yoxdur", "Server is not allowed to open URLs, please check the server configuration" : "URL-ləri açmaq üçün server izin vermir, xahış olunur server quraşdırmalarını yoxlayasınız", "The file exceeds your quota by %s" : "Fayl sizə təyin edilmiş %s məhdudiyyətini aşır", "Error while downloading %s to %s" : "%s-i %s-ə yükləmə zamanı səhv baş verdi", "Error when creating the file" : "Fayl yaratdıqda səhv baş vermişdir", "Folder name cannot be empty." : "Qovluğun adı boş ola bilməz", "Error when creating the folder" : "Qovluğu yaratdıqda səhv baş vermişdir", "Unable to set upload directory." : "Əlavələr qovluğunu təyin etmək mümkün olmadı.", "Invalid Token" : "<PASSWORD>", "No file was uploaded. Unknown error" : "Heç bir fayl uüklənilmədi. Naməlum səhv", "There is no error, the file uploaded with success" : "Səhv yoxdur, fayl uğurla yüklənildi.", "The uploaded file exceeds the upload_max_filesize directive in php.ini: " : "Yüklənilən faylin həcmi php.ini config faylinin upload_max_filesize direktivində göstəriləndən çoxdur.", "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" : "Yüklənilən faylın həcmi HTML formasinda olan MAX_FILE_SIZE direktivində təyin dilmiş həcmi aşır.", "The uploaded file was only partially uploaded" : "Yüklənilən faylın yalnız bir hissəsi yüklənildi", "No file was uploaded" : "Heç bir fayl yüklənilmədi", "Missing a temporary folder" : "Müvəqqəti qovluq çatışmır", "Failed to write to disk" : "Sərt diskə yazmaq mümkün olmadı", "Not enough storage available" : "Tələb edilən qədər yer yoxdur.", "Upload failed. Could not find uploaded file" : "Yüklənmədə səhv oldu. Yüklənmiş faylı tapmaq olmur.", "Upload failed. Could not get file info." : "Yüklənmədə səhv oldu. Faylın informasiyasını almaq mümkün olmadı.", "Invalid directory." : "Yalnış qovluq.", "Files" : "Fayllar", "All files" : "Bütün fayllar", "Unable to upload {filename} as it is a directory or has 0 bytes" : "Yükləmək olmur {filename} ona görə ki, ya qovluqdur yada ki, həcmi 0 baytdır ", "Total file size {size1} exceeds upload limit {size2}" : "Ümumi fayl həcmi {size1} yüklənmə limiti {size2} -ni aşır", "Not enough free space, you are uploading {size1} but only {size2} is left" : "Kifayət qədər boş yer yoxdur, siz yükləyirsiniz {size1} ancaq {size2} var. ", "Upload cancelled." : "Yüklənmə dayandırıldı.", "Could not get result from server." : "Nəticəni serverdən almaq mümkün olmur.", "File upload is in progress. Leaving the page now will cancel the upload." : "Faylın yüklənməsi gedir. Əgər səhifəni indi tərk etsəniz yüklənmə dayanacaq.", "URL cannot be empty" : "URL boş ola bilməz", "{new_name} already exists" : "{new_name} artıq mövcuddur", "Could not create file" : "Faylı yaratmaq olmur", "Could not create folder" : "Qovluğu yaratmaq olmur", "Error fetching URL" : "URL-in gətirilməsində səhv baş verdi", "Rename" : "Adı dəyiş", "Delete" : "Sil", "Download" : "Yüklə", "Error" : "Səhv", "Name" : "Ad", "Size" : "Həcm", "_%n folder_::_%n folders_" : ["",""], "_%n file_::_%n files_" : ["",""], "_Uploading %n file_::_Uploading %n files_" : ["",""], "_matches '{filter}'_::_match '{filter}'_" : ["",""], "Save" : "Saxlamaq", "Settings" : "Quraşdırmalar", "New folder" : "Yeni qovluq", "Folder" : "Qovluq", "Upload" : "Serverə yüklə", "Cancel upload" : "Yüklənməni dayandır" }, "nplurals=2; plural=(n != 1);");
isfinne/photo-editor
DISK_C/PIC/source/read.c
<gh_stars>1-10 #include "head.h" #pragma pack(1) //结构体的边界对齐为1个字节,节省内存 #define maxnSize (long long)1024*35 //可以存储的最大图片大小 /******************************* 读取BMP文件头信息头函数 传入图片头,图片地址 将传入地址的图片信息读入图片头中 读入成功返回1 读入失败返回0 *******************************/ int readBmp(BMPHeader* head,char *address) { int i=0; BITMAPFILEHEADER fileHeader; BITMAPINFOHEADER infoHeader; RGBQUAD pColorTable[256]; FILE* fp; fp = fopen(address, "rb");//address if(fp == NULL) { //printf("Fail to open image!\n"); return 0; } fread(&fileHeader, 1, sizeof(BITMAPFILEHEADER), fp); fread(&infoHeader, 1, sizeof(BITMAPINFOHEADER), fp); if (fileHeader.bfType != 0X4D42) { /* BM */ fprintf(stderr, "Not a BMP file !\n"); return 0; } if (infoHeader.biBitCount > 8) { /* 不能显示真彩色图像 */ fprintf(stderr, "Can not display ture color image !\n"); return 0; } if (infoHeader.biCompression != 0) { /* 不能处理压缩图像 */ fprintf(stderr, "Not non-compressed image !\n"); return 0; } fread(pColorTable,sizeof(RGBQUAD),256,fp); head->fileHead=fileHeader; head->infoHead=infoHeader; for(i=0; i<256; i++) { head->pColorTable[i].rgbBlue=pColorTable[i].rgbBlue; head->pColorTable[i].rgbGreen=pColorTable[i].rgbGreen; head->pColorTable[i].rgbRed=pColorTable[i].rgbRed; head->pColorTable[i].rgbReserved=pColorTable[i].rgbReserved; } fclose(fp); //printf("biBitCount:%d\n",infoHeader.biBitCount); //printf("biWidth:%d\n",infoHeader.biWidth); //printf("rgbBlue:%d\n",pColorTable[100].rgbBlue); return 1; } /******************************* 读取BMP像素块函数 传入图片头,图片地址 将传入地址的图片像素块读入内存中 读入成功返回1 读入失败返回0 *******************************/ int readPix(BYTE* temp,int size,char *address) { FILE *fp; int off; fp=fopen(address,"rb"); if (fp==0) { return 0; } // 计算偏移距离 off=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+sizeof(RGBQUAD)*256; fseek(fp,off,SEEK_SET); fread(temp,size,1,fp); fclose(fp); return 1; } /******************************* 打开判断函数 传入图片头 若可以缩放返回1 若不能缩放返回0 *******************************/ int openJudge(BMPHeader *head) { int width,height,biBitCount,lineByte; long long bfSize; BITMAPFILEHEADER fileHead; BITMAPINFOHEADER infoHead; fileHead=head->fileHead; infoHead=head->infoHead; width=infoHead.biWidth; height=infoHead.biHeight; biBitCount=infoHead.biBitCount; lineByte=(width*biBitCount/8+3)/4*4; bfSize=(long long)height*lineByte+fileHead.bfOffBits; // 计算缩放后大小 bfSize=(bfSize+3)/4*4; if(bfSize>maxnSize) return 0; else return 1; }
erique/embeddedsw
XilinxProcessorIPLib/drivers/hwicap/doc/html/api/xhwicap__intr_8c.js
<reponame>erique/embeddedsw var xhwicap__intr_8c = [ [ "XHwIcap_IntrHandler", "xhwicap__intr_8c.html#ga9cf1ff1dd1056a11f65a903c47492842", null ], [ "XHwIcap_SetInterruptHandler", "xhwicap__intr_8c.html#gaa2f2f23cf842c10f443509f8861a194a", null ] ];
OHDSI/Authenticator
src/main/java/org/ohdsi/authenticator/service/authentication/authenticator/AuthenticatorStandardMode.java
package org.ohdsi.authenticator.service.authentication.authenticator; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import io.jsonwebtoken.Claims; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import javax.annotation.PostConstruct; import org.ohdsi.authenticator.config.AuthSchema; import org.ohdsi.authenticator.exception.AuthenticationException; import org.ohdsi.authenticator.model.AuthenticationToken; import org.ohdsi.authenticator.model.UserInfo; import org.ohdsi.authenticator.service.AuthMethodSettings; import org.ohdsi.authenticator.service.AuthService; import org.ohdsi.authenticator.service.AuthServiceConfig; import org.ohdsi.authenticator.service.authentication.Authenticator; import org.ohdsi.authenticator.service.authentication.TokenProvider; import org.ohdsi.authenticator.service.authentication.TokenService; import org.pac4j.core.credentials.Credentials; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.ClassUtils; public class AuthenticatorStandardMode implements Authenticator { protected static final Logger logger = LoggerFactory.getLogger(Authenticator.class.getName()); public static final String METHOD_KEY = "method"; private static final String BAD_CREDENTIALS_ERROR = "Bad credentials"; private static final String METHOD_NOT_SUPPORTED_ERROR = "Method not supported"; private AuthSchema authSchema; private TokenService tokenService; private TokenProvider tokenProvider; private ObjectMapper objectMapper; private Map<String, AuthService> authServices = new HashMap<>(); public AuthenticatorStandardMode(AuthSchema authSchema, TokenService tokenService, TokenProvider tokenProvider) { this.authSchema = authSchema; this.tokenService = tokenService; this.tokenProvider = tokenProvider; } @PostConstruct private void postConstruct() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { initObjectMapper(); initServices(); } @Override public UserInfo authenticate(String method, Credentials request) { AuthService authService = getForMethod(method); if (authService == null) { throw new AuthenticationException(METHOD_NOT_SUPPORTED_ERROR); } AuthenticationToken authentication = authService.authenticate(request); if (!authentication.isAuthenticated()) { throw new AuthenticationException(BAD_CREDENTIALS_ERROR); } return buildUserInfo(authentication, method); } @Override public String resolveUsername(String token) { return tokenService.resolveAdditionalInfo(token, Claims.SUBJECT, String.class); } @Override public UserInfo refreshToken(String token) { Claims claims = tokenProvider.validateTokenAndGetClaims(token); String usedMethod = claims.get(METHOD_KEY, String.class); AuthService authService = getForMethod(usedMethod); AuthenticationToken authentication = authService.refreshToken(claims); return buildUserInfo(authentication, usedMethod); } @Override public void invalidateToken(String token) { tokenProvider.invalidateToken(token); } private void initObjectMapper() { this.objectMapper = new ObjectMapper(); this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } private void initServices() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { for (Map.Entry<String, AuthMethodSettings> entry : authSchema.getMethods().entrySet()) { String method = entry.getKey(); AuthMethodSettings authMethodSettings = entry.getValue(); String authServiceClassName = authMethodSettings.getService(); Class authServiceClass = ClassUtils.forName(authServiceClassName, this.getClass().getClassLoader()); Class configClass = resolveRequiredConfigClass(authServiceClass); AuthServiceConfig config = resolveConfig(authMethodSettings.getConfig(), configClass); AuthService authService = constructAuthService(authServiceClass, config); authServices.put(method, authService); } } private Class<? extends AuthServiceConfig> resolveRequiredConfigClass(Class authServiceClass) { Constructor[] constructors = authServiceClass.getDeclaredConstructors(); for (Constructor constructor : constructors) { Class[] params = constructor.getParameterTypes(); if (params.length == 1 && AuthServiceConfig.class.isAssignableFrom(params[0])) { return params[0]; } } throw new RuntimeException(String.format("%s doesn't have required constructor", authServiceClass.getCanonicalName())); } private <T> T resolveConfig(Map rawConfig, Class targetType) { return (T) objectMapper.convertValue(rawConfig, targetType); } private AuthService constructAuthService(Class authServiceClass, AuthServiceConfig config) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { return (AuthService) authServiceClass.getDeclaredConstructor(config.getClass()).newInstance(config); } private AuthService getForMethod(String method) { return authServices.get(method); } private UserInfo buildUserInfo(AuthenticationToken authentication, String method) { String username = authentication.getPrincipal().toString(); Map userAdditionalInfo = (Map) authentication.getDetails(); userAdditionalInfo.put(METHOD_KEY, method); String token = tokenProvider.createToken(username, userAdditionalInfo, authentication.getExpirationDate()); UserInfo userInfo = tokenService.resolveUser(token); userInfo.setAdditionalInfo(userAdditionalInfo); return userInfo; } }
ninjadotorg/constant-websites
user/src/settings/basicStyle.js
<reponame>ninjadotorg/constant-websites<gh_stars>0 const rowStyle = { width: '100%', display: 'flex', flexFlow: 'row wrap', marginLeft: 0, marginRight: 0, }; const colStyle = { marginBottom: '16px', }; const colStyle0 = { }; const boxStyle0 = { margin: 0, padding: 0, border: 0, backgroundColor: 'unset' }; const boxStyleBg = (bgImage, pos='right bottom') => { return ({ backgroundImage: `url(${bgImage})`, backgroundRepeat: 'no-repeat', backgroundPosition: `${pos}`, height: 174, padding: '1.5rem' }); }; const gutter = 16; const basicStyle = { rowStyle, colStyle, colStyle0, boxStyle0, boxStyleBg, gutter, }; export default basicStyle;
d3r3kk/toga
examples/beeliza/beeliza/bot.py
<reponame>d3r3kk/toga #---------------------------------------------------------------------- # eliza.py # # A cheezy little Eliza knock-off by <NAME> # with some updates by <NAME> # Hacked into a module and updated by <NAME> # Updated and tweaked for PEP8 compliance by <NAME> # # Original source: https://github.com/jezhiggins/eliza.py # # Used under the terms of the MIT Licence. # # Copyright (c) 2002-2017 JezUK Ltd, <NAME>, <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # #---------------------------------------------------------------------- import random import re class Eliza: #---------------------------------------------------------------------- # reflections, a translation table used to convert things you say # into things the computer says back, e.g. "I am" --> "you are" #---------------------------------------------------------------------- REFLECTIONS = { "am": "are", "was": "were", "i": "you", "i'd": "you would", "i've": "you have", "i'll": "you will", "my": "your", "are": "am", "you've": "I have", "you'll": "I will", "your": "my", "yours": "mine", "you": "me", "me": "you" } #---------------------------------------------------------------------- # RESPONSES, the main response table. Each element of the list is a # two-element list; the first is a regexp, and the second is a # list of possible responses, with group-macros labelled as # {0}, {1}, etc. #---------------------------------------------------------------------- RESPONSES = [ [ re.compile(r'I need (.*)', re.IGNORECASE), [ "Why do you need {0}?", "Would it really help you to get {0}?", "Are you sure you need {0}?" ] ], [ re.compile(r'Why don\'?t you ([^\?]*)\??', re.IGNORECASE), [ "Do you really think I don't {0}?", "Perhaps eventually I will {0}.", "Do you really want me to {0}?" ] ], [ re.compile(r'Why can\'?t I ([^\?]*)\??', re.IGNORECASE), [ "Do you think you should be able to {0}?", "If you could {0}, what would you do?", "I don't know -- why can't you {0}?", "Have you really tried?" ] ], [ re.compile(r'I can\'?t (.*)', re.IGNORECASE), [ "How do you know you can't {0}?", "Perhaps you could {0} if you tried.", "What would it take for you to {0}?" ] ], [ re.compile(r'I am (.*)', re.IGNORECASE), [ "Did you come to me because you are {0}?", "How long have you been {0}?", "How do you feel about being {0}?" ] ], [ re.compile(r'I\'?m (.*)', re.IGNORECASE), [ "How does being {0} make you feel?", "Do you enjoy being {0}?", "Why do you tell me you're {0}?", "Why do you think you're {0}?" ] ], [ re.compile(r'Are you ([^\?]*)\??', re.IGNORECASE), [ "Why does it matter whether I am {0}?", "Would you prefer it if I were not {0}?", "Perhaps you believe I am {0}.", "I may be {0} -- what do you think?" ] ], [ re.compile(r'What (.*)', re.IGNORECASE), [ "Why do you ask?", "How would an answer to that help you?", "What do you think?" ] ], [ re.compile(r'How (.*)', re.IGNORECASE), [ "How do you suppose?", "Perhaps you can answer your own question.", "What is it you're really asking?" ] ], [ re.compile(r'Because (.*)', re.IGNORECASE), [ "Is that the real reason?", "What other reasons come to mind?", "Does that reason apply to anything else?", "If {0}, what else must be true?" ] ], [ re.compile(r'(.*) sorry (.*)', re.IGNORECASE), [ "There are many times when no apology is needed.", "What feelings do you have when you apologize?" ] ], [ re.compile(r'Hello(.*)', re.IGNORECASE), [ "Hello... I'm glad you could drop by today.", "Hi there... how are you today?", "Hello, how are you feeling today?" ] ], [ re.compile(r'I think (.*)', re.IGNORECASE), [ "Do you doubt {0}?", "Do you really think so?", "But you're not sure {0}?" ] ], [ re.compile(r'(.*) friend (.*)', re.IGNORECASE), [ "Tell me more about your friends.", "When you think of a friend, what comes to mind?", "Why don't you tell me about a childhood friend?" ] ], [ re.compile(r'Yes', re.IGNORECASE), [ "You seem quite sure.", "OK, but can you elaborate a bit?" ] ], [ re.compile(r'(.*) computer(.*)', re.IGNORECASE), [ "Are you really talking about me?", "Does it seem strange to talk to a computer?", "How do computers make you feel?", "Do you feel threatened by computers?" ] ], [ re.compile(r'Is it (.*)', re.IGNORECASE), [ "Do you think it is {0}?", "Perhaps it's {0} -- what do you think?", "If it were {0}, what would you do?", "It could well be that {0}." ] ], [ re.compile(r'It is (.*)', re.IGNORECASE), [ "You seem very certain.", "If I told you that it probably isn't {0}, what would you feel?" ] ], [ re.compile(r'Can you ([^\?]*)\??', re.IGNORECASE), [ "What makes you think I can't {0}?", "If I could {0}, then what?", "Why do you ask if I can {0}?" ] ], [ re.compile(r'Can I ([^\?]*)\??', re.IGNORECASE), [ "Perhaps you don't want to {0}.", "Do you want to be able to {0}?", "If you could {0}, would you?" ] ], [ re.compile(r'You are (.*)', re.IGNORECASE), [ "Why do you think I am {0}?", "Does it please you to think that I'm {0}?", "Perhaps you would like me to be {0}.", "Perhaps you're really talking about yourself?" ] ], [ re.compile(r'You\'?re (.*)', re.IGNORECASE), [ "Why do you say I am {0}?", "Why do you think I am {0}?", "Are we talking about you, or me?" ] ], [ re.compile(r'I don\'?t (.*)', re.IGNORECASE), [ "Don't you really {0}?", "Why don't you {0}?", "Do you want to {0}?" ] ], [ re.compile(r'I feel (.*)', re.IGNORECASE), [ "Good, tell me more about these feelings.", "Do you often feel {0}?", "When do you usually feel {0}?", "When you feel {0}, what do you do?" ] ], [ re.compile(r'I have (.*)', re.IGNORECASE), [ "Why do you tell me that you've {0}?", "Have you really {0}?", "Now that you have {0}, what will you do next?" ] ], [ re.compile(r'I would (.*)', re.IGNORECASE), [ "Could you explain why you would {0}?", "Why would you {0}?", "Who else knows that you would {0}?" ] ], [ re.compile(r'Is there (.*)', re.IGNORECASE), [ "Do you think there is {0}?", "It's likely that there is {0}.", "Would you like there to be {0}?" ] ], [ re.compile(r'My (.*)', re.IGNORECASE), [ "I see, your {0}.", "Why do you say that your {0}?", "When your {0}, how do you feel?" ] ], [ re.compile(r'You (.*)', re.IGNORECASE), [ "We should be discussing you, not me.", "Why do you say that about me?", "Why do you care whether I {0}?" ] ], [ re.compile(r'Why (.*)', re.IGNORECASE), [ "Why don't you tell me the reason why {0}?", "Why do you think {0}?" ] ], [ re.compile(r'I want (.*)', re.IGNORECASE), [ "What would it mean to you if you got {0}?", "Why do you want {0}?", "What would you do if you got {0}?", "If you got {0}, then what would you do?" ] ], [ re.compile(r'(.*) mother(.*)', re.IGNORECASE), [ "Tell me more about your mother.", "What was your relationship with your mother like?", "How do you feel about your mother?", "How does this relate to your feelings today?", "Good family relations are important." ] ], [ re.compile(r'(.*) father(.*)', re.IGNORECASE), [ "Tell me more about your father.", "How did your father make you feel?", "How do you feel about your father?", "Does your relationship with your father relate to your feelings today?", "Do you have trouble showing affection with your family?" ] ], [ re.compile(r'(.*) child(.*)', re.IGNORECASE), [ "Did you have close friends as a child?", "What is your favorite childhood memory?", "Do you remember any dreams or nightmares from childhood?", "Did the other children sometimes tease you?", "How do you think your childhood experiences relate to your feelings today?" ] ], [ re.compile(r'(.*)\?', re.IGNORECASE), [ "Why do you ask that?", "Please consider whether you can answer your own question.", "Perhaps the answer lies within yourself?", "Why don't you tell me?" ] ], [ re.compile(r'quit', re.IGNORECASE), [ "Thank you for talking with me.", "Good-bye.", "Thank you, that will be $150. Have a good day!" ] ], [ re.compile(r'(.*)', re.IGNORECASE), [ "Please tell me more.", "Let's change focus a bit... Tell me about your family.", "Can you elaborate on that?", "Why do you say that {0}?", "I see.", "Very interesting.", "{0}.", "I see. And what does that tell you?", "How does that make you feel?", "How do you feel when you say that?" ] ], ] #---------------------------------------------------------------------- # reflect: take an input string, and reflect the direction of any # statments (i.e., "I think I'm happy" - > "you think you're happy") #---------------------------------------------------------------------- def reflect(self, input): return ' '.join( self.REFLECTIONS.get(word, word) for word in input.lower().split() ) #---------------------------------------------------------------------- # respond: take a string, a set of regexps, and a corresponding # set of response lists; find a match, and return a randomly # chosen response from the corresponding list. #---------------------------------------------------------------------- def respond(self, input): # find a match among keys for pattern, responses in self.RESPONSES: match = pattern.match(input) if match: # Found a match; randomly choose a response, # and populate it with the captured regex group data. response = random.choice(responses).format(*[ self.reflect(group) for group in match.groups() ]) # fix punctuation if response[-2:] == '?.': response = response[:-2] + '.' if response[-2:] == '??': response = response[:-2] + '?' return response if __name__ == "__main__": print('Talk to the program by typing in plain English, using normal upper-') print('and lower-case letters and punctuation. Enter "quit" when done.') print('='*72) print('Hello. How are you feeling today?') s = '' bot = Eliza() while s != 'quit': try: s = input('> ') except EOFError: s = 'quit' except KeyboardInterrupt: print() s = 'quit' while s[-1] in '!.': s = s[:-1] print(bot.respond(s))
MaximKulikov/Java-Twitch-Api-Wrapper
src/main/java/com/mb3364/twitch/api/handlers/TopGamesResponseHandler.java
package com.mb3364.twitch.api.handlers; import com.mb3364.twitch.api.models.Top; import java.util.List; public interface TopGamesResponseHandler extends BaseFailureHandler { void onSuccess(int total, List<Top> games); }
paoqi1997/pqnet
raw-examples/linux/threadpool/threadpool.cpp
#include "threadpool.h" void* routine(void *arg) { auto pool = static_cast<ThreadPool*>(arg); Condition& cond = pool->Cond(); for (;;) { cond.lock(); while (pool->isRunning() && pool->isIdle()) { cond.wait(); } if (!pool->isRunning() && pool->isIdle()) { cond.unlock(); break; } Task task = pool->take(); cond.unlock(); task.run(); } return nullptr; } ThreadPool::ThreadPool(std::size_t threadNumber) : running(false), addable(true), tn(threadNumber), pool(threadNumber) { } ThreadPool::~ThreadPool() { cond.notifyAll(); for (auto id : pool) { if (pthread_join(id, nullptr) != 0) { std::cout << std::strerror(errno) << std::endl; } } } void ThreadPool::run() { running = true; for (std::size_t i = 0; i < tn; ++i) { if (pthread_create(&pool[i], nullptr, routine, this) != 0) { std::cout << std::strerror(errno) << std::endl; } } } void ThreadPool::addTask(Task task) { if (!addable) return; if (tn == 0) { task.run(); } else { cond.lock(); taskqueue.push(task); cond.unlock(); cond.notify(); } } Task ThreadPool::take() { Task task = taskqueue.front(); taskqueue.pop(); return task; }
quantumlaser/code2016
LeetCode/Answers/Leetcode-java-solution/longest_palindromic_substring/LongestPalindromicSubstring.java
<gh_stars>0 package longest_palindromic_substring; import static org.junit.Assert.assertEquals; import org.junit.Test; public class LongestPalindromicSubstring { public class Solution { public String longestPalindrome(String s) { String t = "^#"; for (int i = 0; i < s.length(); i++) { t += s.charAt(i); t += '#'; } t += '$'; int[] p = new int[t.length()]; int id = 1; p[1] = 1; int rightIndex = 2; for (int i = 2; i < t.length() - 1; i++) { if (rightIndex > i) { p[i] = Math.min(p[2 * id - i], rightIndex - i); } else { p[i] = 1; } while (t.charAt(i + p[i]) == t.charAt(i - p[i])) { p[i]++; } if (rightIndex < i + p[i]) { rightIndex = i + p[i]; id = i; } } int maxId = 1; for (int i = 2; i < t.length() - 1; i++) { if (p[maxId] < p[i]) { maxId = i; } } int length = p[maxId] - 1; int startIndex = (maxId - p[maxId]) / 2; return s.substring(startIndex, startIndex + length); } } public static class UnitTest { @Test public void testLongestPalindrome() { Solution s = new LongestPalindromicSubstring().new Solution(); assertEquals("a", s.longestPalindrome("a")); } } }
nbwhite/dai-ds
eventsim/src/main/java/com/intel/dai/eventsim/HardwareInventory.java
<filename>eventsim/src/main/java/com/intel/dai/eventsim/HardwareInventory.java package com.intel.dai.eventsim; import com.intel.config_io.ConfigIOParseException; import com.intel.properties.PropertyDocument; import java.io.FileNotFoundException; import java.io.IOException; /** * Description of class HardwareInventory. * set the hardware inventory/discover/query configuration file * fetch respective hardware inventory/discover/query data. */ public class HardwareInventory { /** * This method used to set inventory hardware configuration file. * @param hwInventoryConfigFile location of hardware inventory configuration file. * @throws SimulatorException when unable to set the location of hardware inventory configuration file. */ void setInventoryHardwareConfigLocation(final String hwInventoryConfigFile) throws SimulatorException { if (hwInventoryConfigFile == null || hwInventoryConfigFile.isEmpty()) throw new SimulatorException("Invalid or null hardware inventory config file"); hwInventoryConfigFile_ = hwInventoryConfigFile; } /** * This method used to fetch hardware inventory data. * @return inventory hardware data. * @throws SimulatorException when unable to get inventory hardware data. */ PropertyDocument getHwInventory() throws SimulatorException { try { return processDataAsArray(readConfigFile(hwInventoryConfigFile_)); } catch (final FileNotFoundException e) { throw new SimulatorException("Given hardware inventory data file doesn't exist: " + hwInventoryConfigFile_); } catch (final ConfigIOParseException | IOException e) { throw new SimulatorException("Error while loading hardware inventory data"); } } /** * This method used to set inventory hardware configuration file path. * @param hwInventoryConfigPath location of hardware inventory configuration file path. * @throws SimulatorException when unable to set the location of hardware inventory configuration file path. */ void setInventoryHardwareConfigPath(final String hwInventoryConfigPath) throws SimulatorException { if (hwInventoryConfigPath == null || hwInventoryConfigPath.isEmpty()) throw new SimulatorException("Invalid or null hardware inventory config path"); hwInventoryConfigPath_ = hwInventoryConfigPath; } /** * This method used to fetch hardware inventory for a location data. * @return inventory hardware for a location data. * @throws SimulatorException when unable to get inventory hardware for a location data. */ PropertyDocument getInventoryHardwareForLocation(final String location) throws SimulatorException { String hwInventoryForLocationFile = hwInventoryConfigPath_ + "/" + location + HW_INV_LOC_FILE_EXT; try { return processData(readConfigFile(hwInventoryForLocationFile)); } catch (final FileNotFoundException e) { throw new SimulatorException("Given hardware inventory data file for a location doesn't exist: " + hwInventoryForLocationFile); } catch (final ConfigIOParseException | IOException e) { throw new SimulatorException("Error while loading hardware inventory data for a location"); } } /** * This method used to set hardware inventory query configuration file. * @param hwInventoryQuery location of hardware inventory query configuration file. * @throws SimulatorException when unable to set the location of hardware inventory query configuration file. */ void setInventoryHardwareQueryPath(final String hwInventoryQuery) throws SimulatorException { if (hwInventoryQuery == null || hwInventoryQuery.isEmpty()) throw new SimulatorException("Invalid or null hardware inventory query path"); hwInventoryQueryPath_ = hwInventoryQuery; } /** * This method used to fetch inventory hardware query for a location data. * @param location location of hardware inventory query for a location configuration file. * @throws SimulatorException when unable to set the location of hardware inventory query for a location configuration file. */ PropertyDocument getInventoryHardwareQueryForLocation(final String location) throws SimulatorException { String hwInventoryQueryFileLocation = hwInventoryQueryPath_ + "/" + location + HW_INV_QRY_FILE_EXT; try { return processData(readConfigFile(hwInventoryQueryFileLocation)); } catch (final FileNotFoundException e) { throw new SimulatorException("Given hardware inventory query data file for a location doesn't exist: " + hwInventoryQueryFileLocation); } catch (final ConfigIOParseException | IOException e) { throw new SimulatorException("Error while loading hardware inventory query data for a location"); } } /** * This method process the hardware discovery configuration file data. * @param data hardware discovery configuration file data. * @return processed hardware discovery configuration file data. * @throws SimulatorException when unable to process hardware discovery configuration file data. */ private PropertyDocument processDataAsArray(PropertyDocument data) throws SimulatorException { if (data == null || !data.isArray() || data.getAsArray().isEmpty()) throw new SimulatorException("Error while loading hardware inventory data"); return data.getAsArray(); } /** * This method process the hardware inventory/query configuration file data. * @param data hardware inventory/query file data. * @return processed hardware inventory/query configuration file data. * @throws SimulatorException when unable to process hardware inventory/query configuration file data. */ private PropertyDocument processData(PropertyDocument data) throws SimulatorException { if (data == null) throw new SimulatorException("Error while loading hardware inventory data for a location"); return data; } /** * This method reads the hardware inventory/discover/query configuration file. * @param hwInventoryFile hardware inventory/discover/query configuration file. * @return file data. * @throws IOException unable to find file or parse data. * @throws ConfigIOParseException unable to find file or parse data. */ private PropertyDocument readConfigFile(String hwInventoryFile) throws IOException, ConfigIOParseException { return LoadFileLocation.fromFileLocation(hwInventoryFile); } private String hwInventoryConfigPath_; private String hwInventoryQueryPath_; private String hwInventoryConfigFile_; private final static String HW_INV_LOC_FILE_EXT = ".json"; private final static String HW_INV_QRY_FILE_EXT = ".json"; }
jht1493/p5js-repo
p5-projects/2:5 Display string split/sketch.js
<reponame>jht1493/p5js-repo<gh_stars>0 let str = "The quick brown fox jumped over the lazy dog."; let p; function setup() { createCanvas(400, 400); // Display string in paragraph element p = createP(str); textSize(48); textAlign(LEFT, TOP); // Split string into words let words = str.split(' '); print('words', words); let x = 0; let y = 0; for (let word of words) { text(word, x, y); x += textWidth(word) + textWidth(' '); if (x > width - 50) { x = 10; y += textAscent() + textDescent(); } } }
ThomasBDZ/JAVAFX-Application
src/main/java/eu/telecomnancy/javafx/model/GestionnaireCreneauDispo.java
package eu.telecomnancy.javafx.model; import java.util.ArrayList; import java.util.Date; public class GestionnaireCreneauDispo { public GestionnaireCreneauDispo(){ } public ArrayList<Creneau> pickDispoWeek(Date date, Utilisateur user ){ ArrayList<Creneau> liste=new ArrayList<>(); return liste; } }
ZhnZhn/notes
js/component/zhn-ch/DrawerLeft.js
<reponame>ZhnZhn/notes<gh_stars>1-10 "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); exports.__esModule = true; exports["default"] = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _useToggle2 = _interopRequireDefault(require("../hooks/useToggle")); var _useTheme = _interopRequireDefault(require("../hooks/useTheme")); var _Comp = _interopRequireDefault(require("../style/Comp.Style")); var _jsxRuntime = require("react/jsx-runtime"); var CL = { DRAWER_BT: 'drawer-bt', DRAWER_SPAN: 'drawer-span', DRAWER_SVG: 'drawer-svg', DRAWER: 'drawer-left', DRAWER_MODAL: 'drawer-modal' }; var S = { BT_DRAWER: { width: 'auto', height: 'auto' }, DRAWER_OFF: { transform: 'translateX(-264px)', //transform: 'translateX(264px)', pointerEvents: 'none' }, DRAWER_ON: { transform: 'translate(0px, 0px)' }, MODAL_OFF: { opacity: 0, zIndex: -1, transition: 'opacity 195ms cubic-bezier(0.4, 0, 0.2, 1) 0ms' }, MODAL_ON: { opacity: 1, zIndex: 1000, transition: 'opacity 225ms cubic-bezier(0.4, 0, 0.2, 1) 0ms' } }; var DrawerLeft = function DrawerLeft(_ref) { var btStyle = _ref.btStyle, captionComp = _ref.captionComp, children = _ref.children; var _useToggle = (0, _useToggle2["default"])(false), isOpen = _useToggle[0], toggleIsOpen = _useToggle[1], TS = (0, _useTheme["default"])(_Comp["default"]), _drawerStyle = isOpen ? S.DRAWER_ON : S.DRAWER_OFF, _drawerModalStyle = isOpen ? S.MODAL_ON : S.MODAL_OFF, _onClickWrapper = isOpen ? toggleIsOpen : void 0; return [/*#__PURE__*/(0, _jsxRuntime.jsx)("button", { className: CL.DRAWER_BT, style: (0, _extends2["default"])({}, S.BT_DRAWER, btStyle), "aria-label": "Open Drawer", onClick: toggleIsOpen, children: captionComp }, "bt-drawer"), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { "aria-hidden": !isOpen, className: CL.DRAWER_MODAL, style: _drawerModalStyle, onClick: _onClickWrapper }, "wrapper"), /*#__PURE__*/(0, _jsxRuntime.jsx)("aside", { className: CL.DRAWER, style: (0, _extends2["default"])({}, _drawerStyle, TS.COMP), children: children }, "aside")]; }; var _default = DrawerLeft; exports["default"] = _default; //# sourceMappingURL=DrawerLeft.js.map
Shaditto/centipede-teal
CentipedeGame_gageoconnor/Game Components/TEAL/CollisionInfoAABB.cpp
<filename>CentipedeGame_gageoconnor/Game Components/TEAL/CollisionInfoAABB.cpp // CollisionInfoAABB.h // <NAME>, July 2012 #include "CollisionInfoAABB.h" bool CollisionInfoAABB::PairwiseCollisionTest( CollisionInfo *other ) { return other->CollisionTest( &( getAABB()) ); } bool CollisionInfoAABB::CollisionTest( sf::FloatRect *r ) { return getAABB().intersects(*r); } bool CollisionInfoAABB::CollisionTest( sf::Shape *s) { return CollisionTools::RectangleShapeIntersection( getAABB(), *s ); } bool CollisionInfoAABB::CollisionTest( sf::Sprite *s, CollisionTools::TextureBitmap *b ) { return CollisionTools::RectangleSpriteIntersection( getAABB(), *s, *b); }
1310238398/park-asset
internal/app/bll/impl/internal/b_common.go
<reponame>1310238398/park-asset package internal import ( "context" "fmt" "gxt-park-assets/internal/app/errors" "gxt-park-assets/internal/app/config" icontext "gxt-park-assets/internal/app/context" "gxt-park-assets/internal/app/model" "gxt-park-assets/internal/app/schema" "gxt-park-assets/pkg/logger" "gxt-park-assets/pkg/util" ) // GetRootUser 获取root用户 func GetRootUser() *schema.User { user := config.GetGlobalConfig().Root return &schema.User{ RecordID: user.UserName, UserName: user.UserName, RealName: user.RealName, Password: util.MD5HashString(user.Password), } } // CheckIsRootUser 检查是否是root用户 func CheckIsRootUser(ctx context.Context, userID string) bool { return GetRootUser().RecordID == userID } // GetUserID 获取用户ID func GetUserID(ctx context.Context) string { userID, _ := icontext.FromUserID(ctx) return userID } // TransFunc 定义事务执行函数 type TransFunc func(context.Context) error // ExecTrans 执行事务 func ExecTrans(ctx context.Context, transModel model.ITrans, fn TransFunc) error { if _, ok := icontext.FromTrans(ctx); ok { return fn(ctx) } trans, err := transModel.Begin(ctx) if err != nil { return err } err = fn(icontext.NewTrans(ctx, trans)) if err != nil { _ = transModel.Rollback(ctx, trans) return err } return transModel.Commit(ctx, trans) } // GetSystemParameterValue 获取系统参数值 func GetSystemParameterValue(ctx context.Context, mSystemParameter model.ISystemParameter, code string) (util.S, error) { result, err := mSystemParameter.Query(ctx, schema.SystemParameterQueryParam{ Status: 1, Code: code, }) if err != nil { return "", err } else if len(result.Data) > 0 { return util.S(result.Data[0].Value), nil } return "", nil } // DefaultSystemParameterValue 获取系统参数值(如果出现错误或值为空,则使用默认值) func DefaultSystemParameterValue(ctx context.Context, mSystemParameter model.ISystemParameter, code, defValue string) util.S { val, err := GetSystemParameterValue(ctx, mSystemParameter, code) if err != nil || val == "" { if err != nil { logger.StartSpan(ctx, logger.SetSpanTitle("查询系统参数")).WithField("code", code).Errorf(err.Error()) } return util.S(defValue) } return val } // GetCostTemplate 获取成本模板 func GetCostTemplate(ctx context.Context, mCostItem model.ICostItem) (schema.CostItems, error) { ps := schema.CostItemQueryParam{} cir, err := mCostItem.Query(ctx, ps) if err != nil { return nil, err } result := schema.CostItems{} for _, v := range cir.Data { if v.ParentID == "" { result = append(result, v) } else { for _, k := range cir.Data { if k.RecordID == v.ParentID { k.Children = append(k.Children, v) break } } } } return result, nil } // GetTaxPrice 计算税金 func GetTaxPrice(ctx context.Context, mTaxCalculation model.ITaxCalculation, price float64, taxID string, taxRate float64) (float64, float64, error) { /* 本方法限于成本测算中各成本项的计税 土地增值税,地方附加税等通过按名称查询指定税率的方式查询 */ var taxPrice float64 //取税 tax, err := mTaxCalculation.Get(ctx, taxID) if err != nil { return 0, 0, err } if tax == nil { if taxRate == 0 { return 0, 0, nil } // 默认计税 taxPrice = price * taxRate / (1 + taxRate) return taxPrice, taxRate, nil } if taxRate == 0 { taxRate = tax.TaxRate } //计税 if tax.Type == 1 { taxPrice = price * taxRate / (1 + taxRate) } else if tax.Type == 2 { taxPrice = price * taxRate } return taxPrice, taxRate, nil } // GetTaxRate 获取税率(根据税名) func GetTaxRate(ctx context.Context, mTaxCalculation model.ITaxCalculation, name string, defRate ...float64) (float64, error) { if name == "" { return 0, nil } tax, err := mTaxCalculation.GetByName(ctx, name) if err != nil { return 0, err } if tax == nil { if len(defRate) > 0 { return defRate[0], nil } switch name { case schema.TAX_ADDITIONAL: return 0, errors.ErrNoTaxAdditional case schema.TAX_CONTRACT: return 0, errors.ErrNoTaxContract case schema.TAX_INCOME: return 0, errors.ErrNoTaxIncome case schema.TAX_OUTPUT: return 0, errors.ErrNoTaxOutput case schema.TAX_STAMP: return 0, errors.ErrNoTaxStamp case schema.TAX_USE: return 0, errors.ErrNoTaxUse } return 0, errors.New(fmt.Sprintf("未设置[%s]", name)) } return tax.TaxRate, nil }
FarfallaHu/brainchop
lib/webix/sources/services.js
// resolves circular dependencies // quick solution, must be removed in the next versions const services = {}; export function define(name, value){ services[name] = value; } export function use(name){ return services[name]; }
mmadfox/georule
internal/tracker/errors.go
package tracker import "errors" var ( ErrIdentifierNotDefined = errors.New("tracker/geojson: identifier not defined") ErrNoIndexData = errors.New("tracker/geojson: no index data") ErrInvalidGeoJSONData = errors.New("tracker/geojson: invalid GeoJSON data") )
SveinJH/TheWineBase
src/containers/Pages/Login/Login.js
import React, { useState } from 'react'; import { connect } from 'react-redux'; import * as actions from '../../../store/actions/index'; import classes from './Login.module.scss'; import Input from '../../../components/UI/Input/Input'; import Button from '../../../components/UI/Button/Button'; import { checkValidity } from '../../../shared/utility'; import login_image from '../../../images/login_img.svg'; import Spinner from '../../../components/UI/Spinner/Spinner'; const Login = (props) => { const [inputFormData, setInputFormData] = useState({ email: { elementType: 'input', elementConfig: { type: 'email', label: 'E-post', }, value: '', validation: { email: true, minLength: 3, required: true, }, valid: false, touched: false, }, password: { elementType: 'input', elementConfig: { type: 'password', label: 'Passord', }, value: '', validation: { minLength: 6, required: true, }, valid: false, touched: false, }, }); const [isSignup, setIsSignup] = useState(false); const [validForm, setValidForm] = useState(false); const submitHandler = (event) => { event.preventDefault(); const userData = { email: inputFormData.email.value, password: inputFormData.password.value, }; if (validForm && isSignup) { props.onCreate(userData); } else if (validForm && !isSignup) { props.onLogin(userData); } }; const inputChangedHandler = (event, controlName) => { const updatedInputFormData = { ...inputFormData, [controlName]: { ...inputFormData[controlName], value: event.target.value, valid: checkValidity( event.target.value, inputFormData[controlName].validation ), touched: true, }, }; let formIsValid = true; for (let inputID in updatedInputFormData) { formIsValid = updatedInputFormData[inputID].valid && formIsValid; } setInputFormData(updatedInputFormData); setValidForm(formIsValid); }; const formElements = Object.keys(inputFormData).map((el) => { return { id: el, config: inputFormData[el], }; }); let form = formElements.map((formElement) => { return ( <Input key={formElement.id} elementType={formElement.config.elementType} elementConfig={formElement.config.elementConfig} value={formElement.config.value} invalid={!formElement.config.valid} shouldValidate={formElement.config.validation} touched={formElement.config.touched} changed={(event) => inputChangedHandler(event, formElement.id)} /> ); }); return ( <div className={classes.Login}> <div className={classes.Login__image}> <img src={login_image} alt="" /> </div> <div className={classes.Login__info}> <div className="heading-1">The Wine Base</div> <div className={classes.Login__error}> {props.error ? <>{props.error.message}</> : null} </div> <div className={classes.Login__success}> {props.userCreated ? <>Vennligst bekreft e-posten</> : null} </div> {!props.loading ? ( <form className={classes.Login__form} onSubmit={submitHandler} > {form} <Button btnType="Default" disabled={!validForm}> {!isSignup ? 'LOGG INN' : 'REGISTRER'} </Button> </form> ) : ( <Spinner /> )} {!props.loading && ( <div> {!isSignup ? 'Ikke registrert? ' : 'Allerede registrert? '} <span className={classes.ChangeMode} onClick={() => setIsSignup(!isSignup)} > {!isSignup ? 'Lag en bruker' : 'Logg inn.'} </span> </div> )} <div className={classes.Disclaimer}> <br /> <br /> Denne nettsiden er på ingen måte ferdig enda. Dette er et hobbyprosjekt og er publisert for å vise fremgangen. </div> </div> </div> ); }; const mapStateToProps = (state) => { return { error: state.auth.error, userCreated: state.auth.userCreated, loading: state.auth.loading, }; }; const mapDispatchToProps = (dispatch) => { return { onCreate: (userData) => dispatch(actions.createUser(userData)), onLogin: (userData) => dispatch(actions.loginUser(userData)), }; }; export default connect(mapStateToProps, mapDispatchToProps)(Login);
GypsyDangerous/auth-app-client
src/components/Auth/Register.js
import React, {forwardRef} from "react"; import Input from "../shared/FormElements/Input"; import Form, { ButtonContainer, Footer } from "./Form.styled"; import MailIcon from "@material-ui/icons/Mail"; import { PlaceHolder } from "./Auth.styled"; import LockIcon from "@material-ui/icons/Lock"; import Button from "../shared/FormElements/Button"; import { Link } from "react-router-dom"; import IconButton from "../shared/IconButton"; import Icons from "./Icons"; import PersonIcon from "@material-ui/icons/Person"; import { useForm } from "../../hooks/form-hook"; import { useHttpClient } from "../../hooks/http-hook"; import { useAuth } from "../../hooks/auth-hook"; import ErrorText from "../shared/Error.styled"; import { motion } from "framer-motion"; import { VALIDATOR_EMAIL, VALIDATOR_MAXLENGTH, VALIDATOR_MINLENGTH, VALIDATOR_REQUIRE } from "../../utils/validators"; const Register = forwardRef(({passdownRef, ...props}) => { const [formState, inputHandler, setFormData] = useForm( { username: { value: "", isValid: false, }, email: { value: "", isValid: false, }, password: { value: "", isValid: false, }, }, false ); const { token, login, logout, userId, isLoggedIn } = useAuth(); const { isLoading, error, sendRequest, clearError } = useHttpClient(); const handleFormSubmit = async e => { e.preventDefault(); const body = { username: formState.inputs.username.value, email: formState.inputs.email.value, password: formState.inputs.password.value, }; const response = await sendRequest( `${process.env.REACT_APP_API_URL}/api/v1/auth/register`, "POST", JSON.stringify(body), { "Content-Type": "application/json", } ); if (response) { login(response.userId, response.token); } }; return ( <> <h1>Join thousands of learners from around the world </h1> <p> Master web development by making real-life projects. There are multiple paths for you to choose </p> <Form onSubmit={handleFormSubmit}> <Input onInput={inputHandler} placeholder={ <PlaceHolder style={{ display: "flex", alignItems: "center" }}> <span style={{ marginRight: "1rem" }}> <PersonIcon /> </span>{" "} Username </PlaceHolder> } validators={[VALIDATOR_REQUIRE()]} helpText="Username is required" type="text" name="username" id="username" required /> <Input onInput={inputHandler} placeholder={ <PlaceHolder style={{ display: "flex", alignItems: "center" }}> <span style={{ marginRight: "1rem" }}> <MailIcon /> </span>{" "} Email </PlaceHolder> } validators={[VALIDATOR_REQUIRE(), VALIDATOR_EMAIL()]} helpText="Invalid or Missing Email" type="email" name="email" id="email" required /> <Input onInput={inputHandler} placeholder={ <PlaceHolder style={{ display: "flex", alignItems: "center" }}> <span style={{ marginRight: "1rem" }}> <LockIcon /> </span>{" "} Password </PlaceHolder> } validators={[VALIDATOR_REQUIRE(), VALIDATOR_MINLENGTH(6)]} helpText="Invalid Password, minimum 6 characters" type="password" id="password" name="create-password" required /> {error && <ErrorText>{error}</ErrorText>} <ButtonContainer> <Button type="submit">Start Coding Now</Button> </ButtonContainer> </Form> <Footer> <p>or continue with one of these social profiles</p> <Icons /> <p> Already have an account? <Link to="/auth/login">Login</Link>{" "} </p> </Footer> </> ); }) export default Register;
sylvainr/entityset
sr.entityset.core/src/sr/entityset/EntityTable.java
<gh_stars>0 package sr.entityset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import org.apache.commons.lang.StringUtils; import sr.entityset.constraints.Constraint; import sr.entityset.constraints.ConstraintError; import sr.entityset.constraints.UniqueConstraint; import sr.entityset.exceptions.ConstraintViolationException; import sr.entityset.exceptions.InvalidNullValueException; import sr.entityset.exceptions.PrimaryKeyConstraintException; import sr.entityset.exceptions.RemovedRowAccessException; import sr.entityset.exceptions.WrongTypeException; import ca.odell.glazedlists.EventList; import ca.odell.glazedlists.GlazedLists; import ca.odell.glazedlists.ObservableElementList; import com.google.common.base.Function; import com.google.common.collect.Collections2; public class EntityTable { private String name; private List<EntityColumn> columns = null; private boolean allowStructuralChanges = true; private boolean rejectNullViolations = true; private UniqueConstraint primaryKeyConstraint = null; private List<Constraint> constraints = new ArrayList<Constraint>(); private List<Index> indexes = new ArrayList<Index>(); private ObservableElementList<EntityRow> visibleRows; private Collection<EntityRow> changedRows; private boolean isLoadingData = false; public EntityTable(String name) { this.name = name; EventList<EntityRow> rootlist = GlazedLists.eventList(new ArrayList<EntityRow>()); ObservableElementList<EntityRow> observableElementList = new ObservableElementList<EntityRow>( rootlist, GlazedLists.beanConnector(EntityRow.class)); this.visibleRows = observableElementList; this.changedRows = new HashSet<EntityRow>(); this.columns = new ArrayList<EntityColumn>(); } public EntityColumn addColumn(String name, Class<?> type, boolean allowNul) throws InvalidRowStateException { return this.internalAddColumn(name, type, false, allowNul); } public EntityColumn addColumn(String name, Class<?> type) throws InvalidRowStateException { return this.internalAddColumn(name, type, false, false); } public EntityColumn addPrimaryKeyColumn(String name, Class<?> type) throws InvalidRowStateException { return this.internalAddColumn(name, type, true, false); } public List<EntityColumn> getColumns() { return columns; } public List<Index> getIndexes() { return indexes; } public void addIndex(String... indexColumnNames) { EntityColumn[] indexedColumns = Collections2.transform( Arrays.asList(indexColumnNames), new Function<String, EntityColumn>() { @Override public EntityColumn apply(String arg0) { return getColumn(arg0); } }).toArray(new EntityColumn[] {}); this.indexes.add(new Index(this, indexedColumns)); } /*** * Get a column from its name * @param columnName Name of the column * @return the column if found, else returns null */ public EntityColumn getColumn(String columnName) { for(EntityColumn col : this.getColumns()) { if (col.getName().equals(columnName)) return col; } return null; } public EntityRow newRow() { EntityRow row = new EntityRow(this); return row; } public void addRow(EntityRow row) throws InvalidRowStateException, PrimaryKeyConstraintException, InvalidNullValueException, WrongTypeException { if (row.getState() != RowState.Detached) throw new InvalidRowStateException( "Can not add a row which state is " + row.getState().toString()); if (!this.isLoadingData) ensureValidatesBeforeAdding(row.getObjectArray()); this.internalAddRow(row); } /*** * Warning: adding row with addFastRow bypasses a lot * of the consistent-check logic, e.g. it does not keep * track of the state of the rows. * * May result in undefined behavior. * @param values */ public EntityRow addFastRow(Object... values) { EntityRow row = new EntityRow(this, values, RowState.Added); this.visibleRows.add(row); return row; } public void endAddingFastRow() { this.indexes = new ArrayList<Index>(); } public EntityRow addRow(Object... values) throws IllegalArgumentException, InvalidRowStateException, PrimaryKeyConstraintException, InvalidNullValueException, WrongTypeException { if (values.length != this.columns.size()) throw new IllegalArgumentException("Passed value array size (" + values.length + ") is not the same as the number of columns in the table (" + this.columns.size() + ")"); EntityRow row = this.newRow(); row.setObjectArray(values); this.addRow(row); return row; } public void removeRow(EntityRow row) throws InvalidRowStateException { this.internalRemoveRow(row); } public Collection<EntityRow> changedRows() { return this.changedRows; } public ObservableElementList<EntityRow> rows() { return this.visibleRows; } public String getName() { return name; } public void acceptChanges() { for(EntityRow row : this.visibleRows) row.setState(RowState.Unchanged); for(EntityRow changedRow : this.changedRows) changedRow.acceptChanges(); this.changedRows.clear(); } public Collection<EntityColumn> getPrimaryKeyColumns() { if (this.primaryKeyConstraint == null) return new ArrayList<EntityColumn>(); else return this.primaryKeyConstraint.getColumns(); } public EntityRow findByPrimaryKey(Object singleColumnPrimaryKeyValue) { return this.findByPrimaryKey(new Object[] {singleColumnPrimaryKeyValue}); } public EntityRow findByPrimaryKey(Object... primaryKeyValues) { Index pkIndex = this.getPrimaryKeyIndex(); List<EntityRow> rows = pkIndex.findRows(primaryKeyValues); if (rows.size() > 1) throw new RuntimeException("Got " + rows.size() + " rows returned from primary key index for values '" + StringUtils.join(primaryKeyValues, ", ") + "' when expecting one or zero."); if (rows.size() == 1) return rows.get(0); else return null; } public void addConstraint(Constraint constraint) { this.constraints.add(constraint); } public Index getIndex(Collection<EntityColumn> columns) { EntityColumn[] requstedColumnsArray = columns.toArray(new EntityColumn[0]); for(Index index : this.indexes) { if (Arrays.equals(requstedColumnsArray, index.getColumns())) return index; } Index newIndex = new Index(this, requstedColumnsArray); this.indexes.add(newIndex); return newIndex; } public void beginLoadData() { this.isLoadingData = true; // reset indexes (they won't get updated as we add rows) this.indexes = new ArrayList<Index>(); } public void endLoadData() { // verify all constraints for(Constraint constraint : this.constraints) { for(EntityRow row : this.rows()) { ConstraintError result = constraint.validateExistingRow(row); throwExceptionIfViolation(constraint, result); } } this.isLoadingData = false; } public EntityColumn getDisplayColumn() { Collection<EntityColumn> validUniqueColumns = Collections2.transform( this.getConstraints(), new Function<Constraint, EntityColumn>() { @Override public EntityColumn apply(Constraint arg0) { if (arg0 instanceof UniqueConstraint) { UniqueConstraint uniqueConstraint = (UniqueConstraint)arg0; if (uniqueConstraint.getColumns().size() == 1) { EntityColumn uniqueColumn = uniqueConstraint. getColumns().toArray(new EntityColumn[0])[0]; if (uniqueColumn.getType().equals(String.class)) return uniqueColumn; } } return null; } }); for(EntityColumn col : this.getColumns()) { if (validUniqueColumns.contains(col)) if (this.getPrimaryKeyColumns().contains(col)) { if (col.getType().equals(String.class)) return col; } else return col; } throw new IllegalStateException( "Unable to find a display column for table " + this.getName() + " (table probably lacks a UniqueConstraint)"); } public List<Constraint> getConstraints() { return this.constraints; } public boolean isRejectNullViolations() { return rejectNullViolations; } public void setRejectNullViolations(boolean rejectNullViolations) { this.ensureCanDoStructuralChanges(); this.rejectNullViolations = rejectNullViolations; } public Index getPrimaryKeyIndex() { return this.getIndex(this.getPrimaryKeyColumns()); } public boolean isChanged() { return this.changedRows.size() > 0; } ////////////////////////////////////////////////////////////////////////////////////////////// void onCellValueModificationProposed(EntityRow modifiedRow, Object proposedValue, EntityColumn modifiedCellColumn) throws PrimaryKeyConstraintException, RemovedRowAccessException { if (modifiedRow.getState().equals(RowState.Removed)) throw new RemovedRowAccessException(); ensureNoConstraintViolationsOnModifying(proposedValue, modifiedCellColumn, modifiedRow); //this.internalModifiedRow(modifiedRow); } void onCellValueModificationCommitted(EntityRow row, Object value, EntityColumn column) { this.internalModifiedRow(row); } /////////////////////////////////////////////////////////////////////////////////////////////// private void ensureValidatesBeforeAdding(Object[] valueArray) throws PrimaryKeyConstraintException, InvalidNullValueException, WrongTypeException { // check valid null-state and data-type for(EntityColumn column : this.columns) { Object curValue = valueArray[column.getNumber()]; boolean isPrimaryKeyField = this.getPrimaryKeyColumns().contains(column); if (curValue == null && column.getAllowNull() == false && (this.rejectNullViolations || isPrimaryKeyField)) throw new InvalidNullValueException(column.getName()); if (curValue != null && curValue.getClass().equals(column.getType()) == false) throw new WrongTypeException(column.getType(), curValue.getClass(), column.getName()); } ensureNoConstraintViolationsOnAdding(valueArray); } private void ensureNoConstraintViolationsOnAdding(Object[] valueArray) { for(Constraint constraint : this.constraints) { ConstraintError result = constraint.validatePropositionOnRowAdding(valueArray); throwExceptionIfViolation(constraint, result); } } private void throwExceptionIfViolation(Constraint constraint, ConstraintError result) { if (result != null) if (constraint == this.primaryKeyConstraint) throw new PrimaryKeyConstraintException(result.getMessage()); else throw new ConstraintViolationException(result.getMessage()); } private void ensureNoConstraintViolationsOnModifying( Object proposedValue, EntityColumn modifyingColumn, EntityRow modifyingRow) { for(Constraint constraint : this.constraints) { ConstraintError result = constraint. validatePropositionOnRowModifiying( modifyingRow, proposedValue, modifyingColumn); throwExceptionIfViolation(constraint, result); } } private void ensureNoConstraintViolationsOnRemoving(EntityRow removingRow) { for(Constraint constraint : this.constraints) { ConstraintError result = constraint. validatePropositionOnRowRemoving(removingRow); if (result != null) throw new ConstraintViolationException(result.getMessage()); } } private EntityColumn internalAddColumn(String name, Class<?> type, boolean isPrimaryKey, boolean allowNull) { ensureCanDoStructuralChanges(); EntityColumn col = new EntityColumn(this, this.columns.size(), name, type, allowNull); this.columns.add(col); if (isPrimaryKey) this.internalAddPrimaryKeyColumn(col); return col; } private void internalAddPrimaryKeyColumn(EntityColumn col) { Collection<EntityColumn> incumbentPrimaryKeyColumns = null; if (this.primaryKeyConstraint == null) incumbentPrimaryKeyColumns = new ArrayList<EntityColumn>(); else { incumbentPrimaryKeyColumns = this.primaryKeyConstraint.getColumns(); this.constraints.remove(this.primaryKeyConstraint); } incumbentPrimaryKeyColumns.add(col); this.primaryKeyConstraint = new UniqueConstraint( "PrimaryKeyConstraint", this, incumbentPrimaryKeyColumns, true); this.constraints.add(this.primaryKeyConstraint); } private void internalAddRow(EntityRow row) { this.allowStructuralChanges = false; this.visibleRows.add(row); for(Index index : indexes) index.updateOnRowAdded(row); row.setState(RowState.Added); this.changedRows.add(row); } private void internalModifiedRow(EntityRow row) { for(Index index : indexes) index.updateOnRowModified(row); // if row state is Added: do nothing if (row.getState().equals(RowState.Unchanged)) { row.setState(RowState.Modified); this.changedRows.add(row); } } private void internalRemoveRow(EntityRow row) throws InvalidRowStateException { if (row.getState().equals(RowState.Detached)) throw new InvalidRowStateException( "Can not remove detached row"); this.ensureNoConstraintViolationsOnRemoving(row); this.visibleRows.remove(row); if (row.getState().equals(RowState.Added)) { this.changedRows.remove(row); row.setState(RowState.Detached); } else if (row.getState().equals(RowState.Unchanged)) { this.changedRows.add(row); row.setState(RowState.Removed); } else if (row.getState().equals(RowState.Modified)) { row.setState(RowState.Removed); } for(Index index : indexes) index.updateOnRowRemoved(row); } private void ensureCanDoStructuralChanges() { if (this.allowStructuralChanges == false) throw new IllegalStateException("Can not change table structure " + "after table started handling data."); } }
KAKA0607/Sermant
sermant-agentcore/sermant-agentcore-core/src/test/java/com/huawei/sermant/core/lubanops/integration/netty/NettyClientTest.java
<reponame>KAKA0607/Sermant /* * Copyright (C) 2021-2021 Huawei Technologies Co., Ltd. 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 com.huawei.sermant.core.lubanops.integration.netty; import static org.mockito.Mockito.mock; import com.huawei.sermant.core.lubanops.integration.transport.netty.client.ClientHandler; import com.huawei.sermant.core.lubanops.integration.transport.netty.client.NettyClient; import com.huawei.sermant.core.lubanops.integration.transport.netty.pojo.Message; import io.netty.channel.embedded.EmbeddedChannel; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * ClientHandler单元测试 */ public class NettyClientTest { private NettyClient nettyClient; @Before public void setUp() { nettyClient = mock(NettyClient.class); } /** * 测试入站消息 */ @Test public void testWriteInBound() { EmbeddedChannel embeddedChannel = new EmbeddedChannel(new ClientHandler(nettyClient)); boolean writeInBound = embeddedChannel.writeInbound(Message.ServiceData.newBuilder().build()); Assert.assertTrue(writeInBound); Assert.assertTrue(embeddedChannel.finish()); Object object = embeddedChannel.readInbound(); Assert.assertNotNull(object); } /** * 测试出站消息 */ @Test public void testWriteOutBound() { EmbeddedChannel embeddedChannel = new EmbeddedChannel(new ClientHandler(nettyClient)); boolean writeOutBound = embeddedChannel.writeOutbound(Message.ServiceData.newBuilder().build()); Assert.assertTrue(writeOutBound); Assert.assertTrue(embeddedChannel.finish()); Object object = embeddedChannel.readOutbound(); Assert.assertNotNull(object); } }
jokermonn/fresco
drawee/src/main/java/com/facebook/drawee/debug/listener/ImageLoadingTimeControllerListener.java
<reponame>jokermonn/fresco /* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.drawee.debug.listener; import android.graphics.drawable.Animatable; import com.facebook.drawee.controller.BaseControllerListener; import com.facebook.infer.annotation.Nullsafe; import javax.annotation.Nullable; /** * Currently we are measuring this from Submit to Final Image.But can be extended to include * intermediate time and failure cases also */ @Nullsafe(Nullsafe.Mode.STRICT) public class ImageLoadingTimeControllerListener extends BaseControllerListener { private long mRequestSubmitTimeMs = -1l; private long mFinalImageSetTimeMs = -1l; private @Nullable ImageLoadingTimeListener mImageLoadingTimeListener; public ImageLoadingTimeControllerListener( @Nullable ImageLoadingTimeListener imageLoadingTimeListener) { mImageLoadingTimeListener = imageLoadingTimeListener; } @Override public void onSubmit(String id, Object callerContext) { mRequestSubmitTimeMs = System.currentTimeMillis(); } @Override public void onFinalImageSet( String id, @Nullable Object imageInfo, @Nullable Animatable animatable) { mFinalImageSetTimeMs = System.currentTimeMillis(); if (mImageLoadingTimeListener != null) { mImageLoadingTimeListener.onFinalImageSet(mFinalImageSetTimeMs - mRequestSubmitTimeMs); } } }
koellingh/empirical-p53-simulator
third-party/Empirical/examples/datastructs/TypeMap.cpp
<filename>third-party/Empirical/examples/datastructs/TypeMap.cpp // This file is part of Empirical, https://github.com/devosoft/Empirical // Copyright (C) Michigan State University, 2018. // Released under the MIT Software license; see doc/LICENSE // // // Some example code for using emp::BitSet #include <iostream> #include <string> #include "emp/datastructs/TypeMap.hpp" int main() { std::cout << "TypeMap Example.\n"; emp::TypeMap<std::string> type_map; type_map.Get<bool>() = "This is a bool."; type_map.Get<double>() = "This is a double."; type_map.Get<int>() = "This is an int."; type_map.Get<std::string>() = "This is an std::string."; std::cout << "Bool message: " << type_map.Get<bool>() << std::endl; std::cout << "Double message: " << type_map.Get<double>() << std::endl; std::cout << "Int message: " << type_map.Get<int>() << std::endl; std::cout << "String message: " << type_map.Get<std::string>() << std::endl; }
seeker/commonj
src/main/java/com/github/dozedoff/commonj/io/StreamGobbler.java
<gh_stars>0 /* * The MIT License (MIT) * Copyright (c) 2017 <NAME> * http://opensource.org/licenses/MIT */ package com.github.dozedoff.commonj.io; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class for consuming data provided by {@link InputStream}s. * Based on "When Runtime.exec() won't" from http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html */ public class StreamGobbler extends Thread { private InputStream is; private final static Logger LOGGER = LoggerFactory.getLogger(StreamGobbler.class); private StringBuilder messageBuffer; /** * Create a new {@link StreamGobbler} to consume the {@link InputStream}. * * @param is * to consume */ public StreamGobbler(InputStream is) { this.is = is; this.messageBuffer = new StringBuilder(); } /** * Get the currently buffered text from the {@link InputStream}. * * @return all the text that has been buffered so far */ public String getBuffer() { return messageBuffer.toString(); } public void run() { try { InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { messageBuffer.append(line); } } catch (IOException ioe) { LOGGER.error("", ioe); } } }
KonBAI-Q/RuoYi-Flowable-Plus-
ruoyi-system/src/main/java/com/ruoyi/workflow/domain/bo/WfCategoryBo.java
package com.ruoyi.workflow.domain.bo; import com.ruoyi.common.core.domain.BaseEntity; import com.ruoyi.common.core.validate.AddGroup; import com.ruoyi.common.core.validate.EditGroup; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * 流程分类业务对象 * * @author KonBAI * @date 2022-01-15 */ @Data @EqualsAndHashCode(callSuper = true) @ApiModel("流程分类业务对象") public class WfCategoryBo extends BaseEntity { /** * 分类ID */ @ApiModelProperty(value = "分类ID", required = true) @NotNull(message = "分类ID不能为空", groups = { EditGroup.class }) private Long categoryId; /** * 分类名称 */ @ApiModelProperty(value = "分类名称", required = true) @NotBlank(message = "分类名称不能为空", groups = { AddGroup.class, EditGroup.class }) private String categoryName; /** * 分类编码 */ @ApiModelProperty(value = "分类编码", required = true) @NotBlank(message = "分类编码不能为空", groups = { AddGroup.class, EditGroup.class }) private String code; /** * 备注 */ @ApiModelProperty(value = "备注", required = true) @NotBlank(message = "备注不能为空", groups = { AddGroup.class, EditGroup.class }) private String remark; }
eneufeld/emfcloud-modelserver
bundles/org.eclipse.emfcloud.modelserver.emf/src/org/eclipse/emfcloud/modelserver/emf/common/DefaultSchemaController.java
/******************************************************************************** * Copyright (c) 2019 EclipseSource and others. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * https://www.eclipse.org/legal/epl-2.0, or the MIT License which is * available at https://opensource.org/licenses/MIT. * * SPDX-License-Identifier: EPL-2.0 OR MIT ********************************************************************************/ package org.eclipse.emfcloud.modelserver.emf.common; import static org.eclipse.emfcloud.modelserver.emf.common.util.ContextResponse.notFound; import static org.eclipse.emfcloud.modelserver.emf.common.util.ContextResponse.success; import org.eclipse.emfcloud.modelserver.jsonschema.JsonSchemaConverter; import com.google.inject.Inject; import io.javalin.http.Context; public class DefaultSchemaController implements SchemaController { private final ModelRepository modelRepository; private final SchemaRepository schemaRepository; private final JsonSchemaConverter jsonSchemaConverter; @Inject public DefaultSchemaController(final ModelRepository modelRepository, final SchemaRepository schemaRepository, final JsonSchemaConverter jsonSchemaCreator) { this.modelRepository = modelRepository; this.schemaRepository = schemaRepository; this.jsonSchemaConverter = jsonSchemaCreator; } @Override public void getTypeSchema(final Context ctx, final String modeluri) { this.modelRepository.getModel(modeluri).ifPresentOrElse( instance -> success(ctx, this.jsonSchemaConverter.from(instance)), () -> notFound(ctx, "Type schema for '%s' not found!", modeluri)); } @Override public void getUiSchema(final Context ctx, final String schemaname) { this.schemaRepository.loadUiSchema(schemaname).ifPresentOrElse( jsonNode -> success(ctx, jsonNode), () -> notFound(ctx, "UI schema for '%s' not found!", schemaname)); } }
naaytesting2/gitlab-pages-mirror
internal/source/disk/map_test.go
package disk import ( "crypto/rand" "fmt" "io/ioutil" "os" "strings" "testing" "time" "github.com/karrick/godirwalk" "github.com/stretchr/testify/require" "gitlab.com/gitlab-org/gitlab-pages/internal/testhelpers" ) func getEntries(t require.TestingT) godirwalk.Dirents { fis, err := godirwalk.ReadDirents(".", nil) require.NoError(t, err) return fis } func TestReadProjects(t *testing.T) { cleanup := setUpTests(t) defer cleanup() dm := make(Map) dm.ReadGroups("test.io", getEntries(t)) var domains []string for d := range dm { domains = append(domains, d) } expectedDomains := []string{ "group.test.io", "group.internal.test.io", "test.domain.com", // from config.json "other.domain.com", "domain.404.com", "group.404.test.io", "group.https-only.test.io", "test.my-domain.com", "test2.my-domain.com", "no.cert.com", "private.domain.com", "group.auth.test.io", "group.acme.test.io", "withacmechallenge.domain.com", "capitalgroup.test.io", "group.404.gitlab-example.com", "group.redirects.test.io", "redirects.custom-domain.com", } for _, expected := range domains { require.Contains(t, domains, expected) } for _, actual := range domains { require.Contains(t, expectedDomains, actual) } // Check that multiple domains in the same project are recorded faithfully require.Equal(t, "test.domain.com", dm["test.domain.com"].Name) require.Equal(t, "other.domain.com", dm["other.domain.com"].Name) require.Equal(t, "test", dm["other.domain.com"].CertificateCert) require.Equal(t, "key", dm["other.domain.com"].CertificateKey) // check subgroups domain, ok := dm["group.test.io"] require.True(t, ok, "missing group.test.io domain") subgroup, ok := domain.Resolver.(*Group).subgroups["subgroup"] require.True(t, ok, "missing group.test.io subgroup") _, ok = subgroup.projects["project"] require.True(t, ok, "missing project for subgroup in group.test.io domain") } func TestReadProjectsMaxDepth(t *testing.T) { nGroups := 3 levels := subgroupScanLimit + 5 cleanup := buildFakeDomainsDirectory(t, nGroups, levels) defer cleanup() defaultDomain := "test.io" dm := make(Map) dm.ReadGroups(defaultDomain, getEntries(t)) var domains []string for d := range dm { domains = append(domains, d) } var expectedDomains []string for i := 0; i < nGroups; i++ { expectedDomains = append(expectedDomains, fmt.Sprintf("group-%d.%s", i, defaultDomain)) } for _, expected := range domains { require.Contains(t, domains, expected) } for _, actual := range domains { // we are not checking config.json domains here if !strings.HasSuffix(actual, defaultDomain) { continue } require.Contains(t, expectedDomains, actual) } // check subgroups domain, ok := dm["group-0.test.io"] require.True(t, ok, "missing group-0.test.io domain") subgroup := domain.Resolver.(*Group) for i := 0; i < levels; i++ { subgroup, ok = subgroup.subgroups["sub"] if i <= subgroupScanLimit { require.True(t, ok, "missing group-0.test.io subgroup at level %d", i) _, ok = subgroup.projects["project-0"] require.True(t, ok, "missing project for subgroup in group-0.test.io domain at level %d", i) } else { require.False(t, ok, "subgroup level %d. Maximum allowed nesting level is %d", i, subgroupScanLimit) break } } } // This write must be atomic, otherwise we cannot predict the state of the // domain watcher goroutine. We cannot use ioutil.WriteFile because that // has a race condition where the file is empty, which can get picked up // by the domain watcher. func writeRandomTimestamp(t *testing.T) { b := make([]byte, 10) n, _ := rand.Read(b) require.True(t, n > 0, "read some random bytes") temp, err := ioutil.TempFile(".", "TestWatch") require.NoError(t, err) _, err = temp.Write(b) require.NoError(t, err, "write to tempfile") require.NoError(t, temp.Close(), "close tempfile") require.NoError(t, os.Rename(temp.Name(), updateFile), "rename tempfile") } func TestWatch(t *testing.T) { cleanup := setUpTests(t) defer cleanup() require.NoError(t, os.RemoveAll(updateFile)) update := make(chan Map) go Watch("gitlab.io", func(dm Map) { update <- dm }, time.Microsecond*50) defer os.Remove(updateFile) domains := recvTimeout(t, update) require.NotNil(t, domains, "if the domains are fetched on start") writeRandomTimestamp(t) domains = recvTimeout(t, update) require.NotNil(t, domains, "if the domains are updated after the creation") writeRandomTimestamp(t) domains = recvTimeout(t, update) require.NotNil(t, domains, "if the domains are updated after the timestamp change") } func recvTimeout(t *testing.T, ch <-chan Map) Map { timeout := 5 * time.Second select { case dm := <-ch: return dm case <-time.After(timeout): t.Fatalf("timeout after %v waiting for domain update", timeout) return nil } } func buildFakeDomainsDirectory(t testing.TB, nGroups, levels int) func() { testRoot, err := ioutil.TempDir("", "gitlab-pages-test") require.NoError(t, err) for i := 0; i < nGroups; i++ { parent := fmt.Sprintf("%s/group-%d", testRoot, i) domain := fmt.Sprintf("%d.example.io", i) buildFakeProjectsDirectory(t, parent, domain) for j := 0; j < levels; j++ { parent = fmt.Sprintf("%s/sub", parent) domain = fmt.Sprintf("%d.%s", j, domain) buildFakeProjectsDirectory(t, parent, domain) } if testing.Verbose() && i%100 == 0 { fmt.Print(".") } } cleanup := testhelpers.ChdirInPath(t, testRoot, &chdirSet) return func() { defer cleanup() if testing.Verbose() { fmt.Printf("cleaning up test directory %s\n", testRoot) } os.RemoveAll(testRoot) } } func buildFakeProjectsDirectory(t require.TestingT, groupPath, domain string) { for j := 0; j < 5; j++ { dir := fmt.Sprintf("%s/project-%d", groupPath, j) require.NoError(t, os.MkdirAll(dir+"/public", 0755)) fakeConfig := fmt.Sprintf(`{"Domains":[{"Domain":"foo.%d.%s","Certificate":"bar","Key":"baz"}]}`, j, domain) require.NoError(t, ioutil.WriteFile(dir+"/config.json", []byte(fakeConfig), 0644)) } } // this is a safeguard against compiler optimizations // we use this package variable to make sure the benchmarkReadGroups loop // has side effects outside of the loop. // Without this the compiler (with the optimizations enabled) may remove the whole loop var result int func benchmarkReadGroups(b *testing.B, groups, levels int) { cleanup := buildFakeDomainsDirectory(b, groups, levels) defer cleanup() b.ResetTimer() domainsCnt := 0 for i := 0; i < b.N; i++ { dm := make(Map) dm.ReadGroups("example.com", getEntries(b)) domainsCnt = len(dm) } result = domainsCnt } func BenchmarkReadGroups(b *testing.B) { b.Run("10 groups 3 levels", func(b *testing.B) { benchmarkReadGroups(b, 10, 3) }) b.Run("100 groups 3 levels", func(b *testing.B) { benchmarkReadGroups(b, 100, 3) }) b.Run("1000 groups 3 levels", func(b *testing.B) { benchmarkReadGroups(b, 1000, 3) }) b.Run("10000 groups 1 levels", func(b *testing.B) { benchmarkReadGroups(b, 10000, 1) }) }
haotie1990/learn-javascript
js-interview-question/number-thousands.js
/** * 数字千分位处理 * 将 153812.7 转化为 153,812.7 */ function numberThousands(number) { const numberStr = String(number); let result = ''; let [interger, decimal] = numberStr.split('.'); while (interger.length > 3) { // 倒数三位数字 let subStr = interger.substring(interger.length - 3); interger = interger.replace(subStr, ''); result = `,${subStr}${result}`; } if (interger.length) { result = `${interger}${result}`; } return result + (decimal ? `.${decimal}` : ''); } function toString (number, thousandsSeperator = ',') { const s = String(number) let r = '' for (let i = s.length - 1; i >= 0; i--) { const seperator = (s.length - i - 1) % 3 ? '' : thousandsSeperator r = `${s[i]}${seperator}${r}` } return r.slice(0, -1) } console.log(numberThousands(812.7)); console.log(numberThousands(1812.7)); console.log(numberThousands(2321153812.7)); console.log(numberThousands(343153812.7)); console.log(numberThousands(342153812)); console.log(toString(812.7)); console.log(toString(1812.7)); console.log(toString(2321153812.7)); console.log(toString(343153812.7)); console.log(toString(342153812));
akash143143/weasyl
libweasyl/libweasyl/alembic/versions/cc2f96b0ba35_remove_unused_stream_time_column_from_.py
"""Remove unused stream_time column from profile table Revision ID: <KEY> Revises: <KEY> Create Date: 2020-02-27 23:19:49.133000 """ # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '<KEY>' from alembic import op # lgtm[py/unused-import] import sqlalchemy as sa # lgtm[py/unused-import] def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('profile', 'stream_time') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('profile', sa.Column('stream_time', sa.INTEGER(), autoincrement=False, nullable=True)) # ### end Alembic commands ###
bhimeshchauhan/competitive_programming
scripts/practice/Amazon/KthFactorofN.py
""" The kth Factor of n Given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0. Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors. Example 1: Input: n = 12, k = 3 Output: 3 Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3. Example 2: Input: n = 7, k = 2 Output: 7 Explanation: Factors list is [1, 7], the 2nd factor is 7. Example 3: Input: n = 4, k = 4 Output: -1 Explanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1. Example 4: Input: n = 1, k = 1 Output: 1 Explanation: Factors list is [1], the 1st factor is 1. Example 5: Input: n = 1000, k = 3 Output: 4 Explanation: Factors list is [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 250, 500, 1000]. Constraints: 1 <= k <= n <= 1000 """ class Solution: def kthFactor(self, n: int, k: int) -> int: for x in range(1, n // 2 + 1): if n % x == 0: k -= 1 if k == 0: return x return n if k == 1 else -1
zipated/src
media/audio/alsa/alsa_util.h
<reponame>zipated/src<gh_stars>1000+ // Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_AUDIO_ALSA_ALSA_UTIL_H_ #define MEDIA_AUDIO_ALSA_ALSA_UTIL_H_ #include <alsa/asoundlib.h> #include <string> namespace media { class AlsaWrapper; } namespace alsa_util { snd_pcm_t* OpenCaptureDevice(media::AlsaWrapper* wrapper, const char* device_name, int channels, int sample_rate, snd_pcm_format_t pcm_format, int latency_us); snd_pcm_t* OpenPlaybackDevice(media::AlsaWrapper* wrapper, const char* device_name, int channels, int sample_rate, snd_pcm_format_t pcm_format, int latency_us); int CloseDevice(media::AlsaWrapper* wrapper, snd_pcm_t* handle); snd_mixer_t* OpenMixer(media::AlsaWrapper* wrapper, const std::string& device_name); void CloseMixer(media::AlsaWrapper* wrapper, snd_mixer_t* mixer, const std::string& device_name); snd_mixer_elem_t* LoadCaptureMixerElement(media::AlsaWrapper* wrapper, snd_mixer_t* mixer); } // namespace alsa_util #endif // MEDIA_AUDIO_ALSA_ALSA_UTIL_H_
martijn-heil/NinCore-API
src/main/java/tk/martijn_heil/nincore/api/command/builders/CommandBuilder.java
package tk.martijn_heil.nincore.api.command.builders; import tk.martijn_heil.nincore.api.NinCore; import tk.martijn_heil.nincore.api.command.NinCommand; import tk.martijn_heil.nincore.api.command.NinSubCommand; import tk.martijn_heil.nincore.api.command.executors.NinCommandExecutor; import tk.martijn_heil.nincore.api.localization.LocalizedString; import org.bukkit.command.CommandExecutor; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.List; public class CommandBuilder { private String name; // Required private List<NinSubCommand> subCommands = new ArrayList<>(); // Optional private NinCommandExecutor executor; // Required private LocalizedString localizedDescription; private String requiredPermission; boolean useStaticDescription = false; private JavaPlugin plugin; public CommandBuilder(JavaPlugin plugin) { this.plugin = plugin; } /** * Set this command's name. This is case sensitive and must * mirror a command defined in your plugin.yml. * * @param name The name for this command. Case sensitive * @return {@link CommandBuilder}, for method chaining. */ public CommandBuilder setName(String name) { this.name = name; return this; } public CommandBuilder setLocalizedDescription(LocalizedString localizedDescription) { this.localizedDescription = localizedDescription; return this; } /** * Add a sub command to this command. * * @param subCommand The {@link NinSubCommand} to add. * @return {@link CommandBuilder}, for method chaining. */ public CommandBuilder addSubCommand(NinSubCommand subCommand) { this.subCommands.add(subCommand); return this; } /** * Set this command's executor. * * @param executor This command's {@link CommandExecutor} * @return {@link CommandBuilder}, for method chaining. */ public CommandBuilder setExecutor(NinCommandExecutor executor) { this.executor = executor; return this; } public CommandBuilder setUseStaticDescription(boolean value) { this.useStaticDescription = value; return this; } public CommandBuilder setRequiredPermission(String requiredPermission) { this.requiredPermission = requiredPermission; return this; } /** * Construct the command. * * @return The constructed {@link NinCommand}. */ public NinCommand construct() { return NinCore.get().getCommandImplementation().constructCommand(this.name, this.useStaticDescription, this.localizedDescription, this.requiredPermission, this.executor, this.subCommands, this.plugin); } }
vishalbelsare/smallk
common/include/matrix_generator.hpp
<filename>common/include/matrix_generator.hpp<gh_stars>10-100 // Copyright 2014 Georgia Institute of Technology // // 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. #pragma once #include <vector> #include <thread> #include <cassert> #include <iostream> #include <algorithm> #include "random.hpp" #include "thread_utils.hpp" namespace MatrixGenData { // use sequential code to initialize matrices with fewer than this many // elements; use parallel code for matrices larger than this static unsigned int CUTOFF = 32768; } //----------------------------------------------------------------------------- template <typename T> bool RandomMatrix(std::vector<T>& buf, const unsigned int height, // number of data rows, <= ldim const unsigned int width, // number of data cols Random& rng, const T rng_center = T(0.5), const T rng_radius = T(0.5)) { // Fill a matrix of dimension height x width with random numbers. // The matrix is stored in the buffer 'buf', which will be resized if // needed. typename std::vector<T>::size_type required_size = height*width; if (buf.size() < required_size) buf.resize(required_size); unsigned int max_threads = GetMaxThreadCount(); if ( (required_size < MatrixGenData::CUTOFF) || (1 == max_threads)) RandomMatrixSequential(&buf[0], height, height, width, rng, rng_center, rng_radius); else RandomMatrixParallel(&buf[0], height, height, width, rng, rng_center, rng_radius); return true; } //----------------------------------------------------------------------------- template <typename T> bool RandomMatrix(T* buf, const unsigned int ldim, // leading dimension of buffer const unsigned int height, // number of data rows, <= ldim const unsigned int width, // number of data cols Random& rng, const T rng_center = T(0.5), const T rng_radius = T(0.5)) { // Fill a column-major matrix with random numbers. // Assumes the buffer is large enough. uint64_t size = height * width; unsigned int max_threads = GetMaxThreadCount(); // if fewer than 16k elements use sequential code to avoid thread overhead if ( (size < MatrixGenData::CUTOFF) || (1 == max_threads)) RandomMatrixSequential(buf, ldim, height, width, rng, rng_center, rng_radius); else RandomMatrixParallel(buf, ldim, height, width, rng, rng_center, rng_radius); return true; } //----------------------------------------------------------------------------- // // H E L P E R F U N C T I O N S // // Not to be called from user code. Users should instead call one of the // 'RandomMatrix' functions above. // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- template <typename T> void ThreadFuncRank2W(const int rng_seed, const unsigned int num_threads, const unsigned int index, T* buf, const unsigned int ldim, const unsigned int height, const T rng_center, const T rng_radius) { // This thread function randomly initializes rank2 'W' matrices of // dimension height x 2. Each thread initializes a maximum of // 'height/num_threads' rows in each column. Random rng; rng.SeedFromInt(rng_seed); unsigned int num_elts = height / num_threads; unsigned int start = index * num_elts; unsigned int end = std::min(height, (index+1) * num_elts); // column 0 for (unsigned int r=start; r<end; ++r) buf[r] = (T) rng.RandomDouble(rng_center, rng_radius); // column 1 unsigned int offset = ldim; for (unsigned int r=start; r<end; ++r) buf[offset + r] = (T) rng.RandomDouble(rng_center, rng_radius); } //----------------------------------------------------------------------------- template <typename T> void ThreadFuncInitTall(const int rng_seed, const unsigned int num_threads, const unsigned int index, T* buf, const unsigned int ldim, const unsigned int height, const unsigned int width, const T rng_center, const T rng_radius) { // This thread function randomly initializes matrices having height > width. // Each thread initializes 'height/num_threads' rows in each column. assert(height > width); Random rng; rng.SeedFromInt(rng_seed); unsigned int num_rows = height / num_threads; unsigned int start = index * num_rows; unsigned int end = std::min(height, (index+1) * num_rows); for (unsigned int c=0; c<width; ++c) { unsigned int offset = c*ldim; for (unsigned int r=start; r<end; ++r) { buf[offset + r] = (T) rng.RandomDouble(rng_center, rng_radius); } } } //----------------------------------------------------------------------------- template <typename T> void ThreadFuncRank2H(const int rng_seed, const unsigned int num_threads, const unsigned int index, T* buf, const unsigned int ldim, const unsigned int width, const T rng_center, const T rng_radius) { // This thread function randomly initializes rank2 'H' matrices of // dimension 2 x width. Each thread initializes a maximum of // 'width/num_threads' columns. Random rng; rng.SeedFromInt(rng_seed); unsigned int num_cols = width / num_threads; unsigned int start = index * num_cols; unsigned int end = std::min(width, (index+1) * num_cols); for (unsigned int c=start; c<end; ++c) { unsigned int offset = c*ldim; // row 0 buf[offset + 0] = (T) rng.RandomDouble(rng_center, rng_radius); // row 1 buf[offset + 1] = (T) rng.RandomDouble(rng_center, rng_radius); } } //----------------------------------------------------------------------------- template <typename T> void ThreadFuncInitWide(const int rng_seed, const unsigned int num_threads, const unsigned int index, T* buf, const unsigned int ldim, const unsigned int height, const unsigned int width, const T rng_center, const T rng_radius) { // This thread function randomly initializes matrices having height <= width. // Each thread initializes a maximum of 'width/num_threads' columns. assert(height <= width); Random rng; rng.SeedFromInt(rng_seed); unsigned int num_cols = width / num_threads; unsigned int start = index * num_cols; unsigned int end = std::min(width, (index+1) * num_cols); for (unsigned int c=start; c<end; ++c) { unsigned int offset = c*ldim; for (unsigned int r=0; r<height; ++r) { buf[offset + r] = (T) rng.RandomDouble(rng_center, rng_radius); } } } //----------------------------------------------------------------------------- template <typename T> void RandomMatrixSequential(T* buf, const unsigned int ldim, const unsigned int height, const unsigned int width, Random& rng, const T rng_center, const T rng_radius) { // Fills a column-major matrix with random numbers. // IMPORTANT: this function assumes the buffer is large enough. for (unsigned int c=0; c<width; ++c) { unsigned int col_offset = c*ldim; for (unsigned int r=0; r<height; ++r) { buf[r + col_offset] = (T) rng.RandomDouble(rng_center, rng_radius); } } } //----------------------------------------------------------------------------- template <typename T> void RandomMatrixParallel(T* buf, const unsigned int ldim, const unsigned int height, const unsigned int width, Random& rng, const T rng_center, const T rng_radius) { std::vector<std::thread> threads; unsigned int max_threads = GetMaxThreadCount(); // the rng supplied as argument is used to generate a random seed // for each thread's private rng if (height <= width) { if (2 == height) { // special case for rank2 H matrices for (unsigned int k=0; k<max_threads; ++k) { threads.push_back(std::thread(ThreadFuncRank2H<T>, rng.RandomInt(), max_threads, k, buf, ldim, width, rng_center, rng_radius)); } } else { for (unsigned int k=0; k<max_threads; ++k) { threads.push_back(std::thread(ThreadFuncInitWide<T>, rng.RandomInt(), max_threads, k, buf, ldim, height, width, rng_center, rng_radius)); } } } else { if (2 == width) { // special case for rank2 W matrices for (unsigned int k=0; k<max_threads; ++k) { threads.push_back(std::thread(ThreadFuncRank2W<T>, rng.RandomInt(), max_threads, k, buf, ldim, height, rng_center, rng_radius)); } } else { for (unsigned int k=0; k<max_threads; ++k) { threads.push_back(std::thread(ThreadFuncInitTall<T>, rng.RandomInt(), max_threads, k, buf, ldim, height, width, rng_center, rng_radius)); } } } // wait for threads to finish std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join)); }
HENU515Lab/test
bbs/website/src/main/webapp/static/web/js/file_system/file/operation/collect/favorite.js
<reponame>HENU515Lab/test $(function () { $('form.form_favorte').on("submit", function (e) { e.preventDefault(); let $form = $(this); let hrefUrl = $form.attr('action'); let postData = $form.serializeArray(); let $id = $(this).attr('id'); $.ajax({ url: hrefUrl, type: "POST", data: postData, dataType: "Json", cache: false, timeout: 60000, success: function(resp){ let $span = $('span.' + $id); let $span_cnt = $('span.' + $id + '_favorite'); if (resp.error_message === "add_success"){ $span.addClass('favorite'); $span_cnt.addClass('favorite_number'); $span_cnt.text(resp.favoritecnt); } else if (resp.error_message === 'remove_success'){ $span.removeClass('favorite'); $span_cnt.removeClass('favorite_number'); $span_cnt.text(resp.favoritecnt > 0 ? resp.favoritecnt : ''); } }, error: function(){ } }); return false; }); });
mmm-soares/concurrency-java-9
Chapter09/SearchWithoutIndexing/src/com/javferna/packtpub/mastering/searchWithoutIndexing/serial/main/SerialMainBasicSearch.java
package com.javferna.packtpub.mastering.searchWithoutIndexing.serial.main; import java.io.IOException; import java.nio.file.FileVisitOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Date; public class SerialMainBasicSearch { public static void main(String args[]) { String query = "java"; Path file=Paths.get("data"); try { Date start, end; start=new Date(); ArrayList<String> results=Files.walk(file ,FileVisitOption.FOLLOW_LINKS).filter(f -> f.toString().endsWith(".txt")).collect( ArrayList<String>::new, new SerialStringAccumulator(query), ArrayList::addAll); end=new Date(); System.out.println("Resultados: "+results.size()); System.out.println("*************"); results.forEach(f -> System.out.println(f)); System.out.println("Execution Time: "+(end.getTime()-start.getTime())); } catch (IOException e) { e.printStackTrace(); } } }
danfuzz/archive
uberchat/uberchat-0.32/src/com/milk/command/BaseCommand.java
<gh_stars>1-10 // Copyright (C) 1992-1999, <NAME>, <EMAIL>. All Rights // Reserved. (Shrill TV degreaser.) // // This file is part of the MILK Kodebase. The contents of this file are // subject to the MILK Kodebase Public License; you may not use this file // except in compliance with the License. A copy of the MILK Kodebase Public // License has been included with this distribution, and may be found in the // file named "LICENSE.html". You may also be able to obtain a copy of the // License at <http://www.milk.com/kodebase/legal/LICENSE.html>. Yum! package com.milk.command; import com.milk.util.BaseEvent; import com.milk.util.BugInSubclassException; import com.milk.util.ListenerList; import java.util.EventListener; /** * This is a base class which implements most of the standard * <code>Command</code> functionality. It notably lacks public * <code>makeArgument()</code> and protected <code>commandRun()</code>, * which must be overridden to do reasonable things. * * @author <NAME>, <EMAIL> * @author Copyright 1999 <NAME>, all rights reserved. */ public abstract class BaseCommand implements Command { /** the listener list to use */ private ListenerList myListeners; /** the label */ private String myLabel; /** the description */ private String myDescription; /** the enabled state */ private boolean myEnabled; /** the (intentionally-private) object to synch on */ private Object mySynch; /** * Construct a <code>BaseCommand</code>. It initially has an empty * label and description, and is disabled. */ public BaseCommand () { myListeners = new ListenerList (); myLabel = ""; myDescription = ""; myEnabled = false; mySynch = myListeners; // good enough } // ------------------------------------------------------------------------ // Command interface methods /** * Add a listener for this command. * * @param listener the listener to add */ public final void addListener (EventListener listener) { synchronized (mySynch) { myListeners.add (listener); CommandEvent.labelChanged (this, myLabel).sendTo (listener); CommandEvent.descriptionChanged (this, myDescription). sendTo (listener); CommandEvent.enabledChanged (this, myEnabled).sendTo (listener); } } /** * Remove a listener from this command that was previously added * with <code>addListener</code>. * * @param listener the listener to remove */ public final void removeListener (EventListener listener) { synchronized (mySynch) { myListeners.remove (listener); } } /** * Get the label of this command. * * @return non-null; the label */ public final String getLabel () { synchronized (mySynch) { return myLabel; } } /** * Get the full description of this command. * * @return non-null; the description */ public final String getDescription () { synchronized (mySynch) { return myDescription; } } /** * Return true if this command is currently enabled. * * @return true if this command is currently enabled */ public final boolean isEnabled () { synchronized (mySynch) { return myEnabled; } } /** * Create and return an argument template for this command. Subclasses * must override this to return something appropriate. * * @return non-null; a new argument template for this command, or * null if the command has no arguments */ public abstract Object makeArgument (); /** * Run the command with the given argument. The argument should be * an object that was previously returned from <code>makeArgument</code>. * * @param argument the argument of the command * @return null-ok; the return value of running the command * @exception DisabledCommandException thrown if the command is not * enabled at the time this method is called */ public Object run (Object argument) throws DisabledCommandException { synchronized (mySynch) { if (! myEnabled) { throw new DisabledCommandException (this, argument); } return commandRun (argument); } } // ------------------------------------------------------------------------ // Protected methods which must be overridden /** * Really run this command. <code>BaseCommand.run()</code> calls this, * after checking to make sure the command is enabled. That is, this * method is only ever called on an enabled command. Note that * synchronization in this class ensures that only one thread at a time * is in a particular object's <code>commandRun()</code> method. * * @param argument the argument of the command * @return null-ok; the return value of running the command */ protected abstract Object commandRun (Object argument); // ------------------------------------------------------------------------ // Protected helper methods /** * Set the label of this command. If it is in fact different from the * old label, then a <code>labelChanged</code> event is sent to all * appropriate listeners. * * @param label null-ok; the new label */ protected final void setLabel (String label) { synchronized (mySynch) { if (label == null) { label = ""; } if (label.equals (myLabel)) { // easy out--it didn't change return; } myLabel = label; broadcast (CommandEvent.labelChanged (this, label)); } } /** * Set the description of this command. If it is in fact different from * the old description, then a <code>descriptionChanged</code> event is * sent to all appropriate listeners. * * @param description null-ok; the new description */ protected final void setDescription (String description) { synchronized (mySynch) { if (description == null) { description = ""; } if (description.equals (myDescription)) { // easy out--it didn't change return; } myDescription = description; broadcast (CommandEvent.descriptionChanged (this, description)); } } /** * Set the enabled state of this command. If it is in fact different * from the old state, then an <code>enabledChanged</code> event is * sent to all appropriate listeners. * * @param enabled the new enabled state */ protected final void setEnabled (boolean enabled) { synchronized (mySynch) { if (enabled == myEnabled) { // easy out--it didn't change return; } myEnabled = enabled; broadcast (CommandEvent.enabledChanged (this, enabled)); } } /** * Broadcast an event to all the listeners of this object. * * @param event the event to broadcast */ protected final void broadcast (BaseEvent event) { synchronized (mySynch) { if (event.getSource () != this) { throw new BugInSubclassException ( "BaseCommand.broadcast() called with a " + "different-sourced event:\n" + event); } myListeners.checkedBroadcast (event); } } }
RichardBradley/scapegoat
src/test/scala/com/sksamuel/scapegoat/inspections/EmptyCatchBlockTest.scala
<reponame>RichardBradley/scapegoat<filename>src/test/scala/com/sksamuel/scapegoat/inspections/EmptyCatchBlockTest.scala package com.sksamuel.scapegoat.inspections import com.sksamuel.scapegoat.PluginRunner import org.scalatest.{FreeSpec, Matchers} /** @author <NAME> */ class EmptyCatchBlockTest extends FreeSpec with ASTSugar with Matchers with PluginRunner { override val inspections = Seq(new EmptyCatchBlock) "empty catch block" - { "should report warning" in { val code = """object Test { | try { | val a = System.currentTimeMillis | } catch { | case r: RuntimeException => throw r | case e: Exception => | case t: Throwable => | } } """.stripMargin compileCodeSnippet(code) compiler.scapegoat.reporter.warnings.size shouldBe 2 } } }
PolyStyle/DesktopFashion
src/components/TagSelector/index.js
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { Button, Modal, ModalBody } from 'reactstrap'; import styles from './styles.css'; class TagSelector extends React.Component { constructor(props) { super(props); this.state = { tags: this.props.tags, addedTags: this.props.currentAddedTags, isTagModalOpen: false, }; // For a full list of possible configurations, // please consult http://www.dropzonejs.com/#configuration this.onSaveAll = this.onSaveAll.bind(this); this.onCancelAll = this.onCancelAll.bind(this); this.toggleTagModal = this.toggleTagModal.bind(this); } componentWillReceiveProps(nextProps) { this.setState({ addedTags: nextProps.currentAddedTags, }); } onSaveAll() { this.setState({ isTagModalOpen: false, }); if (this.props.onTagSaveHandler) { this.props.onTagSaveHandler(this.state.addedTags); } } onCancelAll() { if (this.props.onCancelAllHandler) { this.props.onCancelAllHandler(this.state.addedTags); } } addTag(index) { this.setState({ tags: this.state.tags.slice(0, index) .concat(this.state.tags.slice(index + 1)), addedTags: this.state.addedTags.concat(this.state.tags[index]), }); } removeTag(index) { this.setState({ addedTags: this.state.addedTags.slice(0, index) .concat(this.state.addedTags.slice(index + 1)), tags: this.state.tags.concat(this.state.addedTags[index]), }); } toggleTagModal() { if (this.state.isTagModalOpen) { // Modal is Open this.setState({ isTagModalOpen: false, }); } else { this.setState({ isTagModalOpen: true, }); } } render() { return ( <div> <Button size="sm" color="success" onClick={this.toggleTagModal}> Edit Tags </Button> <Modal className={styles.bigModal} isOpen={this.state.isTagModalOpen} toggle={this.toggleTagModal} > <ModalBody> <div className={styles.selectTags}> <h5> Select Tags </h5> {this.state.tags.map((tag, index) => ( <Button key={index} size="sm" color="secondary" onClick={() => this.addTag(index)}> + {tag.displayName} </Button> ))} </div> <div className={styles.selectedTags}> <h5> Select Tags </h5> {this.state.addedTags.map((tag, index) => ( <Button key={index} size="sm" color="primary" onClick={() => this.removeTag(index)}> - {tag.displayName} </Button> ))} </div> <div className={styles.buttons}> <Button size="sm" color="success" onClick={this.onSaveAll}> Save All </Button> <Button size="sm" color="danger" onClick={this.toggleTagModal}> Cancel All </Button> </div> </ModalBody> </Modal> </div> ); } } TagSelector.defaultProps = { tags: [], currentAddedTags: [], }; TagSelector.propTypes = { tags: PropTypes.arrayOf(PropTypes.object), onCancelAllHandler: PropTypes.func, onTagSaveHandler: PropTypes.func, currentAddedTags: PropTypes.arrayOf(PropTypes.object), }; const mapStateToProps = state => ({ tags: state.get('tags').tags }); export default connect(mapStateToProps)(TagSelector);
jinbooooom/design-patterns
factory/simpleFactory/CheesePizza.hpp
<gh_stars>0 #ifndef CHEESE_PIZZA_HPP #define CHEESE_PIZZA_HPP #include "Pizza.hpp" class CheesePizza : public Pizza { public: CheesePizza() { name = "Cheese pizza"; dough = "Thin crust dough"; sauce = "Marinara sauce"; toppings.push_back("Gratted reggiano cheese"); } }; #endif
1484/shirasagi
spec/support/webmail/user.rb
module Webmail module UserSupport cattr_accessor :data def self.extended(obj) dbscope = obj.metadata[:dbscope] dbscope ||= RSpec.configuration.default_dbscope obj.after(dbscope) do Webmail::UserSupport.data = nil end end end end RSpec.configuration.extend(Webmail::UserSupport) def webmail_admin create_webmail_users[:admin] end def webmail_user create_webmail_users[:user] end def webmail_admin_role create_webmail_users[:admin_role] end def webmail_user_role create_webmail_users[:user_role] end def login_webmail_admin login_user(webmail_admin) end def login_webmail_user login_user(webmail_user) end def webmail_imap raise "not supported in imap: false" if SS::WebmailSupport.test_by.blank? create_webmail_users[:imap] end def login_webmail_imap raise "not supported in imap: false" if SS::WebmailSupport.test_by.blank? login_user(webmail_imap) end def create_webmail_users return Webmail::UserSupport.data if Webmail::UserSupport.data.present? g00 = SS::Group.create! name: "シラサギ市", order: 10 g10 = SS::Group.create! name: "シラサギ市/企画政策部", order: 20 g11 = SS::Group.create! name: "シラサギ市/企画政策部/政策課", order: 30 admin_role = create(:webmail_role_admin, name: I18n.t('webmail.roles.admin')) user_role = create(:webmail_role_admin, name: I18n.t('webmail.roles.user')) admin = Webmail::User.create! name: "webmail-admin", uid: "admin", email: "admin<EMAIL>", in_password: "<PASSWORD>", group_ids: [g11.id], webmail_role_ids: [admin_role.id], organization_id: g00.id, organization_uid: "org-admin", deletion_lock_state: "locked" user = Webmail::User.create! name: "webmail-user", uid: "user", email: "<EMAIL>", in_password: "<PASSWORD>", group_ids: [g11.id], webmail_role_ids: [user_role.id], organization_id: g00.id, organization_uid: "org-user" admin.in_password = admin.decrypted_password = '<PASSWORD>' user.in_password = user.decrypted_password = '<PASSWORD>' imap = nil if SS::WebmailSupport.test_by.present? imap = Webmail::User.create! name: "webmail-imap", uid: "imap", email: "<EMAIL>", in_password: SS.config.webmail.test_pass || "<PASSWORD>", group_ids: [g11.id], webmail_role_ids: [user_role.id], organization_id: g00.id, organization_uid: "org-imap" imap.imap_settings = webmail_imap_setting imap.save! imap.in_password = imap.decrypted_password = SS.config.webmail.test_pass || '<PASSWORD>' end return Webmail::UserSupport.data = { admin: admin, user: user, admin_role: admin_role, user_role: user_role, imap: imap } end def webmail_imap_setting conf = SS::WebmailSupport.test_conf setting = Webmail::ImapSetting.default setting[:imap_host] = conf['host'] || 'localhost' setting[:imap_port] = conf['imap_port'] if conf.key?('imap_port') setting[:imap_ssl_use] = conf['imap_ssl_use'] if conf.key?('imap_ssl_use') setting[:imap_auth_type] = conf['imap_auth_type'] if conf.key?('imap_auth_type') setting[:imap_account] = conf['account'] || 'email' setting[:in_imap_password] = conf['password'] || '<PASSWORD>' setting.set_imap_password Webmail::Extensions::ImapSettings.new([setting]) end
clabe45/Glowstone
src/test/java/net/glowstone/constants/GlowStatisticTest.java
<filename>src/test/java/net/glowstone/constants/GlowStatisticTest.java package net.glowstone.constants; import static org.junit.Assert.assertEquals; import net.glowstone.testutils.ServerShim; import org.bukkit.Material; import org.bukkit.Statistic; import org.bukkit.entity.EntityType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class GlowStatisticTest { @BeforeEach public void beforeEach() { ServerShim.install(); } @Test public void testSimpleStatistic() { assertEquals("stat.entityKilledBy", GlowStatistic.getName(Statistic.ENTITY_KILLED_BY)); assertEquals("stat.drop", GlowStatistic.getName(Statistic.DROP)); assertEquals("stat.jump", GlowStatistic.getName(Statistic.JUMP)); assertEquals("stat.chestOpened", GlowStatistic.getName(Statistic.CHEST_OPENED)); assertEquals("stat.playOneMinute", GlowStatistic.getName(Statistic.PLAY_ONE_MINUTE)); } @Test public void testEntityStatistic() { assertEquals("stat.entityKilledBy.Enderman", GlowStatistic.getName(Statistic.ENTITY_KILLED_BY, EntityType.ENDERMAN)); assertEquals("stat.killEntity.Enderman", GlowStatistic.getName(Statistic.KILL_ENTITY, EntityType.ENDERMAN)); assertEquals("stat.killEntity.CaveSpider", GlowStatistic.getName(Statistic.KILL_ENTITY, EntityType.CAVE_SPIDER)); } @Test public void testMaterialStatistic() { assertEquals("stat.drop.minecraft.dirt", GlowStatistic.getName(Statistic.DROP, Material.DIRT)); assertEquals("stat.drop.minecraft.stone", GlowStatistic.getName(Statistic.DROP, Material.STONE)); assertEquals("stat.drop.minecraft.gold_ore", GlowStatistic.getName(Statistic.DROP, Material.GOLD_ORE)); assertEquals("stat.breakItem.minecraft.bow", GlowStatistic.getName(Statistic.BREAK_ITEM, Material.BOW)); assertEquals("stat.breakItem.minecraft.iron_shovel", GlowStatistic.getName(Statistic.BREAK_ITEM, Material.IRON_SHOVEL)); assertEquals("stat.breakItem.minecraft.golden_pickaxe", GlowStatistic.getName(Statistic.BREAK_ITEM, Material.GOLDEN_PICKAXE)); assertEquals("stat.pickup.minecraft.iron_shovel", GlowStatistic.getName(Statistic.PICKUP, Material.IRON_SHOVEL)); assertEquals("stat.pickup.minecraft.golden_axe", GlowStatistic.getName(Statistic.PICKUP, Material.GOLDEN_AXE)); assertEquals("stat.pickup.minecraft.wooden_axe", GlowStatistic.getName(Statistic.PICKUP, Material.WOODEN_AXE)); assertEquals("stat.mineBlock.minecraft.dirt", GlowStatistic.getName(Statistic.MINE_BLOCK, Material.DIRT)); assertEquals("stat.mineBlock.minecraft.gold_ore", GlowStatistic.getName(Statistic.MINE_BLOCK, Material.GOLD_ORE)); assertEquals("stat.useItem.minecraft.golden_pickaxe", GlowStatistic.getName(Statistic.USE_ITEM, Material.GOLDEN_PICKAXE)); assertEquals("stat.useItem.minecraft.diamond_axe", GlowStatistic.getName(Statistic.USE_ITEM, Material.DIAMOND_AXE)); assertEquals("stat.craftItem.minecraft.iron_shovel", GlowStatistic.getName(Statistic.CRAFT_ITEM, Material.IRON_SHOVEL)); assertEquals("stat.craftItem.minecraft.golden_pickaxe", GlowStatistic.getName(Statistic.CRAFT_ITEM, Material.GOLDEN_PICKAXE)); } }
celerik/launch-partners-mern
backend/src/api/home/home.controller.js
// @scripts const { responseSchema } = require('../../utils/res'); function mainController(_req, res) { responseSchema({ data: { version: '1.0.0' }, message: 'LaunchPartner API', res }); } module.exports = { mainController };
qtomlinson/crawler
test/unit/providers/process/scancodeTests.js
// Copyright (c) Microsoft Corporation and others. Licensed under the MIT license. // SPDX-License-Identifier: MIT const chai = require('chai') const expect = chai.expect const proxyquire = require('proxyquire') const sinon = require('sinon') const sandbox = sinon.createSandbox() const { request } = require('../../../../ghcrawler') const { flatten } = require('lodash') let Handler describe('ScanCode misc', () => { it('differentiates real errors', () => { Handler._resultBox.result = { files: [{ scan_errors: ['ValueError: this is a test'] }, { scan_errors: ['bogus package.json'] }] } expect(Handler._hasRealErrors()).to.be.false Handler._resultBox.result = { files: [{ scan_errors: ['Yikes. Tragedy has struck'] }, { scan_errors: ['Panic'] }] } expect(Handler._hasRealErrors()).to.be.true Handler._resultBox.result = { files: [] } expect(Handler._hasRealErrors()).to.be.false Handler._resultBox.result = { files: [{}] } expect(Handler._hasRealErrors()).to.be.false }) beforeEach(() => { const resultBox = {} const fsStub = { readFileSync: () => JSON.stringify(resultBox.result) } const handlerFactory = proxyquire('../../../../providers/process/scancode', { fs: fsStub }) Handler = handlerFactory({ logger: { log: () => { } } }) Handler._resultBox = resultBox }) afterEach(() => { sandbox.restore() }) }) describe('ScanCode process', () => { it('should handle gems', async () => { const { request, processor } = setup('2.9.8/gem.json') await processor.handle(request) expect(request.document._metadata.toolVersion).to.equal('1.2.0') expect(flatten(processor.attachFiles.args.map(x => x[1]))).to.have.members([]) }) it('should handle simple npms', async () => { const { request, processor } = setup('2.9.8/npm-basic.json') await processor.handle(request) expect(flatten(processor.attachFiles.args.map(x => x[1]))).to.have.members(['package/package.json']) }) it('should handle large npms', async () => { const { request, processor } = setup('2.9.8/npm-large.json') await processor.handle(request) expect(flatten(processor.attachFiles.args.map(x => x[1]))).to.have.members(['package/package.json']) }) it('should skip if ScanCode not found', async () => { const { request, processor } = setup(null, null, new Error('error message here')) await processor.handle(request) expect(request.processControl).to.equal('skip') }) it('handles scancode error', async () => { const { request, processor } = setup(null, new Error('error message here')) try { await processor.handle(request) expect(true).to.be.false } catch (error) { expect(request.processControl).to.equal('skip') } }) beforeEach(function () { const resultBox = { error: null, versionResult: 'ScanCode version 1.2.0\n', versionError: null } const processStub = { execFile: (command, parameters, callbackOrOptions, callback) => { if (parameters.includes('--version')) return callbackOrOptions(resultBox.versionError, { stdout: resultBox.versionResult }) callback(resultBox.error) } } Handler = proxyquire('../../../../providers/process/scancode', { child_process: processStub }) Handler._resultBox = resultBox }) afterEach(function () { sandbox.restore() }) }) function setup(fixture, error, versionError) { const options = { options: [], timeout: 200, processes: 2, format: 'json', logger: { log: sinon.stub(), info: sinon.stub() } } const testRequest = new request('npm', 'cd:/npm/npmjs/-/test/1.1') testRequest.document = { _metadata: { links: {} }, location: '/test' } testRequest.crawler = { storeDeadletter: sinon.stub() } Handler._resultBox.error = error Handler._resultBox.versionError = versionError const processor = Handler(options) processor.createTempFile = () => { return { name: `test/fixtures/scancode/${fixture}` } } processor._computeSize = () => { return { k: 13, count: 12 } } processor.attachFiles = sinon.stub() return { request: testRequest, processor } }
CTA/queri
spec/spec_helper.rb
<reponame>CTA/queri require 'rubygems' require 'bundler/setup' require 'queri' Dir[File.join( File.dirname(__FILE__), 'support', '**', '*.rb' )].each {|f| require f} RSpec.configure do |config| include TimeHelper config.treat_symbols_as_metadata_keys_with_true_values = true end
amichard/tfrs
backend/api/models/DocumentComment.py
""" REST API Documentation for the NRS TFRS Credit Trading Application The Transportation Fuels Reporting System is being designed to streamline compliance reporting for transportation fuel suppliers in accordance with the Renewable & Low Carbon Fuel Requirements Regulation. OpenAPI spec version: v1 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.db import models from auditable.models import Auditable class DocumentComment(Auditable): """ Contains all correspondence from fuel suppliers and government (including those with privileged access) related to Secure Document Upload. """ document = models.ForeignKey( 'Document', related_name='document_comments', null=False, on_delete=models.PROTECT) comment = models.CharField( max_length=4000, blank=True, null=True, db_column='document_comment', db_comment='Contains all comments related to a document submission.' 'Comments may be added by fuel suppliers or government, ' 'with some government comments being flagged as ' 'internal only.') # require a permission to view privileged_access = models.BooleanField( null=False, default=True, db_column='is_privileged_access', db_comment='Flag. True if this is for internal government viewing ' 'only.' ) # For tracking the status at the point in time the comment was made document_history_at_creation = models.ForeignKey( 'DocumentHistory', related_name='document_comments', null=True, on_delete=models.PROTECT ) class Meta: db_table = 'document_comments' ordering = ['create_timestamp'] db_table_comment = "Contains all correspondence from fuel suppliers " \ "and government (including those with privileged " \ "access) related to Secure Document Upload."
spincast/spincast-framework
spincast-plugins/spincast-plugins-jackson-xml-parent/spincast-plugins-jackson-xml-tests/src/test/java/org/spincast/plugins/jacksonxml/tests/CustomDeserializerMixinTest.java
<reponame>spincast/spincast-framework package org.spincast.plugins.jacksonxml.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import org.junit.Test; import org.spincast.core.guice.SpincastGuiceModuleBase; import org.spincast.core.xml.XmlManager; import org.spincast.plugins.jacksonxml.XmlMixinInfo; import org.spincast.plugins.jacksonxml.XmlMixinInfoDefault; import org.spincast.testing.defaults.NoAppTestingBase; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.inject.Inject; import com.google.inject.Module; import com.google.inject.multibindings.Multibinder; public class CustomDeserializerMixinTest extends NoAppTestingBase { @Override protected Module getExtraOverridingModule() { return new SpincastGuiceModuleBase() { @Override protected void configure() { //========================================== // Binds our mixin //========================================== Multibinder<XmlMixinInfo> xmlMixinsBinder = Multibinder.newSetBinder(binder(), XmlMixinInfo.class); xmlMixinsBinder.addBinding().toInstance(new XmlMixinInfoDefault(User.class, UserMixin.class)); } }; } @Inject XmlManager xmlManager; protected XmlManager getXmlManager() { return this.xmlManager; } /** * Custom Json deserializer */ protected static class CustomDeserializer extends JsonDeserializer<String> { @Override public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { return "bang!"; } } /** * Our User mixin */ public static abstract class UserMixin implements User { //========================================== // Uses our custom deserializer! //========================================== @Override @JsonDeserialize(using = CustomDeserializer.class) public abstract String getTitle(); } @Test public void customDeserializer() throws Exception { String xml = "<User><name>Stromgol</name><age>123</age><title>alien</title></User>"; User user = getXmlManager().fromXml(xml, UserDefault.class); assertNotNull(user); assertEquals("Stromgol", user.getName()); assertEquals(123, user.getAge()); assertEquals("Title is: bang!", user.getTitle()); } }
adityavs/ant
src/main/org/apache/tools/ant/types/optional/imageio/Arc.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.tools.ant.types.optional.imageio; import java.awt.BasicStroke; import java.awt.Graphics2D; import java.awt.geom.Arc2D; import java.awt.image.BufferedImage; /** * Draw an arc. */ public class Arc extends BasicShape implements DrawOperation { private int start = 0; private int stop = 0; private int type = Arc2D.OPEN; /** * Set the start of the arc. * @param start the start of the arc. */ public void setStart(int start) { this.start = start; } /** * Set the stop of the arc. * @param stop the stop of the arc. */ public void setStop(int stop) { this.stop = stop; } /** * Set the type of arc. * @param strType the type to use - open, pie or chord. * @todo refactor using an EnumeratedAttribute */ public void setType(String strType) { if ("open".equalsIgnoreCase(strType)) { type = Arc2D.OPEN; } else if ("pie".equalsIgnoreCase(strType)) { type = Arc2D.PIE; } else if ("chord".equalsIgnoreCase(strType)) { type = Arc2D.CHORD; } } /** {@inheritDoc}. */ @Override public BufferedImage executeDrawOperation() { BufferedImage bi = new BufferedImage(width + (strokeWidth * 2), height + (strokeWidth * 2), BufferedImage.TYPE_4BYTE_ABGR_PRE); Graphics2D graphics = bi.createGraphics(); if (!"transparent".equalsIgnoreCase(stroke)) { BasicStroke bStroke = new BasicStroke(strokeWidth); graphics.setColor(ColorMapper.getColorByName(stroke)); graphics.setStroke(bStroke); graphics.draw(new Arc2D.Double(strokeWidth, strokeWidth, width, height, start, stop, type)); } if (!"transparent".equalsIgnoreCase(fill)) { graphics.setColor(ColorMapper.getColorByName(fill)); graphics.fill(new Arc2D.Double(strokeWidth, strokeWidth, width, height, start, stop, type)); } for (ImageOperation instr : instructions) { if (instr instanceof DrawOperation) { BufferedImage img = ((DrawOperation) instr).executeDrawOperation(); graphics.drawImage(img, null, 0, 0); } else if (instr instanceof TransformOperation) { bi = ((TransformOperation) instr).executeTransformOperation(bi); graphics = bi.createGraphics(); } } return bi; } }
Bensuo/visioncpp
include/operators/experimental/OP_Median.hpp
// This file is part of VisionCPP, a lightweight C++ template library // for computer vision and image processing. // // Copyright (C) 2016 Codeplay Software Limited. All Rights Reserved. // // Contact: <EMAIL> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// \file OP_Median.hpp /// \brief It applies the median filter in an image. It gets the median value /// of a neighbour after sorted namespace visioncpp { /// \brief User defined functionality for the kernel namespace custom { template <typename T> void bubbleSort(T &a, int N) { bool swapp = true; while (swapp) { swapp = false; for (size_t i = 0; i < N - 1; i++) { if (a[i] > a[i + 1]) { a[i] += a[i + 1]; a[i + 1] = a[i] - a[i + 1]; a[i] -= a[i + 1]; swapp = true; } } } } } /// \brief This functor implements a median filter struct OP_Median { /// \brief This functor implements median filter /// \param nbr - Input image /// \return float - Returns the image with median filter applied template <typename T> T operator()(T nbr) { int size = 5; int bound = size / 2; float v[25]; int k = 0; for (int i = -bound; i <= bound; i++) { for (int j = -bound; j <= bound; j++) { v[k++] = nbr.at(nbr.I_c + i, nbr.I_r + j); } } custom::bubbleSort(v, size * size); return v[size * size / 2]; } }; }
Galenika/Externalit
csgo_external/csgo_external/sdk/utils/utils.h
#pragma once #include "../sdk.h" namespace sdk { class cutils { public: cutils() = default; std::string weapon_config(int weaponid); std::vector<std::string> split(const std::string& str, const std::string& delimiter); std::string animate_string(std::string string); }; extern cutils* c_utils; }
Clunker5/tregmine
util/spleef/src/info/tregmine/spleef/listeners/FallFromArena.java
<reponame>Clunker5/tregmine package info.tregmine.spleef.listeners; import info.tregmine.spleef.Arena; import info.tregmine.spleef.ArenaManager; import info.tregmine.spleef.SettingsManager; import info.tregmine.spleef.Spleef; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerMoveEvent; public class FallFromArena implements Listener { private final Spleef plugin; public FallFromArena(Spleef instance){ this.plugin = instance; } private Location min, max; private Location getLocation(ConfigurationSection path) { return new Location( Bukkit.getServer().getWorld(path.getString("world")), path.getDouble("x"), path.getDouble("y"), path.getDouble("z") ); } public int getTeam(Player p) { Arena a = ArenaManager.getInstance().getArena(p); return a.getID(); } @EventHandler public void onPlayerFallFromArena(PlayerMoveEvent e) { Player p = e.getPlayer(); Location pLoc = p.getLocation(); Block b = pLoc.getBlock(); if (ArenaManager.getInstance().getArena(p) == null) return; ConfigurationSection conf = SettingsManager.getInstance().get(getTeam(e.getPlayer()) + ""); this.min = getLocation(conf.getConfigurationSection("minArenaLoc")); this.max = getLocation(conf.getConfigurationSection("maxArenaLoc")); int spleefMinX = min.getBlockX(); int spleefMaxX = max.getBlockX(); int spleefMinZ = min.getBlockZ(); int spleefMaxZ = max.getBlockZ(); int spleefSnow = min.getBlockY() - 1; Arena aNum = ArenaManager.getInstance().getArena(p); if(aNum.isStarted()){ if (b.getLocation().getBlockX() >= spleefMinX && b.getLocation().getBlockX() <= spleefMaxX){ if (b.getLocation().getBlockZ() >= spleefMinZ && b.getLocation().getBlockZ() <= spleefMaxZ){ if (b.getLocation().getBlockY() == spleefSnow){ ArenaManager.getInstance().getArena(p).clearScore(p); ArenaManager.getInstance().getArena(p).removePlayer(p, true); } } } } } }
Williams-Dan/dotledger
app/assets/javascripts/dot_ledger/initializers/ajax_errors.js
DotLedger.addInitializer(function () { $(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) { if (jqXHR.status === 0) { DotLedger.Helpers.Notification.danger('Could not connect to server.'); } }); });
xenowits/cp
codeforces/571div2/D2.cpp
<reponame>xenowits/cp #include<bits/stdc++.h> using namespace std; #define fori(i,a,b) for (long int i = a; i <= b ; ++i) #define ford(i,a,b) for(long int i = a;i >= b ; --i) #define mk make_pair #define mod 1000000007 #define pb push_back #define ll long long #define rnd mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count()) #define pi pair<int,int> int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; vector<float> v(n+1); ll sum = 0; fori(i,1,n) { cin >> v[i]; sum += (int)floor(v[i]); } //cout << sum << " is the sum" << endl; int i = 1; while (sum != 0) { if (abs(v[i]-(int)v[i]) != 0) { sum += 1; cout << (int)floor(v[i])+1 << endl; } else cout << v[i] << endl; i+=1; } for(int j = i ; j <= n; ++j) cout << (int)floor(v[j]) << endl; return 0; }
lab-csx-ufmg/omtg2gml
src/OMTGRelationship.java
public class OMTGRelationship extends Relationship { private String side; private String entityA, entityB; private OMTGCardinality cardA, cardB, card; private String cardRelationA, cardRelationB; public OMTGRelationship(String name, String type, String entityA, String entityB, OMTGCardinality cardA, OMTGCardinality cardB) { super(name, type); this.entityA = entityA; this.entityB = entityB; this.cardA = cardA; this.cardB = cardB; if (cardA != null && cardB != null) { this.cardRelationA = cardB.getMax(); this.cardRelationB = cardA.getMax(); this.card = new OMTGCardinality(cardRelationA, cardRelationB); } } public String getSide() { return side; } public void setSide(String side) { this.side = side; } public String getEntityA() { return entityA; } public String getEntityB() { return entityB; } public OMTGCardinality getCardA() { return cardA; } public OMTGCardinality getCardB() { return cardB; } public int getParticipationCardA() { return cardA.getParticipation(); } public int getParticipationCardB() { return cardB.getParticipation(); } public boolean isParticipationCardAPartial() { return getParticipationCardA() == 0; } public boolean isParticipationCardBPartial() { return getParticipationCardB() == 0; } public boolean isParticipationCardATotal() { return getParticipationCardA() == 1; } public boolean isParticipationCardBTotal() { return getParticipationCardB() == 1; } public String getCardRelationA() { return cardRelationA; } public String getCardRelationB() { return cardRelationB; } public OMTGCardinality getCard() { return card; } public String toString() { return "(" + cardRelationA + "," + cardRelationB + ")"; } }
dwt/capybara.py
capybara/tests/session/test_assert_title.py
import pytest import re from capybara.exceptions import ExpectationNotMet class TestAssertTitle: @pytest.fixture(autouse=True) def setup_session(self, session): session.visit("/with_js") def test_is_true_if_the_page_title_contains_the_given_string(self, session): assert session.assert_title("js") is True def test_is_true_when_given_an_empty_string(self, session): assert session.assert_title("") is True def test_allows_regex_matches(self, session): assert session.assert_title(re.compile(r"w[a-z]{3}_js")) is True with pytest.raises(ExpectationNotMet) as excinfo: session.assert_title(re.compile(r"w[a-z]{10}_js")) assert "expected 'with_js' to match 'w[a-z]{10}_js'" in str(excinfo.value) @pytest.mark.requires("js") def test_waits_for_title(self, session): session.click_link("Change title") assert session.assert_title("changed title", wait=3) is True def test_raises_error_if_the_page_title_does_not_contain_the_given_string(self, session): with pytest.raises(ExpectationNotMet) as excinfo: session.assert_title("monkey") assert "expected 'with_js' to include 'monkey'" in str(excinfo.value) def test_normalizes_the_given_title(self, session): session.assert_title(" with_js ") def test_normalizes_given_title_in_error_message(self, session): with pytest.raises(ExpectationNotMet) as excinfo: session.assert_title(2) assert "expected 'with_js' to include '2'" in str(excinfo.value) class TestAssertNoTitle: @pytest.fixture(autouse=True) def setup_session(self, session): session.visit("/with_js") def test_raises_error_if_the_title_contains_the_given_string(self, session): with pytest.raises(ExpectationNotMet) as excinfo: session.assert_no_title("with_j") assert "expected 'with_js' not to include 'with_j'" in str(excinfo.value) def test_allows_regex_matches(self, session): with pytest.raises(ExpectationNotMet) as excinfo: session.assert_no_title(re.compile(r"w[a-z]{3}_js")) assert "expected 'with_js' not to match 'w[a-z]{3}_js'" in str(excinfo.value) session.assert_no_title(re.compile(r"monkey")) @pytest.mark.requires("js") def test_waits_for_title_to_disappear(self, session): session.click_link("Change title") assert session.assert_no_title("with_js", wait=3) is True def test_is_true_if_the_title_does_not_contain_the_string(self, session): assert session.assert_no_title("monkey") is True
Chromico/bk-base
src/dataweb/web/src/i18n/en/index.js
/* * Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. * BK-BASE 蓝鲸基础平台 is licensed under the MIT License. * * License for BK-BASE 蓝鲸基础平台: * -------------------------------------------------------------------- * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE */ import common from './common.json'; import dataClean from './dataclean.json'; import dataAccess from './dataAccess.json'; import dataManage from './dataManage.json'; import dataRemoval from './dataRemoval.json'; import sdkNode from './sdkNode.json'; import dataMap from './dataMap.json'; import dataExplore from './dataExplore.json'; import nodeForm from './nodeForm.json'; import dataInventory from './dataInventory.json'; import resourceManage from './resourceManage.json'; import authManage from './authManage.json'; import dataAlert from './dataAlert.json'; import dataLog from './dataLog.json'; import dataView from './dataView.json'; import dataDict from './dataDict.json'; import extend from '@/extends/index'; const i18nExt = extend.callJsFragmentFn('i18n') || {}; export default Object.assign( {}, common, dataMap, dataClean, dataManage, dataRemoval, sdkNode, dataAccess, dataExplore, nodeForm, dataInventory, authManage, dataAlert, dataView, resourceManage, dataLog, dataDict, { ...(i18nExt.langEn || {}) } );
zotov-vs/tg_shop
utils/db_api/models/products.py
<reponame>zotov-vs/tg_shop from sqlalchemy import sql from data.localization import currency_symbol from utils.db_api.database import TimedBaseModel, BaseModel, db class Product(TimedBaseModel): __tablename__ = 'products' id = db.Column(db.Integer, primary_key=True, autoincrement=True) parent_id = db.Column(db.Integer, db.ForeignKey('products.id'), nullable=True) entity_type_id = db.Column(db.Integer, db.ForeignKey('entities_types.id'), nullable=False) product_name = db.Column(db.String(100), nullable=False) product_description = db.Column(db.String(1024), nullable=True) product_image = db.Column(db.String(1024), nullable=True) stock_issue_pattern = db.Column(db.String(1024), nullable=True) key_pattern = db.Column(db.String(1024), nullable=True) product_price = db.Column(db.Integer, nullable=True) comment = db.Column(db.String(255), default='') query: sql.Select async def get_children_list(self): result = await Product.query.where(Product.parent_id == self.id).gino.all() return result # # Возвращает остаток товара # async def get_stock(self): # if self.entity_type_id == 4: async def get_caption(self): result = f'{self.product_name}\n\n' if self.product_description: result += f'{self.product_description}\n\n' if self.product_price: result += f'Цена: {self.product_price}{currency_symbol}\n' \ f'В наличии: \n' \ f'накопительная скидка х%: {currency_symbol}\n' \ f'Промокод: {currency_symbol}\n' \ f'К оплате: {currency_symbol}\n' return result @classmethod async def get(cls, id: int=0): item = await cls.query.where(cls.id == id).gino.first() return item
ACea15/pyNastran
pyNastran/converters/dev/vrml/vrml_to_dict.py
import numpy as np from pyparsing import ParseResults def todicti(data, log): i = 0 dicti = {} log.debug('------') while i < len(data): #print(dicti) key = data[i] #print('%r' % modeli) i += 1 value = data[i] if isinstance(value, str): dicti[key] = value elif isinstance(value, ParseResults): value2 = value.asList() log.debug(f' key={key} value={value2}') dicti[key] = value2 else: print(f' key={key} value={value}') print(dicti) raise NotImplementedError(f'value={value!r} type={type(value)}') i += 1 #print(data) #print(dicti) return dicti def read_transforms(pmodel): #print('**************************') transforms = [] i = 0 i = 0 while i < len(pmodel): modeli = pmodel[i] if modeli == 'Shape': i += 1 data = pmodel[i] shape = toshape(data) #print('shape =', shape) i += 1 transforms.append(shape) else: raise NotImplementedError(f'modeli={modeli!r} type={type(modeli)}') return transforms def tolist(data): data2 = [] for datai in data: if isinstance(datai, ParseResults): datai2 = tolist(datai) data2.append(datai2) elif isinstance(datai, (int, float, str)): data2.append(datai) else: raise NotImplementedError(f'datai={datai!r} type={type(datai)}') return data2 def to_quads_tris(coord_indexs): coord_indexs = np.array(coord_indexs, dtype='int32') #print(coord_indexs) iminus1 = np.where(coord_indexs == -1)[0] #print(iminus1) i0 = 0 quads = [] tris = [] for i1 in iminus1: datai = coord_indexs[i0:i1] #print(datai) ndata = len(datai) if ndata == 3: tris.append(datai) elif ndata == 4: quads.append(datai) else: raise NotImplementedError(datai) i0 = i1 + 1 if quads: quads = np.array(quads) if tris: tris = np.array(tris) return coord_indexs, quads, tris def read_indexed_face_set(data): indexed_face_set = {} #print(data) i = 0 while i < len(data): datai = data[i] if datai == 'coord': i += 1 datai = data[i] assert datai == 'Coordinate', datai i += 1 datai = data[i] assert len(datai) == 2, datai point = datai[1] points = np.array(tolist(point), dtype='float64') indexed_face_set['coord'] = { 'point' : points, } i += 1 elif datai == 'coordIndex': i += 1 coord_index = data[i] coord_indexs = tolist(coord_index) coord_indexs, quads, tris = to_quads_tris(coord_indexs) #indexed_face_set['coord_index'] = coord_index if len(quads): indexed_face_set['quads'] = quads if len(tris): indexed_face_set['tris'] = tris i += 1 elif datai == 'normal': i += 1 datai = data[i] assert datai == 'Normal', datai i += 1 vector_normals = data[i] #print(vector_normals) assert len(vector_normals) == 2, vector_normals normals = np.array(tolist(vector_normals[1]), dtype='float64') indexed_face_set['normals'] = normals i += 1 elif datai == 'texCoord': i += 1 datai = data[i] assert datai == 'TextureCoordinate', datai i += 1 datai = data[i] assert datai == 'point', datai i += 1 point = data[i] #print('point!', point) points = np.array(tolist(point), dtype='float64') indexed_face_set['tex_coord'] = { 'point' : points, } i += 1 elif datai == 'creaseAngle': i += 1 datai = data[i] indexed_face_set['crease_angle'] = datai i += 1 else: raise NotImplementedError(f'datai={datai!r} type={type(datai)}') #print(type(indexed_face_set)) return indexed_face_set def toshape(data): shape = {} i = 0 while i < len(data): datai = data[i] if datai == 'appearance': #key = datai i += 1 datai = data[i] assert data[i] == 'Appearance', data[i] i += 1 #datai = data[i] #i += 1 #datai = data[i] #print(datai) #aa shape['appearance'] = None datai = data[i] if isinstance(datai, ParseResults): datai = datai.asList() if datai[0] == 'texture': i += 1 datai = data[i] #return shape if isinstance(datai, ParseResults): datai = datai.asList() #['material', 'Material', # ['ambientIntensity', 0.21, # 'diffuseColor', [0.49, 0.49, 0.49], # 'specularColor', [0.5, 0.5, 0.5], # 'transparency', 0.0, # 'shininess', 0.6]] i += 1 #j = 0 #while j < len(datai): datai = data[i] if datai == 'geometry': continue raise NotImplementedError(f'datai={datai!r} type={type(datai)}') elif datai == 'geometry': i += 1 datai = data[i] #print(datai) if datai == 'Sphere': shape['geometry'] = 'sphere' elif datai == 'IndexedFaceSet': i += 1 datai = data[i] indexed_face_set = read_indexed_face_set(datai) shape['indexed_face_set'] = indexed_face_set else: raise NotImplementedError(f'datai={datai!r} type={type(datai)}') i += 1 else: raise NotImplementedError(f'datai={datai!r} type={type(datai)}') return shape def todict(pmodel, log): out_model = { 'transforms' : [], } i = 0 while i < len(pmodel): modeli = pmodel[i] if modeli == 'WorldInfo': i += 1 data = pmodel[i] out_model[modeli] = todicti(data, log) i += 1 elif modeli == 'Background': i += 1 data = pmodel[i] out_model[modeli] = todicti(data, log) i += 1 elif modeli == 'NavigationInfo': i += 1 data = pmodel[i] out_model[modeli] = todicti(data, log) i += 1 elif modeli == 'Shape': i += 1 data = pmodel[i] out_model[modeli] = toshape(data) i += 1 elif modeli == 'Transform': i += 1 data = pmodel[i] # children assert data == 'children', data #out_model[modeli] = totransform(data) i += 1 data = pmodel[i] #print(data) transforms = read_transforms(data) #assert 'transforms' not in out_model out_model['transforms'].append(transforms) i += 1 elif isinstance(modeli, ParseResults): modeli = modeli.asList() #print(modeli) #['DirectionalLight', # ['direction', [0.577, -0.577, -0.577], # 'color', [1.0, 1.0, 1.0], # 'intensity', 0.45, # 'ambientIntensity', 1.0]] j = 0 while j < len(modeli): datai = modeli[j] if datai == 'DirectionalLight': j += 2 else: raise NotImplementedError(f'datai={datai!r} type={type(datai)}') i += 1 elif modeli == 'DEF': # DEF Body__115117 Transform i += 1 modeli = pmodel[i] log.debug('%r' % modeli) i += 1 #modeli = pmodel[i] #print('%r' % modeli) #i += 1 else: raise NotImplementedError(f'modeli={modeli!r} type={type(modeli)}') #print('----------------------------') return out_model
sisbell/appia
oulipo-communications/src/test/net/sf/appia/demo/jmx/ActuatorTest.java
/** * Appia: Group communication and protocol composition framework library * Copyright 2009 INESC-ID/IST * * 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. * * Initial developer(s): <NAME> and <NAME>. * Contributor(s): See Appia web page for a list of contributors. */ package net.sf.appia.demo.jmx; import javax.management.Attribute; import net.sf.appia.management.AppiaManagementException; import net.sf.appia.management.jmx.GenericActuator; public class ActuatorTest { /** * @param args */ public static void main(String[] args) { if((args[0].equals("remote") && args.length != 4) || (args[0].equals("local") && args.length != 3)){ System.out.println("Usage:\njava "+ActuatorTest.class.getName()+" remote <host> <port> <channelName>"+ "\nOR\njava "+ActuatorTest.class.getName()+" local <managementMBeanID> <channelName>"); System.exit(-1); } GenericActuator actuator = new GenericActuator(); try { if(args[0].equals("remote")) actuator.connect(args[1], Integer.parseInt(args[2]), args[3]); else actuator.getLocalMBean(args[1], args[2]); System.out.println("Current group attribute: "+actuator.getAttribute("remoteaddr:group")); actuator.setAttribute(new Attribute("remoteaddr:group","NewGroupID")); System.out.println("Current group attribute: "+actuator.getAttribute("remoteaddr:group")); } catch (NumberFormatException e) { e.printStackTrace(); } catch (AppiaManagementException e) { e.printStackTrace(); } } }
kinyz/KServer
server/login/service/user.go
package service import ( utils2 "KServer/library/utils" "KServer/manage" "KServer/server/utils/msg" "KServer/server/utils/pd" "fmt" "github.com/kataras/iris/v12" "gopkg.in/mgo.v2/bson" ) type User struct { Account *pd.Account Manage manage.IManage Encrypt *utils2.Encrypt } func NewUser(manage manage.IManage) *User { u := User{} u.Manage = manage return &u } func (u *User) PreHandler(ctx iris.Context) { ctx.Next() } func (u *User) AccountRegister(ctx iris.Context) { if err := ctx.ReadJSON(&u.Account); err != nil { _, _ = ctx.JSON(iris.Map{"state": "fail", "msg": "系统错误"}) return } if len(u.Account.Account) < 1 || len(u.Account.Account) < 1 { _, _ = ctx.JSON(iris.Map{"state": "fail", "msg": "账号或密码不能为空"}) return } coll := u.Manage.DB().Mongo().GetCollection("user_account") err := coll.Find(bson.M{"account": u.Account.Account}).One(&u.Account) if err == nil { _, _ = ctx.JSON(iris.Map{"state": "fail", "msg": "账号已存在"}) return } u.Account.UUID = u.Encrypt.NewUuid() u.Account.Token = u.Encrypt.NewToken() err = coll.Insert(&u.Account) if err != nil { _, _ = ctx.JSON(iris.Map{"state": "fail", "msg": err.Error()}) return } key := msg.ClientLoginInfoKey + u.Account.UUID _, _ = u.Manage.DB().Redis().GetMasterConn().Set(key).ProtoBuf(u.Account) //_, _ = u.Redis.SetValueByProto(key, &u.Account) u.Account.PassWord = "******" // 返回隐藏密码 _, _ = ctx.JSON(iris.Map{"state": "success", "msg": "注册成功", "result": u.Account}) } func (u *User) AccountLogin(ctx iris.Context) { if err := ctx.ReadJSON(&u.Account); err != nil { _, _ = ctx.JSON(iris.Map{"state": "fail", "msg": "系统错误"}) return } if !u.Manage.Lock().Lock().Auto(msg.LockAccount+u.Account.Account, 10) { //fmt.Println("加锁失败") _, _ = ctx.JSON(iris.Map{"state": "fail", "msg": "登陆失败,请10秒后重试"}) return } defer u.Manage.Lock().SendKafka(msg.LockAccount+u.Account.Account, msg.LockTypeAutoUnLock) if len(u.Account.Account) < 1 || len(u.Account.Account) < 1 { _, _ = ctx.JSON(iris.Map{"state": "fail", "msg": "账号或密码不能为空"}) return } //key := utils.ClientLoginInfoKey + u.Account.UUID //fmt.Println(u.Account.UUID) //dbUser := &pd.Account{} /* if u.Manage.DB().Redis().GetSlaveConn().Get(key).ProtoBuf(dbUser) == nil { if dbUser.Account == u.Account.Account && dbUser.PassWord == u.Account.PassWord { if dbUser.Online == utils.ClientOnline { //dbUser.Token = u.Encrypt.NewToken() _, _ = ctx.JSON(iris.Map{"state": "fail", "msg": "账号已在线"}) return } dbUser.Token = u.Encrypt.NewToken() _, err := u.Manage.DB().Redis().GetMasterConn().Set(utils.ClientLoginInfoKey + u.Account.UUID).ProtoBuf(dbUser) if err != nil { fmt.Println("err1=", err) } //_, _ = u.Redis.SetValueByProto(key, dbUser) dbUser.PassWord = "******" // 返回隐藏密码 fmt.Println(u.Account.UUID) _, _ = ctx.JSON(iris.Map{"state": "success", "msg": "登陆成功", "result": dbUser}) } else { _, _ = ctx.JSON(iris.Map{"state": "fail", "msg": "密码错误"}) } } else { */ coll := u.Manage.DB().Mongo().GetCollection("user_account") loginPassWord := u.Account.PassWord err := coll.Find(bson.M{"account": u.Account.Account}).One(&u.Account) if err != nil { _, _ = ctx.JSON(iris.Map{"state": "fail", "msg": "账号不存在"}) return } if loginPassWord != u.Account.PassWord { _, _ = ctx.JSON(iris.Map{"state": "fail", "msg": "密码错误"}) return } if u.Account.Online == msg.ClientOnline { _, _ = ctx.JSON(iris.Map{"state": "fail", "msg": "账号已在线"}) return } u.Account.Token = u.Encrypt.NewToken() _ = coll.Update(bson.M{"account": u.Account.Account, "PassWord": u.Account.PassWord}, &u.Account) _, err = u.Manage.DB().Redis().GetMasterConn().Set(msg.ClientLoginInfoKey + u.Account.UUID).ProtoBuf(u.Account) if err != nil { fmt.Println("err2=", err) } //_, _ = u.Redis.SetValueByProto(key, &u.Account) u.Account.PassWord = "******" // 返回隐藏密码 fmt.Println(u.Account.UUID) _, _ = ctx.JSON(iris.Map{"state": "success", "msg": "登陆成功", "result": u.Account}) }
stefanbanu/FXGL
src/main/java/com/almasb/fxgl/entity/GameEntity.java
/* * The MIT License (MIT) * * FXGL - JavaFX Game Library * * Copyright (c) 2015-2017 AlmasB (<EMAIL>) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.almasb.fxgl.entity; import com.almasb.ents.Entity; import com.almasb.fxgl.entity.component.*; import javafx.geometry.Point2D; import javafx.geometry.Rectangle2D; import javafx.scene.Node; /** * Entity that guarantees to have Type, Position, Rotation, BoundingBox and View * components. * Provides methods to conveniently access commonly used features. * * @author <NAME> (AlmasB) (<EMAIL>) */ public class GameEntity extends Entity { private TypeComponent type; private PositionComponent position; private RotationComponent rotation; private BoundingBoxComponent bbox; private MainViewComponent view; public GameEntity() { type = new TypeComponent(); position = new PositionComponent(); rotation = new RotationComponent(); bbox = new BoundingBoxComponent(); view = new MainViewComponent(); addComponent(type); addComponent(position); addComponent(rotation); addComponent(bbox); addComponent(view); } /** * @return type component */ public final TypeComponent getTypeComponent() { return type; } /** * @return position component */ public final PositionComponent getPositionComponent() { return position; } /** * @return rotation component */ public final RotationComponent getRotationComponent() { return rotation; } /** * @return bounding box component */ public final BoundingBoxComponent getBoundingBoxComponent() { return bbox; } /** * @return view component */ public final MainViewComponent getMainViewComponent() { return view; } // TYPE BEGIN /** * @return entity type */ public final Object getType() { return type.getValue(); } /** * <pre> * Example: * entity.isType(Type.PLAYER); * </pre> * * @param type entity type * @return true iff this type component is of given type */ public final boolean isType(Object type) { return this.type.isType(type); } // TYPE END // POSITION BEGIN /** * @return top left point of this entity in world coordinates */ public final Point2D getPosition() { return position.getValue(); } /** * Set top left position of this entity in world coordinates. * * @param position point */ public final void setPosition(Point2D position) { this.position.setValue(position); } /** * @return top left x */ public final double getX() { return position.getX(); } /** * @return top left y */ public final double getY() { return position.getY(); } /** * Set position x of this entity. * * @param x x coordinate */ public final void setX(double x) { position.setX(x); } /** * Set position y of this entity. * * @param y y coordinate */ public final void setY(double y) { position.setY(y); } /** * Translate x and y by given vector. * * @param vector translate vector */ public final void translate(Point2D vector) { position.translate(vector); } /** * Translate X by given value. * * @param dx dx */ public final void translateX(double dx) { position.translateX(dx); } /** * Translate Y by given value. * * @param dy dy */ public final void translateY(double dy) { position.translateY(dy); } /** * @param other the other component * @return distance in pixels from this position to the other */ public final double distance(GameEntity other) { return position.distance(other.position); } // POSITION END // ROTATION BEGIN /** * @return rotation angle */ public final double getRotation() { return rotation.getValue(); } /** * Set absolute rotation angle. * * @param angle rotation angle */ public final void setRotation(double angle) { rotation.setValue(angle); } /** * Rotate entity view by given angle clockwise. * To rotate counter clockwise use a negative angle value. * * Note: this doesn't affect hit boxes. For more accurate * collisions use {@link com.almasb.fxgl.physics.PhysicsComponent}. * * @param angle rotation angle in degrees */ public final void rotateBy(double angle) { rotation.rotateBy(angle); } /** * Set absolute rotation of the entity view to angle * between vector and positive X axis. * This is useful for projectiles (bullets, arrows, etc) * which rotate depending on their current velocity. * Note, this assumes that at 0 angle rotation the scene view is * facing right. * * @param vector the rotation vector / velocity vector */ public final void rotateToVector(Point2D vector) { rotation.rotateToVector(vector); } // ROTATION END // BBOX BEGIN /** * @return width of this entity based on bounding box */ public final double getWidth() { return bbox.getWidth(); } /** * @return height of this entity based on bounding box */ public final double getHeight() { return bbox.getHeight(); } /** * @return the righmost x of this entity in world coordinates */ public final double getRightX() { return bbox.getMaxXWorld(); } /** * @return the bottom y of this entity in world coordinates */ public final double getBottomY() { return bbox.getMaxYWorld(); } /** * @return center point of this entity in world coordinates */ public final Point2D getCenter() { return bbox.getCenterWorld(); } /** * @param other the other game entity * @return true iff bbox of this entity is colliding with bbox of other */ public final boolean isColliding(GameEntity other) { return bbox.isCollidingWith(other.bbox); } /** * @param bounds a rectangular box that represents bounds * @return true iff entity is partially or entirely within given bounds */ public final boolean isWithin(Rectangle2D bounds) { return bbox.isWithin(bounds); } // BBOX END // VIEW BEGIN /** * @return entity view */ public final EntityView getView() { return this.view.getView(); } /** * Set view without generating bounding boxes from view. * * @param view the view */ public final void setView(Node view) { this.view.setView(view); } /** * Set view from texture. * * @param textureName name of texture */ public final void setViewFromTexture(String textureName) { this.view.setTexture(textureName); } /** * Set view from texture and generate bbox from it. * * @param textureName name of texture */ public final void setViewFromTextureWithBBox(String textureName) { this.view.setTexture(textureName, true); } /** * Set view and generate bounding boxes from view. * * @param view the view */ public final void setViewWithBBox(Node view) { this.view.setView(view, true); } /** * @return render layer */ public final RenderLayer getRenderLayer() { return this.view.getRenderLayer(); } /** * Set render layer. * * @param layer render layer */ public final void setRenderLayer(RenderLayer layer) { this.view.setRenderLayer(layer); } // VIEW END @Override public String toString() { return "GameEntity(" + type + "," + position + "," + rotation + ")"; } }
yeehanchung/evergreen
src/themes/default/components/table-row.js
const colorMap = { none: { base: 'white', hover: 'colors.gray75', focus: 'colors.gray75', active: 'intents.info.background', current: 'intents.info.background' }, danger: { base: 'intents.danger.background', hover: 'intents.danger.background', focus: 'colors.red100', active: 'colors.red100', current: 'colors.red100' }, warning: { base: 'intents.warning.background', hover: 'intents.warning.background', focus: 'colors.orange100', active: 'colors.orange100', current: 'colors.orange100' }, success: { base: 'intents.success.background', hover: 'intents.success.background', focus: 'colors.green100', active: 'colors.green100', current: 'colors.green100' } } const getBackgroundForIntentAndState = (intent, state) => colorMap[intent][state] const baseStyle = { outline: 'none', textDecoration: 'none', height: 64, _isSelectable: { cursor: 'pointer' } } const appearances = { default: { backgroundColor: (_, props) => getBackgroundForIntentAndState(props.intent, 'base'), _hover: { backgroundColor: (_, props) => getBackgroundForIntentAndState(props.intent, 'hover') }, _focus: { backgroundColor: (_, props) => getBackgroundForIntentAndState(props.intent, 'focus') }, _active: { backgroundColor: (_, props) => getBackgroundForIntentAndState(props.intent, 'active') }, _current: { backgroundColor: (_, props) => getBackgroundForIntentAndState(props.intent, 'current') } } } export default { baseStyle, appearances }
kavish-d/fdk-client-python
fdk_client/application/models/AdminAnnouncementSchema.py
"""Application Models.""" from marshmallow import fields, Schema from marshmallow.validate import OneOf from ..enums import * from ..models.BaseSchema import BaseSchema from .AnnouncementPageSchema import AnnouncementPageSchema from .EditorMeta import EditorMeta from .AnnouncementAuthorSchema import AnnouncementAuthorSchema from .ScheduleSchema import ScheduleSchema class AdminAnnouncementSchema(BaseSchema): # Content swagger.json _id = fields.Str(required=False) platforms = fields.List(fields.Str(required=False), required=False) title = fields.Str(required=False) announcement = fields.Str(required=False) pages = fields.List(fields.Nested(AnnouncementPageSchema, required=False), required=False) editor_meta = fields.Nested(EditorMeta, required=False) author = fields.Nested(AnnouncementAuthorSchema, required=False) created_at = fields.Str(required=False) app = fields.Str(required=False) modified_at = fields.Str(required=False) _schedule = fields.Nested(ScheduleSchema, required=False)
whilewon/Activiti
modules/activiti-rest/src/test/java/org/activiti/rest/api/runtime/ProcessInstanceDiagramResourceTest.java
/* 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.activiti.rest.api.runtime; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.test.Deployment; import org.activiti.rest.BaseRestTestCase; import org.activiti.rest.api.RestUrls; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; /** * @author <NAME> */ public class ProcessInstanceDiagramResourceTest extends BaseRestTestCase { @Deployment public void testGetProcessDiagram() throws Exception { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("simpleProcess"); ClientResource client = getAuthenticatedClient(RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_DIAGRAM, processInstance.getId())); Representation response = client.get(); assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus()); assertTrue(response.isAvailable()); } @Deployment public void testGetProcessDiagramWithoutDiagram() throws Exception { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); ClientResource client = getAuthenticatedClient(RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_DIAGRAM, processInstance.getId())); try { client.get(); fail("Exception expected"); } catch(ResourceException expected) { assertEquals(Status.CLIENT_ERROR_BAD_REQUEST, expected.getStatus()); assertEquals("Process instance with id '" + processInstance.getId() + "' has no graphical notation defined.", expected.getStatus().getDescription()); } } /** * Test getting an unexisting process instance. */ public void testGetUnexistingProcessInstance() { ClientResource client = getAuthenticatedClient(RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_DIAGRAM, "unexistingpi")); try { client.get(); fail("Exception expected"); } catch(ResourceException expected) { assertEquals(Status.CLIENT_ERROR_NOT_FOUND, expected.getStatus()); assertEquals("Could not find a process instance with id 'unexistingpi'.", expected.getStatus().getDescription()); } } }