text
stringlengths
2
100k
meta
dict
/* * Copyright Beijing 58 Information Technology Co.,Ltd. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.bj58.spat.gaea.server.core.communication.telnet; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.group.ChannelGroupFuture; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import com.bj58.spat.gaea.server.contract.context.Global; import com.bj58.spat.gaea.server.contract.log.ILog; import com.bj58.spat.gaea.server.contract.log.LogFactory; import com.bj58.spat.gaea.server.contract.server.IServer; /** * start netty server * * @author Service Platform Architecture Team ([email protected]) */ public class TelnetServer implements IServer { public TelnetServer() { } private static ILog logger = LogFactory.getLogger(TelnetServer.class); /** * netty ServerBootstrap */ private static final ServerBootstrap bootstrap = new ServerBootstrap(); /** * record all channel */ public static final ChannelGroup allChannels = new DefaultChannelGroup("58ControlServer"); /** * start netty server */ @Override public void start() throws Exception { logger.info("----------------telnet server config------------------"); logger.info("-- telnet server listen ip: " + Global.getSingleton().getServiceConfig().getString("gaea.server.telnet.listenIP")); logger.info("-- telnet server port: " + Global.getSingleton().getServiceConfig().getInt("gaea.server.telnet.listenPort")); logger.info("------------------------------------------------------"); bootstrap.setFactory(new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); TelnetHandler handler = new TelnetHandler(); bootstrap.setPipelineFactory(new TelnetPipelineFactory(handler, Global.getSingleton().getServiceConfig().getInt("gaea.server.telnet.frameMaxLength"))); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.receiveBufferSize", Global.getSingleton().getServiceConfig().getInt("gaea.server.telnet.receiveBufferSize")); bootstrap.setOption("child.sendBufferSize", Global.getSingleton().getServiceConfig().getInt("gaea.server.telnet.sendBufferSize")); try { InetSocketAddress socketAddress = null; socketAddress = new InetSocketAddress(Global.getSingleton().getServiceConfig().getString("gaea.server.telnet.listenIP"), Global.getSingleton().getServiceConfig().getInt("gaea.server.telnet.listenPort")); Channel channel = bootstrap.bind(socketAddress); allChannels.add(channel); } catch (Exception e) { e.printStackTrace(); } } /** * stop netty server */ @Override public void stop() throws Exception { logger.info("----------------------------------------------------"); logger.info("-- telnet Server closing..."); logger.info("-- channels count : " + allChannels.size()); ChannelGroupFuture future = allChannels.close(); future.awaitUninterruptibly(); bootstrap.getFactory().releaseExternalResources(); logger.info("-- close success !"); logger.info("----------------------------------------------------"); } }
{ "pile_set_name": "Github" }
awk '1' filename
{ "pile_set_name": "Github" }
#include "include\souistd.h" #include "control\SSpinButton.h" namespace SOUI { SSpinButton::SSpinButton() : m_nMinValue(0) , m_nMaxValue(100) , m_pBuddy(NULL) , m_pSpinSkin(NULL) , m_nHover(-1) , m_uStep(1) , m_bCircle(true) , m_iNextTime(0) { m_bFocusable = TRUE; m_pSpinSkin = GETSKIN(L"_skin.sys.btn.spin", 100); } SSpinButton::~SSpinButton() { } void SSpinButton::SetBuddy(SWindow* pBuddy) { m_pBuddy = pBuddy; } LRESULT SSpinButton::OnCreate(LPVOID) { if (0 != __super::OnCreate(NULL)) return 1; return 0; } void SSpinButton::OnShowWindow(BOOL bShow, UINT nStatus) { __super::OnShowWindow(bShow, nStatus); if (!bShow) { if (IsPlaying()) GetContainer()->UnregisterTimelineHandler(this); } else { if (IsPlaying()) GetContainer()->RegisterTimelineHandler(this); } } void SSpinButton::OnDestroy() { Stop(); } void SSpinButton::OnPaint(IRenderTarget *pRT) { __super::OnPaint(pRT); if (NULL == m_pSpinSkin) return; CRect rcClient; GetClientRect(&rcClient); SIZE si = m_pSpinSkin->GetSkinSize(); int nSepX = (rcClient.right - rcClient.left - si.cx) / 2; int nSepY = (rcClient.bottom - rcClient.top - si.cy) / 4; // ¼ÆËã CRect rc1(rcClient); rc1.left += nSepX; rc1.top += nSepY; rc1.right = rc1.left + si.cx; rc1.bottom = rc1.top + si.cy; CRect rc2(rcClient); rc2.left += nSepX; rc2.bottom -= nSepY; rc2.right = rc2.left + si.cx; rc2.top = rc2.bottom - si.cy; int nState1 = 0; int nState2 = 0; if (1 == m_nHover) { nState1 = IIF_STATE4(GetState(), 0, 1, 2, 0); } else if(2 == m_nHover) { nState2 = IIF_STATE4(GetState(), 0, 1, 2, 0); } m_pSpinSkin->Draw(pRT, rc1, nState1); m_pSpinSkin->Draw(pRT, rc2, nState2+3); } int SSpinButton::HitTest(CPoint pt) { CRect rcClient; GetClientRect(&rcClient); // ¼ÆËã CRect rc1(rcClient); int nHover = (pt.y > (rcClient.bottom - rcClient.top) / 2 + rc1.top) ? 2 : 1; return nHover; } void SSpinButton::OnNextFrame() { if(m_bFirst) { if (m_iNextTime < 50) { ++m_iNextTime; return; } m_iNextTime = 0; m_bFirst = false; } if (m_iNextTime > 5) m_iNextTime = 0; if (m_iNextTime == 0 && IsPlaying()) ChangeValue(m_nHover); ++m_iNextTime; } void SSpinButton::OnLButtonDown(UINT nFlags, CPoint pt) { if (m_bFocusable) SetFocus(); SetCapture(); ModifyState(WndState_PushDown, 0, TRUE); m_nPush = HitTest(pt); ChangeValue(m_nPush); Start(); } void SSpinButton::OnLButtonUp(UINT nFlags, CPoint pt) { SWindow::OnLButtonUp(nFlags, pt); Invalidate(); KillFocus(); Stop(); m_nPush = -1; } void SSpinButton::OnMouseMove(UINT nFlags, CPoint point) { int nHover = HitTest(point); if (nHover != m_nHover) { m_nHover = nHover; Invalidate(); } } void SSpinButton::OnMouseLeave() { SWindow::OnMouseLeave(); m_nHover = -1; Invalidate(); } HRESULT SSpinButton::OnAttrBuddy(const SStringW& strValue, BOOL bLoading) { SWindow* pParent = this; while (true) { pParent = pParent->GetParent(); if (NULL == pParent) break; m_pBuddy = pParent->FindChildByName(strValue); if(NULL != m_pBuddy) break; } return S_OK; } void SSpinButton::Start() { m_bFirst = true; m_iNextTime = 0; if (IsVisible(TRUE)) GetContainer()->RegisterTimelineHandler(this); } void SSpinButton::Stop() { if (IsVisible(TRUE)) GetContainer()->UnregisterTimelineHandler(this); } bool SSpinButton::IsPlaying() { if (m_dwState && WndState_PushDown && m_nPush == m_nHover) return true; return false; } void SSpinButton::ChangeValue(int nHover) { if (NULL == m_pBuddy) { EventSpinValue2String evt(this); evt.nValue = nHover; evt.strValue; FireEvent(evt); return; } SStringT sBuddyValue = m_pBuddy->GetWindowText(TRUE); int nValue = _ttoi(sBuddyValue); if (1 == nHover) { nValue += m_uStep; if (nValue > m_nMaxValue) { if (m_bCircle) nValue = m_nMinValue; else nValue = m_nMaxValue; } } else if (2 == nHover) { nValue -= m_uStep; if (nValue < m_nMinValue) { if (m_bCircle) nValue = m_nMaxValue; else nValue = m_nMinValue; } } EventSpinValue2String evt(this); evt.nValue = nValue; evt.strValue.Format(_T("%d"), nValue); FireEvent(evt); if (!evt.bubbleUp) return; m_pBuddy->SetWindowText(evt.strValue); } }//namespace SOUI
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #pragma mark - // // File: /Applications/Xcode-7GM.app/Contents/Developer/Platforms/WatchSimulator.platform/Developer/SDKs/WatchSimulator.sdk/System/Library/PrivateFrameworks/FontServices.framework/FontServices // UUID: E2805055-BA4C-3A5A-A1E9-54699F3C8AF0 // // Arch: i386 // Current version: 1.0.0 // Compatibility version: 1.0.0 // Source version: 156.0.0.0.0 // // // This file does not contain any Objective-C runtime information. //
{ "pile_set_name": "Github" }
/* * Copyright 2019 Xilinx 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. */ #ifndef __COMMON_H__ #define __COMMON_H__ #include <glog/logging.h> #include <iostream> #include <mutex> #include <opencv2/opencv.hpp> #include <string> #include <thread> #include <vector> /* header file for Vitis AI unified API */ #include <vart/mm/host_flat_tensor_buffer.hpp> #include <vart/runner.hpp> #include <xir/graph/graph.hpp> #include <xir/tensor/tensor.hpp> struct TensorShape { unsigned int height; unsigned int width; unsigned int channel; unsigned int size; }; struct GraphInfo { struct TensorShape* inTensorList; struct TensorShape* outTensorList; std::vector<int> output_mapping; }; int getTensorShape(vart::Runner* runner, GraphInfo* shapes, int cntin, const std::vector<std::string> output_names); int getTensorShape(vart::Runner* runner, GraphInfo* shapes, int cntin, int cnout); inline std::vector<std::unique_ptr<xir::Tensor>> cloneTensorBuffer( const std::vector<const xir::Tensor*>& tensors) { auto ret = std::vector<std::unique_ptr<xir::Tensor>>{}; auto type = xir::DataType::FLOAT; ret.reserve(tensors.size()); for (const auto& tensor : tensors) { ret.push_back(std::unique_ptr<xir::Tensor>(xir::Tensor::create( tensor->get_name(), tensor->get_dims(), type, sizeof(float) * 8u))); } return ret; } inline std::vector<const xir::Subgraph*> get_dpu_subgraph( const xir::Graph* graph) { auto root = graph->get_root_subgraph(); auto children = root->children_topological_sort(); auto ret = std::vector<const xir::Subgraph*>(); for (auto c : children) { CHECK(c->has_attr("device")); auto device = c->get_attr<std::string>("device"); if (device == "DPU") { ret.emplace_back(c); } } return ret; } class CpuFlatTensorBuffer : public vart::TensorBuffer { public: explicit CpuFlatTensorBuffer(void* data, const xir::Tensor* tensor) : TensorBuffer{tensor}, data_{data} {} virtual ~CpuFlatTensorBuffer() = default; public: virtual std::pair<uint64_t, size_t> data( const std::vector<int> idx = {}) override { uint32_t size = std::ceil(tensor_->get_bit_width() / 8.f); if (idx.size() == 0) { return {reinterpret_cast<uint64_t>(data_), tensor_->get_element_num() * size}; } auto dims = tensor_->get_dims(); auto offset = 0; for (auto k = 0; k < tensor_->get_dim_num(); k++) { auto stride = 1; for (auto m = k + 1; m < tensor_->get_dim_num(); m++) { stride *= dims[m]; } offset += idx[k] * stride; } auto elem_num = tensor_->get_element_num(); return {reinterpret_cast<uint64_t>(data_) + offset * size, (elem_num - offset) * size}; } private: void* data_; }; #endif
{ "pile_set_name": "Github" }
package com.android.post.domain.repository import com.android.post.domain.model.Post interface PostsRepository { suspend fun getPosts(): List<Post> }
{ "pile_set_name": "Github" }
[all] hostname = all name = thisname db.host = 127.0.0.1 db.user = username db.pass = password db.name = live one.two.three = multi [staging: all] hostname = staging db.name = dbstaging debug = false [debug:all] hostname = debug debug = true values.changed = yes db.name = dbdebug special.no = no special.null = null special.false = false [other_staging: staging] only_in = otherStaging db.pass = anotherpwd ; invalid keys [leadingdot] .test = dot-test [onedot] . = dot-test [twodots] ... = dot-test [threedots] ... = dot-test [trailingdot] test. = dot-test [extendserror:nonexistent] testing =123 [zf426] db = one db.name = two
{ "pile_set_name": "Github" }
/* ** file.c - File class */ #include "mruby.h" #include "mruby/class.h" #include "mruby/data.h" #include "mruby/string.h" #include "mruby/ext/io.h" #if MRUBY_RELEASE_NO < 10000 #include "error.h" #else #include "mruby/error.h" #endif #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <limits.h> #include <errno.h> #include <stdlib.h> #include <string.h> #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #include <io.h> #define NULL_FILE "NUL" #define UNLINK _unlink #define GETCWD _getcwd #define CHMOD(a, b) 0 #define MAXPATHLEN 1024 #if !defined(PATH_MAX) #define PATH_MAX _MAX_PATH #endif #define realpath(N,R) _fullpath((R),(N),_MAX_PATH) #include <direct.h> #else #define NULL_FILE "/dev/null" #include <unistd.h> #define UNLINK unlink #define GETCWD getcwd #define CHMOD(a, b) chmod(a,b) #include <sys/file.h> #include <libgen.h> #include <sys/param.h> #include <pwd.h> #endif #define FILE_SEPARATOR "/" #if defined(_WIN32) || defined(_WIN64) #define PATH_SEPARATOR ";" #define FILE_ALT_SEPARATOR "\\" #else #define PATH_SEPARATOR ":" #endif #ifndef LOCK_SH #define LOCK_SH 1 #endif #ifndef LOCK_EX #define LOCK_EX 2 #endif #ifndef LOCK_NB #define LOCK_NB 4 #endif #ifndef LOCK_UN #define LOCK_UN 8 #endif #define STAT(p, s) stat(p, s) #ifdef _WIN32 static int flock(int fd, int operation) { OVERLAPPED ov; HANDLE h = (HANDLE)_get_osfhandle(fd); DWORD flags; flags = ((operation & LOCK_NB) ? LOCKFILE_FAIL_IMMEDIATELY : 0) | ((operation & LOCK_SH) ? LOCKFILE_EXCLUSIVE_LOCK : 0); memset(&ov, 0, sizeof(ov)); return LockFileEx(h, flags, 0, 0xffffffff, 0xffffffff, &ov) ? 0 : -1; } #endif mrb_value mrb_file_s_umask(mrb_state *mrb, mrb_value klass) { #if defined(_WIN32) || defined(_WIN64) /* nothing to do on windows */ return mrb_fixnum_value(0); #else mrb_int mask, omask; if (mrb_get_args(mrb, "|i", &mask) == 0) { omask = umask(0); umask(omask); } else { omask = umask(mask); } return mrb_fixnum_value(omask); #endif } static mrb_value mrb_file_s_unlink(mrb_state *mrb, mrb_value obj) { mrb_value *argv; mrb_value pathv; mrb_int argc, i; char *path; mrb_get_args(mrb, "*", &argv, &argc); for (i = 0; i < argc; i++) { const char *utf8_path; pathv = mrb_ensure_string_type(mrb, argv[i]); utf8_path = mrb_string_value_cstr(mrb, &pathv); path = mrb_locale_from_utf8(utf8_path, -1); if (UNLINK(path) < 0) { mrb_locale_free(path); mrb_sys_fail(mrb, utf8_path); } mrb_locale_free(path); } return mrb_fixnum_value(argc); } static mrb_value mrb_file_s_rename(mrb_state *mrb, mrb_value obj) { mrb_value from, to; char *src, *dst; mrb_get_args(mrb, "SS", &from, &to); src = mrb_locale_from_utf8(mrb_string_value_cstr(mrb, &from), -1); dst = mrb_locale_from_utf8(mrb_string_value_cstr(mrb, &to), -1); if (rename(src, dst) < 0) { #if defined(_WIN32) || defined(_WIN64) if (CHMOD(dst, 0666) == 0 && UNLINK(dst) == 0 && rename(src, dst) == 0) { mrb_locale_free(src); mrb_locale_free(dst); return mrb_fixnum_value(0); } #endif mrb_locale_free(src); mrb_locale_free(dst); mrb_sys_fail(mrb, mrb_str_to_cstr(mrb, mrb_format(mrb, "(%S, %S)", from, to))); } mrb_locale_free(src); mrb_locale_free(dst); return mrb_fixnum_value(0); } static mrb_value mrb_file_dirname(mrb_state *mrb, mrb_value klass) { #if defined(_WIN32) || defined(_WIN64) char dname[_MAX_DIR], vname[_MAX_DRIVE]; char buffer[_MAX_DRIVE + _MAX_DIR]; char *path; size_t ridx; mrb_value s; mrb_get_args(mrb, "S", &s); path = mrb_locale_from_utf8(mrb_str_to_cstr(mrb, s), -1); _splitpath((const char*)path, vname, dname, NULL, NULL); snprintf(buffer, _MAX_DRIVE + _MAX_DIR, "%s%s", vname, dname); mrb_locale_free(path); ridx = strlen(buffer); if (ridx == 0) { strncpy(buffer, ".", 2); /* null terminated */ } else if (ridx > 1) { ridx--; while (ridx > 0 && (buffer[ridx] == '/' || buffer[ridx] == '\\')) { buffer[ridx] = '\0'; /* remove last char */ ridx--; } } return mrb_str_new_cstr(mrb, buffer); #else char *dname, *path; mrb_value s; mrb_get_args(mrb, "S", &s); path = mrb_locale_from_utf8(mrb_str_to_cstr(mrb, s), -1); if ((dname = dirname(path)) == NULL) { mrb_locale_free(path); mrb_sys_fail(mrb, "dirname"); } mrb_locale_free(path); return mrb_str_new_cstr(mrb, dname); #endif } static mrb_value mrb_file_basename(mrb_state *mrb, mrb_value klass) { // NOTE: Do not use mrb_locale_from_utf8 here #if defined(_WIN32) || defined(_WIN64) char bname[_MAX_DIR]; char extname[_MAX_EXT]; char *path; size_t ridx; char buffer[_MAX_DIR + _MAX_EXT]; mrb_value s; mrb_get_args(mrb, "S", &s); path = mrb_str_to_cstr(mrb, s); ridx = strlen(path); if (ridx > 0) { ridx--; while (ridx > 0 && (path[ridx] == '/' || path[ridx] == '\\')) { path[ridx] = '\0'; ridx--; } if (strncmp(path, "/", 2) == 0) { return mrb_str_new_cstr(mrb, path); } } _splitpath((const char*)path, NULL, NULL, bname, extname); snprintf(buffer, _MAX_DIR + _MAX_EXT, "%s%s", bname, extname); return mrb_str_new_cstr(mrb, buffer); #else char *bname, *path; mrb_value s; mrb_get_args(mrb, "S", &s); path = mrb_str_to_cstr(mrb, s); if ((bname = basename(path)) == NULL) { mrb_sys_fail(mrb, "basename"); } if (strncmp(bname, "//", 3) == 0) bname[1] = '\0'; /* patch for Cygwin */ return mrb_str_new_cstr(mrb, bname); #endif } static mrb_value mrb_file_realpath(mrb_state *mrb, mrb_value klass) { mrb_value pathname, dir_string, s, result; mrb_int argc; char *cpath; argc = mrb_get_args(mrb, "S|S", &pathname, &dir_string); if (argc == 2) { s = mrb_str_dup(mrb, dir_string); s = mrb_str_append(mrb, s, mrb_str_new_cstr(mrb, FILE_SEPARATOR)); s = mrb_str_append(mrb, s, pathname); pathname = s; } cpath = mrb_locale_from_utf8(mrb_str_to_cstr(mrb, pathname), -1); result = mrb_str_buf_new(mrb, PATH_MAX); if (realpath(cpath, RSTRING_PTR(result)) == NULL) { mrb_locale_free(cpath); mrb_sys_fail(mrb, cpath); } mrb_locale_free(cpath); mrb_str_resize(mrb, result, strlen(RSTRING_PTR(result))); return result; } mrb_value mrb_file__getwd(mrb_state *mrb, mrb_value klass) { mrb_value path; char buf[MAXPATHLEN], *utf8; if (GETCWD(buf, MAXPATHLEN) == NULL) { mrb_sys_fail(mrb, "getcwd(2)"); } utf8 = mrb_utf8_from_locale(buf, -1); path = mrb_str_new_cstr(mrb, utf8); mrb_utf8_free(utf8); return path; } static int mrb_file_is_absolute_path(const char *path) { return (path[0] == '/'); } static mrb_value mrb_file__gethome(mrb_state *mrb, mrb_value klass) { mrb_int argc; char *home; mrb_value path; #ifndef _WIN32 mrb_value username; argc = mrb_get_args(mrb, "|S", &username); if (argc == 0) { home = getenv("HOME"); if (home == NULL) { return mrb_nil_value(); } if (!mrb_file_is_absolute_path(home)) { mrb_raise(mrb, E_ARGUMENT_ERROR, "non-absolute home"); } } else { const char *cuser = mrb_str_to_cstr(mrb, username); struct passwd *pwd = getpwnam(cuser); if (pwd == NULL) { return mrb_nil_value(); } home = pwd->pw_dir; if (!mrb_file_is_absolute_path(home)) { mrb_raisef(mrb, E_ARGUMENT_ERROR, "non-absolute home of ~%S", username); } } home = mrb_locale_from_utf8(home, -1); path = mrb_str_new_cstr(mrb, home); mrb_locale_free(home); return path; #else argc = mrb_get_argc(mrb); if (argc == 0) { home = getenv("USERPROFILE"); if (home == NULL) { return mrb_nil_value(); } if (!mrb_file_is_absolute_path(home)) { mrb_raise(mrb, E_ARGUMENT_ERROR, "non-absolute home"); } } else { return mrb_nil_value(); } home = mrb_locale_from_utf8(home, -1); path = mrb_str_new_cstr(mrb, home); mrb_locale_free(home); return path; #endif } static mrb_value mrb_file_mtime(mrb_state *mrb, mrb_value self) { mrb_value obj; struct stat st; int fd; obj = mrb_obj_value(mrb_class_get(mrb, "Time")); fd = (int)mrb_fixnum(mrb_io_fileno(mrb, self)); if (fstat(fd, &st) == -1) return mrb_false_value(); return mrb_funcall(mrb, obj, "at", 1, mrb_fixnum_value(st.st_mtime)); } mrb_value mrb_file_flock(mrb_state *mrb, mrb_value self) { #if defined(sun) mrb_raise(mrb, E_NOTIMP_ERROR, "flock is not supported on Illumos/Solaris/Windows"); #else mrb_int operation; int fd; mrb_get_args(mrb, "i", &operation); fd = (int)mrb_fixnum(mrb_io_fileno(mrb, self)); while (flock(fd, (int)operation) == -1) { switch (errno) { case EINTR: /* retry */ break; case EAGAIN: /* NetBSD */ #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN case EWOULDBLOCK: /* FreeBSD OpenBSD Linux */ #endif if (operation & LOCK_NB) { return mrb_false_value(); } /* FALLTHRU - should not happen */ default: mrb_sys_fail(mrb, "flock failed"); break; } } #endif return mrb_fixnum_value(0); } static mrb_value mrb_file_s_symlink(mrb_state *mrb, mrb_value klass) { #if defined(_WIN32) || defined(_WIN64) mrb_raise(mrb, E_NOTIMP_ERROR, "symlink is not supported on this platform"); #else mrb_value from, to; const char *src, *dst; int ai = mrb_gc_arena_save(mrb); mrb_get_args(mrb, "SS", &from, &to); src = mrb_locale_from_utf8(mrb_str_to_cstr(mrb, from), -1); dst = mrb_locale_from_utf8(mrb_str_to_cstr(mrb, to), -1); if (symlink(src, dst) == -1) { mrb_locale_free(src); mrb_locale_free(dst); mrb_sys_fail(mrb, mrb_str_to_cstr(mrb, mrb_format(mrb, "(%S, %S)", from, to))); } mrb_locale_free(src); mrb_locale_free(dst); mrb_gc_arena_restore(mrb, ai); #endif return mrb_fixnum_value(0); } static mrb_value mrb_file_s_chmod(mrb_state *mrb, mrb_value klass) { mrb_int mode; mrb_int argc, i; mrb_value *filenames; int ai = mrb_gc_arena_save(mrb); mrb_get_args(mrb, "i*", &mode, &filenames, &argc); for (i = 0; i < argc; i++) { const char *utf8_path = mrb_str_to_cstr(mrb, filenames[i]); char *path = mrb_locale_from_utf8(utf8_path, -1); if (CHMOD(path, mode) == -1) { mrb_locale_free(path); mrb_sys_fail(mrb, utf8_path); } mrb_locale_free(path); } mrb_gc_arena_restore(mrb, ai); return mrb_fixnum_value(argc); } static mrb_value mrb_file_s_readlink(mrb_state *mrb, mrb_value klass) { #if defined(_WIN32) || defined(_WIN64) mrb_raise(mrb, E_NOTIMP_ERROR, "readlink is not supported on this platform"); return mrb_nil_value(); // unreachable #else char *path, *buf, *tmp; size_t bufsize = 100; ssize_t rc; mrb_value ret; int ai = mrb_gc_arena_save(mrb); mrb_get_args(mrb, "z", &path); tmp = mrb_locale_from_utf8(path, -1); buf = (char *)mrb_malloc(mrb, bufsize); while ((rc = readlink(tmp, buf, bufsize)) == (ssize_t)bufsize && rc != -1) { bufsize *= 2; buf = (char *)mrb_realloc(mrb, buf, bufsize); } mrb_locale_free(tmp); if (rc == -1) { mrb_free(mrb, buf); mrb_sys_fail(mrb, path); } tmp = mrb_utf8_from_locale(buf, -1); ret = mrb_str_new(mrb, tmp, rc); mrb_locale_free(tmp); mrb_free(mrb, buf); mrb_gc_arena_restore(mrb, ai); return ret; #endif } void mrb_init_file(mrb_state *mrb) { struct RClass *io, *file, *cnst; io = mrb_class_get(mrb, "IO"); file = mrb_define_class(mrb, "File", io); MRB_SET_INSTANCE_TT(file, MRB_TT_DATA); mrb_define_class_method(mrb, file, "umask", mrb_file_s_umask, MRB_ARGS_REQ(1)); mrb_define_class_method(mrb, file, "delete", mrb_file_s_unlink, MRB_ARGS_ANY()); mrb_define_class_method(mrb, file, "unlink", mrb_file_s_unlink, MRB_ARGS_ANY()); mrb_define_class_method(mrb, file, "rename", mrb_file_s_rename, MRB_ARGS_REQ(2)); mrb_define_class_method(mrb, file, "symlink", mrb_file_s_symlink, MRB_ARGS_REQ(2)); mrb_define_class_method(mrb, file, "chmod", mrb_file_s_chmod, MRB_ARGS_REQ(1) | MRB_ARGS_REST()); mrb_define_class_method(mrb, file, "readlink", mrb_file_s_readlink, MRB_ARGS_REQ(1)); mrb_define_class_method(mrb, file, "dirname", mrb_file_dirname, MRB_ARGS_REQ(1)); mrb_define_class_method(mrb, file, "basename", mrb_file_basename, MRB_ARGS_REQ(1)); mrb_define_class_method(mrb, file, "realpath", mrb_file_realpath, MRB_ARGS_REQ(1)|MRB_ARGS_OPT(1)); mrb_define_class_method(mrb, file, "_getwd", mrb_file__getwd, MRB_ARGS_NONE()); mrb_define_class_method(mrb, file, "_gethome", mrb_file__gethome, MRB_ARGS_OPT(1)); mrb_define_method(mrb, file, "flock", mrb_file_flock, MRB_ARGS_REQ(1)); mrb_define_method(mrb, file, "mtime", mrb_file_mtime, MRB_ARGS_NONE()); cnst = mrb_define_module_under(mrb, file, "Constants"); mrb_define_const(mrb, cnst, "LOCK_SH", mrb_fixnum_value(LOCK_SH)); mrb_define_const(mrb, cnst, "LOCK_EX", mrb_fixnum_value(LOCK_EX)); mrb_define_const(mrb, cnst, "LOCK_UN", mrb_fixnum_value(LOCK_UN)); mrb_define_const(mrb, cnst, "LOCK_NB", mrb_fixnum_value(LOCK_NB)); mrb_define_const(mrb, cnst, "SEPARATOR", mrb_str_new_cstr(mrb, FILE_SEPARATOR)); mrb_define_const(mrb, cnst, "PATH_SEPARATOR", mrb_str_new_cstr(mrb, PATH_SEPARATOR)); #if defined(_WIN32) || defined(_WIN64) mrb_define_const(mrb, cnst, "ALT_SEPARATOR", mrb_str_new_cstr(mrb, FILE_ALT_SEPARATOR)); #else mrb_define_const(mrb, cnst, "ALT_SEPARATOR", mrb_nil_value()); #endif mrb_define_const(mrb, cnst, "NULL", mrb_str_new_cstr(mrb, NULL_FILE)); }
{ "pile_set_name": "Github" }
export { default } from './Applications';
{ "pile_set_name": "Github" }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and software framework */ /* UG --- Ubquity Generator Framework */ /* */ /* Copyright (C) 2010-2013 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* UG is distributed under the terms of the ZIB Academic Licence. */ /* */ /* You should have received a copy of the ZIB Academic License */ /* along with UG; see the file COPYING. If not email to [email protected]. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file scipParaInitiator.h * @brief ParaInitiator extension for SCIP solver. * @author Yuji Shinano * * * */ /*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/ #ifndef __SCIP_PARA_INITIATOR_H__ #define __SCIP_PARA_INITIATOR_H__ #include <string> #include "ug/paraDef.h" #include "scipParaComm.h" #include "ug/paraInitiator.h" #include "scipUserPlugins.h" #include "scipDiffParamSet.h" #include "scipParaInstance.h" #include "scipParaSolution.h" #include "scipParaDiffSubproblem.h" #include "objscip/objscip.h" #include "scip/scip.h" #include "scip/scipdefplugins.h" namespace ParaSCIP { /** Initiator class */ class ScipParaInitiator : public UG::ParaInitiator { UG::ParaParamSet *paraParams; ScipParaInstance *instance; ScipParaSolution *solution; ScipDiffParamSet *scipDiffParamSetRoot; ScipDiffParamSet *scipDiffParamSet; SCIP_MESSAGEHDLR *messagehdlr; FILE *logfile; FILE *solutionFile; FILE *transSolutionFile; SCIP *scip; char *probname; char *settingsNameLC; char *settingsNameRoot; char *settingsName; char *racingSettingsName; char *logname; char *isolname; char *solutionFileName; ScipUserPlugins *userPlugins; SCIP_Real finalDualBound; UG::FinalSolverState finalState; long long nSolved; bool addRootNodeCuts(); void outputProblemInfo(int *nNonLinearConsHdlrs); bool onlyLinearConsHandler(); public: /** constructor */ ScipParaInitiator( UG::ParaComm *inComm ) : ParaInitiator(inComm), paraParams(0), instance(0), solution(0), scipDiffParamSetRoot(0), scipDiffParamSet(0), messagehdlr(0), logfile(0), solutionFile(0), transSolutionFile(0), scip(0), probname(0), settingsNameLC(0), settingsNameRoot(0), settingsName(0), racingSettingsName(0), logname(0), isolname(0), solutionFileName(0), userPlugins(0), finalDualBound(-DBL_MAX), finalState(UG::Aborted), nSolved(0) { } /** destructor */ ~ScipParaInitiator( ) { if( instance ) delete instance; if( solution ) delete solution; if( scipDiffParamSetRoot ) delete scipDiffParamSetRoot; if( scipDiffParamSet ) delete scipDiffParamSet; if( userPlugins ) delete userPlugins; // message handler is mangaed within scip. It is freed at SCIPfree #ifndef SCIP_THREADSAFE_MESSAGEHDLRS if( messagehdlr ) { SCIP_CALL_ABORT( SCIPsetDefaultMessagehdlr() ); SCIP_CALL_ABORT( SCIPfreeObjMessagehdlr(&messagehdlr) ); } #endif /****************** * Close files * ******************/ fclose(solutionFile); if( transSolutionFile ) { fclose(transSolutionFile); } /******************** * Deinitialization * ********************/ if( !paraParams->getBoolParamValue(UG::Quiet) ) { SCIP_CALL_ABORT( SCIPprintStatistics(scip, NULL) ); // output statistics (only for problem info) } if( scip ) { SCIP_CALL_ABORT( SCIPfree(&scip) ); } if( logfile != NULL ) fclose(logfile); BMScheckEmptyMemory(); } /** init function */ int init( UG::ParaParamSet *paraParams, int argc, char** argv ); /** get instance */ UG::ParaInstance *getParaInstance( ) { return instance; } /** make DiffSubproblem object for root node */ ScipParaDiffSubproblem *makeRootNodeDiffSubproblem( ) { return 0; } /** try to set incumbent solution */ bool tryToSetIncumbentSolution(UG::ParaSolution *sol); /** send solver initialization message */ void sendSolverInitializationMessage(); /** generate racing ramp-up parameter sets */ void generateRacingRampUpParameterSets(int nParamSets, UG::ParaRacingRampUpParamSet **racingRampUpParamSets); UG::ParaSolution *getGlobalBestIncumbentSolution() { return solution; } /** convert an internal value to external value */ double convertToExternalValue( double internalValue ) { return instance->convertToExternalValue(internalValue); } /** convert an external value to internal value */ double convertToInternalValue( double externalValue ) { return instance->convertToInternalValue(externalValue); } /** get solution file name */ char *getSolutionFileName( ) { return solutionFileName; } /** get gap */ double getGap(double dualBoundValue); /** get epsilon */ double getEpsilon(); /** write solution */ void writeSolution(const std::string& message); /** write ParaInstance */ void writeParaInstance(const std::string& filename); /** write solver runtime parameters */ void writeSolverParameters(std::ostream *os); /** write checkpoint solution */ void writeCheckpointSolution(const std::string& filename); /** read solution from checkpoint file */ double readSolutionFromCheckpointFile(char *afterCheckpointingSolutionFileName); /** get solving status string */ std::string getStatus(); /** print solver version **/ void printSolverVersion(std::ostream *os); /**< output file (or NULL for standard output) */ /** check if feasilbe soltuion exists or not */ bool isFeasibleSolution() { return ( SCIPgetBestSol(scip) != NULL ); } /** set initial stat on initiator */ void accumulateInitialStat(UG::ParaInitialStat *initialStat); /** set initial stat on DiffSubproblem */ void setInitialStatOnDiffSubproblem(int minDepth, int maxDepth, UG::ParaDiffSubproblem *diffSubproblem); /** set final solver status */ void setFinalSolverStatus(UG::FinalSolverState status); /** set number of nodes solved */ void setNumberOfNodesSolved(long long n); /** set final dual bound */ void setDualBound(double bound); /** output solution status */ void outputFinalSolverStatistics(std::ostream *os, double time); /** set user plugins */ void setUserPlugins(ScipUserPlugins *inUi) { userPlugins = inUi; } /** include user plugins */ void includeUserPlugins(SCIP *inScip) { if( userPlugins ) { (*userPlugins)(inScip); } } }; typedef ScipParaInitiator *ScipParaInitiatorPtr; } #endif // __SCIP_PARA_INITIATOR_H__
{ "pile_set_name": "Github" }
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/CloudDocsDaemon.framework/CloudDocsDaemon */ @interface BRCFileCoordinator : NSFileCoordinator { bool _cancelled; id /* block */ _doneHandler; bool _forRead; bool _isUpdateForReconnecting; BRCAccountSession * _session; unsigned long long _startStamp; NSObject<OS_dispatch_source> * _timer; NSURL * _url1; NSURL * _url2; } @property (nonatomic, readonly) bool forRead; @property (nonatomic) bool isUpdateForReconnecting; + (void)itemAtPath:(id)arg1 logicalFilename:(id)arg2 didMoveToPath:(id)arg3 logicalFilename:(id)arg4 hasContentUpdate:(bool)arg5; + (void)itemAtPath:(id)arg1 origLogicalName:(id)arg2 didBounceToNewLogicalName:(id)arg3; + (void)itemDidAppearAtPath:(id)arg1 logicalFilename:(id)arg2; + (void)itemDidChangeAtPath:(id)arg1 logicalFilename:(id)arg2; + (void)itemDidDisappearAtPath:(id)arg1 logicalFilename:(id)arg2; - (void).cxx_destruct; - (void)_didObtainCoordination:(id)arg1 context:(id)arg2 url1:(id)arg3 url2:(id)arg4 handler:(id /* block */)arg5 fcHandler:(id /* block */)arg6 error:(id)arg7; - (void)_willRequestCoordinationWithContext:(id)arg1 url1:(id)arg2 url2:(id)arg3; - (void)cancel; - (void)cancelAfterDelay:(double)arg1; - (bool)forRead; - (id)initWithSession:(id)arg1 forRead:(bool)arg2 doneHandler:(id /* block */)arg3; - (bool)isUpdateForReconnecting; - (void)scheduleDeleteOfItemAtURL:(id)arg1 queue:(id)arg2 taskTracker:(id)arg3 accessor:(id /* block */)arg4; - (void)scheduleReadOfItemAtURL:(id)arg1 queue:(id)arg2 taskTracker:(id)arg3 accessor:(id /* block */)arg4; - (void)scheduleRenameOfItemAtURL:(id)arg1 toItemAtURL:(id)arg2 contentUpdate:(bool)arg3 queue:(id)arg4 taskTracker:(id)arg5 accessor:(id /* block */)arg6; - (void)scheduleUpdateOfItemAtURL:(id)arg1 queue:(id)arg2 taskTracker:(id)arg3 accessor:(id /* block */)arg4; - (void)setIsUpdateForReconnecting:(bool)arg1; @end
{ "pile_set_name": "Github" }
/* InfoPlist.strings Owncloud iOs Client Created by Noelia Alvarez on 13/09/16. */ "NSPhotoLibraryUsageDescription" = "Upload your selected photos to your account"; "NSLocationAlwaysUsageDescription" = "Used to instantly upload your new photos after a significant change in your location"; "NSLocationWhenInUseUsageDescription" = "Used to instantly upload your new photos after a significant change in your location";
{ "pile_set_name": "Github" }
" I represent a mathematical matrix. I can be build from rows as follows: [[[ PMMatrix rows: #((1 2 3)(4 5 6)). ]]] I understand the usual matrix operations. " Class { #name : #PMMatrix, #superclass : #Object, #instVars : [ 'rows', 'lupDecomposition' ], #category : #'Math-Matrix' } { #category : #example } PMMatrix class >> example [ "" |a b c d| "This is how we can create a matrix, a and b are 2x3 matrices in this example" a := PMMatrix rows: #( ( 1 0 1 ) (-1 -2 3)). b := PMMatrix rows: #( ( 1 2 3 ) (-2 1 7)). "Matrix product" c := a * b. "Elementwise matrix product" d := a hadamardProduct: b. "This is how we can create a vector" a := #(1 4 9 16 25) asPMVector. "Vectors and Matrices support basic logical and arithmetic operations" Float pi sin * d. a sqrt. a > 3. c cos. c < 0. "It is possible to create a vector/matrix of random numbers" a := PMVector randomSize: 10 maxNumber: 3. b := PMMatrix rows: 2 columns: 3 random: 5. "It is also easy to create a vector/matrix of zeros/ones" a := PMVector ones:15. b := PMMatrix zerosRows: 2 cols: 3. "We can also compute the cumulative sum or regular sum the vector/ matrix as following" a := PMMatrix rows: #( ( 1 0 1 ) (-1 -2 3)). a cumsum. "a PMVector(1 1 2)" "a PMVector(-1 -3 0)" a sum. "a PMVector(2 0)" "Matrix trace (sum of a diagonal elements for a square matrix)" a := PMMatrix rows: #((1 2 3)(4 5 6)(7 8 9)). a tr. "15" ] { #category : #'instance creation' } PMMatrix class >> join: anArrayOfMatrices [ "Inverse of the split operation." | rows n row rowSize n1 n2 | rows := OrderedCollection new. n1 := ( anArrayOfMatrices at: 1) numberOfColumns. n2 := n1 + 1. rowSize := n1 + ( anArrayOfMatrices at: 2) numberOfColumns. n := 0. ( anArrayOfMatrices at: 1) rowsDo: [ :each | n := n + 1. row := PMVector new: rowSize. row replaceFrom: 1 to: n1 with: each startingAt: 1; replaceFrom: n2 to: rowSize with: ( ( anArrayOfMatrices at: 2) rowAt: n) startingAt: 1. rows add: row. ]. n := 0. ( anArrayOfMatrices at: 3) rowsDo: [ :each | n := n + 1. row := PMVector new: rowSize. row replaceFrom: 1 to: n1 with: each startingAt: 1; replaceFrom: n2 to: rowSize with: ( ( anArrayOfMatrices at: 4) rowAt: n) startingAt: 1. rows add: row. ]. ^self rows: rows ] { #category : #information } PMMatrix class >> lupCRLCriticalDimension [ ^ 40 ] { #category : #'instance creation' } PMMatrix class >> new: anInteger [ "Create an empty square matrix of dimension anInteger." ^ self new initialize: anInteger ] { #category : #'instance creation' } PMMatrix class >> onesRows: rows cols: columns [ "Creates MxN matrix of ones" | a b | a := (1 to: rows) collect: [ :row | b := PMVector ones: columns ]. ^ self rows: a ] { #category : #'instance creation' } PMMatrix class >> rows: anArrayOrVector [ "Create a new matrix with given components." ^ self new initializeRows: anArrayOrVector ] { #category : #'instance creation' } PMMatrix class >> rows: rowsInteger columns: columnsInteger [ ^ self new initializeRows: rowsInteger columns: columnsInteger ] { #category : #'instance creation' } PMMatrix class >> rows: nRows columns: nCols element: fillElement [ " Answer a new matrix of nRows x nCols initialized with fillElement in all cells " ^ (self new initializeRows: nRows columns: nCols) atAllPut: fillElement; yourself ] { #category : #'as yet unclassified' } PMMatrix class >> rows: rows columns: columns random: aMaxNumber [ "Answer a new Matrix of the given dimensions filled with random numbers" |a b| a:= (1 to: rows) collect: [:row |b:=PMVector new:columns . 1 to: columns do: [:column | b at: column put: (aMaxNumber random)]. b]. ^PMMatrix rows: a ] { #category : #'instance creation' } PMMatrix class >> zerosRows: rows cols: columns [ "Creates MxN matrix of zeros" | a b | a := (1 to: rows) collect: [ :row | b := PMVector zeros: columns ]. ^ self rows: a ] { #category : #operation } PMMatrix >> * aNumberOrMatrixOrVector [ "Answers the product of the receiver with the argument. The argument can be a number, matrix or vector." ^ aNumberOrMatrixOrVector productWithMatrix: self ] { #category : #operation } PMMatrix >> + aMatrixOrNumber [ "Answers the sum of the receiver with aMatrix." ^ aMatrixOrNumber addWithRegularMatrix: self ] { #category : #operation } PMMatrix >> - aMatrix [ "Answers the difference between the receiver and aMatrix." ^ aMatrix subtractWithRegularMatrix: self ] { #category : #operation } PMMatrix >> < aNumber [ "Apply < operator to each element of the matrix" ^ PMMatrix rows: (self rowsCollect: [ :each | each < aNumber ]) ] { #category : #comparing } PMMatrix >> = aNumberOrMatrix [ ^ (aNumberOrMatrix species = self species) and: [ self rows = aNumberOrMatrix rows ] ] { #category : #operation } PMMatrix >> > aNumber [ "Apply > operator to each element of the matrix" ^ PMMatrix rows: (self rowsCollect: [ :each | each > aNumber ]) ] { #category : #arithmetic } PMMatrix >> abs [ "Computes the element-wise absolute value." ^ self class rows: (rows collect: #abs). ] { #category : #'double dispatching' } PMMatrix >> adaptToNumber: rcvr andSend: selector [ "selector must obviously be commutative for this simple solution, but at the moment its only used for multiplication" ^ self perform: selector with: rcvr. ] { #category : #'double dispatching' } PMMatrix >> addWithRegularMatrix: aMatrix [ "Answers the sum of the receiver with aMatrix as a PMMatrix." | n | n := 0. (self numberOfRows = aMatrix numberOfRows) & (self numberOfColumns = aMatrix numberOfColumns) ifFalse: [ SizeMismatch signal ]. ^ PMMatrix rows: ( self rowsCollect: [ :each | n := n + 1. each + ( aMatrix rowAt: n)]) ] { #category : #'double dispatching' } PMMatrix >> addWithSymmetricMatrix: aMatrix [ ^ aMatrix addWithRegularMatrix: self ] { #category : #'as yet unclassified' } PMMatrix >> argMaxOnColumns [ ^ self columnsCollect: [ :each | each argMax ] ] { #category : #'as yet unclassified' } PMMatrix >> argMaxOnRows [ ^ self rowsCollect: [ :each | each argMax ] ] { #category : #transformation } PMMatrix >> asSymmetricMatrix [ "Convert the receiver to a symmetric matrix (no check is made)." ^ PMSymmetricMatrix rows: rows ] { #category : #converting } PMMatrix >> asVector [ ^ self flattenRows. ] { #category : #'cell accessing' } PMMatrix >> at: aRowIndex at: aColumnIndex [ "Answers the aRowIndex-th, aColumnIndex-th entry in the receiver." ^ self rowAt: aRowIndex columnAt: aColumnIndex ] { #category : #'cell accessing' } PMMatrix >> at: rowIndex at: columnIndex put: value [ self rowAt: rowIndex columnAt: columnIndex put: value ] { #category : #'cell accessing' } PMMatrix >> atAllPut: element [ "Put element at every one of the receiver's cells." self rowsDo: [ : row | row atAllPut: element ] ] { #category : #'cell accessing' } PMMatrix >> atColumn: anInteger [ ^ self columnAt: anInteger ] { #category : #'cell accessing' } PMMatrix >> atColumn: aColumnIndex put: aCollection [ aCollection withIndexDo: [: value : rowIndex | self rowAt: rowIndex columnAt: aColumnIndex put: value ] ] { #category : #'cell accessing' } PMMatrix >> atColumn: columnIndex put: aValue repeat: repNumber [ " Example: self atColumn: 1 fillWith: 'BM1818' repeat: 3 produces [ 'BM1818' nil nil nil 'BM1818' nil nil nil 'BM1818' nil nil nil nil nil nil nil nil nil nil nil ] " 1 to: repNumber do: [ : index | self rowAt: index columnAt: columnIndex put: aValue ]. ] { #category : #'cell accessing' } PMMatrix >> atColumn: aColumnNumber put: aCollection startingAt: rowNumber [ " Fill the receiver with aCollection at aColumnNumber begining at rowNumber. " aCollection withIndexDo: [: value : rowIndex | (rowIndex + rowNumber ) <= self numberOfRows ifTrue: [ self rowAt: rowIndex + rowNumber columnAt: aColumnNumber put: value ]] ] { #category : #'cell accessing' } PMMatrix >> atRow: rowIndex put: aCollection [ aCollection withIndexDo: [: value : columnIndex | self rowAt: rowIndex columnAt: columnIndex put: value ] ] { #category : #'cell accessing' } PMMatrix >> atRow: rowIndex put: aCollection startingAt: startColumnNumber [ "Fill the receiver with aCollection at rowIndex beggining at startColumnNumber. " aCollection withIndexDo: [: value : columnIndex | (columnIndex + startColumnNumber ) <= self numberOfColumns ifTrue: [ self rowAt: rowIndex columnAt: columnIndex + startColumnNumber put: value ]] ] { #category : #comparing } PMMatrix >> closeTo: aPMMatrix [ "Tests that we are within the default Float >> #closeTo: precision of aPMMatrix (0.0001)." ^ self closeTo: aPMMatrix precision: 0.0001 ] { #category : #comparing } PMMatrix >> closeTo: aPMMatrix precision: aPrecision [ ^ (self - aPMMatrix) abs sum sum < aPrecision ] { #category : #iterators } PMMatrix >> collect: aBlock [ "Applies aBlock elementwise to each cell of the matrix." ^ self class rows: (rows collect: [ :r | r collect: aBlock ]) ] { #category : #'cell accessing' } PMMatrix >> columnAt: anInteger [ "Answers the anInteger-th column of the receiver." ^ rows collect: [ :each | each at: anInteger ] ] { #category : #iterators } PMMatrix >> columnsCollect: aBlock [ "Perform the collect: operation on the rows of the receiver." | n | n := 0. ^ rows last collect: [ :each | n := n + 1. aBlock value: (self columnAt: n)] ] { #category : #iterators } PMMatrix >> columnsDo: aBlock [ "Perform the collect: operation on the rows of the receiver." | n | n := 0. ^ rows last do: [ :each | n := n + 1. aBlock value: ( self columnAt: n)] ] { #category : #operation } PMMatrix >> cos [ "Apply cos to each element of a matrix" ^ PMMatrix rows: (self rowsCollect: [ :each | each cos ]) ] { #category : #operation } PMMatrix >> cosh [ "Apply cosh to each element of a matrix" ^ PMMatrix rows: (self rowsCollect: [ :each | each cosh ]) ] { #category : #transformation } PMMatrix >> cumsum [ "Computes the cumulative sum for each row." ^ PMMatrix rows: (rows collect: [ :each | each cumsum ]) ] { #category : #'as yet unclassified' } PMMatrix >> decomposeSV [ ^ PMSingularValueDecomposition decompose: self ] { #category : #accessing } PMMatrix >> determinant [ ^ self lupDecomposition determinant ] { #category : #accessing } PMMatrix >> dimension [ ^ self rows size @ (self rows at: 1) size ] { #category : #operation } PMMatrix >> eigen [ "Computes all eigenvalues and eigenvectors of a matrix. Usage: matrix eigen values. matrix eigen vectors." self isSymmetric ifTrue: [ ^ self asSymmetricMatrix eigen ] ifFalse: [ self error: 'Eigenvalues and eigenvectors of non-symmetric matrix are currently not supported' ] ] { #category : #'double dispatching' } PMMatrix >> elementwiseProductWithMatrix: aMatrix [ "Answers the elementwise product between aMatrix and the receiver as a Matrix." | n | n := 0. ^ self class rows: ( aMatrix rowsCollect: [ :each | n := n + 1. each hadamardProduct: ( self rowAt: n)]) ] { #category : #'as yet unclassified' } PMMatrix >> equalsTo: aMatrix [ self rows with: aMatrix rows do: [:a :b| (a equalsTo: b) ifFalse: [ ^false ] ]. ^ true ] { #category : #'as yet unclassified' } PMMatrix >> flattenColumns [ | answer | answer := #(). self columnsDo: [ :each | answer := answer , each asArray ]. ^ answer asPMVector ] { #category : #'as yet unclassified' } PMMatrix >> flattenRows [ | answer | answer := #(). self rowsDo: [ :each | answer := answer , each asArray ]. ^ answer asPMVector ] { #category : #operation } PMMatrix >> hadamardProduct: aMatrix [ ^ aMatrix elementwiseProductWithMatrix: self ] { #category : #comparing } PMMatrix >> hash [ ^ rows hash ] { #category : #initialization } PMMatrix >> initialize: anInteger [ "Build empty components for a square matrix. No check is made: components are assumed to be orgainized in rows." rows := (1 to: anInteger) asPMVector collect: [ :each | PMVector new: anInteger]. ] { #category : #initialization } PMMatrix >> initializeRows: anArrayOrVector [ "Defines the components of the recevier. No check is made: components are assumed to be orgainized in rows." rows := anArrayOrVector asPMVector collect: [ :each | each asPMVector]. ] { #category : #initialization } PMMatrix >> initializeRows: rowsInteger columns: columnsInteger [ "Build empty components for a matrix." rows := (1 to: rowsInteger) asPMVector collect: [ :each | PMVector new: columnsInteger ]. ] { #category : #operation } PMMatrix >> inverse [ "Answer the inverse of the receiver." ^ self isSquare ifTrue: [ self lupInverse ] ifFalse: [ self squared inverse * self transpose ] ] { #category : #'as yet unclassified' } PMMatrix >> inversePivotColumns: anArray [ "uses vector encoding of an interchange permutation matrix in anArray as in qrFactorizationWithPivoting. Does inverse pivoting!" | res | res :=self deepCopy. anArray reverseWith: (1 to: anArray size ) do: [ :piv :ind | piv ~= ind ifTrue: [res swapColumn: piv withColumn: ind ] ]. ^ res ] { #category : #operation } PMMatrix >> inversePureCRL [ "Answer the inverse of the receiver." ^ self squared inversePureCRL * self transpose ] { #category : #testing } PMMatrix >> isSquare [ "Answers true if the number of rows is equal to the number of columns." ^ rows size = rows last size ] { #category : #testing } PMMatrix >> isSymmetric [ ^ self = self transpose ] { #category : #private } PMMatrix >> largestPowerOf2SmallerThan: anInteger [ "Private" | m m2| m := 2. [ m2 := m * 2. m2 < anInteger] whileTrue:[ m := m2]. ^m ] { #category : #operation } PMMatrix >> log [ "Apply log to each element of a matrix" ^ PMMatrix rows: ( self rowsCollect: [ :each | each log]) ] { #category : #accessing } PMMatrix >> lupDecomposition [ lupDecomposition isNil ifTrue: [ lupDecomposition :=PMLUPDecomposition equations: rows ]. ^ lupDecomposition ] { #category : #operation } PMMatrix >> lupInverse [ self lupDecomposition inverseMatrixComponents ifNil: [ PMSingularMatrixError new signal ] ifNotNil: [ :i | ^ self class rows: i ] ] { #category : #'as yet unclassified' } PMMatrix >> mpInverse [ "Moore Penrose Inverse. " |f g| self numberOfRows < self numberOfColumns ifTrue:[ f := self transpose qrFactorizationWithPivoting. g := f first. f := f second inversePivotColumns: (f at:3) ] ifFalse: [ f := self qrFactorizationWithPivoting. g := (f second inversePivotColumns: (f at:3)) transpose. f := f first transpose ]. ^ g * ((f *self *g) inverse) *f ] { #category : #transformation } PMMatrix >> negate [ "Inverse the sign of all components of the receiver." rows do: [ :each |each negate ] ] { #category : #accessing } PMMatrix >> numberOfColumns [ "Answer the number of rows of the receiver." ^ rows last size ] { #category : #accessing } PMMatrix >> numberOfRows [ "Answer the number of rows of the receiver." ^ rows size ] { #category : #'as yet unclassified' } PMMatrix >> orthogonalize [ "returns an orthonormal basis of column (!) vectors for a matrix of column vectors" ^ self qrFactorizationWithPivoting first ] { #category : #'as yet unclassified' } PMMatrix >> principalDiagonal [ "https://en.wikipedia.org/wiki/Diagonal#Matrices for definitions" | diag | "Check for square" self isSquare ifFalse: [ self error: 'Diagonal is not defined for a matrix that is not square.' ]. diag := PMVector new: self rows size. (1 to: diag size) do: [ :i | diag at: i put: (self at:i at: i) ]. ^ diag ] { #category : #printing } PMMatrix >> printOn: aStream [ (rows isNil or: [rows first isNil]) ifTrue: [ super printOn: aStream. aStream nextPutAll:'(uninitialized)'. ^ self ]. rows do: [ :each | each printOn: aStream] separatedBy: [ aStream cr]. ] { #category : #private } PMMatrix >> privateTranspose [ ^ self transpose ] { #category : #'double dispatching' } PMMatrix >> productWithMatrix: aMatrix [ "Answers the product of aMatrix with the receiver (in this order)." ^ self productWithMatrixFinal: aMatrix ] { #category : #'double dispatching' } PMMatrix >> productWithMatrixFinal: aMatrix [ "Answers the product of aMatrix with the receiver (in this order)." "speed optimized" |t| t :=self privateTranspose. ^ PMMatrix rows: ( aMatrix rowsCollect: [ :row | t rowsCollect: [ :col | row * col]]) ] { #category : #'double dispatching' } PMMatrix >> productWithTransposeMatrix: aMatrix [ "Answers the product of the receiver with the transpose of aMatrix(in this order)." ^ PMMatrix rows: (self rowsCollect: [ :row | aMatrix rowsCollect: [ :col | row * col]]) ] { #category : #'double dispatching' } PMMatrix >> productWithVector: aVector [ "Answers the product of the receiver with aVector" ^ self columnsCollect: [ :each | each * aVector ] ] { #category : #'as yet unclassified' } PMMatrix >> qrFactorization [ |identMat q r hh colSize i| self numberOfRows < self numberOfColumns ifTrue:[ self error: 'numberOfRows<numberOfColumns' ]. r :=PMMatrix rows: (rows deepCopy). colSize := self numberOfRows. q := PMSymmetricMatrix identity: colSize. identMat := q deepCopy. 1 to: self numberOfColumns do: [:col| hh := ((r columnAt: col) copyFrom: col to: colSize) householder. i := (PMVector new: col-1withAll: 0) , (hh at:2 ). q := q* (identMat - ((hh at: 1)*i tensorProduct: i ))."not really necessary, should be simplified" i := PMMatrix rows: ( (r rows allButFirst: (col -1)) collect: [:aRow| aRow allButFirst: (col -1)] ). i := i - ((hh at: 2) tensorProduct: ( (hh at: 1)*(hh at: 2)*i ) ) . i rows withIndexDo: [ :aRow :index | aRow withIndexDo: [ :n :c| r rowAt: (col + index -1) columnAt: (col +c -1) put: ((n equalsTo: 0) ifTrue: [0] ifFalse: [n] ) ] ] . "col <colSize ifTrue: [i :=(hh at: 2) copyFrom: 2 to: colSize -col +1. i withIndexDo: [:n :index| r rowAt: col columnAt: index put: n ] ]""and this part is not correct, dont uncomment before the bug is corrected! useful if q is not explicitely necessary" ]. "r rows allButFirst withIndexDo: [:aRow :ri|1 to: (ri min: self numberOfColumns ) do: [:ci|aRow at: ci put:0 ] ] ""not necessary with equalsTo:0" i :=0. [(r rowAt: colSize) allSatisfy: [:n| n=0] ]whileTrue: [i :=i+1.colSize :=colSize -1]. i>0 ifTrue: [ r :=PMMatrix rows: (r rows copyFrom: 1 to: colSize). i := q numberOfColumns - i. q := PMMatrix rows: ( q rows collect: [:row| row copyFrom: 1 to: i]) ]. ^Array with: q with: r ] { #category : #'as yet unclassified' } PMMatrix >> qrFactorizationWithPivoting [ | identMat q r hh colSize i lengthArray rank mx pivot | self numberOfRows < self numberOfColumns ifTrue: [ self error: 'numberOfRows<numberOfColumns' ]. lengthArray := self columnsCollect: [ :col | col * col ]. mx := lengthArray indexOf: lengthArray max. pivot := Array new: lengthArray size. rank := 0. r := PMMatrix rows: rows deepCopy. colSize := self numberOfRows. q := PMSymmetricMatrix identity: colSize. identMat := q deepCopy. [ rank := rank + 1. pivot at: rank put: mx. r swapColumn: rank withColumn: mx. lengthArray swap: rank with: mx. hh := ((r columnAt: rank) copyFrom: rank to: colSize) householder. i := (PMVector new: rank - 1 withAll: 0) , (hh at: 2). q := q * (identMat - ((hh at: 1) * i tensorProduct: i)). i := PMMatrix rows: ((r rows allButFirst: rank - 1) collect: [ :aRow | aRow allButFirst: rank - 1 ]). i := i - ((hh at: 2) tensorProduct: (hh at: 1) * (hh at: 2) * i). i rows withIndexDo: [ :aRow :index | aRow withIndexDo: [ :n :c | r rowAt: rank + index - 1 columnAt: rank + c - 1 put: ((n equalsTo: 0) ifTrue: [ 0 ] ifFalse: [ n ]) ] ]. rank + 1 to: lengthArray size do: [ :ind | lengthArray at: ind put: (lengthArray at: ind) - (r rowAt: rank columnAt: ind) squared ]. rank < lengthArray size ifTrue: [ mx := (lengthArray copyFrom: rank + 1 to: lengthArray size) max. (mx equalsTo: 0) ifTrue: [ mx := 0 ]. mx := mx > 0 ifTrue: [ lengthArray indexOf: mx startingAt: rank + 1 ] ifFalse: [ 0 ] ] ifFalse: [ mx := 0 ]. mx > 0 ] whileTrue. i := 0. [ (r rowAt: colSize) allSatisfy: [ :n | n = 0 ] ] whileTrue: [ i := i + 1. colSize := colSize - 1 ]. i > 0 ifTrue: [ r := PMMatrix rows: (r rows copyFrom: 1 to: colSize). i := q numberOfColumns - i. pivot := pivot copyFrom: 1 to: i. q := PMMatrix rows: (q rows collect: [ :row | row copyFrom: 1 to: i ]) ]. ^ Array with: q with: r with: pivot ] { #category : #'as yet unclassified' } PMMatrix >> rank [ ^ ((self numberOfRows < self numberOfColumns ifTrue: [ self transpose ] ifFalse: [ self ]) qrFactorizationWithPivoting at: 2) rows size ] { #category : #'cell accessing' } PMMatrix >> rowAt: anInteger [ "Answers the anInteger-th row of the receiver." ^ rows at: anInteger ] { #category : #'cell accessing' } PMMatrix >> rowAt: aRowIndex columnAt: aColumnIndex [ "Answers the aRowIndex-th, aColumnIndex-th entry in the receiver." ^ (rows at: aRowIndex) at: aColumnIndex ] { #category : #'cell accessing' } PMMatrix >> rowAt: aRowIndex columnAt: aColumnIndex put: aValue [ ^(rows at: aRowIndex) at: aColumnIndex put: aValue ] { #category : #'cell accessing' } PMMatrix >> rows [ ^rows ] { #category : #iterators } PMMatrix >> rowsCollect: aBlock [ "Perform the collect: operation on the rows of the receiver." ^ rows collect: aBlock ] { #category : #iterators } PMMatrix >> rowsDo: aBlock [ "Perform the collect: operation on the rows of the receiver." ^ rows do: aBlock ] { #category : #transformation } PMMatrix >> scaleBy: aNumber [ rows do: [ :each | each scaleBy: aNumber ] ] { #category : #'cell accessing' } PMMatrix >> setDiagonal: aVector [ | n m | n := self numberOfRows. m := self numberOfColumns. n < m ifTrue: [ 1 to: n do: [ :i | self rowAt: i columnAt: i put: (aVector at: i)]. ] ifFalse: [ 1 to: m do: [ :i | self rowAt: i columnAt: i put: (aVector at: i)]. ]. ^self ] { #category : #operation } PMMatrix >> sign [ "Apply sign to each element of a matrix" ^ PMMatrix rows: (self rowsCollect: [ :each | each sign ]) ] { #category : #operation } PMMatrix >> sin [ "Apply sin to each element of a matrix" ^ PMMatrix rows: (self rowsCollect: [ :each | each sin ]) ] { #category : #operation } PMMatrix >> sinh [ "Apply sinh to each element of a matrix" ^ PMMatrix rows: (self rowsCollect: [ :each | each sinh ]) ] { #category : #private } PMMatrix >> species [ ^ PMMatrix ] { #category : #private } PMMatrix >> split [ "Private - Answers an array of 4 matrices split from the receiver." | n m n1 m1 | n := self numberOfRows. m := self numberOfColumns. n1 := self largestPowerOf2SmallerThan: n. m1 := self largestPowerOf2SmallerThan: m. ^ Array with: ( self class rows: ( ( 1 to: n1) asPMVector collect: [ :k | ( rows at: k) copyFrom: 1 to: m1])) with:( self class rows: ( ( 1 to: n1) asPMVector collect: [ :k | ( rows at: k) copyFrom: (m1 + 1) to: m])) with: ( self class rows: ( ( (n1 + 1) to: n) asPMVector collect: [ :k | ( rows at: k) copyFrom: 1 to: m1])) with:( self class rows: ( ( (n1 + 1) to: n) asPMVector collect: [ :k | ( rows at: k) copyFrom: (m1 + 1) to: m])) ] { #category : #operation } PMMatrix >> sqrt [ "Apply sqrt to each element of a matrix" ^ PMMatrix rows: ( self rowsCollect: [ :each | each sqrt]) ] { #category : #operation } PMMatrix >> squared [ | transposed | transposed :=self privateTranspose. ^ PMSymmetricMatrix new: transposed numberOfRows function: [ :x :y|(transposed rowAt: x) * (transposed rowAt: y) ] ] { #category : #private } PMMatrix >> strassenProductWithMatrix: aMatrix [ "Private" | matrixSplit selfSplit p1 p2 p3 p4 p5 p6 p7 | ( self numberOfRows > 2 and: [ self numberOfColumns > 2]) ifFalse:[ ^self class rows: ( aMatrix rowsCollect: [ :row | self columnsCollect: [ :col | row * col]])]. selfSplit := self split. matrixSplit := aMatrix split. p1 := ( ( selfSplit at: 2) - ( selfSplit at: 4)) strassenProductWithMatrix: ( matrixSplit at: 1). p2 := ( selfSplit at: 4) strassenProductWithMatrix: ( ( matrixSplit at: 1) + ( matrixSplit at: 2)). p3 := ( selfSplit at: 1) strassenProductWithMatrix: ( ( matrixSplit at: 3) + ( matrixSplit at: 4)). p4 := ( ( selfSplit at: 3) - ( selfSplit at: 1)) strassenProductWithMatrix: ( matrixSplit at: 4). p5 := ( ( selfSplit at: 1) + ( selfSplit at: 4)) strassenProductWithMatrix: ( ( matrixSplit at: 1) + ( matrixSplit at: 4)). p6 := ( ( selfSplit at: 3) + ( selfSplit at: 4)) strassenProductWithMatrix: ( ( matrixSplit at: 2) - ( matrixSplit at: 4)). p7 := ( ( selfSplit at: 1) + ( selfSplit at: 2)) strassenProductWithMatrix: ( ( matrixSplit at: 1) - ( matrixSplit at: 3)). ^self class join: ( Array with: ( p5 + p4 + p6 - p2) with: (p1 + p2) with: ( p3 + p4) with: ( p5 + p1 - p3 - p7) ) ] { #category : #'double dispatching' } PMMatrix >> subtractWithRegularMatrix: aMatrix [ "Answers the difference between aMatrix and the receiver as a Matrix." | n | n := 0. ^ PMMatrix rows: ( aMatrix rowsCollect: [ :each | n := n + 1. each - ( self rowAt: n)]) ] { #category : #'double dispatching' } PMMatrix >> subtractWithSymmetricMatrix: aMatrix [ "Answers the difference between aMatrix and the receiver." ^ self subtractWithRegularMatrix: aMatrix ] { #category : #transformation } PMMatrix >> sum [ "Computes the row sum." | a | a := PMVector new: self numberOfRows. 1 to: a size do: [ :n | a at: n put: (self rowAt: n) sum ]. ^ a ] { #category : #'as yet unclassified' } PMMatrix >> swapColumn: anIndex withColumn: a2Index [ self rowsDo: [ :r| r swap: anIndex with: a2Index ] ] { #category : #operation } PMMatrix >> tan [ "Apply tan to each element of a matrix" ^ PMMatrix rows: (self rowsCollect: [ :each | each tan ]) ] { #category : #operation } PMMatrix >> tanh [ "Apply tanh to each element of a matrix" ^ PMMatrix rows: (self rowsCollect: [ :each | each tanh ]) ] { #category : #operation } PMMatrix >> tr [ "Return the trace or sum along diagonals of the array." "https://en.wikipedia.org/wiki/Trace_(linear_algebra)" | result | result := 0. 1 to: self numberOfRows do: [ :n | result := result + (self at: n at: n) ]. ^ result ] { #category : #operation } PMMatrix >> transpose [ "Answer a new matrix, transpose of the receiver." ^ self class rows: ( self columnsCollect: [ :each | each]) ] { #category : #'double dispatching' } PMMatrix >> transposeProductWithMatrix: aMatrix [ "Answers the product of the transpose of the receiver with aMatrix (in this order)." "speed optimized" |t| t :=aMatrix privateTranspose. ^ PMMatrix rows: (self columnsCollect: [ :row | t rowsCollect: [ :col | row * col]]) ]
{ "pile_set_name": "Github" }
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.ExcelApi { /// <summary> /// DispatchInterface CalculatedMember /// SupportByVersion Excel, 10,11,12,14,15,16 /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff193313.aspx </remarks> [SupportByVersion("Excel", 10,11,12,14,15,16)] [EntityType(EntityType.IsDispatchInterface)] public class CalculatedMember : COMObject { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(CalculatedMember); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public CalculatedMember(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public CalculatedMember(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public CalculatedMember(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public CalculatedMember(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public CalculatedMember(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public CalculatedMember(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public CalculatedMember() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public CalculatedMember(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff197314.aspx </remarks> [SupportByVersion("Excel", 10,11,12,14,15,16)] public NetOffice.ExcelApi.Application Application { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Application>(this, "Application", NetOffice.ExcelApi.Application.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff195628.aspx </remarks> [SupportByVersion("Excel", 10,11,12,14,15,16)] public NetOffice.ExcelApi.Enums.XlCreator Creator { get { return Factory.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCreator>(this, "Creator"); } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff837382.aspx </remarks> [SupportByVersion("Excel", 10,11,12,14,15,16), ProxyResult] public object Parent { get { return Factory.ExecuteReferencePropertyGet(this, "Parent"); } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff840367.aspx </remarks> [SupportByVersion("Excel", 10,11,12,14,15,16)] public string Name { get { return Factory.ExecuteStringPropertyGet(this, "Name"); } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff834481.aspx </remarks> [SupportByVersion("Excel", 10,11,12,14,15,16)] public string Formula { get { return Factory.ExecuteStringPropertyGet(this, "Formula"); } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff822867.aspx </remarks> [SupportByVersion("Excel", 10,11,12,14,15,16)] public string SourceName { get { return Factory.ExecuteStringPropertyGet(this, "SourceName"); } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff197565.aspx </remarks> [SupportByVersion("Excel", 10,11,12,14,15,16)] public Int32 SolveOrder { get { return Factory.ExecuteInt32PropertyGet(this, "SolveOrder"); } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff836535.aspx </remarks> [SupportByVersion("Excel", 10,11,12,14,15,16)] public bool IsValid { get { return Factory.ExecuteBoolPropertyGet(this, "IsValid"); } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 10,11,12,14,15,16)] public string _Default { get { return Factory.ExecuteStringPropertyGet(this, "_Default"); } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff823104.aspx </remarks> [SupportByVersion("Excel", 10,11,12,14,15,16)] public NetOffice.ExcelApi.Enums.XlCalculatedMemberType Type { get { return Factory.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCalculatedMemberType>(this, "Type"); } } /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff838011.aspx </remarks> [SupportByVersion("Excel", 14,15,16)] public bool Dynamic { get { return Factory.ExecuteBoolPropertyGet(this, "Dynamic"); } } /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff837040.aspx </remarks> [SupportByVersion("Excel", 14,15,16)] public string DisplayFolder { get { return Factory.ExecuteStringPropertyGet(this, "DisplayFolder"); } } /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get/Set /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff196627.aspx </remarks> [SupportByVersion("Excel", 14,15,16)] public bool HierarchizeDistinct { get { return Factory.ExecuteBoolPropertyGet(this, "HierarchizeDistinct"); } set { Factory.ExecuteValuePropertySet(this, "HierarchizeDistinct", value); } } /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get/Set /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff837990.aspx </remarks> [SupportByVersion("Excel", 14,15,16)] public bool FlattenHierarchies { get { return Factory.ExecuteBoolPropertyGet(this, "FlattenHierarchies"); } set { Factory.ExecuteValuePropertySet(this, "FlattenHierarchies", value); } } /// <summary> /// SupportByVersion Excel 15,16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/jj228547.aspx </remarks> [SupportByVersion("Excel", 15, 16)] public string MeasureGroup { get { return Factory.ExecuteStringPropertyGet(this, "MeasureGroup"); } } /// <summary> /// SupportByVersion Excel 15,16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/jj227533.aspx </remarks> [SupportByVersion("Excel", 15, 16)] public string ParentHierarchy { get { return Factory.ExecuteStringPropertyGet(this, "ParentHierarchy"); } } /// <summary> /// SupportByVersion Excel 15,16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/jj229988.aspx </remarks> [SupportByVersion("Excel", 15, 16)] public string ParentMember { get { return Factory.ExecuteStringPropertyGet(this, "ParentMember"); } } /// <summary> /// SupportByVersion Excel 15,16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/jj228161.aspx </remarks> [SupportByVersion("Excel", 15, 16)] public NetOffice.ExcelApi.Enums.XlCalcMemNumberFormatType NumberFormat { get { return Factory.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCalcMemNumberFormatType>(this, "NumberFormat"); } } #endregion #region Methods /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff194128.aspx </remarks> [SupportByVersion("Excel", 10,11,12,14,15,16)] public void Delete() { Factory.ExecuteMethod(this, "Delete"); } #endregion #pragma warning restore } }
{ "pile_set_name": "Github" }
module FreeFunctor = (F: {type f('a);}) : Functor => { module type F = FreeF with type f('a) = F.f('a); type t('a) = (module F with type a = 'a); let fmap = (type a', type b', f: a' => b', module FF: F with type a = a') : (module F with type a = b') => (module { type f('a) = F.f('a); type a = b'; type i = FF.i; let h = i => f(FF.h(i)); let fi = FF.fi; }); };
{ "pile_set_name": "Github" }
#!/usr/bin/env python #MIT License #Copyright (c) 2017 Massimiliano Patacchiola # #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 numpy as np from mountain_car import MountainCar import matplotlib.pyplot as plt def update_state_action(state_action_matrix, visit_counter_matrix, observation, new_observation, action, new_action, reward, alpha, gamma, tot_bins): '''Return the updated utility matrix @param state_action_matrix the matrix before the update @param observation the state obsrved at t @param new_observation the state observed at t+1 @param action the action at t @param new_action the action at t+1 @param reward the reward observed after the action @param alpha the ste size (learning rate) @param gamma the discount factor @return the updated state action matrix ''' #Getting the values of Q at t and at t+1 col = observation[1] + (observation[0]*tot_bins) q = state_action_matrix[action, col] col_t1 = new_observation[1] + (new_observation[0]*tot_bins) q_t1 = state_action_matrix[new_action ,col_t1] #Calculate alpha based on how many time it #has been visited alpha_counted = 1.0 / (1.0 + visit_counter_matrix[action, col]) #Applying the update rule #Here you can change "alpha" with "alpha_counted" if you want #to take into account how many times that particular state-action #pair has been visited until now. state_action_matrix[action ,col] = state_action_matrix[action ,col] + \ alpha * (reward + gamma * q_t1 - q) return state_action_matrix def update_visit_counter(visit_counter_matrix, observation, action, tot_bins): '''Update the visit counter Counting how many times a state-action pair has been visited. This information can be used during the update. @param visit_counter_matrix a matrix initialised with zeros @param observation the state observed @param action the action taken ''' col = observation[1] + (observation[0]*tot_bins) visit_counter_matrix[action ,col] += 1.0 return visit_counter_matrix def update_policy(policy_matrix, state_action_matrix, observation, tot_bins): '''Return the updated policy matrix @param policy_matrix the matrix before the update @param state_action_matrix the state-action matrix @param observation the state obsrved at t @return the updated state action matrix ''' col = observation[1] + (observation[0]*tot_bins) #Getting the index of the action with the highest utility best_action = np.argmax(state_action_matrix[:, col]) #Updating the policy policy_matrix[observation[0], observation[1]] = best_action return policy_matrix def return_epsilon_greedy_action(policy_matrix, observation, epsilon=0.1): '''Return an action choosing it with epsilon-greedy @param policy_matrix the matrix before the update @param observation the state obsrved at t @param epsilon the value used for computing the probabilities @return the updated policy_matrix ''' tot_actions = int(np.nanmax(policy_matrix) + 1) action = int(policy_matrix[observation[0], observation[1]]) non_greedy_prob = epsilon / tot_actions greedy_prob = 1 - epsilon + non_greedy_prob weight_array = np.full((tot_actions), non_greedy_prob) weight_array[action] = greedy_prob return int(np.random.choice(tot_actions, 1, p=weight_array)) def print_policy(policy_matrix): '''Print the policy using specific symbol. * terminal state ^ > v < up, right, down, left # obstacle ''' counter = 0 shape = policy_matrix.shape policy_string = "" for row in range(shape[0]): for col in range(shape[1]): if(policy_matrix[row,col] == 0): policy_string += " < " elif(policy_matrix[row,col] == 1): policy_string += " O " elif(policy_matrix[row,col] == 2): policy_string += " > " counter += 1 policy_string += '\n' print(policy_string) def return_decayed_value(starting_value, minimum_value, global_step, decay_step): """Returns the decayed value. decayed_value = starting_value * decay_rate ^ (global_step / decay_steps) @param starting_value the value before decaying @param global_step the global step to use for decay (positive integer) @param decay_step the step at which the value is decayed """ decayed_value = starting_value * np.power(0.9, (global_step/decay_step)) if decayed_value < minimum_value: return minimum_value else: return decayed_value def plot_curve(data_list, filepath="./my_plot.png", x_label="X", y_label="Y", x_range=(0, 1), y_range=(0,1), color="-r", kernel_size=50, alpha=0.4, grid=True): """Plot a graph using matplotlib """ if(len(data_list) <=1): return fig = plt.figure() ax = fig.add_subplot(111, autoscale_on=False, xlim=x_range, ylim=y_range) ax.grid(grid) ax.set_xlabel(x_label) ax.set_ylabel(y_label) # The original data is showed in background ax.plot(data_list, color, alpha=alpha) # Smooth the graph using a convolution kernel = np.ones(int(kernel_size))/float(kernel_size) tot_data = len(data_list) lower_boundary = int(kernel_size/2.0) upper_boundary = int(tot_data-(kernel_size/2.0)) data_convolved_array = np.convolve(data_list, kernel, 'same')[lower_boundary:upper_boundary] #print("arange: " + str(np.arange(tot_data)[lower_boundary:upper_boundary])) #print("Convolved: " + str(np.arange(tot_data).shape)) ax.plot(np.arange(tot_data)[lower_boundary:upper_boundary], data_convolved_array, color, alpha=1.0) # Convolved plot fig.savefig(filepath) fig.clear() plt.close(fig) # print(plt.get_fignums()) # print the number of figures opened in background def main(): env = MountainCar(mass=0.2, friction=0.3, delta_t=0.1) # Define the state arrays for velocity and position tot_action = 3 # Three possible actions tot_bins = 12 # the value used to discretize the space velocity_state_array = np.linspace(-1.5, +1.5, num=tot_bins-1, endpoint=False) position_state_array = np.linspace(-1.2, +0.5, num=tot_bins-1, endpoint=False) # Random policy as a square matrix of size (tot_bins x tot_bins) # Three possible actions represented by three integers policy_matrix = np.random.randint(low=0, high=tot_action, size=(tot_bins,tot_bins)) print("Policy Matrix:") print(policy_matrix) # The state-action matrix and the visit counter # The rows are the velocities and the columns the positions. state_action_matrix = np.zeros((tot_action, tot_bins*tot_bins)) visit_counter_matrix = np.zeros((tot_action, tot_bins*tot_bins)) # Variables gamma = 0.999 alpha = 0.001 tot_episode = 100000 epsilon_start = 0.9 # those are the values for epsilon decay epsilon_stop = 0.1 epsilon_decay_step = 3000 print_episode = 500 # print every... movie_episode = 10000 # movie saved every... reward_list = list() step_list = list() for episode in range(tot_episode): epsilon = return_decayed_value(epsilon_start, epsilon_stop, episode, decay_step=epsilon_decay_step) # Reset and return the first observation observation = env.reset(exploring_starts=False) # The observation is digitized, meaning that an integer corresponding # to the bin where the raw float belongs is obtained and use as replacement. observation = (np.digitize(observation[1], velocity_state_array), np.digitize(observation[0], position_state_array)) is_starting = True cumulated_reward = 0 for step in range(100): #Take the action from the action matrix #action = policy_matrix[observation[0], observation[1]] #Take the action using epsilon-greedy action = return_epsilon_greedy_action(policy_matrix, observation, epsilon=epsilon) if(is_starting): action = np.random.randint(0, tot_action) is_starting = False #Move one step in the environment and get obs and reward new_observation, reward, done = env.step(action) new_observation = (np.digitize(new_observation[1], velocity_state_array), np.digitize(new_observation[0], position_state_array)) new_action = policy_matrix[new_observation[0], new_observation[1]] #Updating the state-action matrix state_action_matrix = update_state_action(state_action_matrix, visit_counter_matrix, observation, new_observation, action, new_action, reward, alpha, gamma, tot_bins) #Updating the policy policy_matrix = update_policy(policy_matrix, state_action_matrix, observation, tot_bins) #Increment the visit counter visit_counter_matrix = update_visit_counter(visit_counter_matrix, observation, action, tot_bins) observation = new_observation cumulated_reward += reward if done: break # Store the data for statistics reward_list.append(cumulated_reward) step_list.append(step) # Printing utilities if(episode % print_episode == 0): print("") print("Episode: " + str(episode+1)) print("Epsilon: " + str(epsilon)) print("Episode steps: " + str(step+1)) print("Cumulated Reward: " + str(cumulated_reward)) print("Policy matrix: ") print_policy(policy_matrix) if(episode % movie_episode == 0): print("Saving the reward plot in: ./reward.png") plot_curve(reward_list, filepath="./reward.png", x_label="Episode", y_label="Reward", x_range=(0, len(reward_list)), y_range=(-1.1,1.1), color="red", kernel_size=500, alpha=0.4, grid=True) print("Saving the step plot in: ./step.png") plot_curve(step_list, filepath="./step.png", x_label="Episode", y_label="Steps", x_range=(0, len(step_list)), y_range=(-0.1,100), color="blue", kernel_size=500, alpha=0.4, grid=True) print("Saving the gif in: ./mountain_car.gif") env.render(file_path='./mountain_car.gif', mode='gif') print("Complete!") # Save reward and steps in npz file for later use # np.savez("./statistics.npz", reward=np.asarray(reward_list), step=np.asarray(step_list)) # Time to check the utility matrix obtained print("Policy matrix after " + str(tot_episode) + " episodes:") print_policy(policy_matrix) if __name__ == "__main__": main()
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="VcsDirectoryMappings"> <mapping directory="$PROJECT_DIR$" vcs="Git" /> </component> </project>
{ "pile_set_name": "Github" }
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package workmail const ( // ErrCodeDirectoryServiceAuthenticationFailedException for service response error code // "DirectoryServiceAuthenticationFailedException". // // The directory service doesn't recognize the credentials supplied by WorkMail. ErrCodeDirectoryServiceAuthenticationFailedException = "DirectoryServiceAuthenticationFailedException" // ErrCodeDirectoryUnavailableException for service response error code // "DirectoryUnavailableException". // // The directory on which you are trying to perform operations isn't available. ErrCodeDirectoryUnavailableException = "DirectoryUnavailableException" // ErrCodeEmailAddressInUseException for service response error code // "EmailAddressInUseException". // // The email address that you're trying to assign is already created for a different // user, group, or resource. ErrCodeEmailAddressInUseException = "EmailAddressInUseException" // ErrCodeEntityAlreadyRegisteredException for service response error code // "EntityAlreadyRegisteredException". // // The user, group, or resource that you're trying to register is already registered. ErrCodeEntityAlreadyRegisteredException = "EntityAlreadyRegisteredException" // ErrCodeEntityNotFoundException for service response error code // "EntityNotFoundException". // // The identifier supplied for the user, group, or resource does not exist in // your organization. ErrCodeEntityNotFoundException = "EntityNotFoundException" // ErrCodeEntityStateException for service response error code // "EntityStateException". // // You are performing an operation on a user, group, or resource that isn't // in the expected state, such as trying to delete an active user. ErrCodeEntityStateException = "EntityStateException" // ErrCodeInvalidConfigurationException for service response error code // "InvalidConfigurationException". // // The configuration for a resource isn't valid. A resource must either be able // to auto-respond to requests or have at least one delegate associated that // can do so on its behalf. ErrCodeInvalidConfigurationException = "InvalidConfigurationException" // ErrCodeInvalidParameterException for service response error code // "InvalidParameterException". // // One or more of the input parameters don't match the service's restrictions. ErrCodeInvalidParameterException = "InvalidParameterException" // ErrCodeInvalidPasswordException for service response error code // "InvalidPasswordException". // // The supplied password doesn't match the minimum security constraints, such // as length or use of special characters. ErrCodeInvalidPasswordException = "InvalidPasswordException" // ErrCodeMailDomainNotFoundException for service response error code // "MailDomainNotFoundException". // // For an email or alias to be created in Amazon WorkMail, the included domain // must be defined in the organization. ErrCodeMailDomainNotFoundException = "MailDomainNotFoundException" // ErrCodeMailDomainStateException for service response error code // "MailDomainStateException". // // After a domain has been added to the organization, it must be verified. The // domain is not yet verified. ErrCodeMailDomainStateException = "MailDomainStateException" // ErrCodeNameAvailabilityException for service response error code // "NameAvailabilityException". // // The user, group, or resource name isn't unique in Amazon WorkMail. ErrCodeNameAvailabilityException = "NameAvailabilityException" // ErrCodeOrganizationNotFoundException for service response error code // "OrganizationNotFoundException". // // An operation received a valid organization identifier that either doesn't // belong or exist in the system. ErrCodeOrganizationNotFoundException = "OrganizationNotFoundException" // ErrCodeOrganizationStateException for service response error code // "OrganizationStateException". // // The organization must have a valid state (Active or Synchronizing) to perform // certain operations on the organization or its members. ErrCodeOrganizationStateException = "OrganizationStateException" // ErrCodeReservedNameException for service response error code // "ReservedNameException". // // This user, group, or resource name is not allowed in Amazon WorkMail. ErrCodeReservedNameException = "ReservedNameException" // ErrCodeUnsupportedOperationException for service response error code // "UnsupportedOperationException". // // You can't perform a write operation against a read-only directory. ErrCodeUnsupportedOperationException = "UnsupportedOperationException" )
{ "pile_set_name": "Github" }
// Learning Processing // Daniel Shiffman // http://www.learningprocessing.com // Exercise 1-2: Using the blank graph below, // draw the primitive shapes specified by the code.
{ "pile_set_name": "Github" }
/* * Copyright (C) 2010 Martin Willi * Copyright (C) 2010 revosec AG * * Copyright (C) 2009 Andreas Steffen * HSR Hochschule fuer Technik Rapperswil * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ #include "addrblock_validator.h" #include <utils/debug.h> #include <credentials/certificates/x509.h> #include <selectors/traffic_selector.h> typedef struct private_addrblock_validator_t private_addrblock_validator_t; /** * Private data of an addrblock_validator_t object. */ struct private_addrblock_validator_t { /** * Public addrblock_validator_t interface. */ addrblock_validator_t public; /** * Whether to reject subject certificates not having a addrBlock extension */ bool strict; }; /** * Do the addrblock check for two x509 plugins */ static bool check_addrblock(private_addrblock_validator_t *this, x509_t *subject, x509_t *issuer) { bool subject_const, issuer_const, contained = TRUE; enumerator_t *subject_enumerator, *issuer_enumerator; traffic_selector_t *subject_ts, *issuer_ts; subject_const = subject->get_flags(subject) & X509_IP_ADDR_BLOCKS; issuer_const = issuer->get_flags(issuer) & X509_IP_ADDR_BLOCKS; if (!subject_const && !issuer_const) { return TRUE; } if (!subject_const) { DBG1(DBG_CFG, "subject certificate lacks ipAddrBlocks extension"); return !this->strict; } if (!issuer_const) { DBG1(DBG_CFG, "issuer certificate lacks ipAddrBlocks extension"); return FALSE; } subject_enumerator = subject->create_ipAddrBlock_enumerator(subject); while (subject_enumerator->enumerate(subject_enumerator, &subject_ts)) { contained = FALSE; issuer_enumerator = issuer->create_ipAddrBlock_enumerator(issuer); while (issuer_enumerator->enumerate(issuer_enumerator, &issuer_ts)) { if (subject_ts->is_contained_in(subject_ts, issuer_ts)) { DBG2(DBG_CFG, " subject address block %R is contained in " "issuer address block %R", subject_ts, issuer_ts); contained = TRUE; break; } } issuer_enumerator->destroy(issuer_enumerator); if (!contained) { DBG1(DBG_CFG, "subject address block %R is not contained in any " "issuer address block", subject_ts); break; } } subject_enumerator->destroy(subject_enumerator); return contained; } METHOD(cert_validator_t, validate, bool, private_addrblock_validator_t *this, certificate_t *subject, certificate_t *issuer, bool online, u_int pathlen, bool anchor, auth_cfg_t *auth) { if (subject->get_type(subject) == CERT_X509 && issuer->get_type(issuer) == CERT_X509) { if (!check_addrblock(this, (x509_t*)subject, (x509_t*)issuer)) { lib->credmgr->call_hook(lib->credmgr, CRED_HOOK_POLICY_VIOLATION, subject); return FALSE; } } return TRUE; } METHOD(addrblock_validator_t, destroy, void, private_addrblock_validator_t *this) { free(this); } /** * See header */ addrblock_validator_t *addrblock_validator_create() { private_addrblock_validator_t *this; INIT(this, .public = { .validator = { .validate = _validate, }, .destroy = _destroy, }, .strict = lib->settings->get_bool(lib->settings, "%s.plugins.addrblock.strict", TRUE, lib->ns), ); return &this->public; }
{ "pile_set_name": "Github" }
/** * Copyright (C) 2007 - 2016, Jens Lehmann * * This file is part of DL-Learner. * * DL-Learner is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * DL-Learner is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.dllearner.algorithms.qtl.experiments; import java.util.*; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import com.google.common.collect.Lists; import org.aksw.jena_sparql_api.concepts.Concept; import org.aksw.jena_sparql_api.concepts.ConceptUtils; import org.aksw.jena_sparql_api.core.QueryExecutionFactory; import org.apache.jena.graph.NodeFactory; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.expr.*; import org.apache.jena.vocabulary.RDF; import org.dllearner.utilities.QueryUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Sets; import com.google.common.collect.Sets.SetView; import org.apache.jena.graph.Node; import org.apache.jena.graph.Triple; import org.apache.jena.query.Query; import org.apache.jena.query.QueryExecution; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.QuerySolution; import org.apache.jena.query.ResultSet; import org.apache.jena.sparql.core.TriplePath; import org.apache.jena.sparql.syntax.Element; import org.apache.jena.sparql.syntax.ElementFilter; import org.apache.jena.sparql.syntax.ElementGroup; import org.apache.jena.sparql.syntax.ElementOptional; import org.apache.jena.sparql.syntax.ElementPathBlock; import org.apache.jena.sparql.syntax.ElementTriplesBlock; import org.apache.jena.sparql.syntax.ElementUnion; import org.apache.jena.sparql.syntax.ElementVisitorBase; public class NegativeExampleSPARQLQueryGenerator extends ElementVisitorBase{ private static final Logger logger = LoggerFactory .getLogger(NegativeExampleSPARQLQueryGenerator.class); private boolean inOptionalClause; private Stack<ElementGroup> parentGroup = new Stack<>(); private QueryUtils triplePatternExtractor = new QueryUtils(); private Triple triple; Random randomGen = new Random(123); private QueryExecutionFactory qef; public NegativeExampleSPARQLQueryGenerator(QueryExecutionFactory qef) { this.qef = qef; } public List<String> getNegativeExamples(String targetQuery, int size) { logger.trace("Generating neg. examples..."); Set<String> negExamples = new HashSet<>(); Query query = QueryFactory.create(targetQuery); // generate queries that return neg. examples List<Query> queries = new ArrayList<>(); queries.addAll(generateQueriesByReplacement(query)); queries.addAll(generateQueriesByRemoval(query)); // get a list of resources for each query for (Query q : queries) { q.setLimit(size); logger.info("Trying query\n" + q); QueryExecution qe = qef.createQueryExecution(q); ResultSet rs = qe.execSelect(); while(rs.hasNext()) { QuerySolution qs = rs.next(); String example = qs.getResource(query.getProjectVars().get(0).getName()).getURI(); negExamples.add(example); } qe.close(); } logger.trace("...finished generating neg. examples."); // sanity check: remove all pos. examples QueryExecution qe = qef.createQueryExecution(targetQuery); ResultSet rs = qe.execSelect(); Iterable<QuerySolution> iter = () -> rs; final Var targetVar = query.getProjectVars().get(0); List<String> posExamples = StreamSupport.stream(iter.spliterator(), false) .map(qs -> qs.getResource(targetVar.getName()).getURI()) .collect(Collectors.toList()); negExamples.removeAll(posExamples); return new ArrayList<>(negExamples); } private ElementFilter getNotExistsFilter(Element el){ return new ElementFilter(new E_NotExists(el)); } private List<Query> generateQueriesByReplacement(Query query) { List<Query> queries = new ArrayList<>(); QueryUtils utils = new QueryUtils(); List<Triple> triplePatterns = new ArrayList<>(utils.extractTriplePattern(query)); for (Triple tp : triplePatterns) { List<Triple> remainingTriplePatterns = new ArrayList<>(triplePatterns); remainingTriplePatterns.remove(tp); List<List<Integer>> positions2Replace = new ArrayList<>(); if(tp.getSubject().isURI()) { // s if(tp.getPredicate().isURI()) { // s p ?var positions2Replace.add(Lists.newArrayList(0)); positions2Replace.add(Lists.newArrayList(1)); } else if(tp.getObject().isConcrete()) { // s ?var ?o positions2Replace.add(Lists.newArrayList(0)); positions2Replace.add(Lists.newArrayList(2)); } } else { if(tp.getPredicate().isURI()) { if(tp.getObject().isConcrete()) { // ?var p o positions2Replace.add(Lists.newArrayList(1)); positions2Replace.add(Lists.newArrayList(2)); } } } for (List<Integer> positions : positions2Replace) { Node s = tp.getSubject(); Node p = tp.getPredicate(); Node o = tp.getObject(); List<ElementFilter> filters = new ArrayList<>(); for (Integer pos : positions) { switch (pos) { case 0: { Node var = NodeFactory.createVariable("s_var"); s = var; filters.add(new ElementFilter(new E_LogicalNot(new E_Equals(new ExprVar(var), NodeValue.makeNode(tp.getSubject()))))); break; } case 1: { Node var = NodeFactory.createVariable("p_var"); p = var; // ?var != <p> && ?var != rdf:type filters.add(new ElementFilter(new E_LogicalNot(new E_Equals(new ExprVar(var), NodeValue.makeNode(tp.getPredicate()))))); filters.add(new ElementFilter(new E_LogicalNot(new E_Equals(new ExprVar(var), NodeValue.makeNode(RDF.type.asNode()))))); break; } case 2: { Node var = NodeFactory.createVariable("o_var"); o = var; filters.add(new ElementFilter(new E_LogicalNot(new E_Equals(new ExprVar(var), NodeValue.makeNode(tp.getObject()))))); break; } } } // FILTER(isIRI(?uri)) Var projectVar = query.getProjectVars().get(0); filters.add(new ElementFilter(new E_IsIRI(NodeValue.makeNode(projectVar.asNode())))); Triple newTp = Triple.create(s, p, o); List<Triple> newTriplePatterns = new ArrayList<>(remainingTriplePatterns); newTriplePatterns.add(triplePatterns.indexOf(tp), newTp); Query newQuery = QueryFactory.create(); newQuery.setQuerySelectType(); newQuery.addProjectVars(query.getProjectVars()); newQuery.setDistinct(true); ElementTriplesBlock bgp = new ElementTriplesBlock(); newTriplePatterns.forEach(bgp::addTriple); ElementGroup eg = new ElementGroup(); eg.addElement(bgp); filters.forEach(eg::addElementFilter); Concept attrConcept = new Concept(bgp, query.getProjectVars().get(0)); Concept filterConcept = new Concept(query.getQueryPattern(), query.getProjectVars().get(0)); Map<Var, Var> varMap = ConceptUtils.createVarMap(attrConcept, filterConcept); Concept renamedConcept = ConceptUtils.createRenamedConcept(filterConcept, varMap); E_NotExists notExists = new E_NotExists(renamedConcept.getElement()); eg.addElementFilter(new ElementFilter(notExists)); newQuery.setQueryPattern(eg); queries.add(newQuery); } } return queries; } private List<Query> generateQueriesByRemoval(Query query) { List<Query> queries = new ArrayList<>(); // extract paths Node source = query.getProjectVars().get(0).asNode(); Set<List<Triple>> paths = getPaths(new ArrayList<>(), query, source); // for each path create query which excludes the path by FILTER NOT EXISTS Set<Set<List<Triple>>> pathSubsets = Sets.powerSet(paths); for (Set<List<Triple>> pathSubset : pathSubsets) { if(!pathSubset.isEmpty() && pathSubset.size() < paths.size()) { ElementGroup eg = new ElementGroup(); // keep other paths ElementTriplesBlock existsBlock = new ElementTriplesBlock(); eg.addElement(existsBlock); SetView<List<Triple>> difference = Sets.difference(paths, pathSubset); for(List<Triple> otherPath : difference) { for (Triple tp : otherPath) { existsBlock.addTriple(tp); } } // not exists current path ElementTriplesBlock notExistsBlock = new ElementTriplesBlock(); for(List<Triple> path : pathSubset) { for (Triple tp : path) { notExistsBlock.addTriple(tp); } } ElementGroup notExistsGroup = new ElementGroup(); notExistsGroup.addElement(notExistsBlock); eg.addElementFilter(getNotExistsFilter(notExistsGroup)); Query newQuery = QueryFactory.create(); newQuery.setQuerySelectType(); newQuery.setQueryPattern(eg); newQuery.addProjectVars(query.getProjectVars()); newQuery.setDistinct(true); queries.add(newQuery); } } return queries; } private Set<List<Triple>> getPaths(List<Triple> path, Query query, Node source) { Set<List<Triple>> paths = new LinkedHashSet<>(); Set<Triple> outgoingTriplePatterns = QueryUtils.getOutgoingTriplePatterns(query, source); for (Triple tp : outgoingTriplePatterns) { List<Triple> newPath = new ArrayList<>(path); newPath.add(tp); if(tp.getObject().isVariable()) { paths.addAll(getPaths(newPath, query, tp.getObject())); } else { paths.add(newPath); } } return paths; } /** * Returns a modified SPARQL query such that it is similar but different by choosing one of the triple patterns and use * the negation of its existence. * @param query the SPARQL query */ public Query generateSPARQLQuery(Query query){ //choose a random triple for the modification List<Triple> triplePatterns = new ArrayList<>(triplePatternExtractor.extractTriplePattern(query)); Collections.shuffle(triplePatterns, randomGen); triple = triplePatterns.get(0); Query modifiedQuery = query.cloneQuery(); modifiedQuery.getQueryPattern().visit(this); logger.info("Negative examples query:\n" + modifiedQuery.toString()); return modifiedQuery; } @Override public void visit(ElementGroup el) { parentGroup.push(el); for (Element e : new ArrayList<>(el.getElements())) { e.visit(this); } parentGroup.pop(); } @Override public void visit(ElementOptional el) { inOptionalClause = true; el.getOptionalElement().visit(this); inOptionalClause = false; } @Override public void visit(ElementTriplesBlock el) { for (Iterator<Triple> iterator = el.patternElts(); iterator.hasNext();) { Triple t = iterator.next(); if(inOptionalClause){ } else { if(t.equals(triple)){ ElementGroup parent = parentGroup.peek(); ElementTriplesBlock elementTriplesBlock = new ElementTriplesBlock(); elementTriplesBlock.addTriple(t); ElementGroup eg = new ElementGroup(); eg.addElement(elementTriplesBlock); parent.addElement(new ElementFilter(new E_NotExists(eg))); iterator.remove(); } } } } @Override public void visit(ElementPathBlock el) { for (Iterator<TriplePath> iterator = el.patternElts(); iterator.hasNext();) { TriplePath tp = iterator.next(); if(inOptionalClause){ } else { if(tp.asTriple().equals(triple)){ ElementGroup parent = parentGroup.peek(); ElementPathBlock elementTriplesBlock = new ElementPathBlock(); elementTriplesBlock.addTriple(tp); ElementGroup eg = new ElementGroup(); eg.addElement(elementTriplesBlock); parent.addElement(new ElementFilter(new E_NotExists(eg))); iterator.remove(); } } } } @Override public void visit(ElementUnion el) { for (Element e : el.getElements()) { e.visit(this); } } @Override public void visit(ElementFilter el) { } }
{ "pile_set_name": "Github" }
<div id="container"> <div id="content"></div> </div> #child { height: 20px; width: 20px; }
{ "pile_set_name": "Github" }
--- a/09_shader_base.vert +++ b/17_shader_vertexbuffer.vert @@ -1,25 +1,17 @@ #version 450 #extension GL_ARB_separate_shader_objects : enable -out gl_PerVertex { - vec4 gl_Position; -}; +// NOTE: names must match the `Vertex` struct in Rust +layout(location = 0) in vec2 pos; +layout(location = 1) in vec3 color; layout(location = 0) out vec3 fragColor; -vec2 positions[3] = vec2[]( - vec2(0.0, -0.5), - vec2(0.5, 0.5), - vec2(-0.5, 0.5) -); - -vec3 colors[3] = vec3[]( - vec3(1.0, 0.0, 0.0), - vec3(0.0, 1.0, 0.0), - vec3(0.0, 0.0, 1.0) -); +out gl_PerVertex { + vec4 gl_Position; +}; void main() { - gl_Position = vec4(positions[gl_VertexIndex], 0.0, 1.0); - fragColor = colors[gl_VertexIndex]; + gl_Position = vec4(pos, 0.0, 1.0); + fragColor = color; }
{ "pile_set_name": "Github" }
describe("Ext.CompositeElementLite", function(){ var mainRoot, ce, makeCE, fooTotal = 6, barTotal = 5, bazTotal = 4, child1Total = 5, child2Total = 4, child1RootedTotal = 2, child2RootedTotal = 2, child1MainTotal = 3, child2MainTotal = 2, byId = function(id) { return document.getElementById(id); }; beforeEach(function(){ mainRoot = Ext.getBody().createChild({ id: 'mainRoot' }); mainRoot.dom.innerHTML = [ '<div class="foo toFilter" id="a">', '<div class="child1">c1</div>', '<div class="child2">c2</div>', '<div class="child1">c3</div>', '<div class="child2">c4</div>', '</div>', '<div class="bar" id="b"></div>', '<div class="baz" id="c"></div>', '<div class="foo" id="d"></div>', '<div class="bar" id="e"></div>', '<div class="baz" id="f"></div>', '<div class="foo toFilter" id="g"></div>', '<div class="bar" id="h"></div>', '<div class="baz" id="i"></div>', '<div class="foo" id="j"></div>', '<div class="bar" id="k"></div>', '<div class="baz" id="l"></div>', '<div class="foo" id="m"></div>', '<div class="bar" id="n"></div>', '<div class="foo" id="o"></div>', '<div class="child1" id="p"></div>', '<div class="child2" id="q"></div>', '<div class="child1" id="r"></div>', '<div class="child2" id="s"></div>', '<div class="child1" id="t"></div>' ].join(''); makeCE = function(els) { ce = new Ext.CompositeElementLite(els); }; }); afterEach(function(){ mainRoot.destroy(); makeCE = mainRoot = ce = null; }); describe("constructor", function() { // TODO }); describe("add", function(){ it("should accept a selector", function(){ makeCE(); ce.add('.foo'); expect(ce.getCount()).toBe(fooTotal); }); it("should accept a selector with a root", function(){ makeCE(); ce.add('.child1', 'a'); expect(ce.getCount()).toBe(child1RootedTotal); }); it("should accept another CompositeElement", function(){ var other = new Ext.CompositeElementLite(); other.add(byId('a')); other.add(byId('b')); other.add(byId('c')); makeCE(); ce.add(other); expect(ce.getCount()).toBe(3); }); it("should accept an array of elements", function(){ makeCE(); ce.add([byId('a'), byId('b')]); expect(ce.getCount()).toBe(2); }); it("should accept a NodeList", function(){ makeCE(); ce.add(byId('a').getElementsByTagName('div')); expect(ce.getCount()).toBe(4); }); it("should accept a single element", function(){ makeCE(); ce.add(byId('a')); expect(ce.getCount()).toBe(1); }); it("should accept a null argument", function(){ makeCE(); expect(ce.add(null)).toBe(ce); }); it("should return the CompositeElement", function(){ makeCE(); expect(ce.add('.foo')).toBe(ce); }) }); describe("item", function(){ it("should return null if there are no items", function(){ makeCE(); expect(ce.item(0)).toBeNull(); }); it("should return null if an item at that index does not exist", function(){ makeCE('.foo'); expect(ce.item(fooTotal)).toBeNull(); }); it("should return the item at the specified index", function(){ makeCE('.foo'); expect(ce.item(2).dom.id).toBe('g'); }); describe("first", function(){ it("should return null when there are no items", function(){ makeCE(); expect(ce.first()).toBeNull(); }); it("should return the first item", function(){ makeCE('.foo'); expect(ce.first().dom.id).toBe('a'); }); }); describe("last", function(){ it("should return null when there are no items", function(){ makeCE(); expect(ce.last()).toBeNull(); }); it("should return the last item", function(){ makeCE('.foo'); expect(ce.last().dom.id).toBe('o'); }) }); }); describe("each", function(){ it("should never iterate if there are no items", function(){ var cnt = 0; makeCE(); ce.each(function(){ ++cnt; }); expect(cnt).toBe(0); }); it("should iterate over each item", function(){ var cnt = 0; makeCE('.baz'); ce.each(function(){ ++cnt; }); expect(cnt).toBe(bazTotal); }); it("should default the scope to the element", function(){ var isEl; makeCE(byId('a')); ce.each(function(e){ isEl = (e == this); }); expect(isEl).toBe(true); }); it("should use a specified scope", function(){ var o = {}, scope; makeCE('.foo'); ce.each(function(){ scope = this; }, o); expect(scope).toBe(o); }); it("should pass the element, the ce & the index", function(){ var info; makeCE(byId('a')); ce.each(function(el, theCE, index){ info = [el.dom.id, theCE, index]; }); expect(info).toEqual(['a', ce, 0]); }); it("should exit upon returning false", function(){ var cnt = 0; makeCE('.foo'); ce.each(function(el){ if (el.dom.id == 'd') { return false; } ++cnt; }); expect(cnt).toBe(1); }); it("should return the CompositeElement", function(){ makeCE(); expect(ce.each(function(){})).toBe(ce); }); }); describe("fill", function(){ it("should clear any existing elements", function(){ makeCE('.foo'); ce.fill(null); expect(ce.getCount()).toBe(0); }); it("should accept a selector", function(){ makeCE('.foo'); expect(ce.getCount()).toBe(fooTotal); ce.fill('.bar'); expect(ce.getCount()).toBe(barTotal); }); it("should accept an array of elements", function(){ makeCE(); ce.fill([byId('a'), byId('b')]); expect(ce.getCount()).toBe(2); }); it("should accept a NodeList", function(){ makeCE(); ce.fill(byId('a').getElementsByTagName('div')); expect(ce.getCount()).toBe(4); }); it("should accept another CompositeElement", function(){ var other = new Ext.CompositeElementLite(); other.add(byId('a')); other.add(byId('b')); other.add(byId('c')); makeCE(); ce.fill(other); expect(ce.getCount()).toBe(3); }); it("should return the CompositeElement", function(){ makeCE(); expect(ce.fill(null)).toBe(ce); }); }); describe("slice", function() { beforeEach(function() { makeCE(mainRoot.dom.childNodes); }); it("should return all nodes if no start or end is passed", function() { var nodes = ce.slice(); expect(nodes.length).toBe(20); }); it("should return to the end if a start is specified but the end is omitted", function() { var nodes = ce.slice(17); expect(nodes.length).toBe(3); expect(nodes[0]).toBe(byId('r')); expect(nodes[1]).toBe(byId('s')); expect(nodes[2]).toBe(byId('t')); }); it("should return to the specified range", function() { var nodes = ce.slice(14, 18); expect(nodes.length).toBe(4); expect(nodes[0]).toBe(byId('o')); expect(nodes[1]).toBe(byId('p')); expect(nodes[2]).toBe(byId('q')); expect(nodes[3]).toBe(byId('r')); }); }); describe("filter", function(){ it("should accept a selector", function(){ makeCE('.foo'); expect(ce.getCount()).toBe(fooTotal); expect(ce.filter('.toFilter').getCount()).toBe(2); }); it("should return the CompositeElement", function(){ makeCE(); expect(ce.filter(function(){})).toBe(ce); }); it("should accept a function", function(){ makeCE('.foo'); ce.filter(function(el){ var id = el.dom.id; return id == 'a' || id == 'd' || id == 'g'; }); expect(ce.getCount()).toBe(3); }); it("should set the scope to the element", function(){ var id; makeCE(byId('a')); ce.filter(function(){ id = this.dom.id; }); expect(id).toBe('a'); }); it("should pass the element, the CompositeElement & the index", function(){ var info; makeCE(byId('a')); ce.filter(function(el, otherCE, index){ info = [el.dom.id, otherCE, index]; }); expect(info).toEqual(['a', ce, 0]); }); }); describe("indexOf", function(){ it("should return -1 when there are no items", function(){ makeCE(); expect(ce.indexOf('a')).toBe(-1); }); it("should return -1 when the item doesn't exist in the collection", function(){ makeCE('.bar'); expect(ce.indexOf('a')).toBe(-1); }); it("should accept an id", function(){ makeCE('.foo'); expect(ce.indexOf('a')).toBe(0); }); it("should accept an HTMLElement", function(){ makeCE('.foo'); expect(ce.indexOf(byId('d'))).toBe(1); }); it("should accept an Ext.dom.Element", function(){ makeCE('.foo'); expect(ce.indexOf(Ext.fly('g'))).toBe(2); }); }); describe("contains", function(){ it("should return false when there are no items", function(){ makeCE(); expect(ce.contains('a')).toBe(false); }); it("should return false when the item doesn't exist in the collection", function(){ makeCE('.bar'); expect(ce.contains('a')).toBe(false); }); it("should accept an id", function(){ makeCE('.foo'); expect(ce.contains('a')).toBe(true); }); it("should accept an HTMLElement", function(){ makeCE('.foo'); expect(ce.contains(byId('d'))).toBe(true); }); it("should accept an Ext.dom.Element", function(){ makeCE('.foo'); expect(ce.contains(Ext.fly('g'))).toBe(true); }); }); describe("removeElement", function(){ it("should accept a string id", function(){ makeCE('.foo'); ce.removeElement('a'); expect(ce.contains('a')).toBe(false); }); it("should accept an HTMLElement", function(){ makeCE('.foo'); ce.removeElement(byId('a')); expect(ce.contains('a')).toBe(false); }); it("should accept an Ext.dom.Element", function(){ makeCE('.foo'); ce.removeElement(Ext.fly('a')); expect(ce.contains('a')).toBe(false); }); it("should accept an index", function(){ makeCE('.foo'); ce.removeElement(0); expect(ce.contains('a')).toBe(false); }); it("should remove the element if removeDom is specified", function(){ makeCE('.foo'); ce.removeElement('a', true); // refill from DOM ce.fill('.foo'); expect(ce.contains('a')).toBe(false); }); it("should return the CompositeElement", function(){ makeCE(); expect(ce.removeElement(null)).toBe(ce); }); }); describe("clear", function(){ it("should do nothing when the collection is empty", function(){ makeCE(); ce.clear(); expect(ce.getCount()).toBe(0); }); it("should remove all elements", function(){ makeCE('.foo'); ce.clear(); expect(ce.getCount()).toBe(0); }); }); });
{ "pile_set_name": "Github" }
<?php /** * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Smile ElasticSuite to newer * versions in the future. * * @category Smile * @package Smile\Elasticsuite________ * @author Romain Ruaud <[email protected]> * @copyright 2020 Smile * @license Open Software License ("OSL") v. 3.0 */ namespace Smile\ElasticsuiteThesaurus\Model\ResourceModel\Thesaurus; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\Store; use Smile\ElasticsuiteThesaurus\Api\Data\ThesaurusInterface; /** * Thesaurus Collection Resource Model * * @category Smile * @package Smile\ElasticsuiteThesaurus * @author Romain Ruaud <[email protected]> */ class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection { /** * Store for filter * * @var integer */ private $storeId; /** * Store manager * * @var \Magento\Store\Model\StoreManagerInterface */ private $storeManager; /** * Search resource helper * * @var \Magento\Framework\DB\Helper */ private $resourceHelper; /** * If link with terms has already been established * * @var boolean */ private $termsLinked = false; /** * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory Entity Factory * @param \Psr\Log\LoggerInterface $logger Logger * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy Fetch Strategy * @param \Magento\Framework\Event\ManagerInterface $eventManager Event Manager * @param \Magento\Store\Model\StoreManagerInterface $storeManager Store Manager * @param \Magento\Framework\DB\Helper $resourceHelper Resource Helper * @param \Magento\Framework\DB\Adapter\AdapterInterface $connection Database Connection * @param \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource Abstract Resource */ public function __construct( \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory, \Psr\Log\LoggerInterface $logger, \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy, \Magento\Framework\Event\ManagerInterface $eventManager, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\DB\Helper $resourceHelper, \Magento\Framework\DB\Adapter\AdapterInterface $connection = null, \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null ) { $this->storeManager = $storeManager; $this->resourceHelper = $resourceHelper; parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $connection, $resource); } /** * Set Store ID for filter * * @param Store|int $store The store * * @return $this */ public function setStoreId($store) { if ($store instanceof Store) { $store = $store->getId(); } $this->storeId = $store; return $this; } /** * Retrieve Store ID Filter * * @return int|null */ public function getStoreId() { return $this->storeId; } /** * Set thesaurus term to filter * * @param string $term The term to filter * * @return $this */ public function setTermFilter($term) { $term = preg_replace("/[\s-]/", "%", $term); $this->addTermFilterToSelect($term); return $this; } /** * Filter collection by specified store ids * * @param array|int $storeIds The store ids to filter * * @return $this */ public function addStoreFilter($storeIds) { $defaultStoreId = Store::DEFAULT_STORE_ID; if (!is_array($storeIds)) { $storeIds = [$storeIds]; } if (!in_array($defaultStoreId, $storeIds)) { $storeIds[] = $defaultStoreId; } $this->getSelect() ->join( ['store_table' => $this->getTable(ThesaurusInterface::STORE_TABLE_NAME)], 'main_table.' . ThesaurusInterface::THESAURUS_ID . ' = store_table.' . ThesaurusInterface::THESAURUS_ID, [] ) ->where('store_table.store_id IN (?)', $storeIds) ->group('main_table.' . ThesaurusInterface::THESAURUS_ID); return $this; } /** * Join store relation table if there is store filter * * @SuppressWarnings(PHPMD.CamelCaseMethodName) */ protected function _renderFiltersBefore() { if ($this->getFilter('store')) { $this->getSelect()->join( ['store_table' => $this->getTable(ThesaurusInterface::STORE_TABLE_NAME)], 'main_table.' . ThesaurusInterface::THESAURUS_ID . ' = store_table.' . ThesaurusInterface::THESAURUS_ID, [] )->group( 'main_table.' . ThesaurusInterface::THESAURUS_ID ); } parent::_renderFiltersBefore(); } /** * Init model for collection * * @SuppressWarnings(PHPMD.CamelCaseMethodName) */ protected function _construct() { $this->_init( 'Smile\ElasticsuiteThesaurus\Model\Thesaurus', 'Smile\ElasticsuiteThesaurus\Model\ResourceModel\Thesaurus' ); } /** * Perform operations after collection load * * @SuppressWarnings(PHPMD.CamelCaseMethodName) * * @return $this */ protected function _afterLoad() { $this->loadStores(); $this->loadTermsData(); return parent::_afterLoad(); } /** * Inject terms data on collection * * @param string $term Term filter text. * * @return $this */ private function addTermFilterToSelect($term) { $select = $this->getSelect(); if ($this->termsLinked === false) { $select->joinLeft( ['expansion_table' => $this->getTable(ThesaurusInterface::EXPANSION_TABLE_NAME)], new \Zend_Db_Expr("main_table.thesaurus_id = expansion_table.thesaurus_id"), [ 'expansion_terms' => new \Zend_Db_Expr("GROUP_CONCAT( DISTINCT expansion_table.term SEPARATOR ',')"), ] ); $select->joinLeft( ['reference_table' => $this->getTable(ThesaurusInterface::REFERENCE_TABLE_NAME)], new \Zend_Db_Expr( "reference_table.term_id = expansion_table.term_id " . "AND main_table." . ThesaurusInterface::THESAURUS_ID . " = reference_table." . ThesaurusInterface::THESAURUS_ID ), ['reference_terms' => new \Zend_Db_Expr("GROUP_CONCAT( DISTINCT reference_table.term SEPARATOR ',')")] ); $select->group("main_table." . ThesaurusInterface::THESAURUS_ID); $select->where("expansion_table.term LIKE '%{$term}%'", $term) ->orWhere("reference_table.term LIKE '%{$term}%'", $term); $this->termsLinked = true; } return $select; } /** * Perform operations after collection load * * @return void */ private function loadStores() { $itemIds = array_keys($this->_items); if (count($itemIds)) { $connection = $this->getConnection(); $select = $connection->select() ->from(['thesaurus_entity_store' => $this->getTable(ThesaurusInterface::STORE_TABLE_NAME)]) ->where('thesaurus_entity_store.' . ThesaurusInterface::THESAURUS_ID . ' IN (?)', $itemIds) ; $result = []; foreach ($connection->fetchAll($select) as $item) { $result[$item[ThesaurusInterface::THESAURUS_ID]][] = $item[ThesaurusInterface::STORE_ID]; } if ($result) { foreach ($this as $item) { $entityId = $item->getData(ThesaurusInterface::THESAURUS_ID); if (!isset($result[$entityId])) { continue; } $storeCodes = []; $storeIds = []; foreach ($result[$entityId] as $storeId) { if ($storeId == 0) { $storeIds = array_map(function (StoreInterface $store) { return $store->getId(); }, $this->storeManager->getStores(false, true)); $storeCodes = array_map(function (StoreInterface $store) { return $store->getCode(); }, $this->storeManager->getStores(false, true)); } if ($storeId != 0) { $storeCodes[] = $this->storeManager->getStore($storeId)->getCode(); $storeIds[] = $storeId; } } $item->setData('store_ids', $storeIds); $item->setData('store_codes', implode(";", $storeCodes)); } } } } /** * Perform operations after collection load * * @return void */ private function loadTermsData() { $select = $this->getConnection()->select(); $itemIds = array_keys($this->_items); $select->from(['exp' => $this->getTable(ThesaurusInterface::EXPANSION_TABLE_NAME)], []) ->joinLeft( ['ref' => $this->getTable(ThesaurusInterface::REFERENCE_TABLE_NAME)], "exp.thesaurus_id = ref.thesaurus_id AND exp.term_id = ref.term_id", [] ) ->where('exp.thesaurus_id IN (?)', $itemIds) ->group(["exp.thesaurus_id", "exp.term_id"]) ->columns( [ 'thesaurus_id' => 'exp.thesaurus_id', 'expansions_terms' => new \Zend_Db_Expr("GROUP_CONCAT(exp.term)"), 'expanded_term' => 'ref.term', ] ); $data = $this->getConnection()->fetchAll($select); $this->addTermData($data); $this->addTermExportData($data); } /** * Process terms of each thesaurus and display a summary for each thesaurus. * * @param array $termData Raw terms data loaded from the DB. * * @return $this */ private function addTermData($termData) { $labelsByThesaurusId = []; foreach ($termData as $currentTerm) { $label = $currentTerm['expansions_terms']; if (isset($currentTerm['expanded_term']) && $currentTerm['expanded_term']) { $label = sprintf("%s => %s", $currentTerm['expanded_term'], $label); } $labelsByThesaurusId[$currentTerm['thesaurus_id']][] = $label; } foreach ($labelsByThesaurusId as $thesaurusId => $labels) { $this->_items[$thesaurusId]->setData('terms_summary', implode(" <br/> ", $labels)); } return $this; } /** * Process terms of each thesaurus for export. * * @param array $termData Raw terms data loaded from the DB. * * @return $this */ private function addTermExportData($termData) { $labelsByThesaurusId = []; foreach ($termData as $currentTerm) { $label = $currentTerm['expansions_terms']; if (isset($currentTerm['expanded_term']) && $currentTerm['expanded_term']) { $label = sprintf("%s:%s", $currentTerm['expanded_term'], $label); } $labelsByThesaurusId[$currentTerm['thesaurus_id']][] = $label; } foreach ($labelsByThesaurusId as $thesaurusId => $labels) { $this->_items[$thesaurusId]->setData('terms_export', implode(";", $labels)); } return $this; } }
{ "pile_set_name": "Github" }
// Copyright 2012 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Author: Jyrki Alakuijala ([email protected]) // #include <assert.h> #include <math.h> #include "src/enc/backward_references_enc.h" #include "src/enc/histogram_enc.h" #include "src/dsp/lossless.h" #include "src/dsp/lossless_common.h" #include "src/dsp/dsp.h" #include "src/utils/color_cache_utils.h" #include "src/utils/utils.h" #define MIN_BLOCK_SIZE 256 // minimum block size for backward references #define MAX_ENTROPY (1e30f) // 1M window (4M bytes) minus 120 special codes for short distances. #define WINDOW_SIZE ((1 << WINDOW_SIZE_BITS) - 120) // Minimum number of pixels for which it is cheaper to encode a // distance + length instead of each pixel as a literal. #define MIN_LENGTH 4 // ----------------------------------------------------------------------------- static const uint8_t plane_to_code_lut[128] = { 96, 73, 55, 39, 23, 13, 5, 1, 255, 255, 255, 255, 255, 255, 255, 255, 101, 78, 58, 42, 26, 16, 8, 2, 0, 3, 9, 17, 27, 43, 59, 79, 102, 86, 62, 46, 32, 20, 10, 6, 4, 7, 11, 21, 33, 47, 63, 87, 105, 90, 70, 52, 37, 28, 18, 14, 12, 15, 19, 29, 38, 53, 71, 91, 110, 99, 82, 66, 48, 35, 30, 24, 22, 25, 31, 36, 49, 67, 83, 100, 115, 108, 94, 76, 64, 50, 44, 40, 34, 41, 45, 51, 65, 77, 95, 109, 118, 113, 103, 92, 80, 68, 60, 56, 54, 57, 61, 69, 81, 93, 104, 114, 119, 116, 111, 106, 97, 88, 84, 74, 72, 75, 85, 89, 98, 107, 112, 117 }; extern int VP8LDistanceToPlaneCode(int xsize, int dist); int VP8LDistanceToPlaneCode(int xsize, int dist) { const int yoffset = dist / xsize; const int xoffset = dist - yoffset * xsize; if (xoffset <= 8 && yoffset < 8) { return plane_to_code_lut[yoffset * 16 + 8 - xoffset] + 1; } else if (xoffset > xsize - 8 && yoffset < 7) { return plane_to_code_lut[(yoffset + 1) * 16 + 8 + (xsize - xoffset)] + 1; } return dist + 120; } // Returns the exact index where array1 and array2 are different. For an index // inferior or equal to best_len_match, the return value just has to be strictly // inferior to best_len_match. The current behavior is to return 0 if this index // is best_len_match, and the index itself otherwise. // If no two elements are the same, it returns max_limit. static WEBP_INLINE int FindMatchLength(const uint32_t* const array1, const uint32_t* const array2, int best_len_match, int max_limit) { // Before 'expensive' linear match, check if the two arrays match at the // current best length index. if (array1[best_len_match] != array2[best_len_match]) return 0; return VP8LVectorMismatch(array1, array2, max_limit); } // ----------------------------------------------------------------------------- // VP8LBackwardRefs struct PixOrCopyBlock { PixOrCopyBlock* next_; // next block (or NULL) PixOrCopy* start_; // data start int size_; // currently used size }; extern void VP8LClearBackwardRefs(VP8LBackwardRefs* const refs); void VP8LClearBackwardRefs(VP8LBackwardRefs* const refs) { assert(refs != NULL); if (refs->tail_ != NULL) { *refs->tail_ = refs->free_blocks_; // recycle all blocks at once } refs->free_blocks_ = refs->refs_; refs->tail_ = &refs->refs_; refs->last_block_ = NULL; refs->refs_ = NULL; } void VP8LBackwardRefsClear(VP8LBackwardRefs* const refs) { assert(refs != NULL); VP8LClearBackwardRefs(refs); while (refs->free_blocks_ != NULL) { PixOrCopyBlock* const next = refs->free_blocks_->next_; WebPSafeFree(refs->free_blocks_); refs->free_blocks_ = next; } } void VP8LBackwardRefsInit(VP8LBackwardRefs* const refs, int block_size) { assert(refs != NULL); memset(refs, 0, sizeof(*refs)); refs->tail_ = &refs->refs_; refs->block_size_ = (block_size < MIN_BLOCK_SIZE) ? MIN_BLOCK_SIZE : block_size; } VP8LRefsCursor VP8LRefsCursorInit(const VP8LBackwardRefs* const refs) { VP8LRefsCursor c; c.cur_block_ = refs->refs_; if (refs->refs_ != NULL) { c.cur_pos = c.cur_block_->start_; c.last_pos_ = c.cur_pos + c.cur_block_->size_; } else { c.cur_pos = NULL; c.last_pos_ = NULL; } return c; } void VP8LRefsCursorNextBlock(VP8LRefsCursor* const c) { PixOrCopyBlock* const b = c->cur_block_->next_; c->cur_pos = (b == NULL) ? NULL : b->start_; c->last_pos_ = (b == NULL) ? NULL : b->start_ + b->size_; c->cur_block_ = b; } // Create a new block, either from the free list or allocated static PixOrCopyBlock* BackwardRefsNewBlock(VP8LBackwardRefs* const refs) { PixOrCopyBlock* b = refs->free_blocks_; if (b == NULL) { // allocate new memory chunk const size_t total_size = sizeof(*b) + refs->block_size_ * sizeof(*b->start_); b = (PixOrCopyBlock*)WebPSafeMalloc(1ULL, total_size); if (b == NULL) { refs->error_ |= 1; return NULL; } b->start_ = (PixOrCopy*)((uint8_t*)b + sizeof(*b)); // not always aligned } else { // recycle from free-list refs->free_blocks_ = b->next_; } *refs->tail_ = b; refs->tail_ = &b->next_; refs->last_block_ = b; b->next_ = NULL; b->size_ = 0; return b; } extern void VP8LBackwardRefsCursorAdd(VP8LBackwardRefs* const refs, const PixOrCopy v); void VP8LBackwardRefsCursorAdd(VP8LBackwardRefs* const refs, const PixOrCopy v) { PixOrCopyBlock* b = refs->last_block_; if (b == NULL || b->size_ == refs->block_size_) { b = BackwardRefsNewBlock(refs); if (b == NULL) return; // refs->error_ is set } b->start_[b->size_++] = v; } // ----------------------------------------------------------------------------- // Hash chains int VP8LHashChainInit(VP8LHashChain* const p, int size) { assert(p->size_ == 0); assert(p->offset_length_ == NULL); assert(size > 0); p->offset_length_ = (uint32_t*)WebPSafeMalloc(size, sizeof(*p->offset_length_)); if (p->offset_length_ == NULL) return 0; p->size_ = size; return 1; } void VP8LHashChainClear(VP8LHashChain* const p) { assert(p != NULL); WebPSafeFree(p->offset_length_); p->size_ = 0; p->offset_length_ = NULL; } // ----------------------------------------------------------------------------- static const uint32_t kHashMultiplierHi = 0xc6a4a793u; static const uint32_t kHashMultiplierLo = 0x5bd1e996u; static WEBP_UBSAN_IGNORE_UNSIGNED_OVERFLOW WEBP_INLINE uint32_t GetPixPairHash64(const uint32_t* const argb) { uint32_t key; key = argb[1] * kHashMultiplierHi; key += argb[0] * kHashMultiplierLo; key = key >> (32 - HASH_BITS); return key; } // Returns the maximum number of hash chain lookups to do for a // given compression quality. Return value in range [8, 86]. static int GetMaxItersForQuality(int quality) { return 8 + (quality * quality) / 128; } static int GetWindowSizeForHashChain(int quality, int xsize) { const int max_window_size = (quality > 75) ? WINDOW_SIZE : (quality > 50) ? (xsize << 8) : (quality > 25) ? (xsize << 6) : (xsize << 4); assert(xsize > 0); return (max_window_size > WINDOW_SIZE) ? WINDOW_SIZE : max_window_size; } static WEBP_INLINE int MaxFindCopyLength(int len) { return (len < MAX_LENGTH) ? len : MAX_LENGTH; } int VP8LHashChainFill(VP8LHashChain* const p, int quality, const uint32_t* const argb, int xsize, int ysize, int low_effort) { const int size = xsize * ysize; const int iter_max = GetMaxItersForQuality(quality); const uint32_t window_size = GetWindowSizeForHashChain(quality, xsize); int pos; int argb_comp; uint32_t base_position; int32_t* hash_to_first_index; // Temporarily use the p->offset_length_ as a hash chain. int32_t* chain = (int32_t*)p->offset_length_; assert(size > 0); assert(p->size_ != 0); assert(p->offset_length_ != NULL); if (size <= 2) { p->offset_length_[0] = p->offset_length_[size - 1] = 0; return 1; } hash_to_first_index = (int32_t*)WebPSafeMalloc(HASH_SIZE, sizeof(*hash_to_first_index)); if (hash_to_first_index == NULL) return 0; // Set the int32_t array to -1. memset(hash_to_first_index, 0xff, HASH_SIZE * sizeof(*hash_to_first_index)); // Fill the chain linking pixels with the same hash. argb_comp = (argb[0] == argb[1]); for (pos = 0; pos < size - 2;) { uint32_t hash_code; const int argb_comp_next = (argb[pos + 1] == argb[pos + 2]); if (argb_comp && argb_comp_next) { // Consecutive pixels with the same color will share the same hash. // We therefore use a different hash: the color and its repetition // length. uint32_t tmp[2]; uint32_t len = 1; tmp[0] = argb[pos]; // Figure out how far the pixels are the same. // The last pixel has a different 64 bit hash, as its next pixel does // not have the same color, so we just need to get to the last pixel equal // to its follower. while (pos + (int)len + 2 < size && argb[pos + len + 2] == argb[pos]) { ++len; } if (len > MAX_LENGTH) { // Skip the pixels that match for distance=1 and length>MAX_LENGTH // because they are linked to their predecessor and we automatically // check that in the main for loop below. Skipping means setting no // predecessor in the chain, hence -1. memset(chain + pos, 0xff, (len - MAX_LENGTH) * sizeof(*chain)); pos += len - MAX_LENGTH; len = MAX_LENGTH; } // Process the rest of the hash chain. while (len) { tmp[1] = len--; hash_code = GetPixPairHash64(tmp); chain[pos] = hash_to_first_index[hash_code]; hash_to_first_index[hash_code] = pos++; } argb_comp = 0; } else { // Just move one pixel forward. hash_code = GetPixPairHash64(argb + pos); chain[pos] = hash_to_first_index[hash_code]; hash_to_first_index[hash_code] = pos++; argb_comp = argb_comp_next; } } // Process the penultimate pixel. chain[pos] = hash_to_first_index[GetPixPairHash64(argb + pos)]; WebPSafeFree(hash_to_first_index); // Find the best match interval at each pixel, defined by an offset to the // pixel and a length. The right-most pixel cannot match anything to the right // (hence a best length of 0) and the left-most pixel nothing to the left // (hence an offset of 0). assert(size > 2); p->offset_length_[0] = p->offset_length_[size - 1] = 0; for (base_position = size - 2; base_position > 0;) { const int max_len = MaxFindCopyLength(size - 1 - base_position); const uint32_t* const argb_start = argb + base_position; int iter = iter_max; int best_length = 0; uint32_t best_distance = 0; uint32_t best_argb; const int min_pos = (base_position > window_size) ? base_position - window_size : 0; const int length_max = (max_len < 256) ? max_len : 256; uint32_t max_base_position; pos = chain[base_position]; if (!low_effort) { int curr_length; // Heuristic: use the comparison with the above line as an initialization. if (base_position >= (uint32_t)xsize) { curr_length = FindMatchLength(argb_start - xsize, argb_start, best_length, max_len); if (curr_length > best_length) { best_length = curr_length; best_distance = xsize; } --iter; } // Heuristic: compare to the previous pixel. curr_length = FindMatchLength(argb_start - 1, argb_start, best_length, max_len); if (curr_length > best_length) { best_length = curr_length; best_distance = 1; } --iter; // Skip the for loop if we already have the maximum. if (best_length == MAX_LENGTH) pos = min_pos - 1; } best_argb = argb_start[best_length]; for (; pos >= min_pos && --iter; pos = chain[pos]) { int curr_length; assert(base_position > (uint32_t)pos); if (argb[pos + best_length] != best_argb) continue; curr_length = VP8LVectorMismatch(argb + pos, argb_start, max_len); if (best_length < curr_length) { best_length = curr_length; best_distance = base_position - pos; best_argb = argb_start[best_length]; // Stop if we have reached a good enough length. if (best_length >= length_max) break; } } // We have the best match but in case the two intervals continue matching // to the left, we have the best matches for the left-extended pixels. max_base_position = base_position; while (1) { assert(best_length <= MAX_LENGTH); assert(best_distance <= WINDOW_SIZE); p->offset_length_[base_position] = (best_distance << MAX_LENGTH_BITS) | (uint32_t)best_length; --base_position; // Stop if we don't have a match or if we are out of bounds. if (best_distance == 0 || base_position == 0) break; // Stop if we cannot extend the matching intervals to the left. if (base_position < best_distance || argb[base_position - best_distance] != argb[base_position]) { break; } // Stop if we are matching at its limit because there could be a closer // matching interval with the same maximum length. Then again, if the // matching interval is as close as possible (best_distance == 1), we will // never find anything better so let's continue. if (best_length == MAX_LENGTH && best_distance != 1 && base_position + MAX_LENGTH < max_base_position) { break; } if (best_length < MAX_LENGTH) { ++best_length; max_base_position = base_position; } } } return 1; } static WEBP_INLINE void AddSingleLiteral(uint32_t pixel, int use_color_cache, VP8LColorCache* const hashers, VP8LBackwardRefs* const refs) { PixOrCopy v; if (use_color_cache) { const uint32_t key = VP8LColorCacheGetIndex(hashers, pixel); if (VP8LColorCacheLookup(hashers, key) == pixel) { v = PixOrCopyCreateCacheIdx(key); } else { v = PixOrCopyCreateLiteral(pixel); VP8LColorCacheSet(hashers, key, pixel); } } else { v = PixOrCopyCreateLiteral(pixel); } VP8LBackwardRefsCursorAdd(refs, v); } static int BackwardReferencesRle(int xsize, int ysize, const uint32_t* const argb, int cache_bits, VP8LBackwardRefs* const refs) { const int pix_count = xsize * ysize; int i, k; const int use_color_cache = (cache_bits > 0); VP8LColorCache hashers; if (use_color_cache && !VP8LColorCacheInit(&hashers, cache_bits)) { return 0; } VP8LClearBackwardRefs(refs); // Add first pixel as literal. AddSingleLiteral(argb[0], use_color_cache, &hashers, refs); i = 1; while (i < pix_count) { const int max_len = MaxFindCopyLength(pix_count - i); const int rle_len = FindMatchLength(argb + i, argb + i - 1, 0, max_len); const int prev_row_len = (i < xsize) ? 0 : FindMatchLength(argb + i, argb + i - xsize, 0, max_len); if (rle_len >= prev_row_len && rle_len >= MIN_LENGTH) { VP8LBackwardRefsCursorAdd(refs, PixOrCopyCreateCopy(1, rle_len)); // We don't need to update the color cache here since it is always the // same pixel being copied, and that does not change the color cache // state. i += rle_len; } else if (prev_row_len >= MIN_LENGTH) { VP8LBackwardRefsCursorAdd(refs, PixOrCopyCreateCopy(xsize, prev_row_len)); if (use_color_cache) { for (k = 0; k < prev_row_len; ++k) { VP8LColorCacheInsert(&hashers, argb[i + k]); } } i += prev_row_len; } else { AddSingleLiteral(argb[i], use_color_cache, &hashers, refs); i++; } } if (use_color_cache) VP8LColorCacheClear(&hashers); return !refs->error_; } static int BackwardReferencesLz77(int xsize, int ysize, const uint32_t* const argb, int cache_bits, const VP8LHashChain* const hash_chain, VP8LBackwardRefs* const refs) { int i; int i_last_check = -1; int ok = 0; int cc_init = 0; const int use_color_cache = (cache_bits > 0); const int pix_count = xsize * ysize; VP8LColorCache hashers; if (use_color_cache) { cc_init = VP8LColorCacheInit(&hashers, cache_bits); if (!cc_init) goto Error; } VP8LClearBackwardRefs(refs); for (i = 0; i < pix_count;) { // Alternative#1: Code the pixels starting at 'i' using backward reference. int offset = 0; int len = 0; int j; VP8LHashChainFindCopy(hash_chain, i, &offset, &len); if (len >= MIN_LENGTH) { const int len_ini = len; int max_reach = 0; const int j_max = (i + len_ini >= pix_count) ? pix_count - 1 : i + len_ini; // Only start from what we have not checked already. i_last_check = (i > i_last_check) ? i : i_last_check; // We know the best match for the current pixel but we try to find the // best matches for the current pixel AND the next one combined. // The naive method would use the intervals: // [i,i+len) + [i+len, length of best match at i+len) // while we check if we can use: // [i,j) (where j<=i+len) + [j, length of best match at j) for (j = i_last_check + 1; j <= j_max; ++j) { const int len_j = VP8LHashChainFindLength(hash_chain, j); const int reach = j + (len_j >= MIN_LENGTH ? len_j : 1); // 1 for single literal. if (reach > max_reach) { len = j - i; max_reach = reach; if (max_reach >= pix_count) break; } } } else { len = 1; } // Go with literal or backward reference. assert(len > 0); if (len == 1) { AddSingleLiteral(argb[i], use_color_cache, &hashers, refs); } else { VP8LBackwardRefsCursorAdd(refs, PixOrCopyCreateCopy(offset, len)); if (use_color_cache) { for (j = i; j < i + len; ++j) VP8LColorCacheInsert(&hashers, argb[j]); } } i += len; } ok = !refs->error_; Error: if (cc_init) VP8LColorCacheClear(&hashers); return ok; } // Compute an LZ77 by forcing matches to happen within a given distance cost. // We therefore limit the algorithm to the lowest 32 values in the PlaneCode // definition. #define WINDOW_OFFSETS_SIZE_MAX 32 static int BackwardReferencesLz77Box(int xsize, int ysize, const uint32_t* const argb, int cache_bits, const VP8LHashChain* const hash_chain_best, VP8LHashChain* hash_chain, VP8LBackwardRefs* const refs) { int i; const int pix_count = xsize * ysize; uint16_t* counts; int window_offsets[WINDOW_OFFSETS_SIZE_MAX] = {0}; int window_offsets_new[WINDOW_OFFSETS_SIZE_MAX] = {0}; int window_offsets_size = 0; int window_offsets_new_size = 0; uint16_t* const counts_ini = (uint16_t*)WebPSafeMalloc(xsize * ysize, sizeof(*counts_ini)); int best_offset_prev = -1, best_length_prev = -1; if (counts_ini == NULL) return 0; // counts[i] counts how many times a pixel is repeated starting at position i. i = pix_count - 2; counts = counts_ini + i; counts[1] = 1; for (; i >= 0; --i, --counts) { if (argb[i] == argb[i + 1]) { // Max out the counts to MAX_LENGTH. counts[0] = counts[1] + (counts[1] != MAX_LENGTH); } else { counts[0] = 1; } } // Figure out the window offsets around a pixel. They are stored in a // spiraling order around the pixel as defined by VP8LDistanceToPlaneCode. { int x, y; for (y = 0; y <= 6; ++y) { for (x = -6; x <= 6; ++x) { const int offset = y * xsize + x; int plane_code; // Ignore offsets that bring us after the pixel. if (offset <= 0) continue; plane_code = VP8LDistanceToPlaneCode(xsize, offset) - 1; if (plane_code >= WINDOW_OFFSETS_SIZE_MAX) continue; window_offsets[plane_code] = offset; } } // For narrow images, not all plane codes are reached, so remove those. for (i = 0; i < WINDOW_OFFSETS_SIZE_MAX; ++i) { if (window_offsets[i] == 0) continue; window_offsets[window_offsets_size++] = window_offsets[i]; } // Given a pixel P, find the offsets that reach pixels unreachable from P-1 // with any of the offsets in window_offsets[]. for (i = 0; i < window_offsets_size; ++i) { int j; int is_reachable = 0; for (j = 0; j < window_offsets_size && !is_reachable; ++j) { is_reachable |= (window_offsets[i] == window_offsets[j] + 1); } if (!is_reachable) { window_offsets_new[window_offsets_new_size] = window_offsets[i]; ++window_offsets_new_size; } } } hash_chain->offset_length_[0] = 0; for (i = 1; i < pix_count; ++i) { int ind; int best_length = VP8LHashChainFindLength(hash_chain_best, i); int best_offset; int do_compute = 1; if (best_length >= MAX_LENGTH) { // Do not recompute the best match if we already have a maximal one in the // window. best_offset = VP8LHashChainFindOffset(hash_chain_best, i); for (ind = 0; ind < window_offsets_size; ++ind) { if (best_offset == window_offsets[ind]) { do_compute = 0; break; } } } if (do_compute) { // Figure out if we should use the offset/length from the previous pixel // as an initial guess and therefore only inspect the offsets in // window_offsets_new[]. const int use_prev = (best_length_prev > 1) && (best_length_prev < MAX_LENGTH); const int num_ind = use_prev ? window_offsets_new_size : window_offsets_size; best_length = use_prev ? best_length_prev - 1 : 0; best_offset = use_prev ? best_offset_prev : 0; // Find the longest match in a window around the pixel. for (ind = 0; ind < num_ind; ++ind) { int curr_length = 0; int j = i; int j_offset = use_prev ? i - window_offsets_new[ind] : i - window_offsets[ind]; if (j_offset < 0 || argb[j_offset] != argb[i]) continue; // The longest match is the sum of how many times each pixel is // repeated. do { const int counts_j_offset = counts_ini[j_offset]; const int counts_j = counts_ini[j]; if (counts_j_offset != counts_j) { curr_length += (counts_j_offset < counts_j) ? counts_j_offset : counts_j; break; } // The same color is repeated counts_pos times at j_offset and j. curr_length += counts_j_offset; j_offset += counts_j_offset; j += counts_j_offset; } while (curr_length <= MAX_LENGTH && j < pix_count && argb[j_offset] == argb[j]); if (best_length < curr_length) { best_offset = use_prev ? window_offsets_new[ind] : window_offsets[ind]; if (curr_length >= MAX_LENGTH) { best_length = MAX_LENGTH; break; } else { best_length = curr_length; } } } } assert(i + best_length <= pix_count); assert(best_length <= MAX_LENGTH); if (best_length <= MIN_LENGTH) { hash_chain->offset_length_[i] = 0; best_offset_prev = 0; best_length_prev = 0; } else { hash_chain->offset_length_[i] = (best_offset << MAX_LENGTH_BITS) | (uint32_t)best_length; best_offset_prev = best_offset; best_length_prev = best_length; } } hash_chain->offset_length_[0] = 0; WebPSafeFree(counts_ini); return BackwardReferencesLz77(xsize, ysize, argb, cache_bits, hash_chain, refs); } // ----------------------------------------------------------------------------- static void BackwardReferences2DLocality(int xsize, const VP8LBackwardRefs* const refs) { VP8LRefsCursor c = VP8LRefsCursorInit(refs); while (VP8LRefsCursorOk(&c)) { if (PixOrCopyIsCopy(c.cur_pos)) { const int dist = c.cur_pos->argb_or_distance; const int transformed_dist = VP8LDistanceToPlaneCode(xsize, dist); c.cur_pos->argb_or_distance = transformed_dist; } VP8LRefsCursorNext(&c); } } // Evaluate optimal cache bits for the local color cache. // The input *best_cache_bits sets the maximum cache bits to use (passing 0 // implies disabling the local color cache). The local color cache is also // disabled for the lower (<= 25) quality. // Returns 0 in case of memory error. static int CalculateBestCacheSize(const uint32_t* argb, int quality, const VP8LBackwardRefs* const refs, int* const best_cache_bits) { int i; const int cache_bits_max = (quality <= 25) ? 0 : *best_cache_bits; double entropy_min = MAX_ENTROPY; int cc_init[MAX_COLOR_CACHE_BITS + 1] = { 0 }; VP8LColorCache hashers[MAX_COLOR_CACHE_BITS + 1]; VP8LRefsCursor c = VP8LRefsCursorInit(refs); VP8LHistogram* histos[MAX_COLOR_CACHE_BITS + 1] = { NULL }; int ok = 0; assert(cache_bits_max >= 0 && cache_bits_max <= MAX_COLOR_CACHE_BITS); if (cache_bits_max == 0) { *best_cache_bits = 0; // Local color cache is disabled. return 1; } // Allocate data. for (i = 0; i <= cache_bits_max; ++i) { histos[i] = VP8LAllocateHistogram(i); if (histos[i] == NULL) goto Error; VP8LHistogramInit(histos[i], i, /*init_arrays=*/ 1); if (i == 0) continue; cc_init[i] = VP8LColorCacheInit(&hashers[i], i); if (!cc_init[i]) goto Error; } // Find the cache_bits giving the lowest entropy. The search is done in a // brute-force way as the function (entropy w.r.t cache_bits) can be // anything in practice. while (VP8LRefsCursorOk(&c)) { const PixOrCopy* const v = c.cur_pos; if (PixOrCopyIsLiteral(v)) { const uint32_t pix = *argb++; const uint32_t a = (pix >> 24) & 0xff; const uint32_t r = (pix >> 16) & 0xff; const uint32_t g = (pix >> 8) & 0xff; const uint32_t b = (pix >> 0) & 0xff; // The keys of the caches can be derived from the longest one. int key = VP8LHashPix(pix, 32 - cache_bits_max); // Do not use the color cache for cache_bits = 0. ++histos[0]->blue_[b]; ++histos[0]->literal_[g]; ++histos[0]->red_[r]; ++histos[0]->alpha_[a]; // Deal with cache_bits > 0. for (i = cache_bits_max; i >= 1; --i, key >>= 1) { if (VP8LColorCacheLookup(&hashers[i], key) == pix) { ++histos[i]->literal_[NUM_LITERAL_CODES + NUM_LENGTH_CODES + key]; } else { VP8LColorCacheSet(&hashers[i], key, pix); ++histos[i]->blue_[b]; ++histos[i]->literal_[g]; ++histos[i]->red_[r]; ++histos[i]->alpha_[a]; } } } else { // We should compute the contribution of the (distance,length) // histograms but those are the same independently from the cache size. // As those constant contributions are in the end added to the other // histogram contributions, we can safely ignore them. int len = PixOrCopyLength(v); uint32_t argb_prev = *argb ^ 0xffffffffu; // Update the color caches. do { if (*argb != argb_prev) { // Efficiency: insert only if the color changes. int key = VP8LHashPix(*argb, 32 - cache_bits_max); for (i = cache_bits_max; i >= 1; --i, key >>= 1) { hashers[i].colors_[key] = *argb; } argb_prev = *argb; } argb++; } while (--len != 0); } VP8LRefsCursorNext(&c); } for (i = 0; i <= cache_bits_max; ++i) { const double entropy = VP8LHistogramEstimateBits(histos[i]); if (i == 0 || entropy < entropy_min) { entropy_min = entropy; *best_cache_bits = i; } } ok = 1; Error: for (i = 0; i <= cache_bits_max; ++i) { if (cc_init[i]) VP8LColorCacheClear(&hashers[i]); VP8LFreeHistogram(histos[i]); } return ok; } // Update (in-place) backward references for specified cache_bits. static int BackwardRefsWithLocalCache(const uint32_t* const argb, int cache_bits, VP8LBackwardRefs* const refs) { int pixel_index = 0; VP8LColorCache hashers; VP8LRefsCursor c = VP8LRefsCursorInit(refs); if (!VP8LColorCacheInit(&hashers, cache_bits)) return 0; while (VP8LRefsCursorOk(&c)) { PixOrCopy* const v = c.cur_pos; if (PixOrCopyIsLiteral(v)) { const uint32_t argb_literal = v->argb_or_distance; const int ix = VP8LColorCacheContains(&hashers, argb_literal); if (ix >= 0) { // hashers contains argb_literal *v = PixOrCopyCreateCacheIdx(ix); } else { VP8LColorCacheInsert(&hashers, argb_literal); } ++pixel_index; } else { // refs was created without local cache, so it can not have cache indexes. int k; assert(PixOrCopyIsCopy(v)); for (k = 0; k < v->len; ++k) { VP8LColorCacheInsert(&hashers, argb[pixel_index++]); } } VP8LRefsCursorNext(&c); } VP8LColorCacheClear(&hashers); return 1; } static VP8LBackwardRefs* GetBackwardReferencesLowEffort( int width, int height, const uint32_t* const argb, int* const cache_bits, const VP8LHashChain* const hash_chain, VP8LBackwardRefs* const refs_lz77) { *cache_bits = 0; if (!BackwardReferencesLz77(width, height, argb, 0, hash_chain, refs_lz77)) { return NULL; } BackwardReferences2DLocality(width, refs_lz77); return refs_lz77; } extern int VP8LBackwardReferencesTraceBackwards( int xsize, int ysize, const uint32_t* const argb, int cache_bits, const VP8LHashChain* const hash_chain, const VP8LBackwardRefs* const refs_src, VP8LBackwardRefs* const refs_dst); static VP8LBackwardRefs* GetBackwardReferences( int width, int height, const uint32_t* const argb, int quality, int lz77_types_to_try, int* const cache_bits, const VP8LHashChain* const hash_chain, VP8LBackwardRefs* best, VP8LBackwardRefs* worst) { const int cache_bits_initial = *cache_bits; double bit_cost_best = -1; VP8LHistogram* histo = NULL; int lz77_type, lz77_type_best = 0; VP8LHashChain hash_chain_box; memset(&hash_chain_box, 0, sizeof(hash_chain_box)); histo = VP8LAllocateHistogram(MAX_COLOR_CACHE_BITS); if (histo == NULL) goto Error; for (lz77_type = 1; lz77_types_to_try; lz77_types_to_try &= ~lz77_type, lz77_type <<= 1) { int res = 0; double bit_cost; int cache_bits_tmp = cache_bits_initial; if ((lz77_types_to_try & lz77_type) == 0) continue; switch (lz77_type) { case kLZ77RLE: res = BackwardReferencesRle(width, height, argb, 0, worst); break; case kLZ77Standard: // Compute LZ77 with no cache (0 bits), as the ideal LZ77 with a color // cache is not that different in practice. res = BackwardReferencesLz77(width, height, argb, 0, hash_chain, worst); break; case kLZ77Box: if (!VP8LHashChainInit(&hash_chain_box, width * height)) goto Error; res = BackwardReferencesLz77Box(width, height, argb, 0, hash_chain, &hash_chain_box, worst); break; default: assert(0); } if (!res) goto Error; // Next, try with a color cache and update the references. if (!CalculateBestCacheSize(argb, quality, worst, &cache_bits_tmp)) { goto Error; } if (cache_bits_tmp > 0) { if (!BackwardRefsWithLocalCache(argb, cache_bits_tmp, worst)) { goto Error; } } // Keep the best backward references. VP8LHistogramCreate(histo, worst, cache_bits_tmp); bit_cost = VP8LHistogramEstimateBits(histo); if (lz77_type_best == 0 || bit_cost < bit_cost_best) { VP8LBackwardRefs* const tmp = worst; worst = best; best = tmp; bit_cost_best = bit_cost; *cache_bits = cache_bits_tmp; lz77_type_best = lz77_type; } } assert(lz77_type_best > 0); // Improve on simple LZ77 but only for high quality (TraceBackwards is // costly). if ((lz77_type_best == kLZ77Standard || lz77_type_best == kLZ77Box) && quality >= 25) { const VP8LHashChain* const hash_chain_tmp = (lz77_type_best == kLZ77Standard) ? hash_chain : &hash_chain_box; if (VP8LBackwardReferencesTraceBackwards(width, height, argb, *cache_bits, hash_chain_tmp, best, worst)) { double bit_cost_trace; VP8LHistogramCreate(histo, worst, *cache_bits); bit_cost_trace = VP8LHistogramEstimateBits(histo); if (bit_cost_trace < bit_cost_best) best = worst; } } BackwardReferences2DLocality(width, best); Error: VP8LHashChainClear(&hash_chain_box); VP8LFreeHistogram(histo); return best; } VP8LBackwardRefs* VP8LGetBackwardReferences( int width, int height, const uint32_t* const argb, int quality, int low_effort, int lz77_types_to_try, int* const cache_bits, const VP8LHashChain* const hash_chain, VP8LBackwardRefs* const refs_tmp1, VP8LBackwardRefs* const refs_tmp2) { if (low_effort) { return GetBackwardReferencesLowEffort(width, height, argb, cache_bits, hash_chain, refs_tmp1); } else { return GetBackwardReferences(width, height, argb, quality, lz77_types_to_try, cache_bits, hash_chain, refs_tmp1, refs_tmp2); } }
{ "pile_set_name": "Github" }
import React from 'react'; export const SURFACE_EVENTS = [ {prop: 'onClick', type: 'click'}, {prop: 'onKeyDown', type: 'keydown'}, {prop: 'onKeyPress', type: 'keypress'}, {prop: 'onKeyUp', type: 'keyup'}, {prop: 'onMouseDown', type: 'mousedown'}, {prop: 'onMouseMove', type: 'mousemove'}, {prop: 'onMouseOut', type: 'mouseout'}, {prop: 'onMouseOver', type: 'mouseover'}, {prop: 'onMouseUp', type: 'mouseup'}, {prop: 'onTouchCancel', type: 'touchcancel'}, {prop: 'onTouchEnd', type: 'touchend'}, {prop: 'onTouchMove', type: 'touchmove'}, {prop: 'onTouchStart', type: 'touchstart'} ]; export const SURFACE_PROPTYPES = { eventKey: React.PropTypes.any, onClick: React.PropTypes.func, onKeyDown: React.PropTypes.func, onKeyPress: React.PropTypes.func, onKeyUp: React.PropTypes.func, onMouseDown: React.PropTypes.func, onMouseMove: React.PropTypes.func, onMouseOut: React.PropTypes.func, onMouseOver: React.PropTypes.func, onMouseUp: React.PropTypes.func, onTouchCancel: React.PropTypes.func, onTouchEnd: React.PropTypes.func, onTouchMove: React.PropTypes.func, onTouchStart: React.PropTypes.func }; export default { SURFACE_EVENTS, SURFACE_PROPTYPES };
{ "pile_set_name": "Github" }
/** * @param {Object} $ - Global jQuery object * @param {Object} bolt - The Bolt module */ (function ($, bolt) { 'use strict'; /** * Geolocation field widget. * * @license http://opensource.org/licenses/mit-license.php MIT License * @author rarila * * @class fieldGeolocation * @memberOf jQuery.widget.bolt * @extends jQuery.widget.bolt.baseField */ $.widget('bolt.fieldGeolocation', $.bolt.baseField, /** @lends jQuery.widget.bolt.fieldGeolocation.prototype */ { /** * Default options. * * @property {string} latitude - Latitude * @property {string} longitude - Longitude */ options: { latitude: '', longitude: '' }, /** * The constructor of the geolocation field widget. * * @private */ _create: function () { var self = this, fieldset = self.element; /** * Refs to UI elements of this widget. * * @type {Object} * @name _ui * @memberOf jQuery.widget.bolt.fieldSlug.prototype * @private * * @property {Object} address - Input: Address lookup * @property {Object} matched - Readonly input: displaying matched address * @property {Object} mapholder - Element containing map * @property {Object} spinner - Spinner element * @property {Object} latitude - Input: Latitude * @property {Object} longitude - Input: Longitude * @property {Object} snap - Checkbox: Snap */ this._ui = { address: fieldset.find('.address'), matched: fieldset.find('.matched'), mapholder: fieldset.find('.mapholder'), spinner: fieldset.find('.mapholder i'), latitude: fieldset.find('.latitude'), longitude: fieldset.find('.longitude'), snap: fieldset.find('.snap') }; /** * Google map object. * * @type {Object|null} * @name _map * @memberOf jQuery.widget.bolt.fieldSlug.prototype * @private */ this._map = null; /** * Map marker. * * @type {Object|null} * @name _marker * @memberOf jQuery.widget.bolt.fieldSlug.prototype * @private */ this._marker = null; /** * Timeout resource for location resolving. * * @type {number} * @name _timeout * @memberOf jQuery.widget.bolt.fieldSlug.prototype * @private * * @fires "Bolt.GoogleMapsAPI.Load.Request" * @listens "Bolt.GoogleMapsAPI.Load.Done" * @listens "Bolt.GoogleMapsAPI.Load.Fail" */ this._timeout = 0; // Bind events. self._on({ 'click.expand': self._onExpand, 'click.compress': self._onExpand }); var onGmLoad = function () { bolt.events.off('Bolt.GoogleMapsAPI.Load.Done', onGmLoad); self._initGoogleMap(self.options.latitude, self.options.longitude); }; bolt.events.on('Bolt.GoogleMapsAPI.Load.Done', onGmLoad); bolt.events.on('Bolt.GoogleMapsAPI.Load.Fail', function () { self._ui.spinner.removeClass('fa-spinner fa-spin').addClass('fa-refresh').one('click', function () { self._ui.spinner.removeClass('fa-refresh').addClass('fa-spinner fa-spin'); bolt.events.fire('Bolt.GoogleMapsAPI.Load.Request'); }); }); // Request loading of Google Maps API. bolt.events.fire('Bolt.GoogleMapsAPI.Load.Request'); }, /** * Geocode address or location and display result. * * @private * @param {Object|undefined} search - Optional address or location search */ _geoCode: function (search) { var self = this; if (search) { (new google.maps.Geocoder()).geocode( search, function (results, status) { if (status === google.maps.GeocoderStatus.OK) { var location; if (search.latLng && !self._ui.snap.is(':checked')) { location = search.latLng; } else { location = results[0].geometry.location; } self._display(results[0].formatted_address, location.lat(), location.lng()); self._marker.setPosition(location); self._map.setCenter(location); } } ); } self._display(); }, /** * Displays address and location. * * @private * @param {string|undefined} address - Address to display * @param {string|undefined} latitude - Latitude to display * @param {string|undefined} longitude - Longitude to display */ _display: function (address, latitude, longitude) { this._ui.matched.val(address || ''); this._ui.latitude.val(latitude || ''); this._ui.longitude.val(longitude || ''); }, /** * Displays address and location. * * @private * @param {float} latitude - Initial latitude * @param {float} longitude - Initial longitude */ _initGoogleMap: function (latitude, longitude) { var self = this; var options = { zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP, center: new google.maps.LatLng(latitude, longitude), //disableDoubleClickZoom: true, //addMarker: false, // // Controls // panControl: false, // zoomControl: false, // zoomControlOptions: { // style: google.maps.ZoomControlStyle.DEFAULT // SMALL/LARGE/DEFAULT // position: google.maps.ControlPosition.LEFT_TOP // }, // mapTypeControl: false, // mapTypeControlOptions: { // style: google.maps.MapTypeControlStyle.DEFAULT // HORIZONTAL_BAR/DROPDOWN_MENU/DEFAULT // }, // scaleControl: false, //scaleControlOptions { //}, streetViewControl: false // overviewMapControl: false, // overviewMapControlOptions: { // } // rotateControl: false, // }; // Generate a new map and attach it to the mapholder. self._map = new google.maps.Map(self._ui.mapholder[0], options); // Add marker self._marker = new google.maps.Marker({ map: self._map, position: options.center, title: bolt.data('field.geolocation.marker'), draggable: true, animation: google.maps.Animation.DROP, icon: self.element.data('pin-icon') }); // Set coordinates when marker pin was moved. google.maps.event.addListener(self._marker, 'mouseup', function () { self._geoCode({latLng: self._marker.getPosition()}); }); // Update location when typed into address field. self._ui.address.on('propertychange input', function () { clearTimeout(self._timeout); self._timeout = setTimeout(function () { var address = self._ui.address.val(); self._geoCode(address.length > 2 ? {address: address} : undefined); }, 800); }); // Resize the map when it get's visible after tab change $('a[data-toggle="tab"]').on('shown.bs.tab', function () { if (self._ui.mapholder.closest('div.tab-pane').hasClass('active')) { google.maps.event.trigger(self._map, 'resize'); } }); }, /** * Expand/Compact button clicked. * * @private */ _onExpand: function () { var markerPos = this._marker.getPosition(); this._ui.mapholder.parent().toggleClass('expanded'); google.maps.event.trigger(this._map, 'resize'); this._map.setCenter(markerPos); } }); })(jQuery, Bolt);
{ "pile_set_name": "Github" }
{ "images": [ { "idiom": "universal" }, { "scale": "1x", "idiom": "universal" }, { "scale": "2x", "idiom": "universal" }, { "scale": "3x", "idiom": "universal" }, { "idiom": "iphone" }, { "scale": "1x", "idiom": "iphone" }, { "scale": "2x", "idiom": "iphone" }, { "subtype": "retina4", "scale": "2x", "idiom": "iphone" }, { "scale": "3x", "idiom": "iphone" }, { "idiom": "ipad" }, { "scale": "1x", "idiom": "ipad" }, { "scale": "2x", "idiom": "ipad" } ], "info": { "version": 1, "author": "xcode" } }
{ "pile_set_name": "Github" }
using System.Collections.Generic; using NexusForever.Shared.Network; using NexusForever.Shared.Network.Message; using NexusForever.WorldServer.Game.Housing.Static; namespace NexusForever.WorldServer.Network.Message.Model { [Message(GameMessageOpcode.ServerHousingProperties)] public class ServerHousingProperties : IWritable { public class Residence : IWritable { public ushort RealmId { get; set; } public ulong ResidenceId { get; set; } public ulong NeighbourhoodId { get; set; } public ulong CharacterIdOwner { get; set; } public ulong GuildIdOwner { get; set; } public uint RealmIdOwner{ get; set; } public uint Type { get; set; } public uint TileId { get; set; } public string Name { get; set; } public uint PropertyInfoId { get; set; } public uint ResidenceInfoId { get; set; } public uint WallpaperExterior { get; set; } public uint Entryway { get; set; } public uint Roof { get; set; } public uint Door { get; set; } public uint Music { get; set; } public uint Ground { get; set; } public uint Sky { get; set; } public ResidenceFlags Flags { get; set; } public uint ResourceSharing { get; set; } public uint GardenSharing { get; set; } public bool ResidenceDeleted { get; set; } public void Write(GamePacketWriter writer) { writer.Write(RealmId, 14u); writer.Write(ResidenceId); writer.Write(NeighbourhoodId); writer.Write(CharacterIdOwner); writer.Write(GuildIdOwner); writer.Write(1, 14u); writer.Write(TileId); writer.WriteStringWide(Name); writer.Write(PropertyInfoId); writer.Write(ResidenceInfoId); writer.Write(Roof); writer.Write(WallpaperExterior); writer.Write(Entryway); writer.Write(Door); writer.Write(Sky); writer.Write(Music); writer.Write(Ground); writer.Write(Flags, 32u); writer.Write(ResourceSharing); writer.Write(GardenSharing); writer.WriteBytes(new byte[64]); writer.Write(ResidenceDeleted); } } public List<Residence> Residences { get; } = new List<Residence>(); public void Write(GamePacketWriter writer) { writer.Write(Residences.Count); Residences.ForEach(r => r.Write(writer)); } } }
{ "pile_set_name": "Github" }
""" A sample usage of how ical categories can be used (here to group tasks related to the same project or events related to the same sale opportunity) """ project = None if brainObject is not None: real_context = brainObject else: real_context = context portal_type = real_context.getPortalType() if portal_type == 'Task': project = real_context.getSourceProjectValue() elif portal_type in context.getPortalEventTypeList(): project = real_context.getFollowUpValue() if project is not None: # we have to tweak here because not all object have references if hasattr(project, 'getReference'): return project.getReference() or project.getTitle() else: return project.getTitle() return ''
{ "pile_set_name": "Github" }
form=词 tags= 敛双蛾、冷雨立毡车, 离思上青枫。 想天阶辞辇, 长门分镜, 征骑西东。 应被婵娟早误, 谁遣出深宫。 鸾袖不堪绾, 前事成空。 独掩琵琶无语, 恨主恩太薄, 泪脸弹红。 又争如汉月, 深夜照帘栊。 草青青、年年归梦, 算北来、应自有征鸿。 还堪笑, 玉关何事, 不锁春风。
{ "pile_set_name": "Github" }
gcr.io/google_containers/managed-certificate-controller:v0.3.4
{ "pile_set_name": "Github" }
# # Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 only, as # published by the Free Software Foundation. # # This code is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # version 2 for more details (a copy is included in the LICENSE file that # accompanied this code). # # You should have received a copy of the GNU General Public License version # 2 along with this work; if not, write to the Free Software Foundation, # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. # # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA # or visit www.oracle.com if you need additional information or have any # questions. # # !include ../local.make AdlcOutDir=$(HOTSPOTBUILDSPACE)\$(Variant)\generated\adfiles AdditionalTargets=$(AdlcOutDir)\ad_$(Platform_arch_model).cpp $(AdlcOutDir)\dfa_$(Platform_arch_model).cpp !include $(HOTSPOTWORKSPACE)/make/windows/projectfiles/common/Makefile
{ "pile_set_name": "Github" }
package rand import ( "encoding/binary" "math/rand" "sync" "github.com/influxdata/influxdb/v2" ) var _ influxdb.IDGenerator = (*OrgBucketID)(nil) // OrgBucketID creates an id that does not have ascii // backslash, commas, or spaces. Used to create IDs for organizations // and buckets. // // It is implemented without those characters because orgbucket // pairs are placed in the old measurement field. Measurement // was interpreted as a string delimited with commas. Therefore, // to continue to use the underlying storage engine we need to // sanitize ids. // // Safe for concurrent use by multiple goroutines. type OrgBucketID struct { m sync.Mutex src *rand.Rand } // NewOrgBucketID creates an influxdb.IDGenerator that creates // random numbers seeded with seed. Ascii backslash, comma, // and space are manipulated by incrementing. // // Typically, seed with `time.Now().UnixNano()` func NewOrgBucketID(seed int64) *OrgBucketID { return &OrgBucketID{ src: rand.New(rand.NewSource(seed)), } } // Seed allows one to override the current seed. // Typically, this override is done for tests. func (r *OrgBucketID) Seed(seed int64) { r.m.Lock() r.src = rand.New(rand.NewSource(seed)) r.m.Unlock() } // ID generates an ID that does not have backslashes, commas, or spaces. func (r *OrgBucketID) ID() influxdb.ID { r.m.Lock() n := r.src.Uint64() r.m.Unlock() n = sanitize(n) return influxdb.ID(n) } func sanitize(n uint64) uint64 { b := make([]byte, 8) binary.BigEndian.PutUint64(b, n) for i := range b { switch b[i] { // these bytes must be remove here to prevent the need // to escape/unescape. See the models package for // additional detail. // \ , " " case 0x5C, 0x2C, 0x20: b[i] = b[i] + 1 } } return binary.BigEndian.Uint64(b) }
{ "pile_set_name": "Github" }
using System.Reflection; using Abp.Modules; namespace MultipleDbContextDemo { public class MultipleDbContextDemoCoreModule : AbpModule { public override void Initialize() { IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly()); } } }
{ "pile_set_name": "Github" }
require 'forwardable' require 'rss/rss' module RSS module Maker class Base extend Utils::InheritedReader OTHER_ELEMENTS = [] NEED_INITIALIZE_VARIABLES = [] class << self def other_elements inherited_array_reader("OTHER_ELEMENTS") end def need_initialize_variables inherited_array_reader("NEED_INITIALIZE_VARIABLES") end def inherited_base ::RSS::Maker::Base end def inherited(subclass) subclass.const_set("OTHER_ELEMENTS", []) subclass.const_set("NEED_INITIALIZE_VARIABLES", []) end def add_other_element(variable_name) self::OTHER_ELEMENTS << variable_name end def add_need_initialize_variable(variable_name, init_value="nil") self::NEED_INITIALIZE_VARIABLES << [variable_name, init_value] end def def_array_element(name, plural=nil, klass_name=nil) include Enumerable extend Forwardable plural ||= "#{name}s" klass_name ||= Utils.to_class_name(name) def_delegators("@#{plural}", :<<, :[], :[]=, :first, :last) def_delegators("@#{plural}", :push, :pop, :shift, :unshift) def_delegators("@#{plural}", :each, :size, :empty?, :clear) add_need_initialize_variable(plural, "[]") module_eval(<<-EOC, __FILE__, __LINE__ + 1) def new_#{name} #{name} = self.class::#{klass_name}.new(@maker) @#{plural} << #{name} if block_given? yield #{name} else #{name} end end alias new_child new_#{name} def to_feed(*args) @#{plural}.each do |#{name}| #{name}.to_feed(*args) end end def replace(elements) @#{plural}.replace(elements.to_a) end EOC end def def_classed_element_without_accessor(name, class_name=nil) class_name ||= Utils.to_class_name(name) add_other_element(name) add_need_initialize_variable(name, "make_#{name}") module_eval(<<-EOC, __FILE__, __LINE__ + 1) private def setup_#{name}(feed, current) @#{name}.to_feed(feed, current) end def make_#{name} self.class::#{class_name}.new(@maker) end EOC end def def_classed_element(name, class_name=nil, attribute_name=nil) def_classed_element_without_accessor(name, class_name) if attribute_name module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name} if block_given? yield(@#{name}) else @#{name}.#{attribute_name} end end def #{name}=(new_value) @#{name}.#{attribute_name} = new_value end EOC else attr_reader name end end def def_classed_elements(name, attribute, plural_class_name=nil, plural_name=nil, new_name=nil) plural_name ||= "#{name}s" new_name ||= name def_classed_element(plural_name, plural_class_name) local_variable_name = "_#{name}" new_value_variable_name = "new_value" additional_setup_code = nil if block_given? additional_setup_code = yield(local_variable_name, new_value_variable_name) end module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name} #{local_variable_name} = #{plural_name}.first #{local_variable_name} ? #{local_variable_name}.#{attribute} : nil end def #{name}=(#{new_value_variable_name}) #{local_variable_name} = #{plural_name}.first || #{plural_name}.new_#{new_name} #{additional_setup_code} #{local_variable_name}.#{attribute} = #{new_value_variable_name} end EOC end def def_other_element(name) attr_accessor name def_other_element_without_accessor(name) end def def_other_element_without_accessor(name) add_need_initialize_variable(name) add_other_element(name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def setup_#{name}(feed, current) if !@#{name}.nil? and current.respond_to?(:#{name}=) current.#{name} = @#{name} end end EOC end def def_csv_element(name, type=nil) def_other_element_without_accessor(name) attr_reader(name) converter = "" if type == :integer converter = "{|v| Integer(v)}" end module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(value) @#{name} = Utils::CSV.parse(value)#{converter} end EOC end end attr_reader :maker def initialize(maker) @maker = maker @default_values_are_set = false initialize_variables end def have_required_values? not_set_required_variables.empty? end def variable_is_set? variables.any? {|var| not __send__(var).nil?} end private def initialize_variables self.class.need_initialize_variables.each do |variable_name, init_value| instance_eval("@#{variable_name} = #{init_value}", __FILE__, __LINE__) end end def setup_other_elements(feed, current=nil) current ||= current_element(feed) self.class.other_elements.each do |element| __send__("setup_#{element}", feed, current) end end def current_element(feed) feed end def set_default_values(&block) return yield if @default_values_are_set begin @default_values_are_set = true _set_default_values(&block) ensure @default_values_are_set = false end end def _set_default_values(&block) yield end def setup_values(target) set = false if have_required_values? variables.each do |var| setter = "#{var}=" if target.respond_to?(setter) value = __send__(var) if value target.__send__(setter, value) set = true end end end end set end def set_parent(target, parent) target.parent = parent if target.class.need_parent? end def variables self.class.need_initialize_variables.find_all do |name, init| "nil" == init end.collect do |name, init| name end end def not_set_required_variables required_variable_names.find_all do |var| __send__(var).nil? end end def required_variables_are_set? required_variable_names.each do |var| return false if __send__(var).nil? end true end end module AtomPersonConstructBase def self.append_features(klass) super klass.class_eval(<<-EOC, __FILE__, __LINE__ + 1) %w(name uri email).each do |element| attr_accessor element add_need_initialize_variable(element) end EOC end end module AtomTextConstructBase module EnsureXMLContent class << self def included(base) super base.class_eval do %w(type content xml_content).each do |element| attr_reader element attr_writer element if element != "xml_content" add_need_initialize_variable(element) end alias_method(:xhtml, :xml_content) end end end def ensure_xml_content(content) xhtml_uri = ::RSS::Atom::XHTML_URI unless content.is_a?(RSS::XML::Element) and ["div", xhtml_uri] == [content.name, content.uri] children = content children = [children] unless content.is_a?(Array) children = set_xhtml_uri_as_default_uri(children) content = RSS::XML::Element.new("div", nil, xhtml_uri, {"xmlns" => xhtml_uri}, children) end content end def xml_content=(content) @xml_content = ensure_xml_content(content) end def xhtml=(content) self.xml_content = content end private def set_xhtml_uri_as_default_uri(children) children.collect do |child| if child.is_a?(RSS::XML::Element) and child.prefix.nil? and child.uri.nil? RSS::XML::Element.new(child.name, nil, ::RSS::Atom::XHTML_URI, child.attributes.dup, set_xhtml_uri_as_default_uri(child.children)) else child end end end end def self.append_features(klass) super klass.class_eval do include EnsureXMLContent end end end module SetupDefaultDate private def _set_default_values(&block) keep = { :date => date, :dc_dates => dc_dates.to_a.dup, } _date = date if _date and !dc_dates.any? {|dc_date| dc_date.value == _date} dc_date = self.class::DublinCoreDates::DublinCoreDate.new(self) dc_date.value = _date.dup dc_dates.unshift(dc_date) end self.date ||= self.dc_date super(&block) ensure date = keep[:date] dc_dates.replace(keep[:dc_dates]) end end class RSSBase < Base class << self def make(version, &block) new(version).make(&block) end end %w(xml_stylesheets channel image items textinput).each do |element| attr_reader element add_need_initialize_variable(element, "make_#{element}") module_eval(<<-EOC, __FILE__, __LINE__) private def setup_#{element}(feed) @#{element}.to_feed(feed) end def make_#{element} self.class::#{Utils.to_class_name(element)}.new(self) end EOC end attr_reader :feed_version alias_method(:rss_version, :feed_version) attr_accessor :version, :encoding, :standalone def initialize(feed_version) super(self) @feed_type = nil @feed_subtype = nil @feed_version = feed_version @version = "1.0" @encoding = "UTF-8" @standalone = nil end def make if block_given? yield(self) to_feed else nil end end def to_feed feed = make_feed setup_xml_stylesheets(feed) setup_elements(feed) setup_other_elements(feed) if feed.valid? feed else nil end end private remove_method :make_xml_stylesheets def make_xml_stylesheets XMLStyleSheets.new(self) end end class XMLStyleSheets < Base def_array_element("xml_stylesheet", nil, "XMLStyleSheet") class XMLStyleSheet < Base ::RSS::XMLStyleSheet::ATTRIBUTES.each do |attribute| attr_accessor attribute add_need_initialize_variable(attribute) end def to_feed(feed) xss = ::RSS::XMLStyleSheet.new guess_type_if_need(xss) set = setup_values(xss) if set feed.xml_stylesheets << xss end end private def guess_type_if_need(xss) if @type.nil? xss.href = @href @type = xss.type end end def required_variable_names %w(href type) end end end class ChannelBase < Base include SetupDefaultDate %w(cloud categories skipDays skipHours).each do |name| def_classed_element(name) end %w(generator copyright description title).each do |name| def_classed_element(name, nil, "content") end [ ["link", "href", Proc.new {|target,| "#{target}.href = 'self'"}], ["author", "name"], ["contributor", "name"], ].each do |name, attribute, additional_setup_maker| def_classed_elements(name, attribute, &additional_setup_maker) end %w(id about language managingEditor webMaster rating docs date lastBuildDate ttl).each do |element| attr_accessor element add_need_initialize_variable(element) end def pubDate date end def pubDate=(date) self.date = date end def updated date end def updated=(date) self.date = date end alias_method(:rights, :copyright) alias_method(:rights=, :copyright=) alias_method(:subtitle, :description) alias_method(:subtitle=, :description=) def icon image_favicon.about end def icon=(url) image_favicon.about = url end def logo maker.image.url end def logo=(url) maker.image.url = url end class SkipDaysBase < Base def_array_element("day") class DayBase < Base %w(content).each do |element| attr_accessor element add_need_initialize_variable(element) end end end class SkipHoursBase < Base def_array_element("hour") class HourBase < Base %w(content).each do |element| attr_accessor element add_need_initialize_variable(element) end end end class CloudBase < Base %w(domain port path registerProcedure protocol).each do |element| attr_accessor element add_need_initialize_variable(element) end end class CategoriesBase < Base def_array_element("category", "categories") class CategoryBase < Base %w(domain content label).each do |element| attr_accessor element add_need_initialize_variable(element) end alias_method(:term, :domain) alias_method(:term=, :domain=) alias_method(:scheme, :content) alias_method(:scheme=, :content=) end end class LinksBase < Base def_array_element("link") class LinkBase < Base %w(href rel type hreflang title length).each do |element| attr_accessor element add_need_initialize_variable(element) end end end class AuthorsBase < Base def_array_element("author") class AuthorBase < Base include AtomPersonConstructBase end end class ContributorsBase < Base def_array_element("contributor") class ContributorBase < Base include AtomPersonConstructBase end end class GeneratorBase < Base %w(uri version content).each do |element| attr_accessor element add_need_initialize_variable(element) end end class CopyrightBase < Base include AtomTextConstructBase end class DescriptionBase < Base include AtomTextConstructBase end class TitleBase < Base include AtomTextConstructBase end end class ImageBase < Base %w(title url width height description).each do |element| attr_accessor element add_need_initialize_variable(element) end def link @maker.channel.link end end class ItemsBase < Base def_array_element("item") attr_accessor :do_sort, :max_size def initialize(maker) super @do_sort = false @max_size = -1 end def normalize if @max_size >= 0 sort_if_need[0...@max_size] else sort_if_need[0..@max_size] end end private def sort_if_need if @do_sort.respond_to?(:call) @items.sort do |x, y| @do_sort.call(x, y) end elsif @do_sort @items.sort do |x, y| y <=> x end else @items end end class ItemBase < Base include SetupDefaultDate %w(guid enclosure source categories content).each do |name| def_classed_element(name) end %w(rights description title).each do |name| def_classed_element(name, nil, "content") end [ ["author", "name"], ["link", "href", Proc.new {|target,| "#{target}.href = 'alternate'"}], ["contributor", "name"], ].each do |name, attribute| def_classed_elements(name, attribute) end %w(date comments id published).each do |element| attr_accessor element add_need_initialize_variable(element) end def pubDate date end def pubDate=(date) self.date = date end def updated date end def updated=(date) self.date = date end alias_method(:summary, :description) alias_method(:summary=, :description=) def <=>(other) _date = date || dc_date _other_date = other.date || other.dc_date if _date and _other_date _date <=> _other_date elsif _date 1 elsif _other_date -1 else 0 end end class GuidBase < Base %w(isPermaLink content).each do |element| attr_accessor element add_need_initialize_variable(element) end end class EnclosureBase < Base %w(url length type).each do |element| attr_accessor element add_need_initialize_variable(element) end end class SourceBase < Base %w(authors categories contributors generator icon logo rights subtitle title).each do |name| def_classed_element(name) end [ ["link", "href"], ].each do |name, attribute| def_classed_elements(name, attribute) end %w(id content date).each do |element| attr_accessor element add_need_initialize_variable(element) end alias_method(:url, :link) alias_method(:url=, :link=) def updated date end def updated=(date) self.date = date end private AuthorsBase = ChannelBase::AuthorsBase CategoriesBase = ChannelBase::CategoriesBase ContributorsBase = ChannelBase::ContributorsBase GeneratorBase = ChannelBase::GeneratorBase class IconBase < Base %w(url).each do |element| attr_accessor element add_need_initialize_variable(element) end end LinksBase = ChannelBase::LinksBase class LogoBase < Base %w(uri).each do |element| attr_accessor element add_need_initialize_variable(element) end end class RightsBase < Base include AtomTextConstructBase end class SubtitleBase < Base include AtomTextConstructBase end class TitleBase < Base include AtomTextConstructBase end end CategoriesBase = ChannelBase::CategoriesBase AuthorsBase = ChannelBase::AuthorsBase LinksBase = ChannelBase::LinksBase ContributorsBase = ChannelBase::ContributorsBase class RightsBase < Base include AtomTextConstructBase end class DescriptionBase < Base include AtomTextConstructBase end class ContentBase < Base include AtomTextConstructBase::EnsureXMLContent %w(src).each do |element| attr_accessor(element) add_need_initialize_variable(element) end def xml_content=(content) content = ensure_xml_content(content) if inline_xhtml? @xml_content = content end alias_method(:xml, :xml_content) alias_method(:xml=, :xml_content=) def inline_text? [nil, "text", "html"].include?(@type) end def inline_html? @type == "html" end def inline_xhtml? @type == "xhtml" end def inline_other? !out_of_line? and ![nil, "text", "html", "xhtml"].include?(@type) end def inline_other_text? return false if @type.nil? or out_of_line? /\Atext\//i.match(@type) ? true : false end def inline_other_xml? return false if @type.nil? or out_of_line? /[\+\/]xml\z/i.match(@type) ? true : false end def inline_other_base64? return false if @type.nil? or out_of_line? @type.include?("/") and !inline_other_text? and !inline_other_xml? end def out_of_line? not @src.nil? and @content.nil? end end class TitleBase < Base include AtomTextConstructBase end end end class TextinputBase < Base %w(title description name link).each do |element| attr_accessor element add_need_initialize_variable(element) end end end end
{ "pile_set_name": "Github" }
10 dir 169 http://google-app-engine-samples.googlecode.com/svn/trunk/simple-ajax-chat/css http://google-app-engine-samples.googlecode.com/svn 2008-11-05T15:45:16.673245Z 71 pamela.fox 99225164-8649-0410-878b-2ba91e509939 main.css file 2013-04-30T03:29:32.000000Z c941d31c8d46225d84a02baf755e8bb7 2008-11-05T15:45:16.673245Z 71 pamela.fox 2490
{ "pile_set_name": "Github" }
version https://git-lfs.github.com/spec/v1 oid sha256:726433138e7a987d63f5a1e175b30569231441b09814a47a03776a2acdfd435d size 2228
{ "pile_set_name": "Github" }
#pragma once #include "game_cl_teamdeathmatch.h" class CUIGameAHunt; class game_cl_ArtefactHunt :public game_cl_TeamDeathmatch { friend class CUIMessagesWindow; CUIGameAHunt* m_game_ui; shared_str m_Eff_Af_Spawn; shared_str m_Eff_Af_Disappear; typedef game_cl_TeamDeathmatch inherited; protected: // ref_sound pMessageSounds[8]; protected: virtual const shared_str GetBaseCostSect () {return "artefacthunt_base_cost";} virtual void TranslateGameMessage (u32 msg, NET_Packet& P); virtual void shedule_Update (u32 dt); virtual BOOL CanCallBuyMenu (); virtual bool CanBeReady (); // virtual void OnObjectEnterTeamBase (u16 player_id, u8 zone_team_id); // virtual void OnObjectLeaveTeamBase (u16 player_id, u8 zone_team_id); virtual void UpdateMapLocations (); virtual bool NeedToSendReady_Spectator (int key, game_PlayerState* ps); virtual void LoadSndMessages (); virtual void OnBuySpawnMenu_Ok (); public: u8 artefactsNum;//ah u16 artefactBearerID;//ah,ZoneMap u16 old_artefactBearerID; u8 teamInPossession;//ah,ZoneMap u8 old_teamInPossession; u16 artefactID; u16 old_artefactID; s32 iReinforcementTime; s32 dReinforcementTime; int m_iSpawn_Cost; public : game_cl_ArtefactHunt (); virtual ~game_cl_ArtefactHunt (); virtual void Init (); virtual CUIGameCustom* createGameUI (); virtual void net_import_state (NET_Packet& P); virtual void GetMapEntities(xr_vector<SZoneMapEntityData>& dst); virtual char* getTeamSection (int Team); virtual bool PlayerCanSprint (CActor* pActor); virtual void SetScore (); virtual void OnSellItemsFromRuck (); virtual void OnSpawn (CObject* pObj); virtual void OnDestroy (CObject* pObj); virtual void SendPickUpEvent (u16 ID_who, u16 ID_what); };
{ "pile_set_name": "Github" }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Specialized; using System.Drawing; using System.Drawing.Imaging; using System.Reflection; using System.IO; using System.Web; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenMetaverse.Imaging; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; using Caps = OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Capabilities.Handlers { public class GetTextureHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IAssetService m_assetService; public const string DefaultFormat = "x-j2c"; public GetTextureHandler(IAssetService assService) { m_assetService = assService; } public Hashtable Handle(Hashtable request) { Hashtable ret = new Hashtable(); ret["int_response_code"] = (int)System.Net.HttpStatusCode.NotFound; ret["content_type"] = "text/plain"; ret["int_bytes"] = 0; string textureStr = (string)request["texture_id"]; string format = (string)request["format"]; //m_log.DebugFormat("[GETTEXTURE]: called {0}", textureStr); if (m_assetService == null) { m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service"); } UUID textureID; if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID)) { // m_log.DebugFormat("[GETTEXTURE]: Received request for texture id {0}", textureID); string[] formats; if (!string.IsNullOrEmpty(format)) { formats = new string[1] { format.ToLower() }; } else { formats = new string[1] { DefaultFormat }; // default if (((Hashtable)request["headers"])["Accept"] != null) formats = WebUtil.GetPreferredImageTypes((string)((Hashtable)request["headers"])["Accept"]); if (formats.Length == 0) formats = new string[1] { DefaultFormat }; // default } // OK, we have an array with preferred formats, possibly with only one entry bool foundtexture = false; foreach (string f in formats) { foundtexture = FetchTexture(request, ret, textureID, f); if (foundtexture) break; } if (!foundtexture) { ret["int_response_code"] = 404; ret["error_status_text"] = "not found"; ret["str_response_string"] = "not found"; ret["content_type"] = "text/plain"; ret["int_bytes"] = 0; } } else { m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + (string)request["uri"]); } // m_log.DebugFormat( // "[GETTEXTURE]: For texture {0} sending back response {1}, data length {2}", // textureID, httpResponse.StatusCode, httpResponse.ContentLength); return ret; } /// <summary> /// /// </summary> /// <param name="httpRequest"></param> /// <param name="httpResponse"></param> /// <param name="textureID"></param> /// <param name="format"></param> /// <returns>False for "caller try another codec"; true otherwise</returns> private bool FetchTexture(Hashtable request, Hashtable response, UUID textureID, string format) { // m_log.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format); AssetBase texture; string fullID = textureID.ToString(); if (format != DefaultFormat) fullID = fullID + "-" + format; // try the cache texture = m_assetService.GetCached(fullID); if (texture == null) { //m_log.DebugFormat("[GETTEXTURE]: texture was not in the cache"); // Fetch locally or remotely. Misses return a 404 texture = m_assetService.Get(textureID.ToString()); if (texture != null) { if (texture.Type != (sbyte)AssetType.Texture) return true; if (format == DefaultFormat) { WriteTextureData(request, response, texture, format); return true; } else { AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, (sbyte)AssetType.Texture, texture.Metadata.CreatorID); newTexture.Data = ConvertTextureData(texture, format); if (newTexture.Data.Length == 0) return false; // !!! Caller try another codec, please! newTexture.Flags = AssetFlags.Collectable; newTexture.Temporary = true; newTexture.Local = true; m_assetService.Store(newTexture); WriteTextureData(request, response, newTexture, format); return true; } } } else // it was on the cache { //m_log.DebugFormat("[GETTEXTURE]: texture was in the cache"); WriteTextureData(request, response, texture, format); return true; } //response = new Hashtable(); //WriteTextureData(request,response,null,format); // not found //m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found"); return false; } private void WriteTextureData(Hashtable request, Hashtable response, AssetBase texture, string format) { Hashtable headers = new Hashtable(); response["headers"] = headers; string range = String.Empty; if (((Hashtable)request["headers"])["range"] != null) range = (string)((Hashtable)request["headers"])["range"]; else if (((Hashtable)request["headers"])["Range"] != null) range = (string)((Hashtable)request["headers"])["Range"]; if (!String.IsNullOrEmpty(range)) // JP2's only { // Range request int start, end; if (Util.TryParseHttpRange(range, out start, out end)) { // Before clamping start make sure we can satisfy it in order to avoid // sending back the last byte instead of an error status if (start >= texture.Data.Length) { // m_log.DebugFormat( // "[GETTEXTURE]: Client requested range for texture {0} starting at {1} but texture has end of {2}", // texture.ID, start, texture.Data.Length); // Stricly speaking, as per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html, we should be sending back // Requested Range Not Satisfiable (416) here. However, it appears that at least recent implementations // of the Linden Lab viewer (3.2.1 and 3.3.4 and probably earlier), a viewer that has previously // received a very small texture may attempt to fetch bytes from the server past the // range of data that it received originally. Whether this happens appears to depend on whether // the viewer's estimation of how large a request it needs to make for certain discard levels // (http://wiki.secondlife.com/wiki/Image_System#Discard_Level_and_Mip_Mapping), chiefly discard // level 2. If this estimate is greater than the total texture size, returning a RequestedRangeNotSatisfiable // here will cause the viewer to treat the texture as bad and never display the full resolution // However, if we return PartialContent (or OK) instead, the viewer will display that resolution. // response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable; // viewers don't seem to handle RequestedRangeNotSatisfiable and keep retrying with same parameters response["int_response_code"] = (int)System.Net.HttpStatusCode.NotFound; } else { // Handle the case where no second range value was given. This is equivalent to requesting // the rest of the entity. if (end == -1) end = int.MaxValue; end = Utils.Clamp(end, 0, texture.Data.Length - 1); start = Utils.Clamp(start, 0, end); int len = end - start + 1; // m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID); response["content-type"] = texture.Metadata.ContentType; response["int_response_code"] = (int)System.Net.HttpStatusCode.PartialContent; headers["Content-Range"] = String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length); byte[] d = new byte[len]; Array.Copy(texture.Data, start, d, 0, len); response["bin_response_data"] = d; response["int_bytes"] = len; } } else { m_log.Warn("[GETTEXTURE]: Malformed Range header: " + range); response["int_response_code"] = (int)System.Net.HttpStatusCode.BadRequest; } } else // JP2's or other formats { // Full content request response["int_response_code"] = (int)System.Net.HttpStatusCode.OK; if (format == DefaultFormat) response["content_type"] = texture.Metadata.ContentType; else response["content_type"] = "image/" + format; response["bin_response_data"] = texture.Data; response["int_bytes"] = texture.Data.Length; // response.Body.Write(texture.Data, 0, texture.Data.Length); } // if (response.StatusCode < 200 || response.StatusCode > 299) // m_log.WarnFormat( // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})", // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); // else // m_log.DebugFormat( // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})", // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); } private byte[] ConvertTextureData(AssetBase texture, string format) { m_log.DebugFormat("[GETTEXTURE]: Converting texture {0} to {1}", texture.ID, format); byte[] data = new byte[0]; MemoryStream imgstream = new MemoryStream(); Bitmap mTexture = null; ManagedImage managedImage = null; Image image = null; try { // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data // Decode image to System.Drawing.Image if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image) && image != null) { // Save to bitmap mTexture = new Bitmap(image); using(EncoderParameters myEncoderParameters = new EncoderParameters()) { myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality,95L); // Save bitmap to stream ImageCodecInfo codec = GetEncoderInfo("image/" + format); if (codec != null) { mTexture.Save(imgstream, codec, myEncoderParameters); // Write the stream to a byte array for output data = imgstream.ToArray(); } else m_log.WarnFormat("[GETTEXTURE]: No such codec {0}", format); } } } catch (Exception e) { m_log.WarnFormat("[GETTEXTURE]: Unable to convert texture {0} to {1}: {2}", texture.ID, format, e.Message); } finally { // Reclaim memory, these are unmanaged resources // If we encountered an exception, one or more of these will be null if (mTexture != null) mTexture.Dispose(); if (image != null) image.Dispose(); if(managedImage != null) managedImage.Clear(); if (imgstream != null) imgstream.Dispose(); } return data; } // From msdn private static ImageCodecInfo GetEncoderInfo(String mimeType) { ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (int j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; } } }
{ "pile_set_name": "Github" }
/* Copyright 2010-2016 MongoDB 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. */ using System; namespace MongoDB.Bson { /// <summary> /// Represents the binary data subtype of a BsonBinaryData. /// </summary> #if NET45 [Serializable] #endif public enum BsonBinarySubType { /// <summary> /// Binary data. /// </summary> Binary = 0x00, /// <summary> /// A function. /// </summary> Function = 0x01, /// <summary> /// Obsolete binary data subtype (use Binary instead). /// </summary> [Obsolete("Use Binary instead")] OldBinary = 0x02, /// <summary> /// A UUID in a driver dependent legacy byte order. /// </summary> UuidLegacy = 0x03, /// <summary> /// A UUID in standard network byte order. /// </summary> UuidStandard = 0x04, /// <summary> /// An MD5 hash. /// </summary> MD5 = 0x05, /// <summary> /// User defined binary data. /// </summary> UserDefined = 0x80 } }
{ "pile_set_name": "Github" }
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_HIDAPI /* Handle rumble on a separate thread so it doesn't block the application */ /* Advanced API */ int SDL_HIDAPI_LockRumble(void); SDL_bool SDL_HIDAPI_GetPendingRumbleLocked(SDL_HIDAPI_Device *device, Uint8 **data, int **size, int *maximum_size); int SDL_HIDAPI_SendRumbleAndUnlock(SDL_HIDAPI_Device *device, const Uint8 *data, int size); void SDL_HIDAPI_UnlockRumble(void); /* Simple API, will replace any pending rumble with the new data */ int SDL_HIDAPI_SendRumble(SDL_HIDAPI_Device *device, const Uint8 *data, int size); void SDL_HIDAPI_QuitRumble(void); #endif /* SDL_JOYSTICK_HIDAPI */ /* vi: set ts=4 sw=4 expandtab: */
{ "pile_set_name": "Github" }
import buildBalanceTotal from './operations' import fromRequest from '../mocks/total/operations/received.json' import expectedResult from '../mocks/total/operations/expected.json' describe('balance total details', () => { it('should build the correct total balance', () => { expect(buildBalanceTotal(fromRequest)).toEqual(expectedResult) }) })
{ "pile_set_name": "Github" }
--- weight: 21 title: 'HNPWA with React' github-title: 'taehwanno/hnpwa-react' library: 'React' libraries: - name: 'React' - name: 'React Router' - name: 'Redux' - name: 'Immutable.js' module-bundling: 'Webpack' service-worker: 'Application Shell + data caching and offline google analytics with Workbox' perfomance-patterns: 'Server-side data pre-fetching, preload/prefetch resources' server-side-rendering: 'Yes' api: 'Node-hnapi (unofficial)' hosting: 'Firebase' authors: - name: 'Taehwan, No' lighthouse: '91/100' interactive-em: '5.2s' interactive-faster-3g: '4.3s' lighthouse-link: https://www.webpagetest.org/lighthouse.php?test=171029_69_655c5b28865ee880316d1af49358b1a0&run=1 wpt-em-link: https://www.webpagetest.org/result/171029_6Y_04df9e72abb38731d412b0eeb7be1317/ wpt-faster-3g-link: https://www.webpagetest.org/result/171029_69_655c5b28865ee880316d1af49358b1a0/ image: /assets/images/hnpwa-react.png app-link: https://hnpwa-react.firebaseapp.com/ github-link: https://github.com/taehwanno/hnpwa-react framework-link: https://reactjs.org/ ---
{ "pile_set_name": "Github" }
[package] name = "topgrade" description = "Upgrade all the things" categories = ["os"] keywords = ["upgrade", "update"] license-file = "LICENSE" repository = "https://github.com/r-darwish/topgrade" version = "5.7.1" authors = ["Roey Darwish Dror <[email protected]>"] exclude = ["doc/screenshot.gif"] edition = "2018" readme = "README.md" [dependencies] directories = "3.0.1" serde = { version = "1.0.92", features = ["derive"] } toml = "0.5.1" which_crate = { version = "4.0.0", package = "which" } shellexpand = "2.0.0" structopt = "0.3.0" log = "0.4.6" walkdir = "2.3.1" console = "0.10.0" lazy_static = "1.4.0" chrono = "0.4.6" pretty_env_logger = "0.4.0" glob = "0.3.0" strum = { version = "0.19.2", features = ["derive"] } thiserror = "1.0.9" anyhow = "1.0.25" tempfile = "3.1.0" cfg-if = "0.1.10" tokio = { version = "0.2", features = ["rt-core", "process"] } futures = "0.3" regex = "1.3.9" [target.'cfg(target_os = "macos")'.dependencies] notify-rust = "4.0.0" [target.'cfg(unix)'.dependencies] nix = "0.18.0" self_update_crate = { version = "0.19.0", optional = true, package = "self_update", features = ["archive-tar", "compression-flate2"] } [target.'cfg(windows)'.dependencies] self_update_crate = { version = "0.19.0", optional = true, package = "self_update", features = ["archive-zip", "compression-zip-deflate"] } winapi = "0.3.9" [target.'cfg(target_os = "linux")'.dependencies] rust-ini = "0.15.0" openssl-probe = { version = "0.1.2", optional = true } [profile.release] lto = true [features] default = [] self-update = ["self_update_crate", "openssl-probe"]
{ "pile_set_name": "Github" }
{ "ebu_KE": { "datetime": { "abbr_day_names": [ "Kma", "Tat", "Ine", "Tan", "Arm", "Maa", "NMM" ], "abbr_month_names": [ "Mbe", "Kai", "Kat", "Kan", "Gat", "Gan", "Mug", "Knn", "Ken", "Iku", "Imw", "Igi" ], "day_names": [ "Kiumia", "Njumatatu", "Njumaine", "Njumatano", "Aramithi", "Njumaa", "NJumamothii" ], "format": "%d %B %Y", "month_names": [ "Mweri wa mbere", "Mweri wa kaĩri", "Mweri wa kathatũ", "Mweri wa kana", "Mweri wa gatano", "Mweri wa gatantatũ", "Mweri wa mũgwanja", "Mweri wa kanana", "Mweri wa kenda", "Mweri wa ikũmi", "Mweri wa ikũmi na ũmwe", "Mweri wa ikũmi na Kaĩrĩ" ] } } }
{ "pile_set_name": "Github" }
<% title @moment.name %> <div class="gridRowSpaceBetween"> <%= react_component('StoryDate', props: { date: TimeAgo.created_or_edited(@moment) }) %> <% if [email protected]? %> <%= react_component('StoryDraft', props: { draft: [email protected]? ? t('draft') : nil }) %> <% end %> </div> <div class="smallMarginTop"> <%= react_component('StoryCategories', props: { categories: @moment.category_names_and_slugs }) %> <%= react_component('StoryMoods', props: { moods: @moment.mood_names_and_slugs }) %> </div> <% if @moment.why.present? %> <div class="smallMarginTop"> <div class="label"><%= label_tag t('moments.form.why') %></div> <%= sanitize(@moment.why) %> </div> <% end %> <% if @moment.fix.present? %> <div class="smallMarginTop"> <div class="label"><%= label_tag t('moments.form.fix') %></div> <%= sanitize(@moment.fix) %> </div> <% end %> <% if @moment.strategies.count > 0 %> <div class="smallMarginTop"> <div class="label"><%= label_tag t('moments.show.strategies') %></div> <ul> <% @moment.strategies.each do |item| %> <li><%= link_to item.name, item %></li> <% end %> </ul> </div> <% end %> <% if @moment.resource_recommendations? && @resources_tags.present? %> <div class="smallMarginTop"> <div class="label"><%= label_tag t('moments.show.resources') %></div> <ul> <% @resources.take(3).each do |item| %> <li><%= link_to item['name'], item['link'] %></li> <%end %> <li><%= link_to "#{t('load_more')}...", "/resources?#{@resources_tags}" %></li> </ul> </div> <% end %> <% if @show_crisis_prevention %> <%= react_component('CrisisPrevention') %> <% end %> <% if @moment.owned_by?(current_user) && @moment.shared? %> <div class="smallMarginTop"> <%= react_component('Form', props: secret_share_props(@moment)) %> </div> <% end %> <% if @moment.owned_by?(current_user) %> <div class="gridItemBoxDark smallMarginTop"> <div class="gridRowSpaceBetween"> <div class="gridRowSpaceBetween"> <div class="smallMarginRight"><%= t('common.actions.plural') %>:</div> <%= react_component('StoryActions', props: { dark: true, actions: { edit: { link: edit_moment_path(@moment), name: t('common.actions.edit') }, delete: { name: t('common.actions.delete'), link: url_for(@moment), dataMethod: 'delete', dataConfirm: t('common.actions.confirm') }, viewers: get_viewer_list(@moment.viewers, nil) } }) %> </div> <% if @moment.shared? %> <%= button_to t('moments.secret_share.cancel_secret_share'), secret_share_path(id: @moment.id), { method: :delete, class: 'buttonGhostXS' } %> <% elsif @moment.published? %> <%= button_to t('moments.secret_share.singular'), secret_shares_path(moment: @moment.id), { class: 'buttonGhostXS' } %> <% end %> </div> </div> <% end %> <% if user_signed_in? && @moment.published? && @moment.comment %> <%= render partial: '/shared/comments', locals: { commentable: @moment } %> <% end %>
{ "pile_set_name": "Github" }
// Copyright 2017 The go-ethereum Authors // This file is part of go-ethereum. // // go-ethereum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // go-ethereum is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>. package main import ( "crypto/ecdsa" "fmt" "io/ioutil" "os" "path/filepath" "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/crypto" "github.com/pborman/uuid" "gopkg.in/urfave/cli.v1" ) type outputGenerate struct { Address string AddressEIP55 string } var commandGenerate = cli.Command{ Name: "generate", Usage: "generate new keyfile", ArgsUsage: "[ <keyfile> ]", Description: ` Generate a new keyfile. If you want to encrypt an existing private key, it can be specified by setting --privatekey with the location of the file containing the private key. `, Flags: []cli.Flag{ passphraseFlag, jsonFlag, cli.StringFlag{ Name: "privatekey", Usage: "file containing a raw private key to encrypt", }, cli.BoolFlag{ Name: "lightkdf", Usage: "use less secure scrypt parameters", }, }, Action: func(ctx *cli.Context) error { // Check if keyfile path given and make sure it doesn't already exist. keyfilepath := ctx.Args().First() if keyfilepath == "" { keyfilepath = defaultKeyfileName } if _, err := os.Stat(keyfilepath); err == nil { utils.Fatalf("Keyfile already exists at %s.", keyfilepath) } else if !os.IsNotExist(err) { utils.Fatalf("Error checking if keyfile exists: %v", err) } var privateKey *ecdsa.PrivateKey var err error if file := ctx.String("privatekey"); file != "" { // Load private key from file. privateKey, err = crypto.LoadECDSA(file) if err != nil { utils.Fatalf("Can't load private key: %v", err) } } else { // If not loaded, generate random. privateKey, err = crypto.GenerateKey() if err != nil { utils.Fatalf("Failed to generate random private key: %v", err) } } // Create the keyfile object with a random UUID. id := uuid.NewRandom() key := &keystore.Key{ Id: id, Address: crypto.PubkeyToAddress(privateKey.PublicKey), PrivateKey: privateKey, } // Encrypt key with passphrase. passphrase := getPassphrase(ctx, true) scryptN, scryptP := keystore.StandardScryptN, keystore.StandardScryptP if ctx.Bool("lightkdf") { scryptN, scryptP = keystore.LightScryptN, keystore.LightScryptP } keyjson, err := keystore.EncryptKey(key, passphrase, scryptN, scryptP) if err != nil { utils.Fatalf("Error encrypting key: %v", err) } // Store the file to disk. if err := os.MkdirAll(filepath.Dir(keyfilepath), 0700); err != nil { utils.Fatalf("Could not create directory %s", filepath.Dir(keyfilepath)) } if err := ioutil.WriteFile(keyfilepath, keyjson, 0600); err != nil { utils.Fatalf("Failed to write keyfile to %s: %v", keyfilepath, err) } // Output some information. out := outputGenerate{ Address: key.Address.Hex(), } if ctx.Bool(jsonFlag.Name) { mustPrintJSON(out) } else { fmt.Println("Address:", out.Address) } return nil }, }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_10) on Thu Jan 14 19:23:45 PST 2010 --> <TITLE> ElementHandler (INFLIB v3.0 Public API at 2010-01-14 19:23:22) </TITLE> <META NAME="date" CONTENT="2010-01-14"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ElementHandler (INFLIB v3.0 Public API at 2010-01-14 19:23:22)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../edu/ucla/belief/io/CPTInfo.ReadableWritableTable.html" title="interface in edu.ucla.belief.io"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../edu/ucla/belief/io/Estimate.html" title="interface in edu.ucla.belief.io"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?edu/ucla/belief/io/ElementHandler.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ElementHandler.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> edu.ucla.belief.io</FONT> <BR> Interface ElementHandler</H2> <DL> <DT><B>All Known Implementing Classes:</B> <DD><A HREF="../../../../edu/ucla/belief/io/InstantiationXmlizer.RootCheckHandler.html" title="class in edu.ucla.belief.io">InstantiationXmlizer.RootCheckHandler</A>, <A HREF="../../../../edu/ucla/belief/io/InstantiationXmlizer.ValidRootHandler.html" title="class in edu.ucla.belief.io">InstantiationXmlizer.ValidRootHandler</A>, <A HREF="../../../../edu/ucla/belief/decision/XmlElementHandler.html" title="class in edu.ucla.belief.decision">XmlElementHandler</A></DD> </DL> <HR> <DL> <DT><PRE>public interface <B>ElementHandler</B></DL> </PRE> <P> Moved from SamIam package edu.ucla.belief.ui.util since 020105 <P> <P> <DL> <DT><B>Since:</B></DT> <DD>051903</DD> <DT><B>Author:</B></DT> <DD>Keith Cascio</DD> </DL> <HR> <P> <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../edu/ucla/belief/io/ElementHandler.html#endElement(java.lang.String, java.lang.String, java.lang.String)">endElement</A></B>(<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;uri, <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;localName, <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;qName)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../edu/ucla/belief/io/ElementHandler.html#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)">startElement</A></B>(<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;uri, <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;localName, <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;qName, <A HREF="http://java.sun.com/javase/6/docs/api/org/xml/sax/Attributes.html?is-external=true" title="class or interface in org.xml.sax">Attributes</A>&nbsp;attributes)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)"><!-- --></A><H3> startElement</H3> <PRE> void <B>startElement</B>(<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;uri, <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;localName, <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;qName, <A HREF="http://java.sun.com/javase/6/docs/api/org/xml/sax/Attributes.html?is-external=true" title="class or interface in org.xml.sax">Attributes</A>&nbsp;attributes) throws <A HREF="http://java.sun.com/javase/6/docs/api/org/xml/sax/SAXException.html?is-external=true" title="class or interface in org.xml.sax">SAXException</A></PRE> <DL> <DD><DL> <DT><B>Throws:</B> <DD><CODE><A HREF="http://java.sun.com/javase/6/docs/api/org/xml/sax/SAXException.html?is-external=true" title="class or interface in org.xml.sax">SAXException</A></CODE></DL> </DD> </DL> <HR> <A NAME="endElement(java.lang.String, java.lang.String, java.lang.String)"><!-- --></A><H3> endElement</H3> <PRE> void <B>endElement</B>(<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;uri, <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;localName, <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;qName) throws <A HREF="http://java.sun.com/javase/6/docs/api/org/xml/sax/SAXException.html?is-external=true" title="class or interface in org.xml.sax">SAXException</A></PRE> <DL> <DD><DL> <DT><B>Throws:</B> <DD><CODE><A HREF="http://java.sun.com/javase/6/docs/api/org/xml/sax/SAXException.html?is-external=true" title="class or interface in org.xml.sax">SAXException</A></CODE></DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../edu/ucla/belief/io/CPTInfo.ReadableWritableTable.html" title="interface in edu.ucla.belief.io"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../edu/ucla/belief/io/Estimate.html" title="interface in edu.ucla.belief.io"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?edu/ucla/belief/io/ElementHandler.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ElementHandler.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright 2010 <a href=http://reasoning.cs.ucla.edu>UCLA Automated Reasoning Group</a> </BODY> </HTML>
{ "pile_set_name": "Github" }
# Copyright (C) 1991-1999, 2000-2007, 2009, 2010 Free Software Foundation, Inc. # This file is part of the GNU C Library. # The GNU C Library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # The GNU C Library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public # License along with the GNU C Library; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA # 02111-1307 USA. # # Sub-makefile for POSIX portion of the library. # subdir := posix headers := sys/utsname.h sys/times.h sys/wait.h sys/types.h unistd.h \ glob.h regex.h wordexp.h fnmatch.h getopt.h \ bits/types.h bits/typesizes.h bits/pthreadtypes.h \ bits/posix1_lim.h bits/posix2_lim.h bits/posix_opt.h \ bits/local_lim.h tar.h bits/utsname.h bits/confname.h \ bits/waitflags.h bits/waitstatus.h sys/unistd.h sched.h \ bits/sched.h re_comp.h wait.h bits/environments.h cpio.h \ sys/sysmacros.h spawn.h bits/unistd.h distribute := confstr.h TESTS TESTS2C.sed testcases.h \ PTESTS PTESTS2C.sed ptestcases.h \ globtest.c globtest.sh wordexp-tst.sh annexc.c fnmatch_loop.c \ spawn_int.h tst-getconf.sh regcomp.c regexec.c regex_internal.c \ regex_internal.h fork.h rxspencer/tests rxspencer/COPYRIGHT \ PCRE.tests BOOST.tests routines := \ uname \ times \ wait waitpid wait3 wait4 waitid \ alarm sleep pause nanosleep \ fork vfork _exit \ execve fexecve execv execle execl execvp execlp execvpe \ getpid getppid \ getuid geteuid getgid getegid getgroups setuid setgid group_member \ getpgid setpgid getpgrp bsd-getpgrp setpgrp getsid setsid \ getresuid getresgid setresuid setresgid \ getlogin getlogin_r setlogin \ pathconf sysconf fpathconf \ glob glob64 fnmatch regex \ confstr \ getopt getopt1 getopt_init \ sched_setp sched_getp sched_sets sched_gets sched_yield sched_primax \ sched_primin sched_rr_gi sched_getaffinity sched_setaffinity \ getaddrinfo gai_strerror wordexp \ pread pwrite pread64 pwrite64 \ spawn_faction_init spawn_faction_destroy spawn_faction_addclose \ spawn_faction_addopen spawn_faction_adddup2 \ spawnattr_init spawnattr_destroy \ spawnattr_getdefault spawnattr_setdefault \ spawnattr_getflags spawnattr_setflags \ spawnattr_getpgroup spawnattr_setpgroup spawn spawnp spawni \ spawnattr_getsigmask spawnattr_getschedpolicy spawnattr_getschedparam \ spawnattr_setsigmask spawnattr_setschedpolicy spawnattr_setschedparam \ posix_madvise \ get_child_max sched_cpucount sched_cpualloc sched_cpufree include ../Makeconfig aux := init-posix environ tests := tstgetopt testfnm runtests runptests \ tst-preadwrite tst-preadwrite64 test-vfork regexbug1 \ tst-getlogin tst-mmap tst-getaddrinfo tst-truncate \ tst-truncate64 tst-fork tst-fnmatch tst-regexloc tst-dir \ tst-chmod bug-regex1 bug-regex2 bug-regex3 bug-regex4 \ tst-gnuglob tst-regex bug-regex5 bug-regex6 bug-regex7 \ bug-regex8 bug-regex9 bug-regex10 bug-regex11 bug-regex12 \ bug-regex13 bug-regex14 bug-regex15 bug-regex16 \ bug-regex17 bug-regex18 bug-regex19 bug-regex20 \ bug-regex21 bug-regex22 bug-regex23 bug-regex24 \ bug-regex25 bug-regex26 bug-regex27 bug-regex28 \ bug-regex29 bug-regex30 bug-regex31 \ tst-nice tst-nanosleep tst-regex2 \ transbug tst-rxspencer tst-pcre tst-boost \ bug-ga1 tst-vfork1 tst-vfork2 tst-vfork3 tst-waitid \ tst-getaddrinfo2 bug-glob1 bug-glob2 bug-glob3 tst-sysconf \ tst-execvp1 tst-execvp2 tst-execlp1 tst-execlp2 \ tst-execv1 tst-execv2 tst-execl1 tst-execl2 \ tst-execve1 tst-execve2 tst-execle1 tst-execle2 \ tst-execvp3 tst-execvp4 tst-rfc3484 tst-rfc3484-2 \ tst-rfc3484-3 \ tst-getaddrinfo3 tst-fnmatch2 tst-cpucount tst-cpuset \ bug-getopt1 bug-getopt2 bug-getopt3 bug-getopt4 \ bug-getopt5 xtests := bug-ga2 ifeq (yes,$(build-shared)) test-srcs := globtest tests += wordexp-test tst-exec tst-spawn endif others := getconf install-bin := getconf install-others-programs := $(inst_libexecdir)/getconf before-compile := testcases.h ptestcases.h # So they get cleaned up. generated := $(addprefix wordexp-test-result, 1 2 3 4 5 6 7 8 9 10) \ annexc annexc.out wordexp-tst.out bug-regex2-mem \ bug-regex2.mtrace bug-regex14-mem bug-regex14.mtrace \ bug-regex21-mem bug-regex21.mtrace \ bug-regex31-mem bug-regex31.mtrace \ tst-rxspencer-mem tst-rxspencer.mtrace tst-getconf.out \ tst-pcre-mem tst-pcre.mtrace tst-boost-mem tst-boost.mtrace \ bug-ga2.mtrace bug-ga2-mem bug-glob2.mtrace bug-glob2-mem \ tst-vfork3-mem tst-vfork3.mtrace getconf.speclist \ tst-fnmatch-mem tst-fnmatch.mtrace include ../Rules ifeq (yes,$(build-static-nss)) # We need it for "make check" only. We can skip them if they haven't # been built yet during "make". otherlibs += $(wildcard $(nssobjdir)/libnss_files.a \ $(resolvobjdir)/libnss_dns.a \ $(resolvobjdir)/libresolv.a) endif ifeq (no,$(cross-compiling)) # globtest and wordexp-test currently only works with shared libraries ifeq (yes,$(build-shared)) tests: $(objpfx)globtest.out $(objpfx)wordexp-tst.out $(objpfx)globtest.out: globtest.sh $(objpfx)globtest $(SHELL) -e globtest.sh $(common-objpfx) $(elf-objpfx) \ $(rtld-installed-name) $(objpfx)wordexp-tst.out: wordexp-tst.sh $(objpfx)wordexp-test $(SHELL) -e wordexp-tst.sh $(common-objpfx) $(elf-objpfx) \ $(rtld-installed-name) endif endif # If we will use the generic uname implementation, we must figure out what # it will say by examining the system, and write the results in config-name.h. uname.c: $(objpfx)config-name.h $(objpfx)config-name.h: $(..)scripts/config-uname.sh $(common-objpfx)config.make $< '$(config-os)' '$(config-release)' \ '$(config-machine)-$(config-vendor)' > [email protected] mv -f [email protected] $@ CFLAGS-regex.c = -Wno-strict-prototypes CFLAGS-getaddrinfo.c = -DRESOLVER -fexceptions -DUSE_NSCD CFLAGS-pread.c = -fexceptions -fasynchronous-unwind-tables CFLAGS-pread64.c = -fexceptions -fasynchronous-unwind-tables CFLAGS-pwrite.c = -fexceptions -fasynchronous-unwind-tables CFLAGS-pwrite64.c = -fexceptions -fasynchronous-unwind-tables CFLAGS-sleep.c = -fexceptions CFLAGS-wait.c = -fexceptions -fasynchronous-unwind-tables CFLAGS-waitid.c = -fexceptions -fasynchronous-unwind-tables CFLAGS-waitpid.c = -fexceptions -fasynchronous-unwind-tables CFLAGS-getopt.c = -fexceptions CFLAGS-wordexp.c = -fexceptions CFLAGS-wordexp.os = -fomit-frame-pointer CFLAGS-sysconf.c = -fexceptions -DGETCONF_DIR='"$(libexecdir)/getconf"' CFLAGS-pathconf.c = -fexceptions CFLAGS-fpathconf.c = -fexceptions CFLAGS-spawn.c = -fexceptions CFLAGS-spawn.os = -fomit-frame-pointer CFLAGS-spawnp.c = -fexceptions CFLAGS-spawnp.os = -fomit-frame-pointer CFLAGS-spawni.c = -fexceptions CFLAGS-spawni.os = -fomit-frame-pointer CFLAGS-pause.c = -fexceptions CFLAGS-glob.c = $(uses-callbacks) -fexceptions CFLAGS-glob64.c = $(uses-callbacks) -fexceptions CFLAGS-getconf.c = -DGETCONF_DIR='"$(libexecdir)/getconf"' CFLAGS-execve.os = -fomit-frame-pointer CFLAGS-fexecve.os = -fomit-frame-pointer CFLAGS-execv.os = -fomit-frame-pointer CFLAGS-execle.os = -fomit-frame-pointer CFLAGS-execl.os = -fomit-frame-pointer CFLAGS-execvp.os = -fomit-frame-pointer CFLAGS-execlp.os = -fomit-frame-pointer tstgetopt-ARGS = -a -b -cfoobar --required foobar --optional=bazbug \ --none random --col --color --colour tst-exec-ARGS = -- $(built-program-cmd) tst-spawn-ARGS = -- $(built-program-cmd) tst-dir-ARGS = `pwd` `cd $(common-objdir)/$(subdir); pwd` `cd $(common-objdir); pwd` $(objpfx)tst-dir tst-chmod-ARGS = $(objdir) tst-vfork3-ARGS = --test-dir=$(objpfx) tst-fnmatch-ENV = LOCPATH=$(common-objpfx)localedata tst-regexloc-ENV = LOCPATH=$(common-objpfx)localedata bug-regex1-ENV = LOCPATH=$(common-objpfx)localedata tst-regex-ENV = LOCPATH=$(common-objpfx)localedata tst-regex2-ENV = LOCPATH=$(common-objpfx)localedata bug-regex5-ENV = LOCPATH=$(common-objpfx)localedata bug-regex6-ENV = LOCPATH=$(common-objpfx)localedata bug-regex17-ENV = LOCPATH=$(common-objpfx)localedata bug-regex18-ENV = LOCPATH=$(common-objpfx)localedata bug-regex19-ENV = LOCPATH=$(common-objpfx)localedata bug-regex20-ENV = LOCPATH=$(common-objpfx)localedata bug-regex22-ENV = LOCPATH=$(common-objpfx)localedata bug-regex23-ENV = LOCPATH=$(common-objpfx)localedata bug-regex25-ENV = LOCPATH=$(common-objpfx)localedata bug-regex26-ENV = LOCPATH=$(common-objpfx)localedata bug-regex30-ENV = LOCPATH=$(common-objpfx)localedata tst-rxspencer-ARGS = --utf8 rxspencer/tests tst-rxspencer-ENV = LOCPATH=$(common-objpfx)localedata tst-pcre-ARGS = PCRE.tests tst-boost-ARGS = BOOST.tests bug-glob1-ARGS = "$(objpfx)" tst-execvp3-ARGS = --test-dir=$(objpfx) testcases.h: TESTS TESTS2C.sed sed -f TESTS2C.sed < $< > $@T mv -f $@T $@ ifeq ($(with-cvs),yes) test ! -d CVS || cvs $(CVSOPTS) commit -mRegenerated $@ endif ptestcases.h: PTESTS PTESTS2C.sed sed -f PTESTS2C.sed < $< > $@T mv -f $@T $@ ifeq ($(with-cvs),yes) test ! -d CVS || cvs $(CVSOPTS) commit -mRegenerated $@ endif # Run a test on the header files we use. # XXX Please note that for now we ignore the result of this test. tests: $(objpfx)annexc.out ifeq (no,$(cross-compiling)) tests: $(objpfx)bug-regex2-mem $(objpfx)bug-regex14-mem \ $(objpfx)bug-regex21-mem $(objpfx)bug-regex31-mem $(objpfx)tst-rxspencer-mem\ $(objpfx)tst-pcre-mem $(objpfx)tst-boost-mem $(objpfx)tst-getconf.out \ $(objpfx)bug-glob2-mem $(objpfx)tst-vfork3-mem $(objpfx)tst-fnmatch-mem xtests: $(objpfx)bug-ga2-mem endif $(objpfx)annexc.out: $(objpfx)annexc -$(dir $<)$(notdir $<) '$(CC)' \ '$(patsubst %,-I../%,$(sorted-subdirs)) -I../include $(+sysdep-includes) $(sysincludes) -I..' > $@ annexc-CFLAGS = -O $(objpfx)annexc: annexc.c $(native-compile) tst-fnmatch-ENV += MALLOC_TRACE=$(objpfx)tst-fnmatch.mtrace $(objpfx)tst-fnmatch-mem: $(objpfx)tst-fnmatch.out $(common-objpfx)malloc/mtrace $(objpfx)tst-fnmatch.mtrace > $@ bug-regex2-ENV = MALLOC_TRACE=$(objpfx)bug-regex2.mtrace $(objpfx)bug-regex2-mem: $(objpfx)bug-regex2.out $(common-objpfx)malloc/mtrace $(objpfx)bug-regex2.mtrace > $@ bug-regex14-ENV = MALLOC_TRACE=$(objpfx)bug-regex14.mtrace $(objpfx)bug-regex14-mem: $(objpfx)bug-regex14.out $(common-objpfx)malloc/mtrace $(objpfx)bug-regex14.mtrace > $@ bug-regex21-ENV = MALLOC_TRACE=$(objpfx)bug-regex21.mtrace $(objpfx)bug-regex21-mem: $(objpfx)bug-regex21.out $(common-objpfx)malloc/mtrace $(objpfx)bug-regex21.mtrace > $@ bug-regex31-ENV = MALLOC_TRACE=$(objpfx)bug-regex31.mtrace $(objpfx)bug-regex31-mem: $(objpfx)bug-regex31.out $(common-objpfx)malloc/mtrace $(objpfx)bug-regex31.mtrace > $@ tst-vfork3-ENV = MALLOC_TRACE=$(objpfx)tst-vfork3.mtrace $(objpfx)tst-vfork3-mem: $(objpfx)tst-vfork3.out $(common-objpfx)malloc/mtrace $(objpfx)tst-vfork3.mtrace > $@ # tst-rxspencer.mtrace is generated only when run without --utf8 # option, since otherwise the file has almost 100M and takes very long # time to process. $(objpfx)tst-rxspencer-mem: $(objpfx)tst-rxspencer.out MALLOC_TRACE=$(objpfx)tst-rxspencer.mtrace $(tst-rxspencer-ENV) \ $(run-program-prefix) $(objpfx)tst-rxspencer rxspencer/tests \ > /dev/null $(common-objpfx)malloc/mtrace $(objpfx)tst-rxspencer.mtrace > $@ tst-pcre-ENV = MALLOC_TRACE=$(objpfx)tst-pcre.mtrace $(objpfx)tst-pcre-mem: $(objpfx)tst-pcre.out $(common-objpfx)malloc/mtrace $(objpfx)tst-pcre.mtrace > $@ tst-boost-ENV = MALLOC_TRACE=$(objpfx)tst-boost.mtrace $(objpfx)tst-boost-mem: $(objpfx)tst-boost.out $(common-objpfx)malloc/mtrace $(objpfx)tst-boost.mtrace > $@ $(objpfx)tst-getconf.out: tst-getconf.sh $(objpfx)getconf $(SHELL) -e $< $(common-objpfx) $(elf-objpfx) $(rtld-installed-name) ifeq (yes,$(build-shared)) $(objpfx)tst-regex: $(common-objpfx)rt/librt.so $(objpfx)tst-regex2: $(common-objpfx)rt/librt.so else $(objpfx)tst-regex: $(common-objpfx)rt/librt.a $(objpfx)tst-regex2: $(common-objpfx)rt/librt.a endif $(objpfx)bug-ga2-mem: $(objpfx)bug-ga2.out $(common-objpfx)malloc/mtrace $(objpfx)bug-ga2.mtrace > $@ bug-ga2-ENV = MALLOC_TRACE=$(objpfx)bug-ga2.mtrace bug-glob2-ENV = MALLOC_TRACE=$(objpfx)bug-glob2.mtrace $(objpfx)bug-glob2-mem: $(objpfx)bug-glob2.out $(common-objpfx)malloc/mtrace $(objpfx)bug-glob2.mtrace > $@ $(inst_libexecdir)/getconf: $(inst_bindir)/getconf \ $(objpfx)getconf.speclist FORCE $(addprefix $(..)./scripts/mkinstalldirs ,\ $(filter-out $(wildcard $@),$@)) while read spec; do \ ln -f $< $@/$$spec.new || $(INSTALL_PROGRAM) $< $@/$$spec.new; \ mv -f $@/$$spec.new $@/$$spec; \ done < $(objpfx)getconf.speclist $(objpfx)getconf.speclist: $(objpfx)getconf ifeq (no,$(cross-compiling)) LC_ALL=C GETCONF_DIR=/dev/null \ $(run-program-prefix) $< _POSIX_V7_WIDTH_RESTRICTED_ENVS > [email protected] LC_ALL=C GETCONF_DIR=/dev/null \ $(run-program-prefix) $< _POSIX_V6_WIDTH_RESTRICTED_ENVS >> [email protected] LC_ALL=C GETCONF_DIR=/dev/null \ $(run-program-prefix) $< _XBS5_WIDTH_RESTRICTED_ENVS >> [email protected] else > [email protected] endif mv -f [email protected] $@
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>cluster.eval.eval_node_extra &#8212; tensormsa 1.0 documentation</title> <link rel="stylesheet" href="../../../_static/alabaster.css" type="text/css" /> <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../../../', VERSION: '1.0', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../../../_static/jquery.js"></script> <script type="text/javascript" src="../../../_static/underscore.js"></script> <script type="text/javascript" src="../../../_static/doctools.js"></script> <link rel="top" title="tensormsa 1.0 documentation" href="../../../index.html" /> <link rel="up" title="Module code" href="../../index.html" /> <link rel="stylesheet" href="../../../_static/custom.css" type="text/css" /> <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" /> </head> <body role="document"> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <h1>Source code for cluster.eval.eval_node_extra</h1><div class="highlight"><pre> <span></span><span class="kn">from</span> <span class="nn">cluster.eval.eval_node</span> <span class="k">import</span> <span class="n">EvalNode</span> <span class="kn">from</span> <span class="nn">cluster.common.train_summary_info</span> <span class="k">import</span> <span class="n">TrainSummaryInfo</span> <span class="kn">from</span> <span class="nn">master.workflow.evalconf.workflow_evalconf</span> <span class="k">import</span> <span class="n">WorkFlowEvalConfig</span> <span class="kn">from</span> <span class="nn">master</span> <span class="k">import</span> <span class="n">serializers</span> <span class="kn">import</span> <span class="nn">logging</span> <div class="viewcode-block" id="EvalNodeExtra"><a class="viewcode-back" href="../../../cluster.eval.html#cluster.eval.eval_node_extra.EvalNodeExtra">[docs]</a><span class="k">class</span> <span class="nc">EvalNodeExtra</span><span class="p">(</span><span class="n">EvalNode</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;</span> <span class="sd"> &quot;&quot;&quot;</span> <div class="viewcode-block" id="EvalNodeExtra.run"><a class="viewcode-back" href="../../../cluster.eval.html#cluster.eval.eval_node_extra.EvalNodeExtra.run">[docs]</a> <span class="k">def</span> <span class="nf">run</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">conf_data</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;</span> <span class="sd"> executed on cluster run</span> <span class="sd"> :param conf_data:</span> <span class="sd"> :return:</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">try</span><span class="p">:</span> <span class="c1"># get related nodes</span> <span class="n">net_node</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_prev_node</span><span class="p">(</span><span class="n">grp</span><span class="o">=</span><span class="s1">&#39;netconf&#39;</span><span class="p">)</span> <span class="n">data_node</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_prev_node</span><span class="p">(</span><span class="n">grp</span><span class="o">=</span><span class="s1">&#39;preprocess&#39;</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">_init_node_parm</span><span class="p">(</span><span class="n">conf_data</span><span class="p">[</span><span class="s1">&#39;node_id&#39;</span><span class="p">])</span> <span class="c1"># set result info cls</span> <span class="n">result</span> <span class="o">=</span> <span class="n">TrainSummaryInfo</span><span class="p">(</span><span class="nb">type</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">eval_result_type</span><span class="p">)</span> <span class="n">result</span><span class="o">.</span><span class="n">set_nn_wf_ver_id</span><span class="p">(</span><span class="n">conf_data</span><span class="p">[</span><span class="s1">&#39;wf_ver&#39;</span><span class="p">])</span> <span class="n">result</span><span class="o">.</span><span class="n">set_nn_id</span><span class="p">(</span><span class="n">conf_data</span><span class="p">[</span><span class="s1">&#39;nn_id&#39;</span><span class="p">])</span> <span class="c1"># run eval for each network</span> <span class="n">result</span> <span class="o">=</span> <span class="n">net_node</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">eval</span><span class="p">(</span><span class="n">conf_data</span><span class="p">[</span><span class="s1">&#39;node_id&#39;</span><span class="p">],</span> <span class="n">conf_data</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">data_node</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">result</span><span class="o">=</span><span class="n">result</span><span class="p">)</span> <span class="c1"># set parms for db store</span> <span class="n">input_data</span> <span class="o">=</span> <span class="n">TrainSummaryInfo</span><span class="o">.</span><span class="n">save_result_info</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span> <span class="n">input_data</span><span class="p">[</span><span class="s1">&#39;accuracy&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">result</span><span class="o">.</span><span class="n">get_accuracy</span><span class="p">()</span> <span class="k">return</span> <span class="n">input_data</span> <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span> <span class="n">logging</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="n">e</span><span class="p">)</span> <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="n">e</span><span class="p">)</span></div> <span class="k">def</span> <span class="nf">_init_node_parm</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">node_id</span><span class="p">):</span> <span class="n">netconf</span> <span class="o">=</span> <span class="n">WorkFlowEvalConfig</span><span class="p">(</span><span class="n">node_id</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">eval_result_type</span> <span class="o">=</span> <span class="n">netconf</span><span class="o">.</span><span class="n">get_eval_type</span><span class="p">()</span> <span class="k">def</span> <span class="nf">_set_progress_state</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">pass</span></div> </pre></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"><div class="relations"> <h3>Related Topics</h3> <ul> <li><a href="../../../index.html">Documentation overview</a><ul> <li><a href="../../index.html">Module code</a><ul> </ul></li> </ul></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="../../../search.html" method="get"> <div><input type="text" name="q" /></div> <div><input type="submit" value="Go" /></div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer"> &copy;2017, seungwookim. | Powered by <a href="http://sphinx-doc.org/">Sphinx 1.4.6</a> &amp; <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.9</a> </div> </body> </html>
{ "pile_set_name": "Github" }
<script> $(document).ready(function() { var mail_provider_settings_form_class = '.mail-provider-mailerlite-settings-form'; $(mail_provider_settings_form_class).on('change paste', 'input, select, textarea', function(){ $.post(mw.settings.api_url + 'save_mail_provider', $(mail_provider_settings_form_class).serialize(), function() { mw.notification.success('Settings are saved.'); }); }); $('.mail-provider-test-api-mailerlite').click(function() { $.post(mw.settings.api_url + 'save_mail_provider', $(mail_provider_settings_form_class).serialize()); mw.notification.warning('Testing...'); $.post(mw.settings.api_url + 'test_mail_provider', $(mail_provider_settings_form_class).serialize(), function(data) { if (data === '1') { mw.notification.success('Sucessfull connecting.'); } else { mw.notification.error('Wrong mail provider settings.'); } }); }); }); </script> <form class="mail-provider-mailerlite-settings-form" method="post"> <input type="hidden" name="mail_provider_name" value="mailerlite" /> <?php foreach (get_mailerlite_api_fields() as $field): ?> <div class="demobox"> <label class="mw-ui-label"><?php echo $field['title']; ?></label> <input type="text" value="<?php echo $field['value']; ?>" name="<?php echo $field['name']; ?>" class="mw-ui-field w100 mw_option_field"> </div> <br /> <?php endforeach; ?> <div class="demobox"> <button type="button" class="mw-ui-btn mw-ui-btn-info mail-provider-test-api-mailerlite">Test Api</button> </div> </form>
{ "pile_set_name": "Github" }
--- title: Chipcon 8051 --- <h1>Chipcon Application</h1> <p>This application allows for the debugging of Chipcon radios with embedded 8051 cores, such as the CC2430 and CC2530. The protocol is SPI-like, but with a bi-directional data line. </p> <a href="http://www.flickr.com/photos/travisgoodspeed/3611512761/" title="GoodFET Chipcon pinout by Travis Goodspeed, on Flickr"> <img src="http://farm4.static.flickr.com/3369/3611512761_61d030e6c1.jpg" width="500" height="375" alt="GoodFET Chipcon pinout" /></a> <h2>Clients</h2> <p><a href="/clients/goodfetcc/">chipcon.cc</a> is an actively maintained client application.</p> <h2>Development</h2> <p>Prior to any transactions, the SETUP (0x10) verb should be sent to the Chipcon application to properly set the I/O pin directions. After that, the START (0x20) and STOP (0x21) verbs may be used to enter and exit the debugger. </p> <p>The Chipcon protocol is similar to SPI, but with the difference that a single data line is used. Rather than exchanging register values, the transfer is one-way. Use the WRITE (0x01) instruction only for debugging commands which do not result in a reply. READ (0x00) will write its data to the target, then accept a return byte in reply.</p> <h2>Verbs</h2> <p>While standard verbs are supported on this platform, they are inadequate for full debugging. Verbs 0x80 to 0x8F are debugging primitives, while verbs 0x90 to 0x9F are used for more complicated macro commands.</p> <table border="1"> <tr><th>Hex</th><th>#define</th><th>Description</th></tr> <tr><td>0x00</td><td>READ</td><td>Write any data, return 1-byte reply.</td></tr> <tr><td>0x01</td><td>WRITE</td><td>Write data.</td></tr> <tr><td>0x02</td><td>PEEK</td><td>Read from IRAM.</td></tr> <tr><td>0x03</td><td>POKE</td><td>Write to IRAM.</td></tr> <tr><td>0x10</td><td>SETUP</td><td>Configure I/O pins.</td></tr> <tr><td>0x20</td><td>START</td><td>Start a transaction.</td></tr> <tr><td>0x21</td><td>STOP</td><td>Stop a transaction.</td></tr> <!-- <tr><td>0x7E</td><td>NOK</td><td>No Operation</td></tr> <tr><td>0x7F</td><td>OK</td><td>No Operation</td></tr> --> <!-- Raw debugging commands. --> <tr><td>0x80</td><td>CC_CHIP_ERASE</td><td></td></tr> <tr><td>0x81</td><td>CC_WR_CONFIG</td><td></td></tr> <tr><td>0x82</td><td>CC_RD_CONFIG</td><td></td></tr> <tr><td>0x83</td><td>CC_GET_PC</td><td></td></tr> <tr><td>0x84</td><td>CC_READ_STATUS</td><td></td></tr> <tr><td>0x85</td><td>CC_SET_HW_BRKPNT</td><td></td></tr> <tr><td>0x86</td><td>CC_HALT</td><td></td></tr> <tr><td>0x87</td><td>CC_RESUME</td><td></td></tr> <tr><td>0x88</td><td>CC_DEBUG_INSTR</td><td></td></tr> <tr><td>0x89</td><td>CC_STEP_INSTR</td><td></td></tr> <tr><td>0x8A</td><td>CC_STEP_REPLACE</td><td></td></tr> <tr><td>0x8B</td><td>CC_GET_CHIP_ID</td><td></td></tr> <!--Higher level, make use of raw commands. --> <tr><td>0x90</td><td>CC_READ_CODE_MEMORY</td><td></td></tr> <tr><td>0x91</td><td>CC_READ_XDATA_MEMORY</td><td></td></tr> <tr><td>0x92</td><td>CC_WRITE_XDATA_MEMORY</td><td></td></tr> <tr><td>0x93</td><td>CC_SET_PC</td><td></td></tr> <tr><td>0x94</td><td>CC_CLOCK_INIT</td><td></td></tr> <tr><td>0x95</td><td>CC_WRITE_FLASH_PAGE</td><td></td></tr> <tr><td>0x96</td><td>CC_READ_FLASH_PAGE</td><td></td></tr> <tr><td>0x97</td><td>CC_MASS_ERASE_FLASH</td><td></td></tr> <tr><td>0x98</td><td>CC_PROGRAM_FLASH</td><td>Copy 2kB to Flash.</td></tr> <tr><td>0x99</td><td>CC_WIPEFLASHBUFFER</td><td>Wipe 2kB buffer to 0xFF.</td></tr> <tr><td>0x9A</td><td>CC_LOCKCHIP</td><td>Set security bits.</td></tr> </table> <h2>Thanks</h2> <p>Thanks, and a beer, are due to <a href="http://www.pkuhar.com">Peter Kuhar</a>, both for authoring the first open source Chipcon debugger and for the neighborly contribution of hardware.</p>
{ "pile_set_name": "Github" }
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> </PropertyGroup> <ItemGroup> </ItemGroup> <ItemGroup> <ProjectReference Include="..\FSharpTestA1\FSharpTestA1.fsproj" /> <ProjectReference Include="..\FSharpTestA2\FSharpTestA2.fsproj" /> <ProjectReference Include="..\FSharpTestA3\FSharpTestA3.fsproj" /> <ProjectReference Include="..\FSharpTestA4\FSharpTestA4.fsproj" /> <ProjectReference Include="..\FSharpTestA5\FSharpTestA5.fsproj" /> <ProjectReference Include="..\FSharpTestA6\FSharpTestA6.fsproj" /> <ProjectReference Include="..\FSharpTestA7\FSharpTestA7.fsproj" /> <ProjectReference Include="..\FSharpTestA8\FSharpTestA8.fsproj" /> <ProjectReference Include="..\FSharpTestA9\FSharpTestA9.fsproj" /> <ProjectReference Include="..\FSharpTestA10\FSharpTestA10.fsproj" /> <ProjectReference Include="..\FSharpTestA11\FSharpTestA11.fsproj" /> <ProjectReference Include="..\FSharpTestA12\FSharpTestA12.fsproj" /> <ProjectReference Include="..\FSharpTestA13\FSharpTestA13.fsproj" /> <ProjectReference Include="..\FSharpTestA14\FSharpTestA14.fsproj" /> <ProjectReference Include="..\FSharpTestA15\FSharpTestA15.fsproj" /> <ProjectReference Include="..\FSharpTestA16\FSharpTestA16.fsproj" /> <ProjectReference Include="..\FSharpTestA17\FSharpTestA17.fsproj" /> <ProjectReference Include="..\FSharpTestA18\FSharpTestA18.fsproj" /> <ProjectReference Include="..\FSharpTestA19\FSharpTestA19.fsproj" /> <ProjectReference Include="..\FSharpTestA20\FSharpTestA20.fsproj" /> <ProjectReference Include="..\FSharpTestA21\FSharpTestA21.fsproj" /> <ProjectReference Include="..\FSharpTestA22\FSharpTestA22.fsproj" /> <ProjectReference Include="..\FSharpTestA23\FSharpTestA23.fsproj" /> <ProjectReference Include="..\FSharpTestA24\FSharpTestA24.fsproj" /> <ProjectReference Include="..\FSharpTestA25\FSharpTestA25.fsproj" /> <ProjectReference Include="..\FSharpTestA26\FSharpTestA26.fsproj" /> <ProjectReference Include="..\FSharpTestA27\FSharpTestA27.fsproj" /> <ProjectReference Include="..\FSharpTestA28\FSharpTestA28.fsproj" /> <ProjectReference Include="..\FSharpTestA29\FSharpTestA29.fsproj" /> <ProjectReference Include="..\FSharpTestA30\FSharpTestA30.fsproj" /> <ProjectReference Include="..\FSharpTestA31\FSharpTestA31.fsproj" /> <ProjectReference Include="..\FSharpTestA32\FSharpTestA32.fsproj" /> <ProjectReference Include="..\FSharpTestA33\FSharpTestA33.fsproj" /> <ProjectReference Include="..\FSharpTestA34\FSharpTestA34.fsproj" /> <ProjectReference Include="..\FSharpTestA35\FSharpTestA35.fsproj" /> <ProjectReference Include="..\FSharpTestA36\FSharpTestA36.fsproj" /> <ProjectReference Include="..\FSharpTestA37\FSharpTestA37.fsproj" /> <ProjectReference Include="..\FSharpTestA38\FSharpTestA38.fsproj" /> <ProjectReference Include="..\FSharpTestA39\FSharpTestA39.fsproj" /> <ProjectReference Include="..\FSharpTestA40\FSharpTestA40.fsproj" /> <ProjectReference Include="..\FSharpTestA41\FSharpTestA41.fsproj" /> <ProjectReference Include="..\FSharpTestA42\FSharpTestA42.fsproj" /> <ProjectReference Include="..\FSharpTestA43\FSharpTestA43.fsproj" /> <ProjectReference Include="..\FSharpTestA44\FSharpTestA44.fsproj" /> <ProjectReference Include="..\FSharpTestA45\FSharpTestA45.fsproj" /> <ProjectReference Include="..\FSharpTestA46\FSharpTestA46.fsproj" /> <ProjectReference Include="..\FSharpTestA47\FSharpTestA47.fsproj" /> <ProjectReference Include="..\FSharpTestA48\FSharpTestA48.fsproj" /> <ProjectReference Include="..\FSharpTestA49\FSharpTestA49.fsproj" /> <ProjectReference Include="..\FSharpTestA50\FSharpTestA50.fsproj" /> </ItemGroup> <ItemGroup> </ItemGroup> </Project>
{ "pile_set_name": "Github" }
/* * wpa_supplicant - DPP * Copyright (c) 2017, Qualcomm Atheros, Inc. * Copyright (c) 2018-2019, The Linux Foundation * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "utils/includes.h" #include "utils/common.h" #include "utils/eloop.h" #include "utils/ip_addr.h" #include "common/dpp.h" #include "common/gas.h" #include "common/gas_server.h" #include "rsn_supp/wpa.h" #include "rsn_supp/pmksa_cache.h" #include "wpa_supplicant_i.h" #include "config.h" #include "driver_i.h" #include "offchannel.h" #include "gas_query.h" #include "bss.h" #include "scan.h" #include "notify.h" #include "dpp_supplicant.h" static int wpas_dpp_listen_start(struct wpa_supplicant *wpa_s, unsigned int freq); static void wpas_dpp_reply_wait_timeout(void *eloop_ctx, void *timeout_ctx); static void wpas_dpp_auth_success(struct wpa_supplicant *wpa_s, int initiator); static void wpas_dpp_tx_status(struct wpa_supplicant *wpa_s, unsigned int freq, const u8 *dst, const u8 *src, const u8 *bssid, const u8 *data, size_t data_len, enum offchannel_send_action_result result); static void wpas_dpp_init_timeout(void *eloop_ctx, void *timeout_ctx); static int wpas_dpp_auth_init_next(struct wpa_supplicant *wpa_s); static void wpas_dpp_tx_pkex_status(struct wpa_supplicant *wpa_s, unsigned int freq, const u8 *dst, const u8 *src, const u8 *bssid, const u8 *data, size_t data_len, enum offchannel_send_action_result result); static const u8 broadcast[ETH_ALEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; /* Use a hardcoded Transaction ID 1 in Peer Discovery frames since there is only * a single transaction in progress at any point in time. */ static const u8 TRANSACTION_ID = 1; /** * wpas_dpp_qr_code - Parse and add DPP bootstrapping info from a QR Code * @wpa_s: Pointer to wpa_supplicant data * @cmd: DPP URI read from a QR Code * Returns: Identifier of the stored info or -1 on failure */ int wpas_dpp_qr_code(struct wpa_supplicant *wpa_s, const char *cmd) { struct dpp_bootstrap_info *bi; struct dpp_authentication *auth = wpa_s->dpp_auth; bi = dpp_add_qr_code(wpa_s->dpp, cmd); if (!bi) return -1; if (auth && auth->response_pending && dpp_notify_new_qr_code(auth, bi) == 1) { wpa_printf(MSG_DEBUG, "DPP: Sending out pending authentication response"); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX "dst=" MACSTR " freq=%u type=%d", MAC2STR(auth->peer_mac_addr), auth->curr_freq, DPP_PA_AUTHENTICATION_RESP); offchannel_send_action(wpa_s, auth->curr_freq, auth->peer_mac_addr, wpa_s->own_addr, broadcast, wpabuf_head(auth->resp_msg), wpabuf_len(auth->resp_msg), 500, wpas_dpp_tx_status, 0); } return bi->id; } static void wpas_dpp_auth_resp_retry_timeout(void *eloop_ctx, void *timeout_ctx) { struct wpa_supplicant *wpa_s = eloop_ctx; struct dpp_authentication *auth = wpa_s->dpp_auth; if (!auth || !auth->resp_msg) return; wpa_printf(MSG_DEBUG, "DPP: Retry Authentication Response after timeout"); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX "dst=" MACSTR " freq=%u type=%d", MAC2STR(auth->peer_mac_addr), auth->curr_freq, DPP_PA_AUTHENTICATION_RESP); offchannel_send_action(wpa_s, auth->curr_freq, auth->peer_mac_addr, wpa_s->own_addr, broadcast, wpabuf_head(auth->resp_msg), wpabuf_len(auth->resp_msg), 500, wpas_dpp_tx_status, 0); } static void wpas_dpp_auth_resp_retry(struct wpa_supplicant *wpa_s) { struct dpp_authentication *auth = wpa_s->dpp_auth; unsigned int wait_time, max_tries; if (!auth || !auth->resp_msg) return; if (wpa_s->dpp_resp_max_tries) max_tries = wpa_s->dpp_resp_max_tries; else max_tries = 5; auth->auth_resp_tries++; if (auth->auth_resp_tries >= max_tries) { wpa_printf(MSG_INFO, "DPP: No confirm received from initiator - stopping exchange"); offchannel_send_action_done(wpa_s); dpp_auth_deinit(wpa_s->dpp_auth); wpa_s->dpp_auth = NULL; return; } if (wpa_s->dpp_resp_retry_time) wait_time = wpa_s->dpp_resp_retry_time; else wait_time = 1000; wpa_printf(MSG_DEBUG, "DPP: Schedule retransmission of Authentication Response frame in %u ms", wait_time); eloop_cancel_timeout(wpas_dpp_auth_resp_retry_timeout, wpa_s, NULL); eloop_register_timeout(wait_time / 1000, (wait_time % 1000) * 1000, wpas_dpp_auth_resp_retry_timeout, wpa_s, NULL); } static void wpas_dpp_try_to_connect(struct wpa_supplicant *wpa_s) { wpa_printf(MSG_DEBUG, "DPP: Trying to connect to the new network"); wpa_s->disconnected = 0; wpa_s->reassociate = 1; wpa_s->scan_runs = 0; wpa_s->normal_scans = 0; wpa_supplicant_cancel_sched_scan(wpa_s); wpa_supplicant_req_scan(wpa_s, 0, 0); } static void wpas_dpp_tx_status(struct wpa_supplicant *wpa_s, unsigned int freq, const u8 *dst, const u8 *src, const u8 *bssid, const u8 *data, size_t data_len, enum offchannel_send_action_result result) { const char *res_txt; struct dpp_authentication *auth = wpa_s->dpp_auth; res_txt = result == OFFCHANNEL_SEND_ACTION_SUCCESS ? "SUCCESS" : (result == OFFCHANNEL_SEND_ACTION_NO_ACK ? "no-ACK" : "FAILED"); wpa_printf(MSG_DEBUG, "DPP: TX status: freq=%u dst=" MACSTR " result=%s", freq, MAC2STR(dst), res_txt); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX_STATUS "dst=" MACSTR " freq=%u result=%s", MAC2STR(dst), freq, res_txt); if (!wpa_s->dpp_auth) { wpa_printf(MSG_DEBUG, "DPP: Ignore TX status since there is no ongoing authentication exchange"); return; } #ifdef CONFIG_DPP2 if (auth->connect_on_tx_status) { wpa_printf(MSG_DEBUG, "DPP: Try to connect after completed configuration result"); wpas_dpp_try_to_connect(wpa_s); dpp_auth_deinit(wpa_s->dpp_auth); wpa_s->dpp_auth = NULL; return; } #endif /* CONFIG_DPP2 */ if (wpa_s->dpp_auth->remove_on_tx_status) { wpa_printf(MSG_DEBUG, "DPP: Terminate authentication exchange due to an earlier error"); eloop_cancel_timeout(wpas_dpp_init_timeout, wpa_s, NULL); eloop_cancel_timeout(wpas_dpp_reply_wait_timeout, wpa_s, NULL); eloop_cancel_timeout(wpas_dpp_auth_resp_retry_timeout, wpa_s, NULL); offchannel_send_action_done(wpa_s); dpp_auth_deinit(wpa_s->dpp_auth); wpa_s->dpp_auth = NULL; return; } if (wpa_s->dpp_auth_ok_on_ack) wpas_dpp_auth_success(wpa_s, 1); if (!is_broadcast_ether_addr(dst) && result != OFFCHANNEL_SEND_ACTION_SUCCESS) { wpa_printf(MSG_DEBUG, "DPP: Unicast DPP Action frame was not ACKed"); if (auth->waiting_auth_resp) { /* In case of DPP Authentication Request frame, move to * the next channel immediately. */ offchannel_send_action_done(wpa_s); wpas_dpp_auth_init_next(wpa_s); return; } if (auth->waiting_auth_conf) { wpas_dpp_auth_resp_retry(wpa_s); return; } } if (!is_broadcast_ether_addr(dst) && auth->waiting_auth_resp && result == OFFCHANNEL_SEND_ACTION_SUCCESS) { /* Allow timeout handling to stop iteration if no response is * received from a peer that has ACKed a request. */ auth->auth_req_ack = 1; } if (!wpa_s->dpp_auth_ok_on_ack && wpa_s->dpp_auth->neg_freq > 0 && wpa_s->dpp_auth->curr_freq != wpa_s->dpp_auth->neg_freq) { wpa_printf(MSG_DEBUG, "DPP: Move from curr_freq %u MHz to neg_freq %u MHz for response", wpa_s->dpp_auth->curr_freq, wpa_s->dpp_auth->neg_freq); offchannel_send_action_done(wpa_s); wpas_dpp_listen_start(wpa_s, wpa_s->dpp_auth->neg_freq); } if (wpa_s->dpp_auth_ok_on_ack) wpa_s->dpp_auth_ok_on_ack = 0; } static void wpas_dpp_reply_wait_timeout(void *eloop_ctx, void *timeout_ctx) { struct wpa_supplicant *wpa_s = eloop_ctx; struct dpp_authentication *auth = wpa_s->dpp_auth; unsigned int freq; struct os_reltime now, diff; unsigned int wait_time, diff_ms; if (!auth || !auth->waiting_auth_resp) return; wait_time = wpa_s->dpp_resp_wait_time ? wpa_s->dpp_resp_wait_time : 2000; os_get_reltime(&now); os_reltime_sub(&now, &wpa_s->dpp_last_init, &diff); diff_ms = diff.sec * 1000 + diff.usec / 1000; wpa_printf(MSG_DEBUG, "DPP: Reply wait timeout - wait_time=%u diff_ms=%u", wait_time, diff_ms); if (auth->auth_req_ack && diff_ms >= wait_time) { /* Peer ACK'ed Authentication Request frame, but did not reply * with Authentication Response frame within two seconds. */ wpa_printf(MSG_INFO, "DPP: No response received from responder - stopping initiation attempt"); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_AUTH_INIT_FAILED); offchannel_send_action_done(wpa_s); wpas_dpp_listen_stop(wpa_s); dpp_auth_deinit(auth); wpa_s->dpp_auth = NULL; return; } if (diff_ms >= wait_time) { /* Authentication Request frame was not ACK'ed and no reply * was receiving within two seconds. */ wpa_printf(MSG_DEBUG, "DPP: Continue Initiator channel iteration"); offchannel_send_action_done(wpa_s); wpas_dpp_listen_stop(wpa_s); wpas_dpp_auth_init_next(wpa_s); return; } /* Driver did not support 2000 ms long wait_time with TX command, so * schedule listen operation to continue waiting for the response. * * DPP listen operations continue until stopped, so simply schedule a * new call to this function at the point when the two second reply * wait has expired. */ wait_time -= diff_ms; freq = auth->curr_freq; if (auth->neg_freq > 0) freq = auth->neg_freq; wpa_printf(MSG_DEBUG, "DPP: Continue reply wait on channel %u MHz for %u ms", freq, wait_time); wpa_s->dpp_in_response_listen = 1; wpas_dpp_listen_start(wpa_s, freq); eloop_register_timeout(wait_time / 1000, (wait_time % 1000) * 1000, wpas_dpp_reply_wait_timeout, wpa_s, NULL); } static void wpas_dpp_set_testing_options(struct wpa_supplicant *wpa_s, struct dpp_authentication *auth) { #ifdef CONFIG_TESTING_OPTIONS if (wpa_s->dpp_config_obj_override) auth->config_obj_override = os_strdup(wpa_s->dpp_config_obj_override); if (wpa_s->dpp_discovery_override) auth->discovery_override = os_strdup(wpa_s->dpp_discovery_override); if (wpa_s->dpp_groups_override) auth->groups_override = os_strdup(wpa_s->dpp_groups_override); auth->ignore_netaccesskey_mismatch = wpa_s->dpp_ignore_netaccesskey_mismatch; #endif /* CONFIG_TESTING_OPTIONS */ } static void wpas_dpp_init_timeout(void *eloop_ctx, void *timeout_ctx) { struct wpa_supplicant *wpa_s = eloop_ctx; if (!wpa_s->dpp_auth) return; wpa_printf(MSG_DEBUG, "DPP: Retry initiation after timeout"); wpas_dpp_auth_init_next(wpa_s); } static int wpas_dpp_auth_init_next(struct wpa_supplicant *wpa_s) { struct dpp_authentication *auth = wpa_s->dpp_auth; const u8 *dst; unsigned int wait_time, max_wait_time, freq, max_tries, used; struct os_reltime now, diff; wpa_s->dpp_in_response_listen = 0; if (!auth) return -1; if (auth->freq_idx == 0) os_get_reltime(&wpa_s->dpp_init_iter_start); if (auth->freq_idx >= auth->num_freq) { auth->num_freq_iters++; if (wpa_s->dpp_init_max_tries) max_tries = wpa_s->dpp_init_max_tries; else max_tries = 5; if (auth->num_freq_iters >= max_tries || auth->auth_req_ack) { wpa_printf(MSG_INFO, "DPP: No response received from responder - stopping initiation attempt"); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_AUTH_INIT_FAILED); eloop_cancel_timeout(wpas_dpp_reply_wait_timeout, wpa_s, NULL); offchannel_send_action_done(wpa_s); dpp_auth_deinit(wpa_s->dpp_auth); wpa_s->dpp_auth = NULL; return -1; } auth->freq_idx = 0; eloop_cancel_timeout(wpas_dpp_init_timeout, wpa_s, NULL); if (wpa_s->dpp_init_retry_time) wait_time = wpa_s->dpp_init_retry_time; else wait_time = 10000; os_get_reltime(&now); os_reltime_sub(&now, &wpa_s->dpp_init_iter_start, &diff); used = diff.sec * 1000 + diff.usec / 1000; if (used > wait_time) wait_time = 0; else wait_time -= used; wpa_printf(MSG_DEBUG, "DPP: Next init attempt in %u ms", wait_time); eloop_register_timeout(wait_time / 1000, (wait_time % 1000) * 1000, wpas_dpp_init_timeout, wpa_s, NULL); return 0; } freq = auth->freq[auth->freq_idx++]; auth->curr_freq = freq; if (is_zero_ether_addr(auth->peer_bi->mac_addr)) dst = broadcast; else dst = auth->peer_bi->mac_addr; wpa_s->dpp_auth_ok_on_ack = 0; eloop_cancel_timeout(wpas_dpp_reply_wait_timeout, wpa_s, NULL); wait_time = wpa_s->max_remain_on_chan; max_wait_time = wpa_s->dpp_resp_wait_time ? wpa_s->dpp_resp_wait_time : 2000; if (wait_time > max_wait_time) wait_time = max_wait_time; wait_time += 10; /* give the driver some extra time to complete */ eloop_register_timeout(wait_time / 1000, (wait_time % 1000) * 1000, wpas_dpp_reply_wait_timeout, wpa_s, NULL); wait_time -= 10; if (auth->neg_freq > 0 && freq != auth->neg_freq) { wpa_printf(MSG_DEBUG, "DPP: Initiate on %u MHz and move to neg_freq %u MHz for response", freq, auth->neg_freq); } wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX "dst=" MACSTR " freq=%u type=%d", MAC2STR(dst), freq, DPP_PA_AUTHENTICATION_REQ); auth->auth_req_ack = 0; os_get_reltime(&wpa_s->dpp_last_init); return offchannel_send_action(wpa_s, freq, dst, wpa_s->own_addr, broadcast, wpabuf_head(auth->req_msg), wpabuf_len(auth->req_msg), wait_time, wpas_dpp_tx_status, 0); } int wpas_dpp_auth_init(struct wpa_supplicant *wpa_s, const char *cmd) { const char *pos; struct dpp_bootstrap_info *peer_bi, *own_bi = NULL; struct dpp_authentication *auth; u8 allowed_roles = DPP_CAPAB_CONFIGURATOR; unsigned int neg_freq = 0; int tcp = 0; #ifdef CONFIG_DPP2 int tcp_port = DPP_TCP_PORT; struct hostapd_ip_addr ipaddr; char *addr; #endif /* CONFIG_DPP2 */ wpa_s->dpp_gas_client = 0; pos = os_strstr(cmd, " peer="); if (!pos) return -1; pos += 6; peer_bi = dpp_bootstrap_get_id(wpa_s->dpp, atoi(pos)); if (!peer_bi) { wpa_printf(MSG_INFO, "DPP: Could not find bootstrapping info for the identified peer"); return -1; } #ifdef CONFIG_DPP2 pos = os_strstr(cmd, " tcp_port="); if (pos) { pos += 10; tcp_port = atoi(pos); } addr = get_param(cmd, " tcp_addr="); if (addr) { int res; res = hostapd_parse_ip_addr(addr, &ipaddr); os_free(addr); if (res) return -1; tcp = 1; } #endif /* CONFIG_DPP2 */ pos = os_strstr(cmd, " own="); if (pos) { pos += 5; own_bi = dpp_bootstrap_get_id(wpa_s->dpp, atoi(pos)); if (!own_bi) { wpa_printf(MSG_INFO, "DPP: Could not find bootstrapping info for the identified local entry"); return -1; } if (peer_bi->curve != own_bi->curve) { wpa_printf(MSG_INFO, "DPP: Mismatching curves in bootstrapping info (peer=%s own=%s)", peer_bi->curve->name, own_bi->curve->name); return -1; } } pos = os_strstr(cmd, " role="); if (pos) { pos += 6; if (os_strncmp(pos, "configurator", 12) == 0) allowed_roles = DPP_CAPAB_CONFIGURATOR; else if (os_strncmp(pos, "enrollee", 8) == 0) allowed_roles = DPP_CAPAB_ENROLLEE; else if (os_strncmp(pos, "either", 6) == 0) allowed_roles = DPP_CAPAB_CONFIGURATOR | DPP_CAPAB_ENROLLEE; else goto fail; } pos = os_strstr(cmd, " netrole="); if (pos) { pos += 9; wpa_s->dpp_netrole_ap = os_strncmp(pos, "ap", 2) == 0; } pos = os_strstr(cmd, " neg_freq="); if (pos) neg_freq = atoi(pos + 10); if (!tcp && wpa_s->dpp_auth) { eloop_cancel_timeout(wpas_dpp_init_timeout, wpa_s, NULL); eloop_cancel_timeout(wpas_dpp_reply_wait_timeout, wpa_s, NULL); eloop_cancel_timeout(wpas_dpp_auth_resp_retry_timeout, wpa_s, NULL); offchannel_send_action_done(wpa_s); dpp_auth_deinit(wpa_s->dpp_auth); wpa_s->dpp_auth = NULL; } auth = dpp_auth_init(wpa_s, peer_bi, own_bi, allowed_roles, neg_freq, wpa_s->hw.modes, wpa_s->hw.num_modes); if (!auth) goto fail; wpas_dpp_set_testing_options(wpa_s, auth); if (dpp_set_configurator(wpa_s->dpp, wpa_s, auth, cmd) < 0) { dpp_auth_deinit(auth); goto fail; } auth->neg_freq = neg_freq; if (!is_zero_ether_addr(peer_bi->mac_addr)) os_memcpy(auth->peer_mac_addr, peer_bi->mac_addr, ETH_ALEN); #ifdef CONFIG_DPP2 if (tcp) return dpp_tcp_init(wpa_s->dpp, auth, &ipaddr, tcp_port); #endif /* CONFIG_DPP2 */ wpa_s->dpp_auth = auth; return wpas_dpp_auth_init_next(wpa_s); fail: return -1; } struct wpas_dpp_listen_work { unsigned int freq; unsigned int duration; struct wpabuf *probe_resp_ie; }; static void wpas_dpp_listen_work_free(struct wpas_dpp_listen_work *lwork) { if (!lwork) return; os_free(lwork); } static void wpas_dpp_listen_work_done(struct wpa_supplicant *wpa_s) { struct wpas_dpp_listen_work *lwork; if (!wpa_s->dpp_listen_work) return; lwork = wpa_s->dpp_listen_work->ctx; wpas_dpp_listen_work_free(lwork); radio_work_done(wpa_s->dpp_listen_work); wpa_s->dpp_listen_work = NULL; } static void dpp_start_listen_cb(struct wpa_radio_work *work, int deinit) { struct wpa_supplicant *wpa_s = work->wpa_s; struct wpas_dpp_listen_work *lwork = work->ctx; if (deinit) { if (work->started) { wpa_s->dpp_listen_work = NULL; wpas_dpp_listen_stop(wpa_s); } wpas_dpp_listen_work_free(lwork); return; } wpa_s->dpp_listen_work = work; wpa_s->dpp_pending_listen_freq = lwork->freq; if (wpa_drv_remain_on_channel(wpa_s, lwork->freq, wpa_s->max_remain_on_chan) < 0) { wpa_printf(MSG_DEBUG, "DPP: Failed to request the driver to remain on channel (%u MHz) for listen", lwork->freq); wpa_s->dpp_listen_freq = 0; wpas_dpp_listen_work_done(wpa_s); wpa_s->dpp_pending_listen_freq = 0; return; } wpa_s->off_channel_freq = 0; wpa_s->roc_waiting_drv_freq = lwork->freq; } static int wpas_dpp_listen_start(struct wpa_supplicant *wpa_s, unsigned int freq) { struct wpas_dpp_listen_work *lwork; if (wpa_s->dpp_listen_work) { wpa_printf(MSG_DEBUG, "DPP: Reject start_listen since dpp_listen_work already exists"); return -1; } if (wpa_s->dpp_listen_freq) wpas_dpp_listen_stop(wpa_s); wpa_s->dpp_listen_freq = freq; lwork = os_zalloc(sizeof(*lwork)); if (!lwork) return -1; lwork->freq = freq; if (radio_add_work(wpa_s, freq, "dpp-listen", 0, dpp_start_listen_cb, lwork) < 0) { wpas_dpp_listen_work_free(lwork); return -1; } return 0; } int wpas_dpp_listen(struct wpa_supplicant *wpa_s, const char *cmd) { int freq; freq = atoi(cmd); if (freq <= 0) return -1; if (os_strstr(cmd, " role=configurator")) wpa_s->dpp_allowed_roles = DPP_CAPAB_CONFIGURATOR; else if (os_strstr(cmd, " role=enrollee")) wpa_s->dpp_allowed_roles = DPP_CAPAB_ENROLLEE; else wpa_s->dpp_allowed_roles = DPP_CAPAB_CONFIGURATOR | DPP_CAPAB_ENROLLEE; wpa_s->dpp_qr_mutual = os_strstr(cmd, " qr=mutual") != NULL; wpa_s->dpp_netrole_ap = os_strstr(cmd, " netrole=ap") != NULL; if (wpa_s->dpp_listen_freq == (unsigned int) freq) { wpa_printf(MSG_DEBUG, "DPP: Already listening on %u MHz", freq); return 0; } return wpas_dpp_listen_start(wpa_s, freq); } void wpas_dpp_listen_stop(struct wpa_supplicant *wpa_s) { wpa_s->dpp_in_response_listen = 0; if (!wpa_s->dpp_listen_freq) return; wpa_printf(MSG_DEBUG, "DPP: Stop listen on %u MHz", wpa_s->dpp_listen_freq); wpa_drv_cancel_remain_on_channel(wpa_s); wpa_s->dpp_listen_freq = 0; wpas_dpp_listen_work_done(wpa_s); } void wpas_dpp_cancel_remain_on_channel_cb(struct wpa_supplicant *wpa_s, unsigned int freq) { wpas_dpp_listen_work_done(wpa_s); if (wpa_s->dpp_auth && wpa_s->dpp_in_response_listen) { unsigned int new_freq; /* Continue listen with a new remain-on-channel */ if (wpa_s->dpp_auth->neg_freq > 0) new_freq = wpa_s->dpp_auth->neg_freq; else new_freq = wpa_s->dpp_auth->curr_freq; wpa_printf(MSG_DEBUG, "DPP: Continue wait on %u MHz for the ongoing DPP provisioning session", new_freq); wpas_dpp_listen_start(wpa_s, new_freq); return; } if (wpa_s->dpp_listen_freq) { /* Continue listen with a new remain-on-channel */ wpas_dpp_listen_start(wpa_s, wpa_s->dpp_listen_freq); } } static void wpas_dpp_rx_auth_req(struct wpa_supplicant *wpa_s, const u8 *src, const u8 *hdr, const u8 *buf, size_t len, unsigned int freq) { const u8 *r_bootstrap, *i_bootstrap; u16 r_bootstrap_len, i_bootstrap_len; struct dpp_bootstrap_info *own_bi = NULL, *peer_bi = NULL; if (!wpa_s->dpp) return; wpa_printf(MSG_DEBUG, "DPP: Authentication Request from " MACSTR, MAC2STR(src)); r_bootstrap = dpp_get_attr(buf, len, DPP_ATTR_R_BOOTSTRAP_KEY_HASH, &r_bootstrap_len); if (!r_bootstrap || r_bootstrap_len != SHA256_MAC_LEN) { wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_FAIL "Missing or invalid required Responder Bootstrapping Key Hash attribute"); return; } wpa_hexdump(MSG_MSGDUMP, "DPP: Responder Bootstrapping Key Hash", r_bootstrap, r_bootstrap_len); i_bootstrap = dpp_get_attr(buf, len, DPP_ATTR_I_BOOTSTRAP_KEY_HASH, &i_bootstrap_len); if (!i_bootstrap || i_bootstrap_len != SHA256_MAC_LEN) { wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_FAIL "Missing or invalid required Initiator Bootstrapping Key Hash attribute"); return; } wpa_hexdump(MSG_MSGDUMP, "DPP: Initiator Bootstrapping Key Hash", i_bootstrap, i_bootstrap_len); /* Try to find own and peer bootstrapping key matches based on the * received hash values */ dpp_bootstrap_find_pair(wpa_s->dpp, i_bootstrap, r_bootstrap, &own_bi, &peer_bi); if (!own_bi) { wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_FAIL "No matching own bootstrapping key found - ignore message"); return; } if (wpa_s->dpp_auth) { wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_FAIL "Already in DPP authentication exchange - ignore new one"); return; } wpa_s->dpp_gas_client = 0; wpa_s->dpp_auth_ok_on_ack = 0; wpa_s->dpp_auth = dpp_auth_req_rx(wpa_s, wpa_s->dpp_allowed_roles, wpa_s->dpp_qr_mutual, peer_bi, own_bi, freq, hdr, buf, len); if (!wpa_s->dpp_auth) { wpa_printf(MSG_DEBUG, "DPP: No response generated"); return; } wpas_dpp_set_testing_options(wpa_s, wpa_s->dpp_auth); if (dpp_set_configurator(wpa_s->dpp, wpa_s, wpa_s->dpp_auth, wpa_s->dpp_configurator_params) < 0) { dpp_auth_deinit(wpa_s->dpp_auth); wpa_s->dpp_auth = NULL; return; } os_memcpy(wpa_s->dpp_auth->peer_mac_addr, src, ETH_ALEN); if (wpa_s->dpp_listen_freq && wpa_s->dpp_listen_freq != wpa_s->dpp_auth->curr_freq) { wpa_printf(MSG_DEBUG, "DPP: Stop listen on %u MHz to allow response on the request %u MHz", wpa_s->dpp_listen_freq, wpa_s->dpp_auth->curr_freq); wpas_dpp_listen_stop(wpa_s); } wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX "dst=" MACSTR " freq=%u type=%d", MAC2STR(src), wpa_s->dpp_auth->curr_freq, DPP_PA_AUTHENTICATION_RESP); offchannel_send_action(wpa_s, wpa_s->dpp_auth->curr_freq, src, wpa_s->own_addr, broadcast, wpabuf_head(wpa_s->dpp_auth->resp_msg), wpabuf_len(wpa_s->dpp_auth->resp_msg), 500, wpas_dpp_tx_status, 0); } static void wpas_dpp_start_gas_server(struct wpa_supplicant *wpa_s) { /* TODO: stop wait and start ROC */ } static struct wpa_ssid * wpas_dpp_add_network(struct wpa_supplicant *wpa_s, struct dpp_authentication *auth) { struct wpa_ssid *ssid; #ifdef CONFIG_DPP2 if (auth->akm == DPP_AKM_SAE) { #ifdef CONFIG_SAE struct wpa_driver_capa capa; int res; res = wpa_drv_get_capa(wpa_s, &capa); if (res == 0 && !(capa.key_mgmt & WPA_DRIVER_CAPA_KEY_MGMT_SAE) && !(wpa_s->drv_flags & WPA_DRIVER_FLAGS_SAE)) { wpa_printf(MSG_DEBUG, "DPP: SAE not supported by the driver"); return NULL; } #else /* CONFIG_SAE */ wpa_printf(MSG_DEBUG, "DPP: SAE not supported in the build"); return NULL; #endif /* CONFIG_SAE */ } #endif /* CONFIG_DPP2 */ ssid = wpa_config_add_network(wpa_s->conf); if (!ssid) return NULL; wpas_notify_network_added(wpa_s, ssid); wpa_config_set_network_defaults(ssid); ssid->disabled = 1; ssid->ssid = os_malloc(auth->ssid_len); if (!ssid->ssid) goto fail; os_memcpy(ssid->ssid, auth->ssid, auth->ssid_len); ssid->ssid_len = auth->ssid_len; if (auth->connector) { ssid->key_mgmt = WPA_KEY_MGMT_DPP; ssid->ieee80211w = MGMT_FRAME_PROTECTION_REQUIRED; ssid->dpp_connector = os_strdup(auth->connector); if (!ssid->dpp_connector) goto fail; } if (auth->c_sign_key) { ssid->dpp_csign = os_malloc(wpabuf_len(auth->c_sign_key)); if (!ssid->dpp_csign) goto fail; os_memcpy(ssid->dpp_csign, wpabuf_head(auth->c_sign_key), wpabuf_len(auth->c_sign_key)); ssid->dpp_csign_len = wpabuf_len(auth->c_sign_key); } if (auth->net_access_key) { ssid->dpp_netaccesskey = os_malloc(wpabuf_len(auth->net_access_key)); if (!ssid->dpp_netaccesskey) goto fail; os_memcpy(ssid->dpp_netaccesskey, wpabuf_head(auth->net_access_key), wpabuf_len(auth->net_access_key)); ssid->dpp_netaccesskey_len = wpabuf_len(auth->net_access_key); ssid->dpp_netaccesskey_expiry = auth->net_access_key_expiry; } if (!auth->connector || dpp_akm_psk(auth->akm) || dpp_akm_sae(auth->akm)) { if (!auth->connector) ssid->key_mgmt = 0; if (dpp_akm_psk(auth->akm)) ssid->key_mgmt |= WPA_KEY_MGMT_PSK | WPA_KEY_MGMT_PSK_SHA256 | WPA_KEY_MGMT_FT_PSK; if (dpp_akm_sae(auth->akm)) ssid->key_mgmt |= WPA_KEY_MGMT_SAE | WPA_KEY_MGMT_FT_SAE; ssid->ieee80211w = MGMT_FRAME_PROTECTION_OPTIONAL; if (auth->passphrase[0]) { if (wpa_config_set_quoted(ssid, "psk", auth->passphrase) < 0) goto fail; wpa_config_update_psk(ssid); ssid->export_keys = 1; } else { ssid->psk_set = auth->psk_set; os_memcpy(ssid->psk, auth->psk, PMK_LEN); } } return ssid; fail: wpas_notify_network_removed(wpa_s, ssid); wpa_config_remove_network(wpa_s->conf, ssid->id); return NULL; } static int wpas_dpp_process_config(struct wpa_supplicant *wpa_s, struct dpp_authentication *auth) { struct wpa_ssid *ssid; if (wpa_s->conf->dpp_config_processing < 1) return 0; ssid = wpas_dpp_add_network(wpa_s, auth); if (!ssid) return -1; wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_NETWORK_ID "%d", ssid->id); if (wpa_s->conf->dpp_config_processing == 2) ssid->disabled = 0; #ifndef CONFIG_NO_CONFIG_WRITE if (wpa_s->conf->update_config && wpa_config_write(wpa_s->confname, wpa_s->conf)) wpa_printf(MSG_DEBUG, "DPP: Failed to update configuration"); #endif /* CONFIG_NO_CONFIG_WRITE */ if (wpa_s->conf->dpp_config_processing < 2) return 0; #ifdef CONFIG_DPP2 if (auth->peer_version >= 2) { wpa_printf(MSG_DEBUG, "DPP: Postpone connection attempt to wait for completion of DPP Configuration Result"); auth->connect_on_tx_status = 1; return 0; } #endif /* CONFIG_DPP2 */ wpas_dpp_try_to_connect(wpa_s); return 0; } static int wpas_dpp_handle_config_obj(struct wpa_supplicant *wpa_s, struct dpp_authentication *auth) { wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_CONF_RECEIVED); if (auth->ssid_len) wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_CONFOBJ_SSID "%s", wpa_ssid_txt(auth->ssid, auth->ssid_len)); if (auth->connector) { /* TODO: Save the Connector and consider using a command * to fetch the value instead of sending an event with * it. The Connector could end up being larger than what * most clients are ready to receive as an event * message. */ wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_CONNECTOR "%s", auth->connector); } if (auth->c_sign_key) { char *hex; size_t hexlen; hexlen = 2 * wpabuf_len(auth->c_sign_key) + 1; hex = os_malloc(hexlen); if (hex) { wpa_snprintf_hex(hex, hexlen, wpabuf_head(auth->c_sign_key), wpabuf_len(auth->c_sign_key)); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_C_SIGN_KEY "%s", hex); os_free(hex); } } if (auth->net_access_key) { char *hex; size_t hexlen; hexlen = 2 * wpabuf_len(auth->net_access_key) + 1; hex = os_malloc(hexlen); if (hex) { wpa_snprintf_hex(hex, hexlen, wpabuf_head(auth->net_access_key), wpabuf_len(auth->net_access_key)); if (auth->net_access_key_expiry) wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_NET_ACCESS_KEY "%s %lu", hex, (long unsigned) auth->net_access_key_expiry); else wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_NET_ACCESS_KEY "%s", hex); os_free(hex); } } return wpas_dpp_process_config(wpa_s, auth); } static void wpas_dpp_gas_resp_cb(void *ctx, const u8 *addr, u8 dialog_token, enum gas_query_result result, const struct wpabuf *adv_proto, const struct wpabuf *resp, u16 status_code) { struct wpa_supplicant *wpa_s = ctx; const u8 *pos; struct dpp_authentication *auth = wpa_s->dpp_auth; int res; enum dpp_status_error status = DPP_STATUS_CONFIG_REJECTED; wpa_s->dpp_gas_dialog_token = -1; if (!auth || !auth->auth_success) { wpa_printf(MSG_DEBUG, "DPP: No matching exchange in progress"); return; } if (result != GAS_QUERY_SUCCESS || !resp || status_code != WLAN_STATUS_SUCCESS) { wpa_printf(MSG_DEBUG, "DPP: GAS query did not succeed"); goto fail; } wpa_hexdump_buf(MSG_DEBUG, "DPP: Configuration Response adv_proto", adv_proto); wpa_hexdump_buf(MSG_DEBUG, "DPP: Configuration Response (GAS response)", resp); if (wpabuf_len(adv_proto) != 10 || !(pos = wpabuf_head(adv_proto)) || pos[0] != WLAN_EID_ADV_PROTO || pos[1] != 8 || pos[3] != WLAN_EID_VENDOR_SPECIFIC || pos[4] != 5 || WPA_GET_BE24(&pos[5]) != OUI_WFA || pos[8] != 0x1a || pos[9] != 1) { wpa_printf(MSG_DEBUG, "DPP: Not a DPP Advertisement Protocol ID"); goto fail; } if (dpp_conf_resp_rx(auth, resp) < 0) { wpa_printf(MSG_DEBUG, "DPP: Configuration attempt failed"); goto fail; } res = wpas_dpp_handle_config_obj(wpa_s, auth); if (res < 0) goto fail; status = DPP_STATUS_OK; #ifdef CONFIG_TESTING_OPTIONS if (dpp_test == DPP_TEST_REJECT_CONFIG) { wpa_printf(MSG_INFO, "DPP: TESTING - Reject Config Object"); status = DPP_STATUS_CONFIG_REJECTED; } #endif /* CONFIG_TESTING_OPTIONS */ fail: if (status != DPP_STATUS_OK) wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_CONF_FAILED); #ifdef CONFIG_DPP2 if (auth->peer_version >= 2 && auth->conf_resp_status == DPP_STATUS_OK) { struct wpabuf *msg; wpa_printf(MSG_DEBUG, "DPP: Send DPP Configuration Result"); msg = dpp_build_conf_result(auth, status); if (!msg) goto fail2; wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX "dst=" MACSTR " freq=%u type=%d", MAC2STR(addr), auth->curr_freq, DPP_PA_CONFIGURATION_RESULT); offchannel_send_action(wpa_s, auth->curr_freq, addr, wpa_s->own_addr, broadcast, wpabuf_head(msg), wpabuf_len(msg), 500, wpas_dpp_tx_status, 0); wpabuf_free(msg); /* This exchange will be terminated in the TX status handler */ return; } fail2: #endif /* CONFIG_DPP2 */ dpp_auth_deinit(wpa_s->dpp_auth); wpa_s->dpp_auth = NULL; } static void wpas_dpp_start_gas_client(struct wpa_supplicant *wpa_s) { struct dpp_authentication *auth = wpa_s->dpp_auth; struct wpabuf *buf; char json[100]; int res; wpa_s->dpp_gas_client = 1; os_snprintf(json, sizeof(json), "{\"name\":\"Test\"," "\"wi-fi_tech\":\"infra\"," "\"netRole\":\"%s\"}", wpa_s->dpp_netrole_ap ? "ap" : "sta"); #ifdef CONFIG_TESTING_OPTIONS if (dpp_test == DPP_TEST_INVALID_CONFIG_ATTR_OBJ_CONF_REQ) { wpa_printf(MSG_INFO, "DPP: TESTING - invalid Config Attr"); json[29] = 'k'; /* replace "infra" with "knfra" */ } #endif /* CONFIG_TESTING_OPTIONS */ wpa_printf(MSG_DEBUG, "DPP: GAS Config Attributes: %s", json); offchannel_send_action_done(wpa_s); wpas_dpp_listen_stop(wpa_s); buf = dpp_build_conf_req(auth, json); if (!buf) { wpa_printf(MSG_DEBUG, "DPP: No configuration request data available"); return; } wpa_printf(MSG_DEBUG, "DPP: GAS request to " MACSTR " (freq %u MHz)", MAC2STR(auth->peer_mac_addr), auth->curr_freq); res = gas_query_req(wpa_s->gas, auth->peer_mac_addr, auth->curr_freq, 1, buf, wpas_dpp_gas_resp_cb, wpa_s); if (res < 0) { wpa_msg(wpa_s, MSG_DEBUG, "GAS: Failed to send Query Request"); wpabuf_free(buf); } else { wpa_printf(MSG_DEBUG, "DPP: GAS query started with dialog token %u", res); wpa_s->dpp_gas_dialog_token = res; } } static void wpas_dpp_auth_success(struct wpa_supplicant *wpa_s, int initiator) { wpa_printf(MSG_DEBUG, "DPP: Authentication succeeded"); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_AUTH_SUCCESS "init=%d", initiator); #ifdef CONFIG_TESTING_OPTIONS if (dpp_test == DPP_TEST_STOP_AT_AUTH_CONF) { wpa_printf(MSG_INFO, "DPP: TESTING - stop at Authentication Confirm"); if (wpa_s->dpp_auth->configurator) { /* Prevent GAS response */ wpa_s->dpp_auth->auth_success = 0; } return; } #endif /* CONFIG_TESTING_OPTIONS */ if (wpa_s->dpp_auth->configurator) wpas_dpp_start_gas_server(wpa_s); else wpas_dpp_start_gas_client(wpa_s); } static void wpas_dpp_rx_auth_resp(struct wpa_supplicant *wpa_s, const u8 *src, const u8 *hdr, const u8 *buf, size_t len, unsigned int freq) { struct dpp_authentication *auth = wpa_s->dpp_auth; struct wpabuf *msg; wpa_printf(MSG_DEBUG, "DPP: Authentication Response from " MACSTR " (freq %u MHz)", MAC2STR(src), freq); if (!auth) { wpa_printf(MSG_DEBUG, "DPP: No DPP Authentication in progress - drop"); return; } if (!is_zero_ether_addr(auth->peer_mac_addr) && os_memcmp(src, auth->peer_mac_addr, ETH_ALEN) != 0) { wpa_printf(MSG_DEBUG, "DPP: MAC address mismatch (expected " MACSTR ") - drop", MAC2STR(auth->peer_mac_addr)); return; } eloop_cancel_timeout(wpas_dpp_reply_wait_timeout, wpa_s, NULL); if (auth->curr_freq != freq && auth->neg_freq == freq) { wpa_printf(MSG_DEBUG, "DPP: Responder accepted request for different negotiation channel"); auth->curr_freq = freq; } eloop_cancel_timeout(wpas_dpp_init_timeout, wpa_s, NULL); msg = dpp_auth_resp_rx(auth, hdr, buf, len); if (!msg) { if (auth->auth_resp_status == DPP_STATUS_RESPONSE_PENDING) { wpa_printf(MSG_DEBUG, "DPP: Start wait for full response"); offchannel_send_action_done(wpa_s); wpas_dpp_listen_start(wpa_s, auth->curr_freq); return; } wpa_printf(MSG_DEBUG, "DPP: No confirm generated"); return; } os_memcpy(auth->peer_mac_addr, src, ETH_ALEN); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX "dst=" MACSTR " freq=%u type=%d", MAC2STR(src), auth->curr_freq, DPP_PA_AUTHENTICATION_CONF); offchannel_send_action(wpa_s, auth->curr_freq, src, wpa_s->own_addr, broadcast, wpabuf_head(msg), wpabuf_len(msg), 500, wpas_dpp_tx_status, 0); wpabuf_free(msg); wpa_s->dpp_auth_ok_on_ack = 1; } static void wpas_dpp_rx_auth_conf(struct wpa_supplicant *wpa_s, const u8 *src, const u8 *hdr, const u8 *buf, size_t len) { struct dpp_authentication *auth = wpa_s->dpp_auth; wpa_printf(MSG_DEBUG, "DPP: Authentication Confirmation from " MACSTR, MAC2STR(src)); if (!auth) { wpa_printf(MSG_DEBUG, "DPP: No DPP Authentication in progress - drop"); return; } if (os_memcmp(src, auth->peer_mac_addr, ETH_ALEN) != 0) { wpa_printf(MSG_DEBUG, "DPP: MAC address mismatch (expected " MACSTR ") - drop", MAC2STR(auth->peer_mac_addr)); return; } if (dpp_auth_conf_rx(auth, hdr, buf, len) < 0) { wpa_printf(MSG_DEBUG, "DPP: Authentication failed"); return; } wpas_dpp_auth_success(wpa_s, 0); } #ifdef CONFIG_DPP2 static void wpas_dpp_config_result_wait_timeout(void *eloop_ctx, void *timeout_ctx) { struct wpa_supplicant *wpa_s = eloop_ctx; struct dpp_authentication *auth = wpa_s->dpp_auth; if (!auth || !auth->waiting_conf_result) return; wpa_printf(MSG_DEBUG, "DPP: Timeout while waiting for Configuration Result"); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_CONF_FAILED); dpp_auth_deinit(auth); wpa_s->dpp_auth = NULL; } static void wpas_dpp_rx_conf_result(struct wpa_supplicant *wpa_s, const u8 *src, const u8 *hdr, const u8 *buf, size_t len) { struct dpp_authentication *auth = wpa_s->dpp_auth; enum dpp_status_error status; wpa_printf(MSG_DEBUG, "DPP: Configuration Result from " MACSTR, MAC2STR(src)); if (!auth || !auth->waiting_conf_result) { wpa_printf(MSG_DEBUG, "DPP: No DPP Configuration waiting for result - drop"); return; } if (os_memcmp(src, auth->peer_mac_addr, ETH_ALEN) != 0) { wpa_printf(MSG_DEBUG, "DPP: MAC address mismatch (expected " MACSTR ") - drop", MAC2STR(auth->peer_mac_addr)); return; } status = dpp_conf_result_rx(auth, hdr, buf, len); offchannel_send_action_done(wpa_s); wpas_dpp_listen_stop(wpa_s); if (status == DPP_STATUS_OK) wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_CONF_SENT); else wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_CONF_FAILED); dpp_auth_deinit(auth); wpa_s->dpp_auth = NULL; eloop_cancel_timeout(wpas_dpp_config_result_wait_timeout, wpa_s, NULL); } static int wpas_dpp_process_conf_obj(void *ctx, struct dpp_authentication *auth) { struct wpa_supplicant *wpa_s = ctx; return wpas_dpp_handle_config_obj(wpa_s, auth); } #endif /* CONFIG_DPP2 */ static void wpas_dpp_rx_peer_disc_resp(struct wpa_supplicant *wpa_s, const u8 *src, const u8 *buf, size_t len) { struct wpa_ssid *ssid; const u8 *connector, *trans_id, *status; u16 connector_len, trans_id_len, status_len; struct dpp_introduction intro; struct rsn_pmksa_cache_entry *entry; struct os_time now; struct os_reltime rnow; os_time_t expiry; unsigned int seconds; enum dpp_status_error res; wpa_printf(MSG_DEBUG, "DPP: Peer Discovery Response from " MACSTR, MAC2STR(src)); if (is_zero_ether_addr(wpa_s->dpp_intro_bssid) || os_memcmp(src, wpa_s->dpp_intro_bssid, ETH_ALEN) != 0) { wpa_printf(MSG_DEBUG, "DPP: Not waiting for response from " MACSTR " - drop", MAC2STR(src)); return; } offchannel_send_action_done(wpa_s); for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next) { if (ssid == wpa_s->dpp_intro_network) break; } if (!ssid || !ssid->dpp_connector || !ssid->dpp_netaccesskey || !ssid->dpp_csign) { wpa_printf(MSG_DEBUG, "DPP: Profile not found for network introduction"); return; } trans_id = dpp_get_attr(buf, len, DPP_ATTR_TRANSACTION_ID, &trans_id_len); if (!trans_id || trans_id_len != 1) { wpa_printf(MSG_DEBUG, "DPP: Peer did not include Transaction ID"); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_INTRO "peer=" MACSTR " fail=missing_transaction_id", MAC2STR(src)); goto fail; } if (trans_id[0] != TRANSACTION_ID) { wpa_printf(MSG_DEBUG, "DPP: Ignore frame with unexpected Transaction ID %u", trans_id[0]); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_INTRO "peer=" MACSTR " fail=transaction_id_mismatch", MAC2STR(src)); goto fail; } status = dpp_get_attr(buf, len, DPP_ATTR_STATUS, &status_len); if (!status || status_len != 1) { wpa_printf(MSG_DEBUG, "DPP: Peer did not include Status"); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_INTRO "peer=" MACSTR " fail=missing_status", MAC2STR(src)); goto fail; } if (status[0] != DPP_STATUS_OK) { wpa_printf(MSG_DEBUG, "DPP: Peer rejected network introduction: Status %u", status[0]); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_INTRO "peer=" MACSTR " status=%u", MAC2STR(src), status[0]); goto fail; } connector = dpp_get_attr(buf, len, DPP_ATTR_CONNECTOR, &connector_len); if (!connector) { wpa_printf(MSG_DEBUG, "DPP: Peer did not include its Connector"); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_INTRO "peer=" MACSTR " fail=missing_connector", MAC2STR(src)); goto fail; } res = dpp_peer_intro(&intro, ssid->dpp_connector, ssid->dpp_netaccesskey, ssid->dpp_netaccesskey_len, ssid->dpp_csign, ssid->dpp_csign_len, connector, connector_len, &expiry); if (res != DPP_STATUS_OK) { wpa_printf(MSG_INFO, "DPP: Network Introduction protocol resulted in failure"); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_INTRO "peer=" MACSTR " fail=peer_connector_validation_failed", MAC2STR(src)); goto fail; } entry = os_zalloc(sizeof(*entry)); if (!entry) goto fail; os_memcpy(entry->aa, src, ETH_ALEN); os_memcpy(entry->pmkid, intro.pmkid, PMKID_LEN); os_memcpy(entry->pmk, intro.pmk, intro.pmk_len); entry->pmk_len = intro.pmk_len; entry->akmp = WPA_KEY_MGMT_DPP; if (expiry) { os_get_time(&now); seconds = expiry - now.sec; } else { seconds = 86400 * 7; } os_get_reltime(&rnow); entry->expiration = rnow.sec + seconds; entry->reauth_time = rnow.sec + seconds; entry->network_ctx = ssid; wpa_sm_pmksa_cache_add_entry(wpa_s->wpa, entry); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_INTRO "peer=" MACSTR " status=%u", MAC2STR(src), status[0]); wpa_printf(MSG_DEBUG, "DPP: Try connection again after successful network introduction"); if (wpa_supplicant_fast_associate(wpa_s) != 1) { wpa_supplicant_cancel_sched_scan(wpa_s); wpa_supplicant_req_scan(wpa_s, 0, 0); } fail: os_memset(&intro, 0, sizeof(intro)); } static int wpas_dpp_allow_ir(struct wpa_supplicant *wpa_s, unsigned int freq) { int i, j; if (!wpa_s->hw.modes) return -1; for (i = 0; i < wpa_s->hw.num_modes; i++) { struct hostapd_hw_modes *mode = &wpa_s->hw.modes[i]; for (j = 0; j < mode->num_channels; j++) { struct hostapd_channel_data *chan = &mode->channels[j]; if (chan->freq != (int) freq) continue; if (chan->flag & (HOSTAPD_CHAN_DISABLED | HOSTAPD_CHAN_NO_IR | HOSTAPD_CHAN_RADAR)) continue; return 1; } } wpa_printf(MSG_DEBUG, "DPP: Frequency %u MHz not supported or does not allow PKEX initiation in the current channel list", freq); return 0; } static int wpas_dpp_pkex_next_channel(struct wpa_supplicant *wpa_s, struct dpp_pkex *pkex) { if (pkex->freq == 2437) pkex->freq = 5745; else if (pkex->freq == 5745) pkex->freq = 5220; else if (pkex->freq == 5220) pkex->freq = 60480; else return -1; /* no more channels to try */ if (wpas_dpp_allow_ir(wpa_s, pkex->freq) == 1) { wpa_printf(MSG_DEBUG, "DPP: Try to initiate on %u MHz", pkex->freq); return 0; } /* Could not use this channel - try the next one */ return wpas_dpp_pkex_next_channel(wpa_s, pkex); } static void wpas_dpp_pkex_retry_timeout(void *eloop_ctx, void *timeout_ctx) { struct wpa_supplicant *wpa_s = eloop_ctx; struct dpp_pkex *pkex = wpa_s->dpp_pkex; if (!pkex || !pkex->exchange_req) return; if (pkex->exch_req_tries >= 5) { if (wpas_dpp_pkex_next_channel(wpa_s, pkex) < 0) { wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_FAIL "No response from PKEX peer"); dpp_pkex_free(pkex); wpa_s->dpp_pkex = NULL; return; } pkex->exch_req_tries = 0; } pkex->exch_req_tries++; wpa_printf(MSG_DEBUG, "DPP: Retransmit PKEX Exchange Request (try %u)", pkex->exch_req_tries); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX "dst=" MACSTR " freq=%u type=%d", MAC2STR(broadcast), pkex->freq, DPP_PA_PKEX_EXCHANGE_REQ); offchannel_send_action(wpa_s, pkex->freq, broadcast, wpa_s->own_addr, broadcast, wpabuf_head(pkex->exchange_req), wpabuf_len(pkex->exchange_req), pkex->exch_req_wait_time, wpas_dpp_tx_pkex_status, 0); } static void wpas_dpp_tx_pkex_status(struct wpa_supplicant *wpa_s, unsigned int freq, const u8 *dst, const u8 *src, const u8 *bssid, const u8 *data, size_t data_len, enum offchannel_send_action_result result) { const char *res_txt; struct dpp_pkex *pkex = wpa_s->dpp_pkex; res_txt = result == OFFCHANNEL_SEND_ACTION_SUCCESS ? "SUCCESS" : (result == OFFCHANNEL_SEND_ACTION_NO_ACK ? "no-ACK" : "FAILED"); wpa_printf(MSG_DEBUG, "DPP: TX status: freq=%u dst=" MACSTR " result=%s (PKEX)", freq, MAC2STR(dst), res_txt); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX_STATUS "dst=" MACSTR " freq=%u result=%s", MAC2STR(dst), freq, res_txt); if (!pkex) { wpa_printf(MSG_DEBUG, "DPP: Ignore TX status since there is no ongoing PKEX exchange"); return; } if (pkex->failed) { wpa_printf(MSG_DEBUG, "DPP: Terminate PKEX exchange due to an earlier error"); if (pkex->t > pkex->own_bi->pkex_t) pkex->own_bi->pkex_t = pkex->t; dpp_pkex_free(pkex); wpa_s->dpp_pkex = NULL; return; } if (pkex->exch_req_wait_time && pkex->exchange_req) { /* Wait for PKEX Exchange Response frame and retry request if * no response is seen. */ eloop_cancel_timeout(wpas_dpp_pkex_retry_timeout, wpa_s, NULL); eloop_register_timeout(pkex->exch_req_wait_time / 1000, (pkex->exch_req_wait_time % 1000) * 1000, wpas_dpp_pkex_retry_timeout, wpa_s, NULL); } } static void wpas_dpp_rx_pkex_exchange_req(struct wpa_supplicant *wpa_s, const u8 *src, const u8 *buf, size_t len, unsigned int freq) { struct wpabuf *msg; unsigned int wait_time; wpa_printf(MSG_DEBUG, "DPP: PKEX Exchange Request from " MACSTR, MAC2STR(src)); /* TODO: Support multiple PKEX codes by iterating over all the enabled * values here */ if (!wpa_s->dpp_pkex_code || !wpa_s->dpp_pkex_bi) { wpa_printf(MSG_DEBUG, "DPP: No PKEX code configured - ignore request"); return; } if (wpa_s->dpp_pkex) { /* TODO: Support parallel operations */ wpa_printf(MSG_DEBUG, "DPP: Already in PKEX session - ignore new request"); return; } wpa_s->dpp_pkex = dpp_pkex_rx_exchange_req(wpa_s, wpa_s->dpp_pkex_bi, wpa_s->own_addr, src, wpa_s->dpp_pkex_identifier, wpa_s->dpp_pkex_code, buf, len); if (!wpa_s->dpp_pkex) { wpa_printf(MSG_DEBUG, "DPP: Failed to process the request - ignore it"); return; } msg = wpa_s->dpp_pkex->exchange_resp; wait_time = wpa_s->max_remain_on_chan; if (wait_time > 2000) wait_time = 2000; wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX "dst=" MACSTR " freq=%u type=%d", MAC2STR(src), freq, DPP_PA_PKEX_EXCHANGE_RESP); offchannel_send_action(wpa_s, freq, src, wpa_s->own_addr, broadcast, wpabuf_head(msg), wpabuf_len(msg), wait_time, wpas_dpp_tx_pkex_status, 0); } static void wpas_dpp_rx_pkex_exchange_resp(struct wpa_supplicant *wpa_s, const u8 *src, const u8 *buf, size_t len, unsigned int freq) { struct wpabuf *msg; unsigned int wait_time; wpa_printf(MSG_DEBUG, "DPP: PKEX Exchange Response from " MACSTR, MAC2STR(src)); /* TODO: Support multiple PKEX codes by iterating over all the enabled * values here */ if (!wpa_s->dpp_pkex || !wpa_s->dpp_pkex->initiator || wpa_s->dpp_pkex->exchange_done) { wpa_printf(MSG_DEBUG, "DPP: No matching PKEX session"); return; } eloop_cancel_timeout(wpas_dpp_pkex_retry_timeout, wpa_s, NULL); wpa_s->dpp_pkex->exch_req_wait_time = 0; msg = dpp_pkex_rx_exchange_resp(wpa_s->dpp_pkex, src, buf, len); if (!msg) { wpa_printf(MSG_DEBUG, "DPP: Failed to process the response"); return; } wpa_printf(MSG_DEBUG, "DPP: Send PKEX Commit-Reveal Request to " MACSTR, MAC2STR(src)); wait_time = wpa_s->max_remain_on_chan; if (wait_time > 2000) wait_time = 2000; wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX "dst=" MACSTR " freq=%u type=%d", MAC2STR(src), freq, DPP_PA_PKEX_COMMIT_REVEAL_REQ); offchannel_send_action(wpa_s, freq, src, wpa_s->own_addr, broadcast, wpabuf_head(msg), wpabuf_len(msg), wait_time, wpas_dpp_tx_pkex_status, 0); wpabuf_free(msg); } static struct dpp_bootstrap_info * wpas_dpp_pkex_finish(struct wpa_supplicant *wpa_s, const u8 *peer, unsigned int freq) { struct dpp_bootstrap_info *bi; bi = dpp_pkex_finish(wpa_s->dpp, wpa_s->dpp_pkex, peer, freq); if (!bi) return NULL; wpa_s->dpp_pkex = NULL; return bi; } static void wpas_dpp_rx_pkex_commit_reveal_req(struct wpa_supplicant *wpa_s, const u8 *src, const u8 *hdr, const u8 *buf, size_t len, unsigned int freq) { struct wpabuf *msg; unsigned int wait_time; struct dpp_pkex *pkex = wpa_s->dpp_pkex; wpa_printf(MSG_DEBUG, "DPP: PKEX Commit-Reveal Request from " MACSTR, MAC2STR(src)); if (!pkex || pkex->initiator || !pkex->exchange_done) { wpa_printf(MSG_DEBUG, "DPP: No matching PKEX session"); return; } msg = dpp_pkex_rx_commit_reveal_req(pkex, hdr, buf, len); if (!msg) { wpa_printf(MSG_DEBUG, "DPP: Failed to process the request"); if (pkex->failed) { wpa_printf(MSG_DEBUG, "DPP: Terminate PKEX exchange"); if (pkex->t > pkex->own_bi->pkex_t) pkex->own_bi->pkex_t = pkex->t; dpp_pkex_free(wpa_s->dpp_pkex); wpa_s->dpp_pkex = NULL; } return; } wpa_printf(MSG_DEBUG, "DPP: Send PKEX Commit-Reveal Response to " MACSTR, MAC2STR(src)); wait_time = wpa_s->max_remain_on_chan; if (wait_time > 2000) wait_time = 2000; wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX "dst=" MACSTR " freq=%u type=%d", MAC2STR(src), freq, DPP_PA_PKEX_COMMIT_REVEAL_RESP); offchannel_send_action(wpa_s, freq, src, wpa_s->own_addr, broadcast, wpabuf_head(msg), wpabuf_len(msg), wait_time, wpas_dpp_tx_pkex_status, 0); wpabuf_free(msg); wpas_dpp_pkex_finish(wpa_s, src, freq); } static void wpas_dpp_rx_pkex_commit_reveal_resp(struct wpa_supplicant *wpa_s, const u8 *src, const u8 *hdr, const u8 *buf, size_t len, unsigned int freq) { int res; struct dpp_bootstrap_info *bi; struct dpp_pkex *pkex = wpa_s->dpp_pkex; char cmd[500]; wpa_printf(MSG_DEBUG, "DPP: PKEX Commit-Reveal Response from " MACSTR, MAC2STR(src)); if (!pkex || !pkex->initiator || !pkex->exchange_done) { wpa_printf(MSG_DEBUG, "DPP: No matching PKEX session"); return; } res = dpp_pkex_rx_commit_reveal_resp(pkex, hdr, buf, len); if (res < 0) { wpa_printf(MSG_DEBUG, "DPP: Failed to process the response"); return; } bi = wpas_dpp_pkex_finish(wpa_s, src, freq); if (!bi) return; os_snprintf(cmd, sizeof(cmd), " peer=%u %s", bi->id, wpa_s->dpp_pkex_auth_cmd ? wpa_s->dpp_pkex_auth_cmd : ""); wpa_printf(MSG_DEBUG, "DPP: Start authentication after PKEX with parameters: %s", cmd); if (wpas_dpp_auth_init(wpa_s, cmd) < 0) { wpa_printf(MSG_DEBUG, "DPP: Authentication initialization failed"); return; } } void wpas_dpp_rx_action(struct wpa_supplicant *wpa_s, const u8 *src, const u8 *buf, size_t len, unsigned int freq) { u8 crypto_suite; enum dpp_public_action_frame_type type; const u8 *hdr; unsigned int pkex_t; if (len < DPP_HDR_LEN) return; if (WPA_GET_BE24(buf) != OUI_WFA || buf[3] != DPP_OUI_TYPE) return; hdr = buf; buf += 4; len -= 4; crypto_suite = *buf++; type = *buf++; len -= 2; wpa_printf(MSG_DEBUG, "DPP: Received DPP Public Action frame crypto suite %u type %d from " MACSTR " freq=%u", crypto_suite, type, MAC2STR(src), freq); if (crypto_suite != 1) { wpa_printf(MSG_DEBUG, "DPP: Unsupported crypto suite %u", crypto_suite); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_RX "src=" MACSTR " freq=%u type=%d ignore=unsupported-crypto-suite", MAC2STR(src), freq, type); return; } wpa_hexdump(MSG_MSGDUMP, "DPP: Received message attributes", buf, len); if (dpp_check_attrs(buf, len) < 0) { wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_RX "src=" MACSTR " freq=%u type=%d ignore=invalid-attributes", MAC2STR(src), freq, type); return; } wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_RX "src=" MACSTR " freq=%u type=%d", MAC2STR(src), freq, type); switch (type) { case DPP_PA_AUTHENTICATION_REQ: wpas_dpp_rx_auth_req(wpa_s, src, hdr, buf, len, freq); break; case DPP_PA_AUTHENTICATION_RESP: wpas_dpp_rx_auth_resp(wpa_s, src, hdr, buf, len, freq); break; case DPP_PA_AUTHENTICATION_CONF: wpas_dpp_rx_auth_conf(wpa_s, src, hdr, buf, len); break; case DPP_PA_PEER_DISCOVERY_RESP: wpas_dpp_rx_peer_disc_resp(wpa_s, src, buf, len); break; case DPP_PA_PKEX_EXCHANGE_REQ: wpas_dpp_rx_pkex_exchange_req(wpa_s, src, buf, len, freq); break; case DPP_PA_PKEX_EXCHANGE_RESP: wpas_dpp_rx_pkex_exchange_resp(wpa_s, src, buf, len, freq); break; case DPP_PA_PKEX_COMMIT_REVEAL_REQ: wpas_dpp_rx_pkex_commit_reveal_req(wpa_s, src, hdr, buf, len, freq); break; case DPP_PA_PKEX_COMMIT_REVEAL_RESP: wpas_dpp_rx_pkex_commit_reveal_resp(wpa_s, src, hdr, buf, len, freq); break; #ifdef CONFIG_DPP2 case DPP_PA_CONFIGURATION_RESULT: wpas_dpp_rx_conf_result(wpa_s, src, hdr, buf, len); break; #endif /* CONFIG_DPP2 */ default: wpa_printf(MSG_DEBUG, "DPP: Ignored unsupported frame subtype %d", type); break; } if (wpa_s->dpp_pkex) pkex_t = wpa_s->dpp_pkex->t; else if (wpa_s->dpp_pkex_bi) pkex_t = wpa_s->dpp_pkex_bi->pkex_t; else pkex_t = 0; if (pkex_t >= PKEX_COUNTER_T_LIMIT) { wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_PKEX_T_LIMIT "id=0"); wpas_dpp_pkex_remove(wpa_s, "*"); } } static struct wpabuf * wpas_dpp_gas_req_handler(void *ctx, const u8 *sa, const u8 *query, size_t query_len) { struct wpa_supplicant *wpa_s = ctx; struct dpp_authentication *auth = wpa_s->dpp_auth; struct wpabuf *resp; wpa_printf(MSG_DEBUG, "DPP: GAS request from " MACSTR, MAC2STR(sa)); if (!auth || !auth->auth_success || os_memcmp(sa, auth->peer_mac_addr, ETH_ALEN) != 0) { wpa_printf(MSG_DEBUG, "DPP: No matching exchange in progress"); return NULL; } if (wpa_s->dpp_auth_ok_on_ack && auth->configurator) { wpa_printf(MSG_DEBUG, "DPP: Have not received ACK for Auth Confirm yet - assume it was received based on this GAS request"); /* wpas_dpp_auth_success() would normally have been called from * TX status handler, but since there was no such handler call * yet, simply send out the event message and proceed with * exchange. */ wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_AUTH_SUCCESS "init=1"); wpa_s->dpp_auth_ok_on_ack = 0; } wpa_hexdump(MSG_DEBUG, "DPP: Received Configuration Request (GAS Query Request)", query, query_len); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_CONF_REQ_RX "src=" MACSTR, MAC2STR(sa)); resp = dpp_conf_req_rx(auth, query, query_len); if (!resp) wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_CONF_FAILED); auth->conf_resp = resp; return resp; } static void wpas_dpp_gas_status_handler(void *ctx, struct wpabuf *resp, int ok) { struct wpa_supplicant *wpa_s = ctx; struct dpp_authentication *auth = wpa_s->dpp_auth; if (!auth) { wpabuf_free(resp); return; } if (auth->conf_resp != resp) { wpa_printf(MSG_DEBUG, "DPP: Ignore GAS status report (ok=%d) for unknown response", ok); wpabuf_free(resp); return; } wpa_printf(MSG_DEBUG, "DPP: Configuration exchange completed (ok=%d)", ok); eloop_cancel_timeout(wpas_dpp_reply_wait_timeout, wpa_s, NULL); eloop_cancel_timeout(wpas_dpp_auth_resp_retry_timeout, wpa_s, NULL); #ifdef CONFIG_DPP2 if (ok && auth->peer_version >= 2 && auth->conf_resp_status == DPP_STATUS_OK) { wpa_printf(MSG_DEBUG, "DPP: Wait for Configuration Result"); auth->waiting_conf_result = 1; auth->conf_resp = NULL; wpabuf_free(resp); eloop_cancel_timeout(wpas_dpp_config_result_wait_timeout, wpa_s, NULL); eloop_register_timeout(2, 0, wpas_dpp_config_result_wait_timeout, wpa_s, NULL); return; } #endif /* CONFIG_DPP2 */ offchannel_send_action_done(wpa_s); wpas_dpp_listen_stop(wpa_s); if (ok) wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_CONF_SENT); else wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_CONF_FAILED); dpp_auth_deinit(wpa_s->dpp_auth); wpa_s->dpp_auth = NULL; wpabuf_free(resp); } int wpas_dpp_configurator_sign(struct wpa_supplicant *wpa_s, const char *cmd) { struct dpp_authentication *auth; int ret = -1; char *curve = NULL; auth = os_zalloc(sizeof(*auth)); if (!auth) return -1; curve = get_param(cmd, " curve="); wpas_dpp_set_testing_options(wpa_s, auth); if (dpp_set_configurator(wpa_s->dpp, wpa_s, auth, cmd) == 0 && dpp_configurator_own_config(auth, curve, 0) == 0) ret = wpas_dpp_handle_config_obj(wpa_s, auth); dpp_auth_deinit(auth); os_free(curve); return ret; } static void wpas_dpp_tx_introduction_status(struct wpa_supplicant *wpa_s, unsigned int freq, const u8 *dst, const u8 *src, const u8 *bssid, const u8 *data, size_t data_len, enum offchannel_send_action_result result) { const char *res_txt; res_txt = result == OFFCHANNEL_SEND_ACTION_SUCCESS ? "SUCCESS" : (result == OFFCHANNEL_SEND_ACTION_NO_ACK ? "no-ACK" : "FAILED"); wpa_printf(MSG_DEBUG, "DPP: TX status: freq=%u dst=" MACSTR " result=%s (DPP Peer Discovery Request)", freq, MAC2STR(dst), res_txt); wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX_STATUS "dst=" MACSTR " freq=%u result=%s", MAC2STR(dst), freq, res_txt); /* TODO: Time out wait for response more quickly in error cases? */ } int wpas_dpp_check_connect(struct wpa_supplicant *wpa_s, struct wpa_ssid *ssid, struct wpa_bss *bss) { struct os_time now; struct wpabuf *msg; unsigned int wait_time; const u8 *rsn; struct wpa_ie_data ied; if (!(ssid->key_mgmt & WPA_KEY_MGMT_DPP) || !bss) return 0; /* Not using DPP AKM - continue */ rsn = wpa_bss_get_ie(bss, WLAN_EID_RSN); if (rsn && wpa_parse_wpa_ie(rsn, 2 + rsn[1], &ied) == 0 && !(ied.key_mgmt & WPA_KEY_MGMT_DPP)) return 0; /* AP does not support DPP AKM - continue */ if (wpa_sm_pmksa_exists(wpa_s->wpa, bss->bssid, ssid)) return 0; /* PMKSA exists for DPP AKM - continue */ if (!ssid->dpp_connector || !ssid->dpp_netaccesskey || !ssid->dpp_csign) { wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_MISSING_CONNECTOR "missing %s", !ssid->dpp_connector ? "Connector" : (!ssid->dpp_netaccesskey ? "netAccessKey" : "C-sign-key")); return -1; } os_get_time(&now); if (ssid->dpp_netaccesskey_expiry && (os_time_t) ssid->dpp_netaccesskey_expiry < now.sec) { wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_MISSING_CONNECTOR "netAccessKey expired"); return -1; } wpa_printf(MSG_DEBUG, "DPP: Starting network introduction protocol to derive PMKSA for " MACSTR, MAC2STR(bss->bssid)); msg = dpp_alloc_msg(DPP_PA_PEER_DISCOVERY_REQ, 5 + 4 + os_strlen(ssid->dpp_connector)); if (!msg) return -1; #ifdef CONFIG_TESTING_OPTIONS if (dpp_test == DPP_TEST_NO_TRANSACTION_ID_PEER_DISC_REQ) { wpa_printf(MSG_INFO, "DPP: TESTING - no Transaction ID"); goto skip_trans_id; } if (dpp_test == DPP_TEST_INVALID_TRANSACTION_ID_PEER_DISC_REQ) { wpa_printf(MSG_INFO, "DPP: TESTING - invalid Transaction ID"); wpabuf_put_le16(msg, DPP_ATTR_TRANSACTION_ID); wpabuf_put_le16(msg, 0); goto skip_trans_id; } #endif /* CONFIG_TESTING_OPTIONS */ /* Transaction ID */ wpabuf_put_le16(msg, DPP_ATTR_TRANSACTION_ID); wpabuf_put_le16(msg, 1); wpabuf_put_u8(msg, TRANSACTION_ID); #ifdef CONFIG_TESTING_OPTIONS skip_trans_id: if (dpp_test == DPP_TEST_NO_CONNECTOR_PEER_DISC_REQ) { wpa_printf(MSG_INFO, "DPP: TESTING - no Connector"); goto skip_connector; } if (dpp_test == DPP_TEST_INVALID_CONNECTOR_PEER_DISC_REQ) { char *connector; wpa_printf(MSG_INFO, "DPP: TESTING - invalid Connector"); connector = dpp_corrupt_connector_signature( ssid->dpp_connector); if (!connector) { wpabuf_free(msg); return -1; } wpabuf_put_le16(msg, DPP_ATTR_CONNECTOR); wpabuf_put_le16(msg, os_strlen(connector)); wpabuf_put_str(msg, connector); os_free(connector); goto skip_connector; } #endif /* CONFIG_TESTING_OPTIONS */ /* DPP Connector */ wpabuf_put_le16(msg, DPP_ATTR_CONNECTOR); wpabuf_put_le16(msg, os_strlen(ssid->dpp_connector)); wpabuf_put_str(msg, ssid->dpp_connector); #ifdef CONFIG_TESTING_OPTIONS skip_connector: #endif /* CONFIG_TESTING_OPTIONS */ /* TODO: Timeout on AP response */ wait_time = wpa_s->max_remain_on_chan; if (wait_time > 2000) wait_time = 2000; wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX "dst=" MACSTR " freq=%u type=%d", MAC2STR(bss->bssid), bss->freq, DPP_PA_PEER_DISCOVERY_REQ); offchannel_send_action(wpa_s, bss->freq, bss->bssid, wpa_s->own_addr, broadcast, wpabuf_head(msg), wpabuf_len(msg), wait_time, wpas_dpp_tx_introduction_status, 0); wpabuf_free(msg); /* Request this connection attempt to terminate - new one will be * started when network introduction protocol completes */ os_memcpy(wpa_s->dpp_intro_bssid, bss->bssid, ETH_ALEN); wpa_s->dpp_intro_network = ssid; return 1; } int wpas_dpp_pkex_add(struct wpa_supplicant *wpa_s, const char *cmd) { struct dpp_bootstrap_info *own_bi; const char *pos, *end; unsigned int wait_time; pos = os_strstr(cmd, " own="); if (!pos) return -1; pos += 5; own_bi = dpp_bootstrap_get_id(wpa_s->dpp, atoi(pos)); if (!own_bi) { wpa_printf(MSG_DEBUG, "DPP: Identified bootstrap info not found"); return -1; } if (own_bi->type != DPP_BOOTSTRAP_PKEX) { wpa_printf(MSG_DEBUG, "DPP: Identified bootstrap info not for PKEX"); return -1; } wpa_s->dpp_pkex_bi = own_bi; own_bi->pkex_t = 0; /* clear pending errors on new code */ os_free(wpa_s->dpp_pkex_identifier); wpa_s->dpp_pkex_identifier = NULL; pos = os_strstr(cmd, " identifier="); if (pos) { pos += 12; end = os_strchr(pos, ' '); if (!end) return -1; wpa_s->dpp_pkex_identifier = os_malloc(end - pos + 1); if (!wpa_s->dpp_pkex_identifier) return -1; os_memcpy(wpa_s->dpp_pkex_identifier, pos, end - pos); wpa_s->dpp_pkex_identifier[end - pos] = '\0'; } pos = os_strstr(cmd, " code="); if (!pos) return -1; os_free(wpa_s->dpp_pkex_code); wpa_s->dpp_pkex_code = os_strdup(pos + 6); if (!wpa_s->dpp_pkex_code) return -1; if (os_strstr(cmd, " init=1")) { struct dpp_pkex *pkex; struct wpabuf *msg; wpa_printf(MSG_DEBUG, "DPP: Initiating PKEX"); dpp_pkex_free(wpa_s->dpp_pkex); wpa_s->dpp_pkex = dpp_pkex_init(wpa_s, own_bi, wpa_s->own_addr, wpa_s->dpp_pkex_identifier, wpa_s->dpp_pkex_code); pkex = wpa_s->dpp_pkex; if (!pkex) return -1; msg = pkex->exchange_req; wait_time = wpa_s->max_remain_on_chan; if (wait_time > 2000) wait_time = 2000; pkex->freq = 2437; wpa_msg(wpa_s, MSG_INFO, DPP_EVENT_TX "dst=" MACSTR " freq=%u type=%d", MAC2STR(broadcast), pkex->freq, DPP_PA_PKEX_EXCHANGE_REQ); offchannel_send_action(wpa_s, pkex->freq, broadcast, wpa_s->own_addr, broadcast, wpabuf_head(msg), wpabuf_len(msg), wait_time, wpas_dpp_tx_pkex_status, 0); if (wait_time == 0) wait_time = 2000; pkex->exch_req_wait_time = wait_time; pkex->exch_req_tries = 1; } /* TODO: Support multiple PKEX info entries */ os_free(wpa_s->dpp_pkex_auth_cmd); wpa_s->dpp_pkex_auth_cmd = os_strdup(cmd); return 1; } int wpas_dpp_pkex_remove(struct wpa_supplicant *wpa_s, const char *id) { unsigned int id_val; if (os_strcmp(id, "*") == 0) { id_val = 0; } else { id_val = atoi(id); if (id_val == 0) return -1; } if ((id_val != 0 && id_val != 1) || !wpa_s->dpp_pkex_code) return -1; /* TODO: Support multiple PKEX entries */ os_free(wpa_s->dpp_pkex_code); wpa_s->dpp_pkex_code = NULL; os_free(wpa_s->dpp_pkex_identifier); wpa_s->dpp_pkex_identifier = NULL; os_free(wpa_s->dpp_pkex_auth_cmd); wpa_s->dpp_pkex_auth_cmd = NULL; wpa_s->dpp_pkex_bi = NULL; /* TODO: Remove dpp_pkex only if it is for the identified PKEX code */ dpp_pkex_free(wpa_s->dpp_pkex); wpa_s->dpp_pkex = NULL; return 0; } void wpas_dpp_stop(struct wpa_supplicant *wpa_s) { dpp_auth_deinit(wpa_s->dpp_auth); wpa_s->dpp_auth = NULL; dpp_pkex_free(wpa_s->dpp_pkex); wpa_s->dpp_pkex = NULL; if (wpa_s->dpp_gas_client && wpa_s->dpp_gas_dialog_token >= 0) gas_query_stop(wpa_s->gas, wpa_s->dpp_gas_dialog_token); } int wpas_dpp_init(struct wpa_supplicant *wpa_s) { struct dpp_global_config config; u8 adv_proto_id[7]; adv_proto_id[0] = WLAN_EID_VENDOR_SPECIFIC; adv_proto_id[1] = 5; WPA_PUT_BE24(&adv_proto_id[2], OUI_WFA); adv_proto_id[5] = DPP_OUI_TYPE; adv_proto_id[6] = 0x01; if (gas_server_register(wpa_s->gas_server, adv_proto_id, sizeof(adv_proto_id), wpas_dpp_gas_req_handler, wpas_dpp_gas_status_handler, wpa_s) < 0) return -1; os_memset(&config, 0, sizeof(config)); config.msg_ctx = wpa_s; config.cb_ctx = wpa_s; #ifdef CONFIG_DPP2 config.process_conf_obj = wpas_dpp_process_conf_obj; #endif /* CONFIG_DPP2 */ wpa_s->dpp = dpp_global_init(&config); return wpa_s->dpp ? 0 : -1; } void wpas_dpp_deinit(struct wpa_supplicant *wpa_s) { #ifdef CONFIG_TESTING_OPTIONS os_free(wpa_s->dpp_config_obj_override); wpa_s->dpp_config_obj_override = NULL; os_free(wpa_s->dpp_discovery_override); wpa_s->dpp_discovery_override = NULL; os_free(wpa_s->dpp_groups_override); wpa_s->dpp_groups_override = NULL; wpa_s->dpp_ignore_netaccesskey_mismatch = 0; #endif /* CONFIG_TESTING_OPTIONS */ if (!wpa_s->dpp) return; dpp_global_clear(wpa_s->dpp); eloop_cancel_timeout(wpas_dpp_pkex_retry_timeout, wpa_s, NULL); eloop_cancel_timeout(wpas_dpp_reply_wait_timeout, wpa_s, NULL); eloop_cancel_timeout(wpas_dpp_init_timeout, wpa_s, NULL); eloop_cancel_timeout(wpas_dpp_auth_resp_retry_timeout, wpa_s, NULL); #ifdef CONFIG_DPP2 eloop_cancel_timeout(wpas_dpp_config_result_wait_timeout, wpa_s, NULL); dpp_pfs_free(wpa_s->dpp_pfs); wpa_s->dpp_pfs = NULL; #endif /* CONFIG_DPP2 */ offchannel_send_action_done(wpa_s); wpas_dpp_listen_stop(wpa_s); wpas_dpp_stop(wpa_s); wpas_dpp_pkex_remove(wpa_s, "*"); os_memset(wpa_s->dpp_intro_bssid, 0, ETH_ALEN); os_free(wpa_s->dpp_configurator_params); wpa_s->dpp_configurator_params = NULL; } #ifdef CONFIG_DPP2 int wpas_dpp_controller_start(struct wpa_supplicant *wpa_s, const char *cmd) { struct dpp_controller_config config; const char *pos; os_memset(&config, 0, sizeof(config)); if (cmd) { pos = os_strstr(cmd, " tcp_port="); if (pos) { pos += 10; config.tcp_port = atoi(pos); } } config.configurator_params = wpa_s->dpp_configurator_params; return dpp_controller_start(wpa_s->dpp, &config); } #endif /* CONFIG_DPP2 */
{ "pile_set_name": "Github" }
seeds OK
{ "pile_set_name": "Github" }
/* * Copyright (c) 2007-2011 Atheros Communications Inc. * Copyright (c) 2011-2012 Qualcomm Atheros, Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "hif.h" #include <linux/export.h> #include "core.h" #include "target.h" #include "hif-ops.h" #include "debug.h" #define MAILBOX_FOR_BLOCK_SIZE 1 #define ATH6KL_TIME_QUANTUM 10 /* in ms */ static int ath6kl_hif_cp_scat_dma_buf(struct hif_scatter_req *req, bool from_dma) { u8 *buf; int i; buf = req->virt_dma_buf; for (i = 0; i < req->scat_entries; i++) { if (from_dma) memcpy(req->scat_list[i].buf, buf, req->scat_list[i].len); else memcpy(buf, req->scat_list[i].buf, req->scat_list[i].len); buf += req->scat_list[i].len; } return 0; } int ath6kl_hif_rw_comp_handler(void *context, int status) { struct htc_packet *packet = context; ath6kl_dbg(ATH6KL_DBG_HIF, "hif rw completion pkt 0x%p status %d\n", packet, status); packet->status = status; packet->completion(packet->context, packet); return 0; } EXPORT_SYMBOL(ath6kl_hif_rw_comp_handler); #define REG_DUMP_COUNT_AR6003 60 #define REGISTER_DUMP_LEN_MAX 60 static void ath6kl_hif_dump_fw_crash(struct ath6kl *ar) { __le32 regdump_val[REGISTER_DUMP_LEN_MAX]; u32 i, address, regdump_addr = 0; int ret; if (ar->target_type != TARGET_TYPE_AR6003) return; /* the reg dump pointer is copied to the host interest area */ address = ath6kl_get_hi_item_addr(ar, HI_ITEM(hi_failure_state)); address = TARG_VTOP(ar->target_type, address); /* read RAM location through diagnostic window */ ret = ath6kl_diag_read32(ar, address, &regdump_addr); if (ret || !regdump_addr) { ath6kl_warn("failed to get ptr to register dump area: %d\n", ret); return; } ath6kl_dbg(ATH6KL_DBG_IRQ, "register dump data address 0x%x\n", regdump_addr); regdump_addr = TARG_VTOP(ar->target_type, regdump_addr); /* fetch register dump data */ ret = ath6kl_diag_read(ar, regdump_addr, (u8 *)&regdump_val[0], REG_DUMP_COUNT_AR6003 * (sizeof(u32))); if (ret) { ath6kl_warn("failed to get register dump: %d\n", ret); return; } ath6kl_info("crash dump:\n"); ath6kl_info("hw 0x%x fw %s\n", ar->wiphy->hw_version, ar->wiphy->fw_version); BUILD_BUG_ON(REG_DUMP_COUNT_AR6003 % 4); for (i = 0; i < REG_DUMP_COUNT_AR6003; i += 4) { ath6kl_info("%d: 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x\n", i, le32_to_cpu(regdump_val[i]), le32_to_cpu(regdump_val[i + 1]), le32_to_cpu(regdump_val[i + 2]), le32_to_cpu(regdump_val[i + 3])); } } static int ath6kl_hif_proc_dbg_intr(struct ath6kl_device *dev) { u32 dummy; int ret; ath6kl_warn("firmware crashed\n"); /* * read counter to clear the interrupt, the debug error interrupt is * counter 0. */ ret = hif_read_write_sync(dev->ar, COUNT_DEC_ADDRESS, (u8 *)&dummy, 4, HIF_RD_SYNC_BYTE_INC); if (ret) ath6kl_warn("Failed to clear debug interrupt: %d\n", ret); ath6kl_hif_dump_fw_crash(dev->ar); ath6kl_read_fwlogs(dev->ar); return ret; } /* mailbox recv message polling */ int ath6kl_hif_poll_mboxmsg_rx(struct ath6kl_device *dev, u32 *lk_ahd, int timeout) { struct ath6kl_irq_proc_registers *rg; int status = 0, i; u8 htc_mbox = 1 << HTC_MAILBOX; for (i = timeout / ATH6KL_TIME_QUANTUM; i > 0; i--) { /* this is the standard HIF way, load the reg table */ status = hif_read_write_sync(dev->ar, HOST_INT_STATUS_ADDRESS, (u8 *) &dev->irq_proc_reg, sizeof(dev->irq_proc_reg), HIF_RD_SYNC_BYTE_INC); if (status) { ath6kl_err("failed to read reg table\n"); return status; } /* check for MBOX data and valid lookahead */ if (dev->irq_proc_reg.host_int_status & htc_mbox) { if (dev->irq_proc_reg.rx_lkahd_valid & htc_mbox) { /* * Mailbox has a message and the look ahead * is valid. */ rg = &dev->irq_proc_reg; *lk_ahd = le32_to_cpu(rg->rx_lkahd[HTC_MAILBOX]); break; } } /* delay a little */ mdelay(ATH6KL_TIME_QUANTUM); ath6kl_dbg(ATH6KL_DBG_HIF, "hif retry mbox poll try %d\n", i); } if (i == 0) { ath6kl_err("timeout waiting for recv message\n"); status = -ETIME; /* check if the target asserted */ if (dev->irq_proc_reg.counter_int_status & ATH6KL_TARGET_DEBUG_INTR_MASK) /* * Target failure handler will be called in case of * an assert. */ ath6kl_hif_proc_dbg_intr(dev); } return status; } /* * Disable packet reception (used in case the host runs out of buffers) * using the interrupt enable registers through the host I/F */ int ath6kl_hif_rx_control(struct ath6kl_device *dev, bool enable_rx) { struct ath6kl_irq_enable_reg regs; int status = 0; ath6kl_dbg(ATH6KL_DBG_HIF, "hif rx %s\n", enable_rx ? "enable" : "disable"); /* take the lock to protect interrupt enable shadows */ spin_lock_bh(&dev->lock); if (enable_rx) dev->irq_en_reg.int_status_en |= SM(INT_STATUS_ENABLE_MBOX_DATA, 0x01); else dev->irq_en_reg.int_status_en &= ~SM(INT_STATUS_ENABLE_MBOX_DATA, 0x01); memcpy(&regs, &dev->irq_en_reg, sizeof(regs)); spin_unlock_bh(&dev->lock); status = hif_read_write_sync(dev->ar, INT_STATUS_ENABLE_ADDRESS, &regs.int_status_en, sizeof(struct ath6kl_irq_enable_reg), HIF_WR_SYNC_BYTE_INC); return status; } int ath6kl_hif_submit_scat_req(struct ath6kl_device *dev, struct hif_scatter_req *scat_req, bool read) { int status = 0; if (read) { scat_req->req = HIF_RD_SYNC_BLOCK_FIX; scat_req->addr = dev->ar->mbox_info.htc_addr; } else { scat_req->req = HIF_WR_ASYNC_BLOCK_INC; scat_req->addr = (scat_req->len > HIF_MBOX_WIDTH) ? dev->ar->mbox_info.htc_ext_addr : dev->ar->mbox_info.htc_addr; } ath6kl_dbg(ATH6KL_DBG_HIF, "hif submit scatter request entries %d len %d mbox 0x%x %s %s\n", scat_req->scat_entries, scat_req->len, scat_req->addr, !read ? "async" : "sync", (read) ? "rd" : "wr"); if (!read && scat_req->virt_scat) { status = ath6kl_hif_cp_scat_dma_buf(scat_req, false); if (status) { scat_req->status = status; scat_req->complete(dev->ar->htc_target, scat_req); return 0; } } status = ath6kl_hif_scat_req_rw(dev->ar, scat_req); if (read) { /* in sync mode, we can touch the scatter request */ scat_req->status = status; if (!status && scat_req->virt_scat) scat_req->status = ath6kl_hif_cp_scat_dma_buf(scat_req, true); } return status; } static int ath6kl_hif_proc_counter_intr(struct ath6kl_device *dev) { u8 counter_int_status; ath6kl_dbg(ATH6KL_DBG_IRQ, "counter interrupt\n"); counter_int_status = dev->irq_proc_reg.counter_int_status & dev->irq_en_reg.cntr_int_status_en; ath6kl_dbg(ATH6KL_DBG_IRQ, "valid interrupt source(s) in COUNTER_INT_STATUS: 0x%x\n", counter_int_status); /* * NOTE: other modules like GMBOX may use the counter interrupt for * credit flow control on other counters, we only need to check for * the debug assertion counter interrupt. */ if (counter_int_status & ATH6KL_TARGET_DEBUG_INTR_MASK) return ath6kl_hif_proc_dbg_intr(dev); return 0; } static int ath6kl_hif_proc_err_intr(struct ath6kl_device *dev) { int status; u8 error_int_status; u8 reg_buf[4]; ath6kl_dbg(ATH6KL_DBG_IRQ, "error interrupt\n"); error_int_status = dev->irq_proc_reg.error_int_status & 0x0F; if (!error_int_status) { WARN_ON(1); return -EIO; } ath6kl_dbg(ATH6KL_DBG_IRQ, "valid interrupt source(s) in ERROR_INT_STATUS: 0x%x\n", error_int_status); if (MS(ERROR_INT_STATUS_WAKEUP, error_int_status)) ath6kl_dbg(ATH6KL_DBG_IRQ, "error : wakeup\n"); if (MS(ERROR_INT_STATUS_RX_UNDERFLOW, error_int_status)) ath6kl_err("rx underflow\n"); if (MS(ERROR_INT_STATUS_TX_OVERFLOW, error_int_status)) ath6kl_err("tx overflow\n"); /* Clear the interrupt */ dev->irq_proc_reg.error_int_status &= ~error_int_status; /* set W1C value to clear the interrupt, this hits the register first */ reg_buf[0] = error_int_status; reg_buf[1] = 0; reg_buf[2] = 0; reg_buf[3] = 0; status = hif_read_write_sync(dev->ar, ERROR_INT_STATUS_ADDRESS, reg_buf, 4, HIF_WR_SYNC_BYTE_FIX); if (status) WARN_ON(1); return status; } static int ath6kl_hif_proc_cpu_intr(struct ath6kl_device *dev) { int status; u8 cpu_int_status; u8 reg_buf[4]; ath6kl_dbg(ATH6KL_DBG_IRQ, "cpu interrupt\n"); cpu_int_status = dev->irq_proc_reg.cpu_int_status & dev->irq_en_reg.cpu_int_status_en; if (!cpu_int_status) { WARN_ON(1); return -EIO; } ath6kl_dbg(ATH6KL_DBG_IRQ, "valid interrupt source(s) in CPU_INT_STATUS: 0x%x\n", cpu_int_status); /* Clear the interrupt */ dev->irq_proc_reg.cpu_int_status &= ~cpu_int_status; /* * Set up the register transfer buffer to hit the register 4 times , * this is done to make the access 4-byte aligned to mitigate issues * with host bus interconnects that restrict bus transfer lengths to * be a multiple of 4-bytes. */ /* set W1C value to clear the interrupt, this hits the register first */ reg_buf[0] = cpu_int_status; /* the remaining are set to zero which have no-effect */ reg_buf[1] = 0; reg_buf[2] = 0; reg_buf[3] = 0; status = hif_read_write_sync(dev->ar, CPU_INT_STATUS_ADDRESS, reg_buf, 4, HIF_WR_SYNC_BYTE_FIX); if (status) WARN_ON(1); return status; } /* process pending interrupts synchronously */ static int proc_pending_irqs(struct ath6kl_device *dev, bool *done) { struct ath6kl_irq_proc_registers *rg; int status = 0; u8 host_int_status = 0; u32 lk_ahd = 0; u8 htc_mbox = 1 << HTC_MAILBOX; ath6kl_dbg(ATH6KL_DBG_IRQ, "proc_pending_irqs: (dev: 0x%p)\n", dev); /* * NOTE: HIF implementation guarantees that the context of this * call allows us to perform SYNCHRONOUS I/O, that is we can block, * sleep or call any API that can block or switch thread/task * contexts. This is a fully schedulable context. */ /* * Process pending intr only when int_status_en is clear, it may * result in unnecessary bus transaction otherwise. Target may be * unresponsive at the time. */ if (dev->irq_en_reg.int_status_en) { /* * Read the first 28 bytes of the HTC register table. This * will yield us the value of different int status * registers and the lookahead registers. * * length = sizeof(int_status) + sizeof(cpu_int_status) * + sizeof(error_int_status) + * sizeof(counter_int_status) + * sizeof(mbox_frame) + sizeof(rx_lkahd_valid) * + sizeof(hole) + sizeof(rx_lkahd) + * sizeof(int_status_en) + * sizeof(cpu_int_status_en) + * sizeof(err_int_status_en) + * sizeof(cntr_int_status_en); */ status = hif_read_write_sync(dev->ar, HOST_INT_STATUS_ADDRESS, (u8 *) &dev->irq_proc_reg, sizeof(dev->irq_proc_reg), HIF_RD_SYNC_BYTE_INC); if (status) goto out; ath6kl_dump_registers(dev, &dev->irq_proc_reg, &dev->irq_en_reg); /* Update only those registers that are enabled */ host_int_status = dev->irq_proc_reg.host_int_status & dev->irq_en_reg.int_status_en; /* Look at mbox status */ if (host_int_status & htc_mbox) { /* * Mask out pending mbox value, we use "lookAhead as * the real flag for mbox processing. */ host_int_status &= ~htc_mbox; if (dev->irq_proc_reg.rx_lkahd_valid & htc_mbox) { rg = &dev->irq_proc_reg; lk_ahd = le32_to_cpu(rg->rx_lkahd[HTC_MAILBOX]); if (!lk_ahd) ath6kl_err("lookAhead is zero!\n"); } } } if (!host_int_status && !lk_ahd) { *done = true; goto out; } if (lk_ahd) { int fetched = 0; ath6kl_dbg(ATH6KL_DBG_IRQ, "pending mailbox msg, lk_ahd: 0x%X\n", lk_ahd); /* * Mailbox Interrupt, the HTC layer may issue async * requests to empty the mailbox. When emptying the recv * mailbox we use the async handler above called from the * completion routine of the callers read request. This can * improve performance by reducing context switching when * we rapidly pull packets. */ status = ath6kl_htc_rxmsg_pending_handler(dev->htc_cnxt, lk_ahd, &fetched); if (status) goto out; if (!fetched) /* * HTC could not pull any messages out due to lack * of resources. */ dev->htc_cnxt->chk_irq_status_cnt = 0; } /* now handle the rest of them */ ath6kl_dbg(ATH6KL_DBG_IRQ, "valid interrupt source(s) for other interrupts: 0x%x\n", host_int_status); if (MS(HOST_INT_STATUS_CPU, host_int_status)) { /* CPU Interrupt */ status = ath6kl_hif_proc_cpu_intr(dev); if (status) goto out; } if (MS(HOST_INT_STATUS_ERROR, host_int_status)) { /* Error Interrupt */ status = ath6kl_hif_proc_err_intr(dev); if (status) goto out; } if (MS(HOST_INT_STATUS_COUNTER, host_int_status)) /* Counter Interrupt */ status = ath6kl_hif_proc_counter_intr(dev); out: /* * An optimization to bypass reading the IRQ status registers * unecessarily which can re-wake the target, if upper layers * determine that we are in a low-throughput mode, we can rely on * taking another interrupt rather than re-checking the status * registers which can re-wake the target. * * NOTE : for host interfaces that makes use of detecting pending * mbox messages at hif can not use this optimization due to * possible side effects, SPI requires the host to drain all * messages from the mailbox before exiting the ISR routine. */ ath6kl_dbg(ATH6KL_DBG_IRQ, "bypassing irq status re-check, forcing done\n"); if (!dev->htc_cnxt->chk_irq_status_cnt) *done = true; ath6kl_dbg(ATH6KL_DBG_IRQ, "proc_pending_irqs: (done:%d, status=%d\n", *done, status); return status; } /* interrupt handler, kicks off all interrupt processing */ int ath6kl_hif_intr_bh_handler(struct ath6kl *ar) { struct ath6kl_device *dev = ar->htc_target->dev; unsigned long timeout; int status = 0; bool done = false; /* * Reset counter used to flag a re-scan of IRQ status registers on * the target. */ dev->htc_cnxt->chk_irq_status_cnt = 0; /* * IRQ processing is synchronous, interrupt status registers can be * re-read. */ timeout = jiffies + msecs_to_jiffies(ATH6KL_HIF_COMMUNICATION_TIMEOUT); while (time_before(jiffies, timeout) && !done) { status = proc_pending_irqs(dev, &done); if (status) break; } return status; } EXPORT_SYMBOL(ath6kl_hif_intr_bh_handler); static int ath6kl_hif_enable_intrs(struct ath6kl_device *dev) { struct ath6kl_irq_enable_reg regs; int status; spin_lock_bh(&dev->lock); /* Enable all but ATH6KL CPU interrupts */ dev->irq_en_reg.int_status_en = SM(INT_STATUS_ENABLE_ERROR, 0x01) | SM(INT_STATUS_ENABLE_CPU, 0x01) | SM(INT_STATUS_ENABLE_COUNTER, 0x01); /* * NOTE: There are some cases where HIF can do detection of * pending mbox messages which is disabled now. */ dev->irq_en_reg.int_status_en |= SM(INT_STATUS_ENABLE_MBOX_DATA, 0x01); /* Set up the CPU Interrupt status Register */ dev->irq_en_reg.cpu_int_status_en = 0; /* Set up the Error Interrupt status Register */ dev->irq_en_reg.err_int_status_en = SM(ERROR_STATUS_ENABLE_RX_UNDERFLOW, 0x01) | SM(ERROR_STATUS_ENABLE_TX_OVERFLOW, 0x1); /* * Enable Counter interrupt status register to get fatal errors for * debugging. */ dev->irq_en_reg.cntr_int_status_en = SM(COUNTER_INT_STATUS_ENABLE_BIT, ATH6KL_TARGET_DEBUG_INTR_MASK); memcpy(&regs, &dev->irq_en_reg, sizeof(regs)); spin_unlock_bh(&dev->lock); status = hif_read_write_sync(dev->ar, INT_STATUS_ENABLE_ADDRESS, &regs.int_status_en, sizeof(regs), HIF_WR_SYNC_BYTE_INC); if (status) ath6kl_err("failed to update interrupt ctl reg err: %d\n", status); return status; } int ath6kl_hif_disable_intrs(struct ath6kl_device *dev) { struct ath6kl_irq_enable_reg regs; spin_lock_bh(&dev->lock); /* Disable all interrupts */ dev->irq_en_reg.int_status_en = 0; dev->irq_en_reg.cpu_int_status_en = 0; dev->irq_en_reg.err_int_status_en = 0; dev->irq_en_reg.cntr_int_status_en = 0; memcpy(&regs, &dev->irq_en_reg, sizeof(regs)); spin_unlock_bh(&dev->lock); return hif_read_write_sync(dev->ar, INT_STATUS_ENABLE_ADDRESS, &regs.int_status_en, sizeof(regs), HIF_WR_SYNC_BYTE_INC); } /* enable device interrupts */ int ath6kl_hif_unmask_intrs(struct ath6kl_device *dev) { int status = 0; /* * Make sure interrupt are disabled before unmasking at the HIF * layer. The rationale here is that between device insertion * (where we clear the interrupts the first time) and when HTC * is finally ready to handle interrupts, other software can perform * target "soft" resets. The ATH6KL interrupt enables reset back to an * "enabled" state when this happens. */ ath6kl_hif_disable_intrs(dev); /* unmask the host controller interrupts */ ath6kl_hif_irq_enable(dev->ar); status = ath6kl_hif_enable_intrs(dev); return status; } /* disable all device interrupts */ int ath6kl_hif_mask_intrs(struct ath6kl_device *dev) { /* * Mask the interrupt at the HIF layer to avoid any stray interrupt * taken while we zero out our shadow registers in * ath6kl_hif_disable_intrs(). */ ath6kl_hif_irq_disable(dev->ar); return ath6kl_hif_disable_intrs(dev); } int ath6kl_hif_setup(struct ath6kl_device *dev) { int status = 0; spin_lock_init(&dev->lock); /* * NOTE: we actually get the block size of a mailbox other than 0, * for SDIO the block size on mailbox 0 is artificially set to 1. * So we use the block size that is set for the other 3 mailboxes. */ dev->htc_cnxt->block_sz = dev->ar->mbox_info.block_size; /* must be a power of 2 */ if ((dev->htc_cnxt->block_sz & (dev->htc_cnxt->block_sz - 1)) != 0) { WARN_ON(1); status = -EINVAL; goto fail_setup; } /* assemble mask, used for padding to a block */ dev->htc_cnxt->block_mask = dev->htc_cnxt->block_sz - 1; ath6kl_dbg(ATH6KL_DBG_HIF, "hif block size %d mbox addr 0x%x\n", dev->htc_cnxt->block_sz, dev->ar->mbox_info.htc_addr); /* usb doesn't support enabling interrupts */ /* FIXME: remove check once USB support is implemented */ if (dev->ar->hif_type == ATH6KL_HIF_TYPE_USB) return 0; status = ath6kl_hif_disable_intrs(dev); fail_setup: return status; }
{ "pile_set_name": "Github" }
// Copyright Joyent, Inc. and other Node contributors. // // 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. var pathModule = require('path'); var isWindows = process.platform === 'win32'; var fs = require('fs'); // JavaScript implementation of realpath, ported from node pre-v6 var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. var callback; if (DEBUG) { var backtrace = new Error; callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err) { if (err) { backtrace.message = err.message; err = backtrace; missingCallback(err); } } function missingCallback(err) { if (err) { if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs else if (!process.noDeprecation) { var msg = 'fs: missing callback ' + (err.stack || err.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); } var normalize = pathModule.normalize; // Regexp that finds the next partion of a (partial) path // result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] if (isWindows) { var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { var nextPartRe = /(.*?)(?:[\/]+|$)/g; } // Regex to find the device root, including trailing slash. E.g. 'c:\\'. if (isWindows) { var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { var splitRootRe = /^[\/]*/; } exports.realpathSync = function realpathSync(p, cache) { // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return cache[p]; } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstatSync(base); knownHard[base] = true; } } // walk down the path, swapping out linked pathparts for their real // values // NB: p.length changes. while (pos < p.length) { // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { continue; } var resolvedLink; if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // some known symbolic link. no need to stat again. resolvedLink = cache[base]; } else { var stat = fs.lstatSync(base); if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; continue; } // read the link if it wasn't read before // dev/ino always return 0 on windows, so skip the check. var linkTarget = null; if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs.statSync(base); linkTarget = fs.readlinkSync(base); } resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache. if (cache) cache[base] = resolvedLink; if (!isWindows) seenLinks[id] = linkTarget; } // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; exports.realpath = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return process.nextTick(cb.bind(null, null, cache[p])); } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstat(base, function(err) { if (err) return cb(err); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } // walk down the path, swapping out linked pathparts for their real // values function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs.lstat(base, gotStat); } function gotStat(err, stat) { if (err) return cb(err); // if not a symlink, skip to the next path part if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; return process.nextTick(LOOP); } // stat & read the link if not read before // call gotTarget as soon as the link target is known // dev/ino always return 0 on windows, so skip the check. if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs.stat(base, function(err) { if (err) return cb(err); fs.readlink(base, function(err, target) { if (!isWindows) seenLinks[id] = target; gotTarget(err, target); }); }); } function gotTarget(err, target, base) { if (err) return cb(err); var resolvedLink = pathModule.resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } };
{ "pile_set_name": "Github" }
<?php /** * Spyc -- A Simple PHP YAML Class * @version 0.5 * @author Vlad Andersen <[email protected]> * @author Chris Wanstrath <[email protected]> * @link http://code.google.com/p/spyc/ * @copyright Copyright 2005-2006 Chris Wanstrath, 2006-2011 Vlad Andersen * @license http://www.opensource.org/licenses/mit-license.php MIT License * @package Spyc */ if (!function_exists('spyc_load')) { /** * Parses YAML to array. * @param string $string YAML string. * @return array */ function spyc_load($string) { return Spyc::YAMLLoadString($string); } } if (!function_exists('spyc_load_file')) { /** * Parses YAML to array. * @param string $file Path to YAML file. * @return array */ function spyc_load_file($file) { return Spyc::YAMLLoad($file); } } /** * The Simple PHP YAML Class. * * This class can be used to read a YAML file and convert its contents * into a PHP array. It currently supports a very limited subsection of * the YAML spec. * * Usage: * <code> * $Spyc = new Spyc; * $array = $Spyc->load($file); * </code> * or: * <code> * $array = Spyc::YAMLLoad($file); * </code> * or: * <code> * $array = spyc_load_file($file); * </code> * @package Spyc */ class spyc { // SETTINGS const REMPTY = "\0\0\0\0\0"; /** * Setting this to true will force YAMLDump to enclose any string value in * quotes. False by default. * * @var bool */ public $setting_dump_force_quotes = false; /** * Setting this to true will forse YAMLLoad to use syck_load function when * possible. False by default. * @var bool */ public $setting_use_syck_is_possible = false; /**#@+ * @access private * @var mixed */ private $_dumpIndent; private $_dumpWordWrap; private $_containsGroupAnchor = false; private $_containsGroupAlias = false; private $path; private $result; private $LiteralPlaceHolder = '___YAML_Literal_Block___'; private $SavedGroups = array(); private $indent; /** * Path modifier that should be applied after adding current element. * @var array */ private $delayedPath = array(); /**#@+ * @access public * @var mixed */ public $_nodeId; /** * Load a valid YAML string to Spyc. * @param string $input * @return array */ public function load($input) { return $this->__loadString($input); } /** * Load a valid YAML file to Spyc. * @param string $file * @return array */ public function loadFile($file) { return $this->__load($file); } /** * Load YAML into a PHP array statically * * The load method, when supplied with a YAML stream (string or file), * will do its best to convert YAML in a file into a PHP array. Pretty * simple. * Usage: * <code> * $array = Spyc::YAMLLoad('lucky.yaml'); * print_r($array); * </code> * @access public * @return array * @param string $input Path of YAML file or string containing YAML */ public static function YAMLLoad($input) { $Spyc = new Spyc; return $Spyc->__load($input); } /** * Load a string of YAML into a PHP array statically * * The load method, when supplied with a YAML string, will do its best * to convert YAML in a string into a PHP array. Pretty simple. * * Note: use this function if you don't want files from the file system * loaded and processed as YAML. This is of interest to people concerned * about security whose input is from a string. * * Usage: * <code> * $array = Spyc::YAMLLoadString("---\n0: hello world\n"); * print_r($array); * </code> * @access public * @return array * @param string $input String containing YAML */ public static function YAMLLoadString($input) { $Spyc = new Spyc; return $Spyc->__loadString($input); } /** * Dump YAML from PHP array statically * * The dump method, when supplied with an array, will do its best * to convert the array into friendly YAML. Pretty simple. Feel free to * save the returned string as nothing.yaml and pass it around. * * Oh, and you can decide how big the indent is and what the wordwrap * for folding is. Pretty cool -- just pass in 'false' for either if * you want to use the default. * * Indent's default is 2 spaces, wordwrap's default is 40 characters. And * you can turn off wordwrap by passing in 0. * * @access public * @return string * @param array $array PHP array * @param int $indent Pass in false to use the default, which is 2 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40) */ public static function YAMLDump($array,$indent = false,$wordwrap = false) { $spyc = new Spyc; return $spyc->dump($array,$indent,$wordwrap); } /** * Dump PHP array to YAML * * The dump method, when supplied with an array, will do its best * to convert the array into friendly YAML. Pretty simple. Feel free to * save the returned string as tasteful.yaml and pass it around. * * Oh, and you can decide how big the indent is and what the wordwrap * for folding is. Pretty cool -- just pass in 'false' for either if * you want to use the default. * * Indent's default is 2 spaces, wordwrap's default is 40 characters. And * you can turn off wordwrap by passing in 0. * * @access public * @return string * @param array $array PHP array * @param int $indent Pass in false to use the default, which is 2 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40) */ public function dump($array,$indent = false,$wordwrap = false) { // Dumps to some very clean YAML. We'll have to add some more features // and options soon. And better support for folding. // New features and options. if ($indent === false or !is_numeric($indent)) { $this->_dumpIndent = 2; } else { $this->_dumpIndent = $indent; } if ($wordwrap === false or !is_numeric($wordwrap)) { $this->_dumpWordWrap = 40; } else { $this->_dumpWordWrap = $wordwrap; } // New YAML document $string = "---\n"; // Start at the base of the array and move through it. if ($array) { $array = (array) $array; $previous_key = -1; foreach ($array as $key => $value) { if (!isset($first_key)) $first_key = $key; $string .= $this->_yamlize($key,$value,0,$previous_key, $first_key, $array); $previous_key = $key; } } return $string; } /** * Attempts to convert a key / value array item to YAML * @access private * @return string * @param $key The name of the key * @param $value The value of the item * @param $indent The indent of the current node */ private function _yamlize($key,$value,$indent, $previous_key = -1, $first_key = 0, $source_array = null) { if (is_array($value)) { if (empty ($value)) return $this->_dumpNode($key, array(), $indent, $previous_key, $first_key, $source_array); // It has children. What to do? // Make it the right kind of item $string = $this->_dumpNode($key, self::REMPTY, $indent, $previous_key, $first_key, $source_array); // Add the indent $indent += $this->_dumpIndent; // Yamlize the array $string .= $this->_yamlizeArray($value,$indent); } elseif (!is_array($value)) { // It doesn't have children. Yip. $string = $this->_dumpNode($key, $value, $indent, $previous_key, $first_key, $source_array); } return $string; } /** * Attempts to convert an array to YAML * @access private * @return string * @param $array The array you want to convert * @param $indent The indent of the current level */ private function _yamlizeArray($array,$indent) { if (is_array($array)) { $string = ''; $previous_key = -1; foreach ($array as $key => $value) { if (!isset($first_key)) $first_key = $key; $string .= $this->_yamlize($key, $value, $indent, $previous_key, $first_key, $array); $previous_key = $key; } return $string; } else { return false; } } /** * Returns YAML from a key and a value * @access private * @return string * @param $key The name of the key * @param $value The value of the item * @param $indent The indent of the current node */ private function _dumpNode($key, $value, $indent, $previous_key = -1, $first_key = 0, $source_array = null) { // do some folding here, for blocks if (is_string ($value) && ((strpos($value,"\n") !== false || strpos($value,": ") !== false || strpos($value,"- ") !== false || strpos($value,"*") !== false || strpos($value,"#") !== false || strpos($value,"<") !== false || strpos($value,">") !== false || strpos ($value, ' ') !== false || strpos($value,"[") !== false || strpos($value,"]") !== false || strpos($value,"{") !== false || strpos($value,"}") !== false) || strpos($value,"&") !== false || strpos($value, "'") !== false || strpos($value, "!") === 0 || substr ($value, -1, 1) == ':') ) { $value = $this->_doLiteralBlock($value,$indent); } else { $value = $this->_doFolding($value,$indent); } if ($value === array()) $value = '[ ]'; if (in_array ($value, array ('true', 'TRUE', 'false', 'FALSE', 'y', 'Y', 'n', 'N', 'null', 'NULL'), true)) { $value = $this->_doLiteralBlock($value,$indent); } if (trim ($value) != $value) $value = $this->_doLiteralBlock($value,$indent); if (is_bool($value)) { $value = ($value) ? "true" : "false"; } if ($value === null) $value = 'null'; if ($value === "'" . self::REMPTY . "'") $value = null; $spaces = str_repeat(' ',$indent); //if (is_int($key) && $key - 1 == $previous_key && $first_key===0) { if (is_array ($source_array) && array_keys($source_array) === range(0, count($source_array) - 1)) { // It's a sequence $string = $spaces.'- '.$value."\n"; } else { // if ($first_key===0) throw new Exception('Keys are all screwy. The first one was zero, now it\'s "'. $key .'"'); // It's mapped if (strpos($key, ":") !== false || strpos($key, "#") !== false) { $key = '"' . $key . '"'; } $string = rtrim ($spaces.$key.': '.$value)."\n"; } return $string; } /** * Creates a literal block for dumping * @access private * @return string * @param $value * @param $indent int The value of the indent */ private function _doLiteralBlock($value,$indent) { if ($value === "\n") return '\n'; if (strpos($value, "\n") === false && strpos($value, "'") === false) { return sprintf ("'%s'", $value); } if (strpos($value, "\n") === false && strpos($value, '"') === false) { return sprintf ('"%s"', $value); } $exploded = explode("\n",$value); $newValue = '|'; $indent += $this->_dumpIndent; $spaces = str_repeat(' ',$indent); foreach ($exploded as $line) { $newValue .= "\n" . $spaces . ($line); } return $newValue; } /** * Folds a string of text, if necessary * @access private * @return string * @param $value The string you wish to fold */ private function _doFolding($value,$indent) { // Don't do anything if wordwrap is set to 0 if ($this->_dumpWordWrap !== 0 && is_string ($value) && strlen($value) > $this->_dumpWordWrap) { $indent += $this->_dumpIndent; $indent = str_repeat(' ',$indent); $wrapped = wordwrap($value,$this->_dumpWordWrap,"\n$indent"); $value = ">\n".$indent.$wrapped; } else { if ($this->setting_dump_force_quotes && is_string ($value) && $value !== self::REMPTY) $value = '"' . $value . '"'; } return $value; } // LOADING FUNCTIONS private function __load($input) { $Source = $this->loadFromSource($input); return $this->loadWithSource($Source); } private function __loadString($input) { $Source = $this->loadFromString($input); return $this->loadWithSource($Source); } private function loadWithSource($Source) { if (empty ($Source)) return array(); if ($this->setting_use_syck_is_possible && function_exists ('syck_load')) { $array = syck_load (implode ('', $Source)); return is_array($array) ? $array : array(); } $this->path = array(); $this->result = array(); $cnt = count($Source); for ($i = 0; $i < $cnt; $i++) { $line = $Source[$i]; $this->indent = strlen($line) - strlen(ltrim($line)); $tempPath = $this->getParentPathByIndent($this->indent); $line = self::stripIndent($line, $this->indent); if (self::isComment($line)) continue; if (self::isEmpty($line)) continue; $this->path = $tempPath; $literalBlockStyle = self::startsLiteralBlock($line); if ($literalBlockStyle) { $line = rtrim ($line, $literalBlockStyle . " \n"); $literalBlock = ''; $line .= $this->LiteralPlaceHolder; $literal_block_indent = strlen($Source[$i+1]) - strlen(ltrim($Source[$i+1])); while (++$i < $cnt && $this->literalBlockContinues($Source[$i], $this->indent)) { $literalBlock = $this->addLiteralLine($literalBlock, $Source[$i], $literalBlockStyle, $literal_block_indent); } $i--; } while (++$i < $cnt && self::greedilyNeedNextLine($line)) { $line = rtrim ($line, " \n\t\r") . ' ' . ltrim ($Source[$i], " \t"); } $i--; if (strpos ($line, '#')) { if (strpos ($line, '"') === false && strpos ($line, "'") === false) $line = preg_replace('/\s+#(.+)$/','',$line); } $lineArray = $this->_parseLine($line); if ($literalBlockStyle) $lineArray = $this->revertLiteralPlaceHolder ($lineArray, $literalBlock); $this->addArray($lineArray, $this->indent); foreach ($this->delayedPath as $indent => $delayedPath) $this->path[$indent] = $delayedPath; $this->delayedPath = array(); } return $this->result; } private function loadFromSource($input) { if (!empty($input) && strpos($input, "\n") === false && file_exists($input)) return file($input); return $this->loadFromString($input); } private function loadFromString($input) { $lines = explode("\n",$input); foreach ($lines as $k => $_) { $lines[$k] = rtrim ($_, "\r"); } return $lines; } /** * Parses YAML code and returns an array for a node * @access private * @return array * @param string $line A line from the YAML file */ private function _parseLine($line) { if (!$line) return array(); $line = trim($line); if (!$line) return array(); $array = array(); $group = $this->nodeContainsGroup($line); if ($group) { $this->addGroup($line, $group); $line = $this->stripGroup ($line, $group); } if ($this->startsMappedSequence($line)) return $this->returnMappedSequence($line); if ($this->startsMappedValue($line)) return $this->returnMappedValue($line); if ($this->isArrayElement($line)) return $this->returnArrayElement($line); if ($this->isPlainArray($line)) return $this->returnPlainArray($line); return $this->returnKeyValuePair($line); } /** * Finds the type of the passed value, returns the value as the new type. * @access private * @param string $value * @return mixed */ private function _toType($value) { if ($value === '') return null; $first_character = $value[0]; $last_character = substr($value, -1, 1); $is_quoted = false; do { if (!$value) break; if ($first_character != '"' && $first_character != "'") break; if ($last_character != '"' && $last_character != "'") break; $is_quoted = true; } while (0); if ($is_quoted) return strtr(substr ($value, 1, -1), array ('\\"' => '"', '\'\'' => '\'', '\\\'' => '\'')); if (strpos($value, ' #') !== false && !$is_quoted) $value = preg_replace('/\s+#(.+)$/','',$value); if (!$is_quoted) $value = str_replace('\n', "\n", $value); if ($first_character == '[' && $last_character == ']') { // Take out strings sequences and mappings $innerValue = trim(substr ($value, 1, -1)); if ($innerValue === '') return array(); $explode = $this->_inlineEscape($innerValue); // Propagate value array $value = array(); foreach ($explode as $v) { $value[] = $this->_toType($v); } return $value; } if (strpos($value,': ')!==false && $first_character != '{') { $array = explode(': ',$value); $key = trim($array[0]); array_shift($array); $value = trim(implode(': ',$array)); $value = $this->_toType($value); return array($key => $value); } if ($first_character == '{' && $last_character == '}') { $innerValue = trim(substr ($value, 1, -1)); if ($innerValue === '') return array(); // Inline Mapping // Take out strings sequences and mappings $explode = $this->_inlineEscape($innerValue); // Propagate value array $array = array(); foreach ($explode as $v) { $SubArr = $this->_toType($v); if (empty($SubArr)) continue; if (is_array ($SubArr)) { $array[key($SubArr)] = $SubArr[key($SubArr)]; continue; } $array[] = $SubArr; } return $array; } if ($value == 'null' || $value == 'NULL' || $value == 'Null' || $value == '' || $value == '~') { return null; } if ( is_numeric($value) && preg_match ('/^(-|)[1-9]+[0-9]*$/', $value) ) { $intvalue = (int) $value; if ($intvalue != PHP_INT_MAX) $value = $intvalue; return $value; } if (in_array($value, array('true', 'on', '+', 'yes', 'y', 'True', 'TRUE', 'On', 'ON', 'YES', 'Yes', 'Y'))) { return true; } if (in_array(strtolower($value), array('false', 'off', '-', 'no', 'n'))) { return false; } if (is_numeric($value)) { if ($value === '0') return 0; if (rtrim ($value, 0) === $value) $value = (float) $value; return $value; } return $value; } /** * Used in inlines to check for more inlines or quoted strings * @access private * @return array */ private function _inlineEscape($inline) { // There's gotta be a cleaner way to do this... // While pure sequences seem to be nesting just fine, // pure mappings and mappings with sequences inside can't go very // deep. This needs to be fixed. $seqs = array(); $maps = array(); $saved_strings = array(); // Check for strings $regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/'; if (preg_match_all($regex,$inline,$strings)) { $saved_strings = $strings[0]; $inline = preg_replace($regex,'YAMLString',$inline); } unset($regex); $i = 0; do { // Check for sequences while (preg_match('/\[([^{}\[\]]+)\]/U',$inline,$matchseqs)) { $seqs[] = $matchseqs[0]; $inline = preg_replace('/\[([^{}\[\]]+)\]/U', ('YAMLSeq' . (count($seqs) - 1) . 's'), $inline, 1); } // Check for mappings while (preg_match('/{([^\[\]{}]+)}/U',$inline,$matchmaps)) { $maps[] = $matchmaps[0]; $inline = preg_replace('/{([^\[\]{}]+)}/U', ('YAMLMap' . (count($maps) - 1) . 's'), $inline, 1); } if ($i++ >= 10) break; } while (strpos ($inline, '[') !== false || strpos ($inline, '{') !== false); $explode = explode(', ',$inline); $stringi = 0; $i = 0; while (1) { // Re-add the sequences if (!empty($seqs)) { foreach ($explode as $key => $value) { if (strpos($value,'YAMLSeq') !== false) { foreach ($seqs as $seqk => $seq) { $explode[$key] = str_replace(('YAMLSeq'.$seqk.'s'),$seq,$value); $value = $explode[$key]; } } } } // Re-add the mappings if (!empty($maps)) { foreach ($explode as $key => $value) { if (strpos($value,'YAMLMap') !== false) { foreach ($maps as $mapk => $map) { $explode[$key] = str_replace(('YAMLMap'.$mapk.'s'), $map, $value); $value = $explode[$key]; } } } } // Re-add the strings if (!empty($saved_strings)) { foreach ($explode as $key => $value) { while (strpos($value,'YAMLString') !== false) { $explode[$key] = preg_replace('/YAMLString/',$saved_strings[$stringi],$value, 1); unset($saved_strings[$stringi]); ++$stringi; $value = $explode[$key]; } } } $finished = true; foreach ($explode as $key => $value) { if (strpos($value,'YAMLSeq') !== false) { $finished = false; break; } if (strpos($value,'YAMLMap') !== false) { $finished = false; break; } if (strpos($value,'YAMLString') !== false) { $finished = false; break; } } if ($finished) break; $i++; if ($i > 10) break; // Prevent infinite loops. } return $explode; } private function literalBlockContinues($line, $lineIndent) { if (!trim($line)) return true; if (strlen($line) - strlen(ltrim($line)) > $lineIndent) return true; return false; } private function referenceContentsByAlias($alias) { do { if (!isset($this->SavedGroups[$alias])) { echo "Bad group name: $alias."; break; } $groupPath = $this->SavedGroups[$alias]; $value = $this->result; foreach ($groupPath as $k) { $value = $value[$k]; } } while (false); return $value; } private function addArrayInline($array, $indent) { $CommonGroupPath = $this->path; if (empty ($array)) return false; foreach ($array as $k => $_) { $this->addArray(array($k => $_), $indent); $this->path = $CommonGroupPath; } return true; } private function addArray($incoming_data, $incoming_indent) { // print_r ($incoming_data); if (count ($incoming_data) > 1) return $this->addArrayInline ($incoming_data, $incoming_indent); $key = key ($incoming_data); $value = isset($incoming_data[$key]) ? $incoming_data[$key] : null; if ($key === '__!YAMLZero') $key = '0'; if ($incoming_indent == 0 && !$this->_containsGroupAlias && !$this->_containsGroupAnchor) { // Shortcut for root-level values. if ($key || $key === '' || $key === '0') { $this->result[$key] = $value; } else { $this->result[] = $value; end ($this->result); $key = key ($this->result); } $this->path[$incoming_indent] = $key; return; } $history = array(); // Unfolding inner array tree. $history[] = $_arr = $this->result; foreach ($this->path as $k) { $history[] = $_arr = $_arr[$k]; } if ($this->_containsGroupAlias) { $value = $this->referenceContentsByAlias($this->_containsGroupAlias); $this->_containsGroupAlias = false; } // Adding string or numeric key to the innermost level or $this->arr. if (is_string($key) && $key == '<<') { if (!is_array ($_arr)) { $_arr = array (); } $_arr = array_merge ($_arr, $value); } elseif ($key || $key === '' || $key === '0') { if (!is_array ($_arr)) $_arr = array ($key=>$value); else $_arr[$key] = $value; } else { if (!is_array ($_arr)) { $_arr = array ($value); $key = 0; } else { $_arr[] = $value; end ($_arr); $key = key ($_arr); } } $reverse_path = array_reverse($this->path); $reverse_history = array_reverse ($history); $reverse_history[0] = $_arr; $cnt = count($reverse_history) - 1; for ($i = 0; $i < $cnt; $i++) { $reverse_history[$i+1][$reverse_path[$i]] = $reverse_history[$i]; } $this->result = $reverse_history[$cnt]; $this->path[$incoming_indent] = $key; if ($this->_containsGroupAnchor) { $this->SavedGroups[$this->_containsGroupAnchor] = $this->path; if (is_array ($value)) { $k = key ($value); if (!is_int ($k)) { $this->SavedGroups[$this->_containsGroupAnchor][$incoming_indent + 2] = $k; } } $this->_containsGroupAnchor = false; } } private static function startsLiteralBlock($line) { $lastChar = substr (trim($line), -1); if ($lastChar != '>' && $lastChar != '|') return false; if ($lastChar == '|') return $lastChar; // HTML tags should not be counted as literal blocks. if (preg_match ('#<.*?>$#', $line)) return false; return $lastChar; } private static function greedilyNeedNextLine($line) { $line = trim ($line); if (!strlen($line)) return false; if (substr ($line, -1, 1) == ']') return false; if ($line[0] == '[') return true; if (preg_match ('#^[^:]+?:\s*\[#', $line)) return true; return false; } private function addLiteralLine($literalBlock, $line, $literalBlockStyle, $indent = -1) { $line = self::stripIndent($line, $indent); if ($literalBlockStyle !== '|') { $line = self::stripIndent($line); } $line = rtrim ($line, "\r\n\t ") . "\n"; if ($literalBlockStyle == '|') { return $literalBlock . $line; } if (strlen($line) == 0) return rtrim($literalBlock, ' ') . "\n"; if ($line == "\n" && $literalBlockStyle == '>') { return rtrim ($literalBlock, " \t") . "\n"; } if ($line != "\n") $line = trim ($line, "\r\n ") . " "; return $literalBlock . $line; } public function revertLiteralPlaceHolder($lineArray, $literalBlock) { foreach ($lineArray as $k => $_) { if (is_array($_)) $lineArray[$k] = $this->revertLiteralPlaceHolder ($_, $literalBlock); else if (substr($_, -1 * strlen ($this->LiteralPlaceHolder)) == $this->LiteralPlaceHolder) $lineArray[$k] = rtrim ($literalBlock, " \r\n"); } return $lineArray; } private static function stripIndent($line, $indent = -1) { if ($indent == -1) $indent = strlen($line) - strlen(ltrim($line)); return substr ($line, $indent); } private function getParentPathByIndent($indent) { if ($indent == 0) return array(); $linePath = $this->path; do { end($linePath); $lastIndentInParentPath = key($linePath); if ($indent <= $lastIndentInParentPath) array_pop ($linePath); } while ($indent <= $lastIndentInParentPath); return $linePath; } private function clearBiggerPathValues($indent) { if ($indent == 0) $this->path = array(); if (empty ($this->path)) return true; foreach ($this->path as $k => $_) { if ($k > $indent) unset ($this->path[$k]); } return true; } private static function isComment($line) { if (!$line) return false; if ($line[0] == '#') return true; if (trim($line, " \r\n\t") == '---') return true; return false; } private static function isEmpty($line) { return (trim ($line) === ''); } private function isArrayElement($line) { if (!$line) return false; if ($line[0] != '-') return false; if (strlen ($line) > 3) if (substr($line,0,3) == '---') return false; return true; } private function isHashElement($line) { return strpos($line, ':'); } private function isLiteral($line) { if ($this->isArrayElement($line)) return false; if ($this->isHashElement($line)) return false; return true; } private static function unquote($value) { if (!$value) return $value; if (!is_string($value)) return $value; if ($value[0] == '\'') return trim ($value, '\''); if ($value[0] == '"') return trim ($value, '"'); return $value; } private function startsMappedSequence($line) { return ($line[0] == '-' && substr ($line, -1, 1) == ':'); } private function returnMappedSequence($line) { $array = array(); $key = self::unquote(trim(substr($line,1,-1))); $array[$key] = array(); $this->delayedPath = array(strpos ($line, $key) + $this->indent => $key); return array($array); } private function returnMappedValue($line) { $array = array(); $key = self::unquote (trim(substr($line,0,-1))); $array[$key] = ''; return $array; } private function startsMappedValue($line) { return (substr ($line, -1, 1) == ':'); } private function isPlainArray($line) { return ($line[0] == '[' && substr ($line, -1, 1) == ']'); } private function returnPlainArray($line) { return $this->_toType($line); } private function returnKeyValuePair($line) { $array = array(); $key = ''; if (strpos ($line, ':')) { // It's a key/value pair most likely // If the key is in double quotes pull it out if (($line[0] == '"' || $line[0] == "'") && preg_match('/^(["\'](.*)["\'](\s)*:)/',$line,$matches)) { $value = trim(str_replace($matches[1],'',$line)); $key = $matches[2]; } else { // Do some guesswork as to the key and the value $explode = explode(':',$line); $key = trim($explode[0]); array_shift($explode); $value = trim(implode(':',$explode)); } // Set the type of the value. Int, string, etc $value = $this->_toType($value); if ($key === '0') $key = '__!YAMLZero'; $array[$key] = $value; } else { $array = array ($line); } return $array; } private function returnArrayElement($line) { if (strlen($line) <= 1) return array(array()); // Weird %) $array = array(); $value = trim(substr($line,1)); $value = $this->_toType($value); $array[] = $value; return $array; } private function nodeContainsGroup($line) { $symbolsForReference = 'A-z0-9_\-'; if (strpos($line, '&') === false && strpos($line, '*') === false) return false; // Please die fast ;-) if ($line[0] == '&' && preg_match('/^(&['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1]; if ($line[0] == '*' && preg_match('/^(\*['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1]; if (preg_match('/(&['.$symbolsForReference.']+)$/', $line, $matches)) return $matches[1]; if (preg_match('/(\*['.$symbolsForReference.']+$)/', $line, $matches)) return $matches[1]; if (preg_match ('#^\s*<<\s*:\s*(\*[^\s]+).*$#', $line, $matches)) return $matches[1]; return false; } private function addGroup($line, $group) { if ($group[0] == '&') $this->_containsGroupAnchor = substr ($group, 1); if ($group[0] == '*') $this->_containsGroupAlias = substr ($group, 1); //print_r ($this->path); } private function stripGroup($line, $group) { $line = trim(str_replace($group, '', $line)); return $line; } } // Enable use of Spyc from command line // The syntax is the following: php spyc.php spyc.yaml define ('SPYC_FROM_COMMAND_LINE', false); do { if (!SPYC_FROM_COMMAND_LINE) break; if (empty ($_SERVER['argc']) || $_SERVER['argc'] < 2) break; if (empty ($_SERVER['PHP_SELF']) || $_SERVER['PHP_SELF'] != 'spyc.php') break; $file = $argv[1]; printf ("Spyc loading file: %s\n", $file); print_r (spyc_load_file ($file)); } while (0);
{ "pile_set_name": "Github" }
/*********************************************************************************** ** ** GUIGenericTextEntry.h ** ** Компонента для отображения поля для ввода текста гампов от сервера ** ** Copyright (C) August 2016 Hotride ** ************************************************************************************ */ //---------------------------------------------------------------------------------- #ifndef GUIGENERICTEXTENTRY_H #define GUIGENERICTEXTENTRY_H //---------------------------------------------------------------------------------- class CGUIGenericTextEntry : public CGUITextEntry { public: //!Индекс текста uint TextID = 0; CGUIGenericTextEntry( int serial, int index, ushort color, int x, int y, int maxWidth = 0, int maxLength = 0); virtual ~CGUIGenericTextEntry(); }; //---------------------------------------------------------------------------------- #endif //----------------------------------------------------------------------------------
{ "pile_set_name": "Github" }
# # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. # # Copyright (c) 2010-2013 Oracle and/or its affiliates. All rights reserved. # # The contents of this file are subject to the terms of either the GNU # General Public License Version 2 only ("GPL") or the Common Development # and Distribution License("CDDL") (collectively, the "License"). You # may not use this file except in compliance with the License. You can # obtain a copy of the License at # https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html # or packager/legal/LICENSE.txt. See the License for the specific # language governing permissions and limitations under the License. # # When distributing the software, include this License Header Notice in each # file and include the License file at packager/legal/LICENSE.txt. # # GPL Classpath Exception: # Oracle designates this particular file as subject to the "Classpath" # exception as provided by Oracle in the GPL Version 2 section of the License # file that accompanied this code. # # Modifications: # If applicable, add the following below the License Header, with the fields # enclosed by brackets [] replaced by your own identifying information: # "Portions Copyright [year] [name of copyright owner]" # # Contributor(s): # If you wish your version of this file to be governed by only the CDDL or # only the GPL Version 2, indicate your decision by adding "[Contributor] # elects to include this software in this distribution under the [CDDL or GPL # Version 2] license." If you don't indicate a single choice of license, a # recipient has the option to distribute your version of this file under # either the CDDL, the GPL Version 2 or to extend the choice of license to # its licensees as provided above. However, if you add GPL Version 2 code # and therefore, elected the GPL Version 2 license, then the option applies # only if the new code is made subject to such option by the copyright # holder. # puinfo.jta-ds-not-configured=\u4E00\u500B\u540D\u70BA [{0}] \u7684\u6301\u7E8C\u6027\u55AE\u5143\u88AB\u7D44\u614B\u70BA JTA\uFF0C\u4F46 persistence.xml \u4E2D\u53EA\u63D0\u4F9B\u975E JTA \u8CC7\u6599\u4F86\u6E90\u540D\u7A31\u3002
{ "pile_set_name": "Github" }
@echo off start "arma2" /min /high arma2oaserver.exe -port=2302 "-config=C:\DZE_Server_Config\24_napf.cfg" "-cfg=C:\DZE_Server_Config\basic.cfg" "-profiles=C:\DZE_Server_Config" -name=server "-mod=@DayZ_Epoch;@DayZ_Epoch_Server;"
{ "pile_set_name": "Github" }
/** * Module dependencies. */ var tty = require('tty'); var util = require('util'); /** * This is the Node.js implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = require('./debug'); exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(function (key) { return /^debug_/i.test(key); }).reduce(function (obj, key) { // camel-case var prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); // coerce string value into JS value var val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) val = true; else if (/^(no|off|false|disabled)$/i.test(val)) val = false; else if (val === 'null') val = null; else val = Number(val); obj[prop] = val; return obj; }, {}); /** * The file descriptor to write the `debug()` calls to. * Set the `DEBUG_FD` env variable to override with another value. i.e.: * * $ DEBUG_FD=3 node script.js 3>debug.log */ var fd = parseInt(process.env.DEBUG_FD, 10) || 2; if (1 !== fd && 2 !== fd) { util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() } var stream = 1 === fd ? process.stdout : 2 === fd ? process.stderr : createWritableStdioStream(fd); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(fd); } /** * Map %o to `util.inspect()`, all on a single line. */ exports.formatters.o = function(v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n').map(function(str) { return str.trim() }).join(' '); }; /** * Map %o to `util.inspect()`, allowing multiple lines if needed. */ exports.formatters.O = function(v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { var name = this.namespace; var useColors = this.useColors; if (useColors) { var c = this.color; var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); } else { args[0] = new Date().toUTCString() + ' ' + name + ' ' + args[0]; } } /** * Invokes `util.format()` with the specified arguments and writes to `stream`. */ function log() { return stream.write(util.format.apply(util, arguments) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (null == namespaces) { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } else { process.env.DEBUG = namespaces; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Copied from `node/src/node.js`. * * XXX: It's lame that node doesn't expose this API out-of-the-box. It also * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. */ function createWritableStdioStream (fd) { var stream; var tty_wrap = process.binding('tty_wrap'); // Note stream._type is used for test-module-load-list.js switch (tty_wrap.guessHandleType(fd)) { case 'TTY': stream = new tty.WriteStream(fd); stream._type = 'tty'; // Hack to have stream not keep the event loop alive. // See https://github.com/joyent/node/issues/1726 if (stream._handle && stream._handle.unref) { stream._handle.unref(); } break; case 'FILE': var fs = require('fs'); stream = new fs.SyncWriteStream(fd, { autoClose: false }); stream._type = 'fs'; break; case 'PIPE': case 'TCP': var net = require('net'); stream = new net.Socket({ fd: fd, readable: false, writable: true }); // FIXME Should probably have an option in net.Socket to create a // stream from an existing fd which is writable only. But for now // we'll just add this hack and set the `readable` member to false. // Test: ./node test/fixtures/echo.js < /etc/passwd stream.readable = false; stream.read = null; stream._type = 'pipe'; // FIXME Hack to have stream not keep the event loop alive. // See https://github.com/joyent/node/issues/1726 if (stream._handle && stream._handle.unref) { stream._handle.unref(); } break; default: // Probably an error on in uv_guess_handle() throw new Error('Implement me. Unknown stream file type!'); } // For supporting legacy API we put the FD here. stream.fd = fd; stream._isStdio = true; return stream; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init (debug) { debug.inspectOpts = {}; var keys = Object.keys(exports.inspectOpts); for (var i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } /** * Enable namespaces listed in `process.env.DEBUG` initially. */ exports.enable(load());
{ "pile_set_name": "Github" }
#!/bin/sh dotnet DnsServerApp.dll
{ "pile_set_name": "Github" }
package org.pushingpixels.demo.flamingo.svg.filetypes.transcoded; import java.awt.*; import java.awt.geom.*; import java.awt.image.BufferedImage; import java.io.*; import java.lang.ref.WeakReference; import java.util.Base64; import java.util.Stack; import javax.imageio.ImageIO; import javax.swing.SwingUtilities; import javax.swing.plaf.UIResource; import org.pushingpixels.neon.api.icon.ResizableIcon; import org.pushingpixels.neon.api.icon.ResizableIconUIResource; /** * This class has been automatically generated using <a * href="https://github.com/kirill-grouchnikov/radiance">Photon SVG transcoder</a>. */ public class ext_webm implements ResizableIcon { private Shape shape = null; private GeneralPath generalPath = null; private Paint paint = null; private Stroke stroke = null; private Shape clip = null; private Stack<AffineTransform> transformsStack = new Stack<>(); private void _paint0(Graphics2D g,float origAlpha) { transformsStack.push(g.getTransform()); // g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(0.009999999776482582f, 0.0f, 0.0f, 0.009999999776482582f, 0.13999999687075615f, -0.0f)); // _0 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_0 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(45.2f, 1.0f); generalPath.lineTo(72.2f, 27.7f); generalPath.lineTo(72.2f, 99.0f); generalPath.lineTo(0.2f, 99.0f); generalPath.lineTo(0.2f, 1.0f); generalPath.lineTo(45.2f, 1.0f); generalPath.closePath(); shape = generalPath; paint = new LinearGradientPaint(new Point2D.Double(36.20000076293945, 101.0), new Point2D.Double(36.20000076293945, 3.005000114440918), new float[] {0.0f,0.17f,0.313f,0.447f,0.575f,0.698f,0.819f,0.934f,1.0f}, new Color[] {new Color(226, 205, 228, 255),new Color(224, 202, 226, 255),new Color(219, 192, 221, 255),new Color(210, 177, 212, 255),new Color(199, 157, 199, 255),new Color(186, 132, 185, 255),new Color(171, 104, 169, 255),new Color(156, 69, 152, 255),new Color(147, 42, 142, 255)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 102.0f)); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_1 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(45.2f, 1.0f); generalPath.lineTo(72.2f, 27.7f); generalPath.lineTo(72.2f, 99.0f); generalPath.lineTo(0.2f, 99.0f); generalPath.lineTo(0.2f, 1.0f); generalPath.lineTo(45.2f, 1.0f); generalPath.closePath(); shape = generalPath; paint = new Color(0, 0, 0, 0); g.setPaint(paint); g.fill(shape); paint = new Color(136, 35, 131, 255); stroke = new BasicStroke(2.0f,0,0,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(45.2f, 1.0f); generalPath.lineTo(72.2f, 27.7f); generalPath.lineTo(72.2f, 99.0f); generalPath.lineTo(0.2f, 99.0f); generalPath.lineTo(0.2f, 1.0f); generalPath.lineTo(45.2f, 1.0f); generalPath.closePath(); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_2 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(8.2f, 91.1f); generalPath.lineTo(4.7f, 76.8f); generalPath.lineTo(7.7f, 76.8f); generalPath.lineTo(9.9f, 86.600006f); generalPath.lineTo(12.5f, 76.8f); generalPath.lineTo(16.0f, 76.8f); generalPath.lineTo(18.5f, 86.8f); generalPath.lineTo(20.7f, 76.8f); generalPath.lineTo(23.6f, 76.8f); generalPath.lineTo(20.1f, 91.100006f); generalPath.lineTo(17.0f, 91.100006f); generalPath.lineTo(14.1f, 80.40001f); generalPath.lineTo(11.200001f, 91.100006f); generalPath.lineTo(8.200001f, 91.100006f); generalPath.closePath(); generalPath.moveTo(25.2f, 91.1f); generalPath.lineTo(25.2f, 76.8f); generalPath.lineTo(35.9f, 76.8f); generalPath.lineTo(35.9f, 79.200005f); generalPath.lineTo(28.100002f, 79.200005f); generalPath.lineTo(28.100002f, 82.4f); generalPath.lineTo(35.4f, 82.4f); generalPath.lineTo(35.4f, 84.8f); generalPath.lineTo(28.100002f, 84.8f); generalPath.lineTo(28.100002f, 88.700005f); generalPath.lineTo(36.200005f, 88.700005f); generalPath.lineTo(36.200005f, 91.100006f); generalPath.lineTo(25.200005f, 91.100006f); generalPath.closePath(); generalPath.moveTo(38.7f, 76.799995f); generalPath.lineTo(44.5f, 76.799995f); generalPath.curveTo(45.6f, 76.799995f, 46.5f, 76.799995f, 47.1f, 76.899994f); generalPath.curveTo(47.699997f, 76.99999f, 48.199997f, 77.2f, 48.6f, 77.49999f); generalPath.curveTo(49.0f, 77.799995f, 49.399998f, 78.19999f, 49.699997f, 78.69999f); generalPath.curveTo(49.999996f, 79.19999f, 50.1f, 79.79999f, 50.1f, 80.39999f); generalPath.curveTo(50.1f, 81.09998f, 49.899998f, 81.69999f, 49.6f, 82.19999f); generalPath.curveTo(49.3f, 82.69999f, 48.699997f, 83.19999f, 48.1f, 83.49999f); generalPath.curveTo(49.0f, 83.799995f, 49.699997f, 84.19999f, 50.1f, 84.799995f); generalPath.curveTo(50.5f, 85.4f, 50.8f, 86.1f, 50.8f, 86.99999f); generalPath.curveTo(50.8f, 87.69999f, 50.6f, 88.299995f, 50.3f, 88.899994f); generalPath.curveTo(50.0f, 89.49999f, 49.6f, 89.99999f, 49.0f, 90.399994f); generalPath.curveTo(48.4f, 90.799995f, 47.8f, 90.99999f, 47.0f, 91.09999f); generalPath.curveTo(46.5f, 91.19999f, 45.3f, 91.19999f, 43.5f, 91.19999f); generalPath.lineTo(38.6f, 91.19999f); generalPath.lineTo(38.6f, 76.8f); generalPath.closePath(); generalPath.moveTo(41.600002f, 79.1f); generalPath.lineTo(41.600002f, 82.4f); generalPath.lineTo(45.600002f, 82.4f); generalPath.curveTo(46.100002f, 82.3f, 46.500004f, 82.200005f, 46.800003f, 81.9f); generalPath.curveTo(47.100002f, 81.6f, 47.200005f, 81.200005f, 47.200005f, 80.8f); generalPath.curveTo(47.200005f, 80.4f, 47.100006f, 80.0f, 46.800003f, 79.700005f); generalPath.curveTo(46.600002f, 79.4f, 46.200005f, 79.3f, 45.700005f, 79.200005f); generalPath.lineTo(41.600006f, 79.200005f); generalPath.closePath(); generalPath.moveTo(41.600002f, 84.799995f); generalPath.lineTo(41.600002f, 88.6f); generalPath.lineTo(44.300003f, 88.6f); generalPath.curveTo(45.4f, 88.6f, 46.000004f, 88.6f, 46.300003f, 88.5f); generalPath.curveTo(46.700005f, 88.4f, 47.100002f, 88.2f, 47.4f, 87.9f); generalPath.curveTo(47.7f, 87.6f, 47.800003f, 87.200005f, 47.800003f, 86.700005f); generalPath.curveTo(47.800003f, 86.3f, 47.700005f, 85.9f, 47.500004f, 85.600006f); generalPath.curveTo(47.300003f, 85.3f, 47.000004f, 85.100006f, 46.600002f, 84.90001f); generalPath.curveTo(46.2f, 84.70001f, 45.300003f, 84.70001f, 44.000004f, 84.70001f); generalPath.lineTo(41.600002f, 84.70001f); generalPath.closePath(); generalPath.moveTo(53.200005f, 91.1f); generalPath.lineTo(53.200005f, 76.8f); generalPath.lineTo(57.600006f, 76.8f); generalPath.lineTo(60.200005f, 86.600006f); generalPath.lineTo(62.800003f, 76.8f); generalPath.lineTo(67.200005f, 76.8f); generalPath.lineTo(67.200005f, 91.100006f); generalPath.lineTo(64.50001f, 91.100006f); generalPath.lineTo(64.50001f, 79.8f); generalPath.lineTo(61.600006f, 91.100006f); generalPath.lineTo(58.800007f, 91.100006f); generalPath.lineTo(56.0f, 79.8f); generalPath.lineTo(56.0f, 91.100006f); generalPath.lineTo(53.2f, 91.100006f); generalPath.closePath(); shape = generalPath; paint = new Color(255, 255, 255, 255); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_3 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(64.3f, 55.5f); generalPath.curveTo(62.600002f, 55.3f, 60.9f, 55.2f, 59.200005f, 55.2f); generalPath.curveTo(51.900005f, 55.100002f, 45.900005f, 56.8f, 40.400005f, 58.9f); generalPath.curveTo(34.900005f, 61.000004f, 29.6f, 63.6f, 23.3f, 64.0f); generalPath.curveTo(19.9f, 64.2f, 15.999999f, 63.4f, 14.799999f, 61.6f); generalPath.curveTo(13.999999f, 60.3f, 13.999999f, 58.1f, 13.799999f, 55.899998f); generalPath.curveTo(13.199999f, 50.199997f, 12.199999f, 44.199997f, 11.4f, 38.6f); generalPath.curveTo(12.2f, 37.699997f, 13.5f, 37.3f, 14.799999f, 36.899998f); generalPath.curveTo(15.199999f, 37.999996f, 14.999999f, 39.6f, 15.4f, 40.699997f); generalPath.curveTo(22.5f, 41.399998f, 29.0f, 40.299995f, 35.4f, 39.199997f); generalPath.curveTo(41.7f, 38.1f, 47.800003f, 36.999996f, 54.800003f, 36.6f); generalPath.curveTo(58.200005f, 36.399998f, 61.700005f, 36.399998f, 65.100006f, 36.6f); generalPath.moveTo(55.200005f, 51.899998f); generalPath.curveTo(55.700005f, 51.699997f, 56.300003f, 51.6f, 57.100006f, 51.699997f); generalPath.curveTo(57.300007f, 47.999996f, 57.400005f, 44.399998f, 57.400005f, 40.499996f); generalPath.curveTo(51.200005f, 40.699997f, 45.500008f, 41.399998f, 40.400005f, 42.699997f); generalPath.curveTo(40.600006f, 46.699997f, 40.800007f, 50.499996f, 40.700005f, 54.699997f); generalPath.curveTo(44.700005f, 53.6f, 48.400005f, 52.199997f, 53.300003f, 51.999996f); generalPath.moveTo(55.300003f, 39.899994f); generalPath.lineTo(56.4f, 39.899994f); generalPath.curveTo(56.800003f, 39.499992f, 56.600002f, 38.699993f, 56.600002f, 37.999992f); generalPath.curveTo(55.100002f, 37.399994f, 54.800003f, 38.999992f, 55.300003f, 39.899994f); generalPath.closePath(); generalPath.moveTo(59.200005f, 39.699993f); generalPath.lineTo(60.700005f, 39.699993f); generalPath.lineTo(60.700005f, 38.0f); generalPath.lineTo(59.400005f, 38.0f); generalPath.curveTo(59.400005f, 38.7f, 59.000004f, 38.9f, 59.200005f, 39.7f); generalPath.closePath(); generalPath.moveTo(63.200005f, 39.699993f); generalPath.curveTo(63.700005f, 39.599995f, 64.00001f, 39.699993f, 64.3f, 39.899994f); generalPath.curveTo(64.700005f, 39.599995f, 64.5f, 38.699993f, 64.5f, 37.999992f); generalPath.lineTo(63.2f, 37.999992f); generalPath.lineTo(63.2f, 39.699993f); generalPath.closePath(); generalPath.moveTo(51.700005f, 39.999992f); generalPath.lineTo(52.600006f, 39.999992f); generalPath.curveTo(53.000008f, 39.699993f, 52.800007f, 38.79999f, 52.800007f, 38.09999f); generalPath.curveTo(51.400005f, 37.69999f, 51.20001f, 39.29999f, 51.70001f, 39.999992f); generalPath.closePath(); generalPath.moveTo(47.700005f, 40.399994f); generalPath.curveTo(48.400005f, 40.599995f, 48.500004f, 40.099995f, 49.200005f, 40.199993f); generalPath.lineTo(49.200005f, 38.499992f); generalPath.curveTo(47.700005f, 38.09999f, 47.500004f, 39.09999f, 47.700005f, 40.399994f); generalPath.closePath(); generalPath.moveTo(44.100006f, 39.299995f); generalPath.curveTo(44.100006f, 39.899994f, 44.000008f, 40.699997f, 44.300007f, 40.999996f); generalPath.curveTo(44.800007f, 41.099995f, 44.800007f, 40.599995f, 45.400005f, 40.799995f); generalPath.curveTo(45.200005f, 40.199997f, 45.900005f, 38.799995f, 45.000004f, 38.899994f); generalPath.curveTo(44.900005f, 39.299995f, 44.200005f, 38.999992f, 44.100002f, 39.299995f); generalPath.closePath(); generalPath.moveTo(12.600006f, 40.099995f); generalPath.curveTo(13.000006f, 39.999996f, 13.7000065f, 40.699993f, 13.900006f, 40.099995f); generalPath.curveTo(13.400006f, 40.099995f, 13.800006f, 39.299995f, 13.7000065f, 38.999996f); generalPath.curveTo(13.000007f, 39.199997f, 12.400006f, 39.299995f, 12.600006f, 40.099995f); generalPath.closePath(); generalPath.moveTo(40.900005f, 39.699993f); generalPath.curveTo(40.600006f, 39.999992f, 41.100006f, 40.79999f, 40.900005f, 41.599995f); generalPath.curveTo(41.500004f, 41.799995f, 41.500004f, 41.299995f, 42.000004f, 41.399994f); generalPath.curveTo(41.800003f, 40.799995f, 42.500004f, 39.399994f, 41.600002f, 39.499992f); generalPath.curveTo(41.500004f, 39.79999f, 41.2f, 39.699993f, 40.9f, 39.699993f); generalPath.closePath(); generalPath.moveTo(37.400005f, 42.499992f); generalPath.curveTo(37.900005f, 42.399994f, 38.300007f, 42.29999f, 38.700005f, 42.09999f); generalPath.curveTo(38.900005f, 41.29999f, 38.300003f, 41.19999f, 38.500004f, 40.39999f); generalPath.lineTo(37.600002f, 40.39999f); generalPath.curveTo(37.300003f, 40.69999f, 37.500004f, 41.69999f, 37.4f, 42.49999f); generalPath.closePath(); generalPath.moveTo(64.3f, 40.699993f); generalPath.curveTo(62.200005f, 40.599995f, 61.000004f, 40.499992f, 58.800003f, 40.499992f); generalPath.curveTo(58.300003f, 43.899994f, 58.800003f, 48.29999f, 58.300003f, 51.699993f); generalPath.curveTo(60.700005f, 51.699993f, 61.9f, 51.79999f, 64.100006f, 51.999992f); generalPath.moveTo(33.4f, 41.6f); generalPath.curveTo(33.9f, 41.8f, 33.5f, 42.8f, 33.600002f, 43.3f); generalPath.curveTo(34.100002f, 43.2f, 34.7f, 43.1f, 35.100002f, 42.899998f); generalPath.curveTo(35.7f, 40.999996f, 34.2f, 40.499996f, 33.4f, 41.6f); generalPath.closePath(); generalPath.moveTo(28.7f, 42.199997f); generalPath.lineTo(28.7f, 44.1f); generalPath.curveTo(29.6f, 44.3f, 29.900002f, 43.899998f, 30.6f, 43.899998f); generalPath.curveTo(30.5f, 43.199997f, 30.800001f, 42.199997f, 30.4f, 41.8f); generalPath.curveTo(29.9f, 42.0f, 29.1f, 41.899998f, 28.699999f, 42.2f); generalPath.closePath(); generalPath.moveTo(23.400002f, 42.799995f); generalPath.curveTo(23.7f, 43.299995f, 23.400002f, 44.399994f, 23.800001f, 44.899994f); generalPath.curveTo(24.500002f, 44.999992f, 24.6f, 44.499992f, 25.300001f, 44.699993f); generalPath.curveTo(25.2f, 43.999992f, 25.000002f, 43.499992f, 25.1f, 42.599995f); generalPath.curveTo(24.300001f, 42.399994f, 24.2f, 42.899994f, 23.4f, 42.799995f); generalPath.closePath(); generalPath.moveTo(15.900002f, 44.799995f); generalPath.lineTo(17.0f, 44.799995f); generalPath.curveTo(17.2f, 43.899994f, 16.6f, 43.599995f, 16.8f, 42.699997f); generalPath.curveTo(16.4f, 42.799995f, 15.599999f, 42.399998f, 15.499999f, 42.899998f); generalPath.curveTo(16.099998f, 43.1f, 15.399999f, 44.6f, 15.899999f, 44.8f); generalPath.closePath(); generalPath.moveTo(19.300001f, 45.799995f); generalPath.curveTo(19.400002f, 49.899994f, 20.2f, 55.099995f, 20.7f, 59.499996f); generalPath.curveTo(28.7f, 59.599995f, 33.800003f, 56.799995f, 39.9f, 54.999996f); generalPath.curveTo(39.4f, 51.099995f, 40.0f, 46.299995f, 39.2f, 42.799995f); generalPath.curveTo(33.0f, 44.399994f, 27.1f, 45.999996f, 19.300001f, 45.799995f); generalPath.closePath(); generalPath.moveTo(19.800001f, 44.999996f); generalPath.lineTo(20.900002f, 44.999996f); generalPath.curveTo(21.300001f, 44.499996f, 20.7f, 43.799995f, 20.900002f, 42.899998f); generalPath.lineTo(19.400002f, 42.899998f); generalPath.curveTo(19.500002f, 43.6f, 19.500002f, 44.499996f, 19.800001f, 44.999996f); generalPath.closePath(); generalPath.moveTo(14.400002f, 52.799995f); generalPath.curveTo(14.600001f, 52.799995f, 14.700002f, 52.999996f, 14.800001f, 53.199997f); generalPath.curveTo(14.400002f, 52.499996f, 14.100001f, 53.699997f, 14.600001f, 53.799995f); generalPath.curveTo(14.700002f, 53.599995f, 14.600001f, 53.399994f, 14.800001f, 53.399994f); generalPath.curveTo(15.100001f, 53.899994f, 14.000001f, 54.099995f, 14.600001f, 54.199993f); generalPath.curveTo(15.300001f, 53.699993f, 15.900002f, 52.999992f, 17.000002f, 52.699993f); generalPath.curveTo(16.900002f, 54.199993f, 17.400002f, 55.099995f, 17.400002f, 56.499992f); generalPath.curveTo(16.7f, 56.999992f, 15.700002f, 57.199993f, 15.500002f, 58.199993f); generalPath.curveTo(16.700003f, 58.899994f, 18.000002f, 59.399994f, 19.7f, 59.499992f); generalPath.curveTo(19.0f, 54.59999f, 18.6f, 50.699993f, 18.1f, 45.79999f); generalPath.curveTo(15.900001f, 46.09999f, 14.1f, 44.999992f, 13.0f, 44.89999f); generalPath.curveTo(13.9f, 45.69999f, 13.6f, 47.39999f, 13.8f, 48.49999f); generalPath.curveTo(13.8f, 48.299988f, 13.8f, 48.099987f, 14.0f, 48.099987f); generalPath.curveTo(13.9f, 48.799988f, 14.1f, 49.799988f, 13.8f, 50.199986f); generalPath.curveTo(14.5f, 50.499985f, 14.3f, 49.999985f, 14.2f, 51.099987f); generalPath.moveTo(58.8f, 54.299988f); generalPath.lineTo(59.899998f, 54.299988f); generalPath.curveTo(60.199997f, 53.99999f, 60.1f, 53.19999f, 60.1f, 52.599987f); generalPath.lineTo(58.8f, 52.599987f); generalPath.lineTo(58.8f, 54.299988f); generalPath.closePath(); generalPath.moveTo(54.8f, 52.899986f); generalPath.lineTo(54.8f, 54.199986f); generalPath.curveTo(55.2f, 54.599987f, 55.5f, 53.999985f, 56.3f, 54.199986f); generalPath.lineTo(56.3f, 52.699986f); generalPath.curveTo(55.7f, 52.699986f, 55.1f, 52.699986f, 54.8f, 52.899986f); generalPath.closePath(); generalPath.moveTo(62.399998f, 54.299988f); generalPath.lineTo(63.699997f, 54.299988f); generalPath.lineTo(63.699997f, 52.799988f); generalPath.lineTo(62.399998f, 52.799988f); generalPath.curveTo(62.499996f, 53.299988f, 62.399998f, 53.799988f, 62.399998f, 54.299988f); generalPath.closePath(); generalPath.moveTo(51.399998f, 53.299988f); generalPath.lineTo(51.399998f, 54.599987f); generalPath.lineTo(52.499996f, 54.599987f); generalPath.curveTo(52.799995f, 54.299988f, 52.899998f, 52.899986f, 52.299995f, 52.899986f); generalPath.curveTo(52.199997f, 53.299988f, 51.499996f, 52.999985f, 51.399994f, 53.299988f); generalPath.closePath(); generalPath.moveTo(47.8f, 53.69999f); generalPath.curveTo(47.899998f, 54.299988f, 47.5f, 55.39999f, 48.2f, 55.39999f); generalPath.curveTo(48.2f, 55.09999f, 48.7f, 55.19999f, 49.100002f, 55.19999f); generalPath.curveTo(48.9f, 54.69999f, 49.500004f, 53.39999f, 48.7f, 53.49999f); generalPath.curveTo(48.600002f, 53.799988f, 48.100002f, 53.69999f, 47.8f, 53.69999f); generalPath.closePath(); generalPath.moveTo(44.399998f, 54.69999f); generalPath.lineTo(44.399998f, 56.19999f); generalPath.curveTo(45.1f, 56.39999f, 44.999996f, 55.799988f, 45.699997f, 55.99999f); generalPath.curveTo(45.499996f, 55.49999f, 46.1f, 54.19999f, 45.299995f, 54.299988f); generalPath.curveTo(45.199997f, 54.599987f, 44.499996f, 54.49999f, 44.399994f, 54.69999f); generalPath.closePath(); generalPath.moveTo(15.0f, 57.0f); generalPath.curveTo(15.7f, 56.5f, 16.3f, 55.3f, 15.2f, 54.7f); generalPath.curveTo(14.5f, 55.100002f, 14.4f, 56.3f, 15.0f, 57.0f); generalPath.closePath(); generalPath.moveTo(41.1f, 55.7f); generalPath.curveTo(41.0f, 56.4f, 41.5f, 56.5f, 41.3f, 57.2f); generalPath.curveTo(42.2f, 57.2f, 42.5f, 56.600002f, 42.399998f, 55.5f); generalPath.curveTo(41.999996f, 55.0f, 41.6f, 55.6f, 41.1f, 55.7f); generalPath.closePath(); generalPath.moveTo(38.1f, 58.4f); generalPath.curveTo(39.1f, 58.4f, 39.3f, 57.600002f, 39.199997f, 56.5f); generalPath.lineTo(38.299995f, 56.5f); generalPath.curveTo(37.999996f, 56.9f, 38.199997f, 57.8f, 38.099995f, 58.4f); generalPath.closePath(); generalPath.moveTo(34.5f, 58.0f); generalPath.lineTo(34.5f, 59.7f); generalPath.curveTo(35.1f, 59.600002f, 35.8f, 59.5f, 36.0f, 58.9f); generalPath.curveTo(35.4f, 58.9f, 36.3f, 57.300003f, 35.4f, 57.600002f); generalPath.curveTo(35.4f, 58.000004f, 34.7f, 57.7f, 34.5f, 58.000004f); generalPath.closePath(); generalPath.moveTo(16.0f, 60.8f); generalPath.curveTo(15.6f, 60.1f, 15.8f, 58.8f, 14.7f, 58.899998f); generalPath.curveTo(14.9f, 59.6f, 14.9f, 61.6f, 16.0f, 60.8f); generalPath.closePath(); generalPath.moveTo(29.8f, 59.899998f); generalPath.curveTo(30.3f, 59.899998f, 29.9f, 60.8f, 30.0f, 61.199997f); generalPath.curveTo(30.8f, 61.299995f, 31.2f, 60.999996f, 31.7f, 60.799995f); generalPath.lineTo(31.7f, 59.099995f); generalPath.curveTo(30.800001f, 58.999996f, 30.1f, 59.199993f, 29.800001f, 59.899994f); generalPath.closePath(); generalPath.moveTo(25.099998f, 60.499996f); generalPath.curveTo(25.099998f, 61.299995f, 24.999998f, 62.199997f, 25.499998f, 62.399998f); generalPath.curveTo(25.499998f, 61.899998f, 26.299997f, 62.3f, 26.599998f, 62.199997f); generalPath.curveTo(26.899998f, 61.899998f, 26.399998f, 61.1f, 26.599998f, 60.299995f); generalPath.curveTo(25.899998f, 60.099995f, 25.599998f, 60.399994f, 25.099998f, 60.499996f); generalPath.closePath(); generalPath.moveTo(19.0f, 62.3f); generalPath.lineTo(19.0f, 60.6f); generalPath.curveTo(18.5f, 60.6f, 18.4f, 60.199997f, 17.7f, 60.399998f); generalPath.curveTo(17.6f, 61.499996f, 17.7f, 62.499996f, 19.0f, 62.3f); generalPath.closePath(); generalPath.moveTo(21.5f, 62.5f); generalPath.lineTo(22.8f, 62.5f); generalPath.curveTo(23.0f, 61.6f, 22.5f, 61.4f, 22.599998f, 60.6f); generalPath.lineTo(21.3f, 60.6f); generalPath.curveTo(21.199999f, 61.5f, 21.5f, 61.8f, 21.5f, 62.5f); generalPath.closePath(); shape = generalPath; paint = new LinearGradientPaint(new Point2D.Double(11.51099967956543, 51.715999603271484), new Point2D.Double(65.21099853515625, 51.715999603271484), new float[] {0.005f,1.0f}, new Color[] {new Color(150, 52, 145, 255),new Color(112, 19, 107, 255)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 102.0f)); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_4 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(45.2f, 1.0f); generalPath.lineTo(72.2f, 27.7f); generalPath.lineTo(45.199997f, 27.7f); generalPath.lineTo(45.199997f, 1.0f); generalPath.closePath(); shape = generalPath; paint = new LinearGradientPaint(new Point2D.Double(45.26900100708008, 74.20600128173828), new Point2D.Double(58.76900100708008, 87.70600128173828), new float[] {0.0f,0.378f,0.515f,0.612f,0.69f,0.757f,0.817f,0.871f,0.921f,0.965f,1.0f}, new Color[] {new Color(249, 239, 246, 255),new Color(248, 237, 245, 255),new Color(243, 230, 241, 255),new Color(236, 219, 235, 255),new Color(227, 204, 226, 255),new Color(215, 184, 215, 255),new Color(202, 161, 201, 255),new Color(188, 136, 187, 255),new Color(174, 108, 171, 255),new Color(159, 77, 155, 255),new Color(147, 42, 142, 255)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 102.0f)); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_5 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(45.2f, 1.0f); generalPath.lineTo(72.2f, 27.7f); generalPath.lineTo(45.199997f, 27.7f); generalPath.lineTo(45.199997f, 1.0f); generalPath.closePath(); shape = generalPath; paint = new Color(0, 0, 0, 0); g.setPaint(paint); g.fill(shape); paint = new Color(136, 35, 131, 255); stroke = new BasicStroke(2.0f,0,2,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(45.2f, 1.0f); generalPath.lineTo(72.2f, 27.7f); generalPath.lineTo(45.199997f, 27.7f); generalPath.lineTo(45.199997f, 1.0f); generalPath.closePath(); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); } @SuppressWarnings("unused") private void innerPaint(Graphics2D g) { float origAlpha = 1.0f; Composite origComposite = g.getComposite(); if (origComposite instanceof AlphaComposite) { AlphaComposite origAlphaComposite = (AlphaComposite)origComposite; if (origAlphaComposite.getRule() == AlphaComposite.SRC_OVER) { origAlpha = origAlphaComposite.getAlpha(); } } _paint0(g, origAlpha); shape = null; generalPath = null; paint = null; stroke = null; clip = null; transformsStack.clear(); } /** * Returns the X of the bounding box of the original SVG image. * * @return The X of the bounding box of the original SVG image. */ public static double getOrigX() { return 0.13199996948242188; } /** * Returns the Y of the bounding box of the original SVG image. * * @return The Y of the bounding box of the original SVG image. */ public static double getOrigY() { return 0.0; } /** * Returns the width of the bounding box of the original SVG image. * * @return The width of the bounding box of the original SVG image. */ public static double getOrigWidth() { return 0.7400000095367432; } /** * Returns the height of the bounding box of the original SVG image. * * @return The height of the bounding box of the original SVG image. */ public static double getOrigHeight() { return 1.0; } /** The current width of this resizable icon. */ private int width; /** The current height of this resizable icon. */ private int height; /** * Creates a new transcoded SVG image. This is marked as private to indicate that app * code should be using the {@link #of(int, int)} method to obtain a pre-configured instance. */ private ext_webm() { this.width = (int) getOrigWidth(); this.height = (int) getOrigHeight(); } @Override public int getIconHeight() { return height; } @Override public int getIconWidth() { return width; } @Override public synchronized void setDimension(Dimension newDimension) { this.width = newDimension.width; this.height = newDimension.height; } @Override public synchronized void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2d = (Graphics2D) g.create(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.translate(x, y); double coef1 = (double) this.width / getOrigWidth(); double coef2 = (double) this.height / getOrigHeight(); double coef = Math.min(coef1, coef2); g2d.clipRect(0, 0, this.width, this.height); g2d.scale(coef, coef); g2d.translate(-getOrigX(), -getOrigY()); if (coef1 != coef2) { if (coef1 < coef2) { int extraDy = (int) ((getOrigWidth() - getOrigHeight()) / 2.0); g2d.translate(0, extraDy); } else { int extraDx = (int) ((getOrigHeight() - getOrigWidth()) / 2.0); g2d.translate(extraDx, 0); } } Graphics2D g2ForInner = (Graphics2D) g2d.create(); innerPaint(g2ForInner); g2ForInner.dispose(); g2d.dispose(); } /** * Returns a new instance of this icon with specified dimensions. * * @param width Required width of the icon * @param height Required height of the icon * @return A new instance of this icon with specified dimensions. */ public static ResizableIcon of(int width, int height) { ext_webm base = new ext_webm(); base.width = width; base.height = height; return base; } /** * Returns a new {@link UIResource} instance of this icon with specified dimensions. * * @param width Required width of the icon * @param height Required height of the icon * @return A new {@link UIResource} instance of this icon with specified dimensions. */ public static ResizableIconUIResource uiResourceOf(int width, int height) { ext_webm base = new ext_webm(); base.width = width; base.height = height; return new ResizableIconUIResource(base); } /** * Returns a factory that returns instances of this icon on demand. * * @return Factory that returns instances of this icon on demand. */ public static Factory factory() { return ext_webm::new; } }
{ "pile_set_name": "Github" }
#------------------------------------------------- # # Project created by QtCreator 2017-10-20T09:59:00 # #------------------------------------------------- QT += core gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = exampleforwindows TEMPLATE = app SOURCES += main.cpp\ mainwindow.cpp HEADERS += mainwindow.h FORMS += mainwindow.ui win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/../framelesswindow/release/ -lframelesswindow else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../framelesswindow/debug/ -lframelesswindow else:macx: LIBS += -L$$OUT_PWD/../framelesswindow/ -lframelesswindow INCLUDEPATH += $$PWD/../framelesswindow DEPENDPATH += $$PWD/../framelesswindow win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$OUT_PWD/../framelesswindow/release/libframelesswindow.a else:win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$OUT_PWD/../framelesswindow/debug/libframelesswindow.a else:win32:!win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$OUT_PWD/../framelesswindow/release/framelesswindow.lib else:win32:!win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$OUT_PWD/../framelesswindow/debug/framelesswindow.lib else:macx: PRE_TARGETDEPS += $$OUT_PWD/../framelesswindow/libframelesswindow.a include (../projectinclude/common.pri)
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <spirit:design xmlns:xilinx="http://www.xilinx.com" xmlns:spirit="http://www.spiritconsortium.org/XMLSchema/SPIRIT/1685-2009" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <spirit:vendor>xilinx.com</spirit:vendor> <spirit:library>xci</spirit:library> <spirit:name>unknown</spirit:name> <spirit:version>1.0</spirit:version> <spirit:componentInstances> <spirit:componentInstance> <spirit:instanceName>bd_2abc_s02tr_0</spirit:instanceName> <spirit:componentRef spirit:vendor="xilinx.com" spirit:library="ip" spirit:name="sc_transaction_regulator" spirit:version="1.0"/> <spirit:configurableElementValues> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.CLK.ASSOCIATED_BUSIF">S_AXI:M_AXI</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.CLK.ASSOCIATED_RESET">aresetn</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.CLK.CLK_DOMAIN">zusys_zynq_ultra_ps_e_0_0_pl_clk0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.CLK.FREQ_HZ">199999969</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.CLK.INSERT_VIP">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.CLK.PHASE">0.000</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.ADDR_WIDTH">32</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.ARUSER_WIDTH">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.AWUSER_WIDTH">1024</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.BUSER_WIDTH">1024</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.CLK_DOMAIN">zusys_zynq_ultra_ps_e_0_0_pl_clk0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.DATA_WIDTH">64</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.FREQ_HZ">199999969</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_BRESP">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_BURST">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_CACHE">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_LOCK">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_PROT">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_QOS">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_REGION">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_RRESP">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_WSTRB">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.ID_WIDTH">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.INSERT_VIP">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.MAX_BURST_LENGTH">256</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.NUM_READ_OUTSTANDING">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.NUM_READ_THREADS">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.NUM_WRITE_OUTSTANDING">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.NUM_WRITE_THREADS">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.PHASE">0.000</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.PROTOCOL">AXI4</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.READ_WRITE_MODE">WRITE_ONLY</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.RUSER_BITS_PER_BYTE">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.RUSER_WIDTH">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.SUPPORTS_NARROW_BURST">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.WUSER_BITS_PER_BYTE">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.M_AXI.WUSER_WIDTH">1024</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.RST.INSERT_VIP">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.RST.POLARITY">ACTIVE_LOW</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.RST.TYPE">INTERCONNECT</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.ADDR_WIDTH">32</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.ARUSER_WIDTH">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.AWUSER_WIDTH">1024</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.BUSER_WIDTH">1024</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.CLK_DOMAIN">zusys_zynq_ultra_ps_e_0_0_pl_clk0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.DATA_WIDTH">64</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.FREQ_HZ">199999969</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_BRESP">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_BURST">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_CACHE">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_LOCK">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_PROT">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_QOS">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_REGION">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_RRESP">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_WSTRB">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.ID_WIDTH">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.INSERT_VIP">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.MAX_BURST_LENGTH">256</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.NUM_READ_OUTSTANDING">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.NUM_READ_THREADS">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.NUM_WRITE_OUTSTANDING">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.NUM_WRITE_THREADS">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.PHASE">0.000</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.PROTOCOL">AXI4</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.READ_WRITE_MODE">WRITE_ONLY</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.RUSER_BITS_PER_BYTE">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.RUSER_WIDTH">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.SUPPORTS_NARROW_BURST">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.WUSER_BITS_PER_BYTE">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="BUSIFPARAM_VALUE.S_AXI.WUSER_WIDTH">1024</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_ADDR_WIDTH">32</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_ENABLE_PIPELINING">0x1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_FAMILY">zynquplus</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_IS_CASCADED">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_MEP_IDENTIFIER">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_MEP_IDENTIFIER_WIDTH">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_M_ID_WIDTH">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_NUM_READ_OUTSTANDING">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_NUM_READ_THREADS">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_NUM_WRITE_OUTSTANDING">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_NUM_WRITE_THREADS">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_RDATA_WIDTH">64</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_READ_ACCEPTANCE">32</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_SEP_ROUTE_WIDTH">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_SINGLE_ISSUING">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_SUPPORTS_READ_DEADLOCK">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_SUPPORTS_WRITE_DEADLOCK">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_S_ID_WIDTH">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_WDATA_WIDTH">64</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_WRITE_ACCEPTANCE">32</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.ADDR_WIDTH">32</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.Component_Name">bd_2abc_s02tr_0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.ENABLE_PIPELINING">0x1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.HAS_ACLKEN">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.IS_CASCADED">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.MEP_IDENTIFIER">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.MEP_IDENTIFIER_WIDTH">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.M_ID_WIDTH">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.NUM_READ_OUTSTANDING">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.NUM_READ_THREADS">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.NUM_WRITE_OUTSTANDING">2</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.NUM_WRITE_THREADS">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.RDATA_WIDTH">64</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.READ_ACCEPTANCE">32</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.READ_WRITE_MODE">WRITE_ONLY</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.SEP_ROUTE_WIDTH">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.SINGLE_ISSUING">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.SUPPORTS_READ_DEADLOCK">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.SUPPORTS_WRITE_DEADLOCK">1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.S_ID_WIDTH">0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.WDATA_WIDTH">64</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.WRITE_ACCEPTANCE">32</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.ARCHITECTURE">zynquplus</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.BASE_BOARD_PART">trenz.biz:te0820_3eg_1e:part0:2.0</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.BOARD_CONNECTIONS"/> <spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.DEVICE">xczu3eg</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.PACKAGE">sfvc784</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.PREFHDL">VERILOG</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.SILICON_REVISION"/> <spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.SIMULATOR_LANGUAGE">MIXED</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.SPEEDGRADE">-1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.STATIC_POWER"/> <spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.TEMPERATURE_GRADE">E</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.USE_RDI_CUSTOMIZATION">TRUE</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.USE_RDI_GENERATION">TRUE</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.IPCONTEXT">IP_Integrator</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.IPREVISION">8</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.MANAGED">TRUE</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.OUTPUTDIR">.</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.SELECTEDSIMMODEL"/> <spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.SHAREDDIR">../../../../../ipshared</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.SWVERSION">2019.1</spirit:configurableElementValue> <spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.SYNTHESISFLOW">GLOBAL</spirit:configurableElementValue> </spirit:configurableElementValues> <spirit:vendorExtensions> <xilinx:componentInstanceExtensions> <xilinx:configElementInfos> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.CLK.ASSOCIATED_BUSIF" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.CLK.ASSOCIATED_RESET" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.CLK.CLK_DOMAIN" xilinx:valueSource="default_prop" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.CLK.FREQ_HZ" xilinx:valueSource="user_prop" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.CLK.PHASE" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.ADDR_WIDTH" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.ARUSER_WIDTH" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.AWUSER_WIDTH" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.BUSER_WIDTH" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.CLK_DOMAIN" xilinx:valueSource="default_prop" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.DATA_WIDTH" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.FREQ_HZ" xilinx:valueSource="user_prop" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_BRESP" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_BURST" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_CACHE" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_LOCK" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_PROT" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_QOS" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_REGION" xilinx:valueSource="constant" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_RRESP" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.HAS_WSTRB" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.ID_WIDTH" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.MAX_BURST_LENGTH" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.NUM_READ_OUTSTANDING" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.NUM_WRITE_OUTSTANDING" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.PROTOCOL" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.READ_WRITE_MODE" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.RUSER_WIDTH" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.SUPPORTS_NARROW_BURST" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.M_AXI.WUSER_WIDTH" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.RST.POLARITY" xilinx:valueSource="constant_prop" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.ADDR_WIDTH" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.ARUSER_WIDTH" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.AWUSER_WIDTH" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.BUSER_WIDTH" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.CLK_DOMAIN" xilinx:valueSource="default_prop" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.DATA_WIDTH" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.FREQ_HZ" xilinx:valueSource="user_prop" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_BRESP" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_BURST" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_CACHE" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_LOCK" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_PROT" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_QOS" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_REGION" xilinx:valueSource="constant" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_RRESP" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.HAS_WSTRB" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.ID_WIDTH" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.MAX_BURST_LENGTH" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.NUM_READ_OUTSTANDING" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.NUM_WRITE_OUTSTANDING" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.PROTOCOL" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.READ_WRITE_MODE" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.RUSER_WIDTH" xilinx:valueSource="propagated" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.SUPPORTS_NARROW_BURST" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="BUSIFPARAM_VALUE.S_AXI.WUSER_WIDTH" xilinx:valuePermission="bd"/> <xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.ADDR_WIDTH" xilinx:valueSource="user"/> <xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.IS_CASCADED" xilinx:valueSource="user"/> <xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.MEP_IDENTIFIER" xilinx:valueSource="user"/> <xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.MEP_IDENTIFIER_WIDTH" xilinx:valueSource="user"/> <xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.NUM_READ_OUTSTANDING" xilinx:valueSource="user"/> <xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.NUM_WRITE_OUTSTANDING" xilinx:valueSource="user"/> <xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.RDATA_WIDTH" xilinx:valueSource="user"/> <xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.READ_WRITE_MODE" xilinx:valueSource="user"/> <xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.SEP_ROUTE_WIDTH" xilinx:valueSource="user"/> <xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.SUPPORTS_READ_DEADLOCK" xilinx:valueSource="user"/> <xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.SUPPORTS_WRITE_DEADLOCK" xilinx:valueSource="user"/> <xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.S_ID_WIDTH" xilinx:valueSource="user"/> <xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.WDATA_WIDTH" xilinx:valueSource="user"/> </xilinx:configElementInfos> </xilinx:componentInstanceExtensions> </spirit:vendorExtensions> </spirit:componentInstance> </spirit:componentInstances> </spirit:design>
{ "pile_set_name": "Github" }
/* * Copyright (C) 2009-2017 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <cmath> #include <wtf/Optional.h> #include <wtf/Ref.h> #include <wtf/RefCounted.h> #if PLATFORM(IOS_FAMILY) OBJC_CLASS CLLocation; #endif namespace WebCore { class GeolocationPositionData { public: GeolocationPositionData() = default; GeolocationPositionData(double timestamp, double latitude, double longitude, double accuracy) : timestamp(timestamp) , latitude(latitude) , longitude(longitude) , accuracy(accuracy) { } #if PLATFORM(IOS_FAMILY) WEBCORE_EXPORT explicit GeolocationPositionData(CLLocation*); #endif double timestamp { std::numeric_limits<double>::quiet_NaN() }; double latitude { std::numeric_limits<double>::quiet_NaN() }; double longitude { std::numeric_limits<double>::quiet_NaN() }; double accuracy { std::numeric_limits<double>::quiet_NaN() }; Optional<double> altitude; Optional<double> altitudeAccuracy; Optional<double> heading; Optional<double> speed; Optional<double> floorLevel; bool isValid() const; template<class Encoder> void encode(Encoder&) const; template<class Decoder> static WARN_UNUSED_RETURN bool decode(Decoder&, GeolocationPositionData&); }; template<class Encoder> void GeolocationPositionData::encode(Encoder& encoder) const { encoder << timestamp; encoder << latitude; encoder << longitude; encoder << accuracy; encoder << altitude; encoder << altitudeAccuracy; encoder << heading; encoder << speed; encoder << floorLevel; } template<class Decoder> bool GeolocationPositionData::decode(Decoder& decoder, GeolocationPositionData& position) { if (!decoder.decode(position.timestamp)) return false; if (!decoder.decode(position.latitude)) return false; if (!decoder.decode(position.longitude)) return false; if (!decoder.decode(position.accuracy)) return false; if (!decoder.decode(position.altitude)) return false; if (!decoder.decode(position.altitudeAccuracy)) return false; if (!decoder.decode(position.heading)) return false; if (!decoder.decode(position.speed)) return false; if (!decoder.decode(position.floorLevel)) return false; return true; } inline bool GeolocationPositionData::isValid() const { return !std::isnan(timestamp) && !std::isnan(latitude) && !std::isnan(longitude) && !std::isnan(accuracy); } } // namespace WebCore
{ "pile_set_name": "Github" }
/* * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 2.0, as published by the * Free Software Foundation. * * This program is also distributed with certain software (including but not * limited to OpenSSL) that is licensed under separate terms, as designated in a * particular file or component or in included license documentation. The * authors of MySQL hereby grant you an additional permission to link the * program and your derivative works with the separately licensed software that * they have included with MySQL. * * Without limiting anything contained in the foregoing, this file, which is * part of MySQL Connector/J, is also subject to the Universal FOSS Exception, * version 1.0, a copy of which can be found at * http://oss.oracle.com/licenses/universal-foss-exception. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, * for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.mysql.cj.protocol; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.nio.channels.ReadPendingException; import java.nio.channels.WritePendingException; import java.util.LinkedList; import java.util.Objects; import java.util.Queue; import java.util.concurrent.TimeUnit; /** * A layer over {@link AsynchronousSocketChannel} that serializes all incoming write requests. This means we queue any incoming buffer and don't begin writing * it until the previous buffer has been written fully. All buffers are transmitted atomically with respect to the caller/callback. */ public class SerializingBufferWriter implements CompletionHandler<Long, Void> { // TODO make WRITES_AT_ONCE configurable private static int WRITES_AT_ONCE = 200; // Empirical value. Helps improving i/o rate for large number of concurrent asynchronous requests protected AsynchronousSocketChannel channel; /** * Maintain a queue of pending writes. */ private Queue<ByteBufferWrapper> pendingWrites = new LinkedList<>(); /** * Keeps the link between ByteBuffer to be written and the CompletionHandler * object to be invoked for this one write operation. */ private static class ByteBufferWrapper { private ByteBuffer buffer; private CompletionHandler<Long, Void> handler = null; ByteBufferWrapper(ByteBuffer buffer, CompletionHandler<Long, Void> completionHandler) { this.buffer = buffer; this.handler = completionHandler; } public ByteBuffer getBuffer() { return this.buffer; } public CompletionHandler<Long, Void> getHandler() { return this.handler; } } public SerializingBufferWriter(AsynchronousSocketChannel channel) { this.channel = channel; } /** * Initiate a write of the current pending buffers. This method can only be called when no other writes are in progress. This method should be called under * a mutex for this.pendingWrites to prevent concurrent writes to the channel. */ private void initiateWrite() { try { // We must limit the number of buffers which may be sent at once with gathering write because of two reasons: // 1. Operating systems impose a limit on the number of buffers that may be used in an I/O operation, for example default Linux kernel value is 1024. // When the number of buffers exceeds this limit, then the I/O operation is performed with the maximum number of buffers allowed by the operating system. // That slows down the I/O significantly and could even hang it in case of asynchronous I/O when server response can't be read because write operation has drained all available buffers. // 2. With a large number of small asynchronous requests pendingWrites queue is filled much faster than it's freed so that the OS limit can be reached easily. ByteBuffer bufs[] = this.pendingWrites.stream().limit(WRITES_AT_ONCE).map(ByteBufferWrapper::getBuffer).toArray(size -> new ByteBuffer[size]); this.channel.write(bufs, 0, bufs.length, 0L, TimeUnit.MILLISECONDS, null, this); } catch (ReadPendingException | WritePendingException t) { return; } catch (Throwable t) { failed(t, null); } } /** * Queue a buffer to be written to the channel. This method uses a mutex on the buffer list to synchronize for the following cases: * <ul> * <li>The buffer list becomes empty after we check and miss writing to the channel.</li> * <li>LinkedList is not thread-safe.</li> * </ul> * * @param buf * {@link ByteBuffer} * @param callback * {@link CompletionHandler} */ public void queueBuffer(ByteBuffer buf, CompletionHandler<Long, Void> callback) { synchronized (this.pendingWrites) { this.pendingWrites.add(new ByteBufferWrapper(buf, callback)); // if there's no write in progress, we need to initiate a write of this buffer. otherwise the completion of the current write will do it if (this.pendingWrites.size() == 1) { initiateWrite(); } } } /** * Completion handler for channel writes. * * @param bytesWritten * number of processed bytes * @param v * Void */ public void completed(Long bytesWritten, Void v) { // collect completed writes to notify after initiating the next write LinkedList<CompletionHandler<Long, Void>> completedWrites = new LinkedList<>(); synchronized (this.pendingWrites) { while (this.pendingWrites.peek() != null && !this.pendingWrites.peek().getBuffer().hasRemaining() && completedWrites.size() < WRITES_AT_ONCE) { completedWrites.add(this.pendingWrites.remove().getHandler()); } // notify handler(s) before initiating write to satisfy ordering guarantees completedWrites.stream().filter(Objects::nonNull).forEach(l -> { // prevent exceptions in handler from blocking other notifications try { l.completed(0L, null); } catch (Throwable ex) { // presumably unexpected, notify so futures don't block try { l.failed(ex, null); } catch (Throwable ex2) { // nothing we can do here ex2.printStackTrace(); // TODO log error normally instead of sysout } } }); if (this.pendingWrites.size() > 0) { initiateWrite(); } } } public void failed(Throwable t, Void v) { // error writing, can't continue try { this.channel.close(); } catch (Exception ex) { } LinkedList<CompletionHandler<Long, Void>> failedWrites = new LinkedList<>(); synchronized (this.pendingWrites) { while (this.pendingWrites.peek() != null) { ByteBufferWrapper bw = this.pendingWrites.remove(); if (bw.getHandler() != null) { failedWrites.add(bw.getHandler()); } } } failedWrites.forEach((CompletionHandler<Long, Void> l) -> { try { l.failed(t, null); } catch (Exception ex) { } }); failedWrites.clear(); } /** * Allow overwriting the channel once the writer has been established. Required for SSL/TLS connections when the encryption doesn't start until we send the * capability flag to X Plugin. * * @param channel * {@link AsynchronousSocketChannel} */ public void setChannel(AsynchronousSocketChannel channel) { this.channel = channel; } }
{ "pile_set_name": "Github" }
/* Plugin-SDK (Grand Theft Auto 3) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" #include "CCutsceneObject.h" class CCutsceneHead : public CCutsceneObject { public: RwFrame *m_pHeadNode; //funcs void PlayAnimation(char const* name); CCutsceneHead(CObject* object); }; VALIDATE_SIZE(CCutsceneHead, 0x19C);
{ "pile_set_name": "Github" }
// Copyright 2016 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. #include "src/string-case.h" #include "src/assert-scope.h" #include "src/base/logging.h" #include "src/globals.h" #include "src/utils.h" namespace v8 { namespace internal { #ifdef DEBUG bool CheckFastAsciiConvert(char* dst, const char* src, int length, bool changed, bool is_to_lower) { bool expected_changed = false; for (int i = 0; i < length; i++) { if (dst[i] == src[i]) continue; expected_changed = true; if (is_to_lower) { DCHECK('A' <= src[i] && src[i] <= 'Z'); DCHECK(dst[i] == src[i] + ('a' - 'A')); } else { DCHECK('a' <= src[i] && src[i] <= 'z'); DCHECK(dst[i] == src[i] - ('a' - 'A')); } } return (expected_changed == changed); } #endif const uintptr_t kOneInEveryByte = kUintptrAllBitsSet / 0xFF; const uintptr_t kAsciiMask = kOneInEveryByte << 7; // Given a word and two range boundaries returns a word with high bit // set in every byte iff the corresponding input byte was strictly in // the range (m, n). All the other bits in the result are cleared. // This function is only useful when it can be inlined and the // boundaries are statically known. // Requires: all bytes in the input word and the boundaries must be // ASCII (less than 0x7F). static inline uintptr_t AsciiRangeMask(uintptr_t w, char m, char n) { // Use strict inequalities since in edge cases the function could be // further simplified. DCHECK(0 < m && m < n); // Has high bit set in every w byte less than n. uintptr_t tmp1 = kOneInEveryByte * (0x7F + n) - w; // Has high bit set in every w byte greater than m. uintptr_t tmp2 = w + kOneInEveryByte * (0x7F - m); return (tmp1 & tmp2 & (kOneInEveryByte * 0x80)); } template <bool is_lower> int FastAsciiConvert(char* dst, const char* src, int length, bool* changed_out) { #ifdef DEBUG char* saved_dst = dst; #endif const char* saved_src = src; DisallowHeapAllocation no_gc; // We rely on the distance between upper and lower case letters // being a known power of 2. DCHECK_EQ('a' - 'A', 1 << 5); // Boundaries for the range of input characters than require conversion. static const char lo = is_lower ? 'A' - 1 : 'a' - 1; static const char hi = is_lower ? 'Z' + 1 : 'z' + 1; bool changed = false; const char* const limit = src + length; // dst is newly allocated and always aligned. DCHECK(IsAligned(reinterpret_cast<intptr_t>(dst), sizeof(uintptr_t))); // Only attempt processing one word at a time if src is also aligned. if (IsAligned(reinterpret_cast<intptr_t>(src), sizeof(uintptr_t))) { // Process the prefix of the input that requires no conversion one aligned // (machine) word at a time. while (src <= limit - sizeof(uintptr_t)) { const uintptr_t w = *reinterpret_cast<const uintptr_t*>(src); if ((w & kAsciiMask) != 0) return static_cast<int>(src - saved_src); if (AsciiRangeMask(w, lo, hi) != 0) { changed = true; break; } *reinterpret_cast<uintptr_t*>(dst) = w; src += sizeof(uintptr_t); dst += sizeof(uintptr_t); } // Process the remainder of the input performing conversion when // required one word at a time. while (src <= limit - sizeof(uintptr_t)) { const uintptr_t w = *reinterpret_cast<const uintptr_t*>(src); if ((w & kAsciiMask) != 0) return static_cast<int>(src - saved_src); uintptr_t m = AsciiRangeMask(w, lo, hi); // The mask has high (7th) bit set in every byte that needs // conversion and we know that the distance between cases is // 1 << 5. *reinterpret_cast<uintptr_t*>(dst) = w ^ (m >> 2); src += sizeof(uintptr_t); dst += sizeof(uintptr_t); } } // Process the last few bytes of the input (or the whole input if // unaligned access is not supported). while (src < limit) { char c = *src; if ((c & kAsciiMask) != 0) return static_cast<int>(src - saved_src); if (lo < c && c < hi) { c ^= (1 << 5); changed = true; } *dst = c; ++src; ++dst; } DCHECK( CheckFastAsciiConvert(saved_dst, saved_src, length, changed, is_lower)); *changed_out = changed; return length; } template int FastAsciiConvert<false>(char* dst, const char* src, int length, bool* changed_out); template int FastAsciiConvert<true>(char* dst, const char* src, int length, bool* changed_out); } // namespace internal } // namespace v8
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" href="../../css/froala_editor.css"> <link rel="stylesheet" href="../../css/froala_style.css"> <link rel="stylesheet" href="../../css/plugins/code_view.css"> <link rel="stylesheet" href="../../css/plugins/colors.css"> <link rel="stylesheet" href="../../css/plugins/emoticons.css"> <link rel="stylesheet" href="../../css/plugins/image_manager.css"> <link rel="stylesheet" href="../../css/plugins/image.css"> <link rel="stylesheet" href="../../css/plugins/line_breaker.css"> <link rel="stylesheet" href="../../css/plugins/table.css"> <link rel="stylesheet" href="../../css/plugins/char_counter.css"> <link rel="stylesheet" href="../../css/plugins/video.css"> <link rel="stylesheet" href="../../css/plugins/fullscreen.css"> <link rel="stylesheet" href="../../css/plugins/file.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.3.0/codemirror.min.css"> <style> body { text-align: center; } div#editor { width: 81%; margin: auto; text-align: left; } </style> </head> <body> <div id="editor"> <div id='edit' style="margin-top: 30px;"> <h1>Init on Click</h1> <p>Init on click improves the page performance by initializing only the basic code when the page is loaded and the rest of the code when clicking in the editable area. It is highly recommended to use the <a href="../docs/options#initOnClick" target="_blank" title="initOnClick option">initOnClick</a> option if you have more rich text editors on the same page.</p> <p><strong>Click here to initialize the WYSIWYG HTML editor on this text.</strong></p> <img class="fr-fir fr-dii" src="../../img/photo1.jpg" alt="Old Clock" width="300" />Lorem <strong>ipsum</strong> dolor sit amet, consectetur <strong>adipiscing <em>elit.</em> Donec</strong> facilisis diam in odio iaculis blandit. Nunc eu mauris sit amet purus <strong>viverra</strong><em> gravida</em> ut a dui.<br /> <ul> <li>Vivamus nec rutrum augue, pharetra faucibus purus. Maecenas non orci sagittis, vehicula lorem et, dignissim nunc.</li> <li>Suspendisse suscipit, diam non varius facilisis, enim libero tincidunt magna, sit amet iaculis eros libero sit amet eros. Vestibulum a rhoncus felis.<ol> <li>Nam lacus nulla, consequat ac lacus sit amet, accumsan pellentesque risus. Aenean viverra mi at urna mattis fermentum.</li> <li>Curabitur porta metus in tortor elementum, in semper nulla ullamcorper. Vestibulum mattis tempor tortor quis gravida. In rhoncus risus nibh. Nullam condimentum dapibus massa vel fringilla. Sed hendrerit sed est quis facilisis. Ut sit amet nibh sem. Pellentesque imperdiet mollis libero.</li> </ol> </li> </ul> </div> </div> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.3.0/codemirror.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.3.0/mode/xml/xml.min.js"></script> <script type="text/javascript" src="../../js/froala_editor.min.js"></script> <script type="text/javascript" src="../../js/plugins/align.min.js"></script> <script type="text/javascript" src="../../js/plugins/code_beautifier.min.js"></script> <script type="text/javascript" src="../../js/plugins/code_view.min.js"></script> <script type="text/javascript" src="../../js/plugins/colors.min.js"></script> <script type="text/javascript" src="../../js/plugins/emoticons.min.js"></script> <script type="text/javascript" src="../../js/plugins/draggable.min.js"></script> <script type="text/javascript" src="../../js/plugins/font_size.min.js"></script> <script type="text/javascript" src="../../js/plugins/font_family.min.js"></script> <script type="text/javascript" src="../../js/plugins/image.min.js"></script> <script type="text/javascript" src="../../js/plugins/file.min.js"></script> <script type="text/javascript" src="../../js/plugins/image_manager.min.js"></script> <script type="text/javascript" src="../../js/plugins/line_breaker.min.js"></script> <script type="text/javascript" src="../../js/plugins/link.min.js"></script> <script type="text/javascript" src="../../js/plugins/lists.min.js"></script> <script type="text/javascript" src="../../js/plugins/paragraph_format.min.js"></script> <script type="text/javascript" src="../../js/plugins/paragraph_style.min.js"></script> <script type="text/javascript" src="../../js/plugins/video.min.js"></script> <script type="text/javascript" src="../../js/plugins/table.min.js"></script> <script type="text/javascript" src="../../js/plugins/url.min.js"></script> <script type="text/javascript" src="../../js/plugins/entities.min.js"></script> <script type="text/javascript" src="../../js/plugins/char_counter.min.js"></script> <script type="text/javascript" src="../../js/plugins/inline_style.min.js"></script> <script type="text/javascript" src="../../js/plugins/save.min.js"></script> <script type="text/javascript" src="../../js/plugins/fullscreen.min.js"></script> <script type="text/javascript" src="../../js/plugins/quote.min.js"></script> <script> (function () { new FroalaEditor("#edit", { initOnClick: true }) })() </script> </body> </html>
{ "pile_set_name": "Github" }
package longpath import ( "path/filepath" "strings" ) // LongAbs makes a path absolute and returns it in NT long path form. func LongAbs(path string) (string, error) { if strings.HasPrefix(path, `\\?\`) || strings.HasPrefix(path, `\\.\`) { return path, nil } if !filepath.IsAbs(path) { absPath, err := filepath.Abs(path) if err != nil { return "", err } path = absPath } if strings.HasPrefix(path, `\\`) { return `\\?\UNC\` + path[2:], nil } return `\\?\` + path, nil }
{ "pile_set_name": "Github" }
var helper = require(__dirname + "/test-helper"); test('executing query', function() { test("queing query", function() { test('when connection is ready', function() { var client = helper.client(); assert.empty(client.connection.queries); client.connection.emit('readyForQuery'); client.query('yes'); assert.lengthIs(client.connection.queries, 1); assert.equal(client.connection.queries, 'yes'); }); test('when connection is not ready', function() { var client = helper.client(); test('query is not sent', function() { client.query('boom'); assert.empty(client.connection.queries); }); test('sends query to connection once ready', function() { assert.ok(client.connection.emit('readyForQuery')); assert.lengthIs(client.connection.queries, 1); assert.equal(client.connection.queries[0], "boom"); }); }); test("multiple in the queue", function() { var client = helper.client(); var connection = client.connection; var queries = connection.queries; client.query('one'); client.query('two'); client.query('three'); assert.empty(queries); test("after one ready for query",function() { connection.emit('readyForQuery'); assert.lengthIs(queries, 1); assert.equal(queries[0], "one"); }); test('after two ready for query', function() { connection.emit('readyForQuery'); assert.lengthIs(queries, 2); }); test("after a bunch more", function() { connection.emit('readyForQuery'); connection.emit('readyForQuery'); connection.emit('readyForQuery'); assert.lengthIs(queries, 3); assert.equal(queries[0], "one"); assert.equal(queries[1], 'two'); assert.equal(queries[2], 'three'); }); }); }); test("query event binding and flow", function() { var client = helper.client(); var con = client.connection; var query = client.query('whatever'); test("has no queries sent before ready", function() { assert.empty(con.queries); }); test('sends query on readyForQuery event', function() { con.emit('readyForQuery'); assert.lengthIs(con.queries, 1); assert.equal(con.queries[0], 'whatever'); }); test('handles rowDescription message', function() { var handled = con.emit('rowDescription',{ fields: [{ name: 'boom' }] }); assert.ok(handled, "should have handlded rowDescription"); }); test('handles dataRow messages', function() { assert.emits(query, 'row', function(row) { assert.equal(row['boom'], "hi"); }); var handled = con.emit('dataRow', { fields: ["hi"] }); assert.ok(handled, "should have handled first data row message"); assert.emits(query, 'row', function(row) { assert.equal(row['boom'], "bye"); }); var handledAgain = con.emit('dataRow', { fields: ["bye"] }); assert.ok(handledAgain, "should have handled seciond data row message"); }); //multiple command complete messages will be sent //when multiple queries are in a simple command test('handles command complete messages', function() { con.emit('commandComplete', { text: 'INSERT 31 1' }); }); test('removes itself after another readyForQuery message', function() { return false; assert.emits(query, "end", function(msg) { //TODO do we want to check the complete messages? }); con.emit("readyForQuery"); //this would never actually happen ['dataRow','rowDescription', 'commandComplete'].forEach(function(msg) { assert.equal(con.emit(msg), false, "Should no longer be picking up '"+ msg +"' messages"); }); }); }); });
{ "pile_set_name": "Github" }
import viewModelBase = require("viewmodels/viewModelBase"); import appUrl = require("common/appUrl"); import database = require("models/resources/database"); import saveTimeSeriesConfigurationCommand = require("commands/database/documents/timeSeries/saveTimeSeriesConfigurationCommand"); import eventsCollector = require("common/eventsCollector"); import generalUtils = require("common/generalUtils"); import messagePublisher = require("common/messagePublisher"); import collectionsTracker = require("common/helpers/database/collectionsTracker"); import getTimeSeriesConfigurationCommand = require("commands/database/documents/timeSeries/getTimeSeriesConfigurationCommand"); import timeSeriesConfigurationEntry = require("models/database/documents/timeSeriesConfigurationEntry"); import popoverUtils = require("common/popoverUtils"); class timeSeries extends viewModelBase { perCollectionConfigurations = ko.observableArray<timeSeriesConfigurationEntry>([]); isSaveEnabled: KnockoutComputed<boolean>; collections = collectionsTracker.default.collections; selectionState: KnockoutComputed<checkbox>; selectedItems = ko.observableArray<timeSeriesConfigurationEntry>([]); policyCheckFrequency = ko.observable<number>(10 * 60); currentlyEditedItem = ko.observable<timeSeriesConfigurationEntry>(); // reference to cloned and currently being edited item currentBackingItem = ko.observable<timeSeriesConfigurationEntry>(null); // original item which is edited spinners = { save: ko.observable<boolean>(false) }; constructor() { super(); this.bindToCurrentInstance("saveChanges", "deleteItem", "editItem", "applyChanges", "exitEditMode", "enableConfiguration", "disableConfiguration", "toggleSelectAll"); this.initObservables(); } private initObservables() { this.selectionState = ko.pureComputed<checkbox>(() => { const selectedCount = this.selectedItems().length; const totalCount = this.perCollectionConfigurations().length; if (totalCount && selectedCount === totalCount) return "checked"; if (selectedCount > 0) return "some_checked"; return "unchecked"; }); } canActivate(args: any): boolean | JQueryPromise<canActivateResultDto> { return $.when<any>(super.canActivate(args)) .then(() => { const deferred = $.Deferred<canActivateResultDto>(); this.fetchConfiguration(this.activeDatabase()) .done(() => deferred.resolve({ can: true })) .fail(() => deferred.resolve({ redirect: appUrl.forDatabaseRecord(this.activeDatabase()) })); return deferred; }); } activate(args: any) { super.activate(args); this.dirtyFlag = new ko.DirtyFlag([this.perCollectionConfigurations, this.policyCheckFrequency, this.currentlyEditedItem]); this.isSaveEnabled = ko.pureComputed<boolean>(() => { const dirty = this.dirtyFlag().isDirty(); const saving = this.spinners.save(); return dirty && !saving; }); } private fetchConfiguration(db: database): JQueryPromise<Raven.Client.Documents.Operations.TimeSeries.TimeSeriesConfiguration> { return new getTimeSeriesConfigurationCommand(db) .execute() .done((config: Raven.Client.Documents.Operations.TimeSeries.TimeSeriesConfiguration) => { this.onConfigurationLoaded(config); }); } onConfigurationLoaded(data: Raven.Client.Documents.Operations.TimeSeries.TimeSeriesConfiguration) { if (data) { this.policyCheckFrequency(generalUtils.timeSpanToSeconds(data.PolicyCheckFrequency)); if (data.Collections) { this.perCollectionConfigurations(_.map(data.Collections, (configuration, collection) => { const entry = new timeSeriesConfigurationEntry(collection); entry.withRetention(configuration); return entry; })); } if (data.NamedValues) { _.map(data.NamedValues, (configuration, collection) => { let matchingItem = this.perCollectionConfigurations().find(x => x.collection() === collection); if (!matchingItem) { matchingItem = new timeSeriesConfigurationEntry(collection); this.perCollectionConfigurations.push(matchingItem); } matchingItem.withNamedValues(configuration); }); } this.dirtyFlag().reset(); } else { this.perCollectionConfigurations([]); } } createCollectionNameAutocompleter(item: timeSeriesConfigurationEntry) { return ko.pureComputed(() => { const key = item.collection(); const options = collectionsTracker.default.getCollectionNames(); const usedOptions = this.perCollectionConfigurations().filter(f => f !== item).map(x => x.collection()); const filteredOptions = _.difference(options, usedOptions); if (key) { return filteredOptions.filter(x => x.toLowerCase().includes(key.toLowerCase())); } else { return filteredOptions; } }); } addCollectionSpecificConfiguration() { eventsCollector.default.reportEvent("timeSeriesSettings", "create"); this.currentBackingItem(null); this.currentlyEditedItem(timeSeriesConfigurationEntry.empty()); this.currentlyEditedItem().validationGroup.errors.showAllMessages(false); this.initTooltips(); } private initTooltips() { popoverUtils.longWithHover($(".aggregation-info"), { content: ` <small><br> <ul> <li> <strong>A new time series</strong> is created by each Rollup Policy defined.<br> Its name will be <code>&lt;Raw-data-time-series-name&gt;@&lt;Rollup-policy-name&gt;</code> </li><br> <li> Each entry in such auto-generated time series has the following values:<br> <i>First, Last, Min, Max, Sum, Count</i> (per each original raw value)<br> which is rolled-up data <strong>based only on the Aggregation Time Frame defined by the policy!</strong> </li><br> <li> The data generated by the first Rollup Policy is based on the Raw time series data.<br> After that, input data for each Rollup Policy is the data generated by the previous policy. </li><br> <li> <strong>Important</strong>:<br> Rollup entries are not created for time series that have entries with more than 5 values!<br> (even if policy is defined) </li> </ul> </small> `, placement: "left", html: true, container: ".time-series-config" }); popoverUtils.longWithHover($(".named-values-info"), { content: ` <small> <ul> <li><strong>Associate names with your time series values</strong>. </li><br> <li>The default name per value is the value's position (i.e. <code>Value #0</code>)<br> Instead, values names can be customized. </li><br> <li><strong>For example</strong>: If time series tracks stock exchange data,<br> the following names can be assigned: Open, Close, High, Low, Volume. </li> </ul> </small> `, placement: "left", html: true, container: ".time-series-config" }); } removeConfiguration(entry: timeSeriesConfigurationEntry) { eventsCollector.default.reportEvent("timeSeriesSettings", "remove"); this.perCollectionConfigurations.remove(entry); } applyChanges() { const itemToSave = this.currentlyEditedItem(); const isEdit = !!this.currentBackingItem(); let hasErrors = false; if (!this.isValid(itemToSave.validationGroup)) { hasErrors = true; } if (!this.isValid(itemToSave.rawPolicy().validationGroup)) { hasErrors = true; } for (let namedValues of itemToSave.namedValues()) { if (!this.isValid(namedValues.validationGroup)) { hasErrors = true; } for (let namedValue of namedValues.namedValues()) { if (!this.isValid(namedValue.validationGroup)) { hasErrors = true; } } } for (let policy of itemToSave.policies()) { if (!this.isValid(policy.validationGroup)) { hasErrors = true; } } if (hasErrors) { return; } if (isEdit) { this.currentBackingItem().copyFrom(itemToSave); } else { this.perCollectionConfigurations.push(itemToSave); } this.exitEditMode(); } toDto(): Raven.Client.Documents.Operations.TimeSeries.TimeSeriesConfiguration { const perCollectionConfigurations = this.perCollectionConfigurations(); const collectionsDto = {} as { [key: string]: Raven.Client.Documents.Operations.TimeSeries.TimeSeriesCollectionConfiguration; }; const namedValuesDto = {} as {[key: string]: System.Collections.Generic.Dictionary<string, string[]>;}; perCollectionConfigurations.forEach(config => { if (config.hasPoliciesOrRetentionConfig()) { collectionsDto[config.collection()] = config.toPoliciesDto(); } if (config.hasNamedValuesConfig()) { namedValuesDto[config.collection()] = config.toNamedValuesDto(); } }); return { Collections: collectionsDto, PolicyCheckFrequency: this.policyCheckFrequency() ? generalUtils.formatAsTimeSpan(this.policyCheckFrequency() * 1000) : null, NamedValues : namedValuesDto } } saveChanges() { // first apply current changes: const itemBeingEdited = this.currentlyEditedItem(); if (itemBeingEdited) { if (this.isValid(itemBeingEdited.validationGroup)) { this.applyChanges(); if (this.currentlyEditedItem()) { // looks like we didn't exit edit mode - validation errors? return; } } else { // we have validation error - stop saving return; } } this.spinners.save(true); eventsCollector.default.reportEvent("timeSeriesSettings", "save"); const dto = this.toDto(); new saveTimeSeriesConfigurationCommand(this.activeDatabase(), dto) .execute() .done(() => { this.dirtyFlag().reset(); messagePublisher.reportSuccess(`Time series configuration has been saved`); }) .always(() => { this.spinners.save(false); const db = this.activeDatabase(); db.hasRevisionsConfiguration(true); collectionsTracker.default.configureRevisions(db); }); } editItem(entry: timeSeriesConfigurationEntry) { this.currentBackingItem(entry); const clone = timeSeriesConfigurationEntry.empty().copyFrom(entry); this.currentlyEditedItem(clone); this.initTooltips(); } deleteItem(entry: timeSeriesConfigurationEntry) { this.selectedItems.remove(entry); this.perCollectionConfigurations.remove(entry); this.exitEditMode(); } exitEditMode() { this.currentBackingItem(null); this.currentlyEditedItem(null); } enableConfiguration(entry: timeSeriesConfigurationEntry) { entry.disabled(false); } disableConfiguration(entry: timeSeriesConfigurationEntry) { entry.disabled(true); } enableSelected() { this.selectedItems().forEach(item => item.disabled(false)); } disableSelected() { this.selectedItems().forEach(item => item.disabled(true)); } toggleSelectAll() { eventsCollector.default.reportEvent("timeSeries", "toggle-select-all"); const selectedCount = this.selectedItems().length; if (selectedCount > 0) { this.selectedItems([]); } else { const selectedItems = this.perCollectionConfigurations().slice(); this.selectedItems(selectedItems); } } } export = timeSeries;
{ "pile_set_name": "Github" }
namespace Apress.Recipes.WebApi { public class Player { public int Id { get; set; } public string Name { get; set; } public string Team { get; set; } public SkaterStat Stats { get; set; } } }
{ "pile_set_name": "Github" }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ /** * Support for integration tests for the Elasticsearch SQL CLI client * and integration tests shared between multiple qa projects. */ package org.elasticsearch.xpack.sql.qa.cli;
{ "pile_set_name": "Github" }
/***************************************************************************/ /* */ /* fnterrs.h */ /* */ /* Win FNT/FON error codes (specification only). */ /* */ /* Copyright 2001 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This file is used to define the Windows FNT/FON error enumeration */ /* constants. */ /* */ /*************************************************************************/ #ifndef __FNTERRS_H__ #define __FNTERRS_H__ #include FT_MODULE_ERRORS_H #undef __FTERRORS_H__ #define FT_ERR_PREFIX FNT_Err_ #define FT_ERR_BASE FT_Mod_Err_Winfonts #include FT_ERRORS_H #endif /* __FNTERRS_H__ */ /* END */
{ "pile_set_name": "Github" }
class IncludesMath include Math end
{ "pile_set_name": "Github" }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.pentaho.di.ui.trans.steps.olapinput; import java.io.IOException; import java.io.StringReader; import java.util.Hashtable; import java.util.Map; import java.util.Vector; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.LineStyleEvent; import org.eclipse.swt.custom.LineStyleListener; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; public class MDXValuesHighlight implements LineStyleListener { JavaScanner scanner = new JavaScanner(); int[] tokenColors; Color[] colors; Vector<int[]> blockComments = new Vector<int[]>(); public static final int EOF = -1; public static final int EOL = 10; public static final int WORD = 0; public static final int WHITE = 1; public static final int KEY = 2; public static final int COMMENT = 3; // single line comment: // public static final int STRING = 5; public static final int OTHER = 6; public static final int NUMBER = 7; public static final int FUNCTIONS = 8; public static final int MAXIMUM_TOKEN = 9; public MDXValuesHighlight() { initializeColors(); scanner = new JavaScanner(); } public MDXValuesHighlight( String[] strArrSQLFunctions ) { initializeColors(); scanner = new JavaScanner(); scanner.setSQLKeywords( strArrSQLFunctions ); scanner.initializeMDXFunctions(); } Color getColor( int type ) { if ( type < 0 || type >= tokenColors.length ) { return null; } return colors[tokenColors[type]]; } boolean inBlockComment( int start, int end ) { for ( int i = 0; i < blockComments.size(); i++ ) { int[] offsets = blockComments.elementAt( i ); // start of comment in the line if ( ( offsets[0] >= start ) && ( offsets[0] <= end ) ) { return true; } // end of comment in the line if ( ( offsets[1] >= start ) && ( offsets[1] <= end ) ) { return true; } if ( ( offsets[0] <= start ) && ( offsets[1] >= end ) ) { return true; } } return false; } void initializeColors() { Display display = Display.getDefault(); colors = new Color[] { new Color( display, new RGB( 0, 0, 0 ) ), // black new Color( display, new RGB( 255, 0, 0 ) ), // red new Color( display, new RGB( 63, 127, 95 ) ), // green new Color( display, new RGB( 0, 0, 255 ) ), // blue new Color( display, new RGB( 255, 0, 255 ) ) // SQL Functions / Rose }; tokenColors = new int[MAXIMUM_TOKEN]; tokenColors[WORD] = 0; tokenColors[WHITE] = 0; tokenColors[KEY] = 3; tokenColors[COMMENT] = 2; tokenColors[STRING] = 1; tokenColors[OTHER] = 0; tokenColors[NUMBER] = 0; tokenColors[FUNCTIONS] = 4; } void disposeColors() { for ( int i = 0; i < colors.length; i++ ) { colors[i].dispose(); } } /** * Event.detail line start offset (input) Event.text line text (input) LineStyleEvent.styles Enumeration of * StyleRanges, need to be in order. (output) LineStyleEvent.background line background color (output) */ public void lineGetStyle( LineStyleEvent event ) { Vector<StyleRange> styles = new Vector<StyleRange>(); int token; StyleRange lastStyle; if ( inBlockComment( event.lineOffset, event.lineOffset + event.lineText.length() ) ) { styles.addElement( new StyleRange( event.lineOffset, event.lineText.length() + 4, colors[1], null ) ); event.styles = new StyleRange[styles.size()]; styles.copyInto( event.styles ); return; } scanner.setRange( event.lineText ); String xs = ( (StyledText) event.widget ).getText(); if ( xs != null ) { parseBlockComments( xs ); } token = scanner.nextToken(); while ( token != EOF ) { if ( token != OTHER ) { if ( ( token == WHITE ) && ( !styles.isEmpty() ) ) { int start = scanner.getStartOffset() + event.lineOffset; lastStyle = styles.lastElement(); if ( lastStyle.fontStyle != SWT.NORMAL ) { if ( lastStyle.start + lastStyle.length == start ) { // have the white space take on the style before it to minimize font style // changes lastStyle.length += scanner.getLength(); } } } else { Color color = getColor( token ); if ( color != colors[0] ) { // hardcoded default foreground color, black StyleRange style = new StyleRange( scanner.getStartOffset() + event.lineOffset, scanner.getLength(), color, null ); // if ( token == KEY ) { // style.fontStyle = SWT.BOLD; // } if ( styles.isEmpty() ) { styles.addElement( style ); } else { lastStyle = styles.lastElement(); if ( lastStyle.similarTo( style ) && ( lastStyle.start + lastStyle.length == style.start ) ) { lastStyle.length += style.length; } else { styles.addElement( style ); } } } } } token = scanner.nextToken(); } event.styles = new StyleRange[styles.size()]; styles.copyInto( event.styles ); } public void parseBlockComments( String text ) { blockComments = new Vector<int[]>(); StringReader buffer = new StringReader( text ); int ch; boolean blkComment = false; int cnt = 0; int[] offsets = new int[2]; boolean done = false; try { while ( !done ) { switch ( ch = buffer.read() ) { case -1: { if ( blkComment ) { offsets[1] = cnt; blockComments.addElement( offsets ); } done = true; break; } case '/': { ch = buffer.read(); if ( ( ch == '*' ) && ( !blkComment ) ) { offsets = new int[2]; offsets[0] = cnt; blkComment = true; cnt++; } else { cnt++; } cnt++; break; } case '*': { if ( blkComment ) { ch = buffer.read(); cnt++; if ( ch == '/' ) { blkComment = false; offsets[1] = cnt; blockComments.addElement( offsets ); } } cnt++; break; } default: { cnt++; break; } } } } catch ( IOException e ) { // ignore errors } } /** * A simple fuzzy scanner for Java */ public class JavaScanner { protected Map<String, Integer> fgKeys = null; protected Map<?, ?> fgFunctions = null; protected Map<String, Integer> kfKeys = null; protected Map<?, ?> kfFunctions = null; protected StringBuilder fBuffer = new StringBuilder(); protected String fDoc; protected int fPos; protected int fEnd; protected int fStartToken; protected boolean fEofSeen = false; private String[] kfKeywords = { "Ancestor", "ClosingPeriod", "Cousin", "FirstChild", "FirstSibling", "Item", "Lag", "LastChild", "LastSibling", "Lead", "LinkMember", "OpeningPeriod", "ParallelPeriod", "Parent", "PrevMember", "StrToMember", "UnknownMember", "ValidMeasure", "Error", "Current", "Item", "Root", "StrToTuple", "Leaves", "This", "UserName", "UniqueName", "TupleToStr", "SetToStr", "Properties", "Name", "MemberToStr", "LookupCube", "IIf", "Generate", "CoalesceEmpty", "CalculationPassValue", "ISEMPTY", "ABSOLUTE", "COUNT", "AVERAGE", "min", "max" }; private String[] fgKeywords = { "ABSOLUTE", "DESC", "LEAVES", "SELF_BEFORE_AFTER", "INTERSECT", "SELECT", "on", "column", "crossjoin", "join", "or", "by", "non", "set", "all", "after", "distinct", "asc", "as", "and", "axis", "false", "true", "for", "null", "union", "global", "select", "columns", "row", "rows", "from", "cell", "call", "filter", "topsum", "freeze", "tree", "totals", "topcount", "type", "unique", "use", "pass", "post", "ignore", "value", "where", "with", "xor", "lead", "LASTCHILD", "value", "group", "generate", "cell", "calculations", "totals", "drop", "sort", "level", "sort", "DESCENDANTS", "DRILLDOWNLEVEL", "DRILLDOWNLEVELBOTTOM", "members", "DEFAULT_MEMBER", "DEFAULTMEMBER", "CHILDREN", "PAGES", "DIMENSIONS", "DIMENSION", "INDEX", "var", "RECURSIVE", "WITH", "CACHE", "filter", "NEXTMEMBER", "EMPTY", "MEASURE", "DISTINCTCOUNT", "UPDATE", "CUBE", "error" }; public JavaScanner() { initialize(); initializeMDXFunctions(); } /** * Returns the ending location of the current token in the document. */ public final int getLength() { return fPos - fStartToken; } /** * Initialize the lookup table. */ void initialize() { fgKeys = new Hashtable<String, Integer>(); Integer k = new Integer( KEY ); for ( int i = 0; i < fgKeywords.length; i++ ) { fgKeys.put( fgKeywords[i], k ); } } public void setSQLKeywords( String[] kfKeywords ) { this.kfKeywords = kfKeywords; } void initializeMDXFunctions() { kfKeys = new Hashtable<String, Integer>(); Integer k = new Integer( FUNCTIONS ); for ( int i = 0; i < kfKeywords.length; i++ ) { kfKeys.put( kfKeywords[i], k ); } } /** * Returns the starting location of the current token in the document. */ public final int getStartOffset() { return fStartToken; } /** * Returns the next lexical token in the document. */ public int nextToken() { int c; fStartToken = fPos; while ( true ) { switch ( c = read() ) { case EOF: return EOF; case '/': // comment c = read(); if ( c == '/' ) { while ( true ) { c = read(); if ( ( c == EOF ) || ( c == EOL ) ) { unread( c ); return COMMENT; } } } else { unread( c ); } return OTHER; case '-': // comment c = read(); if ( c == '-' ) { while ( true ) { c = read(); if ( ( c == EOF ) || ( c == EOL ) ) { unread( c ); return COMMENT; } } } else { unread( c ); } return OTHER; case '\'': // char const for ( ;; ) { c = read(); switch ( c ) { case '\'': return STRING; case EOF: unread( c ); return STRING; case '\\': c = read(); break; default: break; } } case '"': // string for ( ;; ) { c = read(); switch ( c ) { case '"': return STRING; case EOF: unread( c ); return STRING; case '\\': c = read(); break; default: break; } } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': do { c = read(); } while ( Character.isDigit( (char) c ) ); unread( c ); return NUMBER; default: if ( Character.isWhitespace( (char) c ) ) { do { c = read(); } while ( Character.isWhitespace( (char) c ) ); unread( c ); return WHITE; } if ( Character.isJavaIdentifierStart( (char) c ) ) { fBuffer.setLength( 0 ); do { fBuffer.append( (char) c ); c = read(); } while ( Character.isJavaIdentifierPart( (char) c ) ); unread( c ); Integer i = fgKeys.get( fBuffer.toString() ); if ( i != null ) { return i.intValue(); } i = kfKeys.get( fBuffer.toString() ); if ( i != null ) { return i.intValue(); } return WORD; } return OTHER; } } } /** * Returns next character. */ protected int read() { if ( fPos <= fEnd ) { return fDoc.charAt( fPos++ ); } return EOF; } public void setRange( String text ) { fDoc = text.toLowerCase(); fPos = 0; fEnd = fDoc.length() - 1; } protected void unread( int c ) { if ( c != EOF ) { fPos--; } } } }
{ "pile_set_name": "Github" }
package command import ( "strings" "github.com/mitchellh/cli" ) type SentinelCommand struct { Meta } func (f *SentinelCommand) Help() string { helpText := ` Usage: nomad sentinel <subcommand> [options] [args] This command groups subcommands for interacting with Sentinel policies. Sentinel policies allow operators to express fine-grained policies as code and have their policies automatically enforced. This allows operators to define a "sandbox" and restrict actions to only those compliant with policy. The Sentinel integration builds on the ACL System. Users can read existing Sentinel policies, create new policies, delete and list existing policies, and more. For a full guide on Sentinel policies see: https://www.nomadproject.io/guides/sentinel-policy.html Read an existing policy: $ nomad sentinel read <name> List existing policies: $ nomad sentinel list Create a new Sentinel policy: $ nomad sentinel apply <name> <path> Please see the individual subcommand help for detailed usage information. ` return strings.TrimSpace(helpText) } func (f *SentinelCommand) Synopsis() string { return "Interact with Sentinel policies" } func (f *SentinelCommand) Name() string { return "sentinel" } func (f *SentinelCommand) Run(args []string) int { return cli.RunResultHelp }
{ "pile_set_name": "Github" }
/* mpn/generic/mod_1.c forced to use mul-by-inverse udiv_qrnnd_preinv. Copyright 2000 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. The GNU MP Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with the GNU MP Library. If not, see https://www.gnu.org/licenses/. */ #define OPERATION_mod_1 #include "gmp-impl.h" #undef MOD_1_NORM_THRESHOLD #undef MOD_1_UNNORM_THRESHOLD #undef MOD_1N_TO_MOD_1_1_THRESHOLD #undef MOD_1U_TO_MOD_1_1_THRESHOLD #define MOD_1_NORM_THRESHOLD 0 #define MOD_1_UNNORM_THRESHOLD 0 #define MOD_1N_TO_MOD_1_1_THRESHOLD MP_SIZE_T_MAX #define MOD_1U_TO_MOD_1_1_THRESHOLD MP_SIZE_T_MAX #define __gmpn_mod_1 mpn_mod_1_inv #include "mpn/generic/mod_1.c"
{ "pile_set_name": "Github" }
// *************************************************************************** // * // * Copyright (C) 2010 International Business Machines // * Corporation and others. All Rights Reserved. // * Tool: com.ibm.icu.dev.tool.cldr.LDML2ICUConverter.java // * Source File:<path>/common/main/sr_Cyrl_BA.xml // * // *************************************************************************** sr_Cyrl_BA{ Version{"2.0.45.82"} calendar{ gregorian{ DateTimePatterns{ "HH 'часова', mm 'минута', ss 'секунди' zzzz", "HH.mm.ss z", "HH:mm:ss", "HH:mm", "EEEE, dd. MMMM y.", "dd. MMMM y.", "yyyy-MM-dd", "yy-MM-dd", "{1} {0}", "{1} {0}", "{1} {0}", "{1} {0}", "{1} {0}", } dayNames{ format{ abbreviated{ "нед", "пон", "уто", "сри", "чет", "пет", "суб", } wide{ "недеља", "понедељак", "уторак", "сриједа", "четвртак", "петак", "субота", } } } monthNames{ format{ wide{ "јануар", "фебруар", "март", "април", "мај", "јуни", "јули", "август", "септембар", "октобар", "новембар", "децембар", } } } } } }
{ "pile_set_name": "Github" }
<?php namespace Jane\OpenApiCommon; use Jane\JsonSchema\Generator\ChainGenerator; use Jane\JsonSchema\Generator\Context\Context; use Jane\JsonSchema\Generator\Naming; use Jane\JsonSchema\Guesser\ChainGuesser; use Jane\JsonSchema\Registry\Registry; use Jane\OpenApiCommon\Contracts\WhitelistFetchInterface; use Jane\OpenApiCommon\Guesser\Guess\ClassGuess; use Jane\OpenApiCommon\Guesser\Guess\MultipleClass; use Jane\OpenApiCommon\Registry\Registry as OpenApiRegistry; use Jane\OpenApiCommon\Registry\Schema; use Jane\OpenApiCommon\SchemaParser\SchemaParser; use Symfony\Component\Serializer\Encoder\JsonDecode; use Symfony\Component\Serializer\Encoder\JsonEncode; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Encoder\YamlEncoder; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; use Symfony\Component\Serializer\Serializer; use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\Yaml\Dumper; use Symfony\Component\Yaml\Parser; abstract class JaneOpenApi extends ChainGenerator { protected const OBJECT_NORMALIZER_CLASS = null; protected const WHITELIST_FETCH_CLASS = null; /** @var SchemaParser */ protected $schemaParser; /** @var ChainGuesser */ protected $chainGuesser; /** @var Naming */ protected $naming; /** @var bool */ protected $strict; /** @var SerializerInterface */ protected $serializer; public function __construct(string $schemaParserClass, ChainGuesser $chainGuesser, bool $strict = true) { $this->serializer = self::buildSerializer(); $this->schemaParser = new $schemaParserClass($this->serializer); $this->chainGuesser = $chainGuesser; $this->strict = $strict; $this->naming = new Naming(); } public function getSerializer(): SerializerInterface { return $this->serializer; } /** * @param OpenApiRegistry $registry */ public function createContext(Registry $registry): Context { /** @var Schema[] $schemas */ $schemas = array_values($registry->getSchemas()); foreach ($schemas as $schema) { $openApiSpec = $this->schemaParser->parseSchema($schema->getOrigin()); $this->chainGuesser->guessClass($openApiSpec, $schema->getRootName(), $schema->getOrigin() . '#', $registry); $schema->setParsed($openApiSpec); } foreach ($schemas as $schema) { foreach ($schema->getClasses() as $class) { $properties = $this->chainGuesser->guessProperties($class->getObject(), $schema->getRootName(), $class->getReference(), $registry); $names = []; foreach ($properties as $property) { $property->setPhpName($this->naming->getPropertyName($property->getName())); $i = 2; $newName = $property->getPhpName(); while (\in_array(strtolower($newName), $names, true)) { $newName = $property->getPhpName() . $i; ++$i; } if ($newName !== $property->getPhpName()) { $property->setPhpName($newName); } $names[] = strtolower($property->getPhpName()); $property->setType($this->chainGuesser->guessType($property->getObject(), $property->getName(), $property->getReference(), $registry)); } $class->setProperties($properties); $schema->addClassRelations($class); $extensionsTypes = []; foreach ($class->getExtensionsObject() as $pattern => $extensionData) { $extensionsTypes[$pattern] = $this->chainGuesser->guessType($extensionData['object'], $class->getName(), $extensionData['reference'], $registry); } $class->setExtensionsType($extensionsTypes); } $this->hydrateDiscriminatedClasses($schema, $registry); // when we have a whitelist, we want to have only needed models to be generated if (\count($registry->getWhitelistedPaths() ?? []) > 0) { $this->whitelistFetch($schema, $registry); } } return new Context($registry, $this->strict); } /** * @param OpenApiRegistry $registry */ protected function whitelistFetch(Schema $schema, Registry $registry): void { $whitelistFetchClass = static::WHITELIST_FETCH_CLASS; /** @var WhitelistFetchInterface $whitelistedSchema */ $whitelistedSchema = new $whitelistFetchClass($schema, self::buildSerializer()); foreach ($schema->getOperations() as $operation) { $whitelistedSchema->addOperationRelations($operation, $registry); } foreach ($schema->getClasses() as $class) { if (!$schema->needsRelation($class->getName())) { $schema->removeClass($class->getReference()); } } } protected function hydrateDiscriminatedClasses(Schema $schema, Registry $registry) { foreach ($schema->getClasses() as $class) { if ($class instanceof MultipleClass) { // is parent class foreach ($class->getReferences() as $reference) { $guess = $registry->getClass($reference); if ($guess instanceof ClassGuess) { // is child class $guess->setMultipleClass($class); } } } } } public static function buildSerializer() { $encoders = [ new JsonEncoder(new JsonEncode([JsonEncode::OPTIONS => JSON_UNESCAPED_SLASHES]), new JsonDecode()), new YamlEncoder(new Dumper(), new Parser()), ]; $objectNormalizerClass = static::OBJECT_NORMALIZER_CLASS; return new Serializer([new $objectNormalizerClass()], $encoders); } abstract protected static function create(array $options = []): self; abstract protected static function generators(DenormalizerInterface $denormalizer, array $options = []): \Generator; public static function build(array $options = []) { $instance = static::create($options); /** @var DenormalizerInterface $denormalizer */ $denormalizer = $instance->getSerializer(); $generators = static::generators($denormalizer, $options); foreach ($generators as $generator) { $instance->addGenerator($generator); } return $instance; } }
{ "pile_set_name": "Github" }
// // UIControl+LinkBlock.m // // Created by NOVO on 15/8/18. // Copyright (c) 2015年 NOVO. All rights reserved. // #import "LinkBlock.h" #import <objc/runtime.h> @implementation NSObject(UIControlLinkBlock) - (UIControl *(^)(BOOL))controlEnable { return ^id(BOOL enable){ LinkHandle_REF(UIControl) LinkGroupHandle_REF(controlEnable,enable) _self.enabled=enable; return _self; }; } - (UIControl *(^)(void))controlEnableYES { return ^id(){ LinkHandle_REF(UIControl) LinkGroupHandle_REF(controlEnableYES) _self.enabled=YES; return _self; }; } - (UIControl* (^)(void))controlEnableNO { return ^id(){ LinkHandle_REF(UIControl) LinkGroupHandle_REF(controlEnableNO) _self.enabled=NO; return _self; }; } - (UIControl *(^)(BOOL))controlSelected { return ^id(BOOL selected){ LinkHandle_REF(UIControl) LinkGroupHandle_REF(controlSelected,selected) _self.selected=selected; return _self; }; } - (UIControl *(^)(BOOL))controlHighlighted { return ^id(BOOL highlighted){ LinkHandle_REF(UIControl) LinkGroupHandle_REF(controlHighlighted,highlighted) _self.highlighted=highlighted; return _self; }; } - (UIControl *(^)(UIControlContentVerticalAlignment))controlContentVerticalAlignment { return ^id(UIControlContentVerticalAlignment alignment){ LinkHandle_REF(UIControl) LinkGroupHandle_REF(controlContentVerticalAlignment,alignment) _self.contentVerticalAlignment = alignment; return _self; }; } - (UIControl *(^)(UIControlContentHorizontalAlignment))controlContentHorizontalAlignment { return ^id(UIControlContentHorizontalAlignment alignment){ LinkHandle_REF(UIControl) LinkGroupHandle_REF(controlContentHorizontalAlignment,alignment) _self.contentHorizontalAlignment = alignment; return _self; }; } - (UIControl *(^)(void))controlSelectedYES { return ^id(){ LinkHandle_REF(UIControl) LinkGroupHandle_REF(controlSelectedYES) _self.selected=YES; return _self; }; } - (UIControl *(^)(void))controlSelectedNO { return ^id(){ LinkHandle_REF(UIControl) LinkGroupHandle_REF(controlSelectedYES) _self.selected=NO; return _self; }; } #define lb_controlContentHorizontalAlignment(symbol)\ \ - (UIControl *(^)(void))controlContentHorizontalAlignment##symbol\ {\ return ^id(){\ \ LinkHandle_REF(UIControl)\ LinkGroupHandle_REF(controlContentHorizontalAlignment##symbol)\ \ _self.contentHorizontalAlignment = UIControlContentHorizontalAlignment##symbol;\ return _self;\ };\ } lb_controlContentHorizontalAlignment(Center) lb_controlContentHorizontalAlignment(Left) lb_controlContentHorizontalAlignment(Right) lb_controlContentHorizontalAlignment(Fill) lb_controlContentHorizontalAlignment(Leading) lb_controlContentHorizontalAlignment(Trailing) //- (UIControl *(^)(void))controlContentVerticalAlignmentCenter #define lb_controlContentVerticalAlignment(symbol)\ \ - (UIControl *(^)(void))controlContentVerticalAlignment##symbol\ {\ return ^id(){\ \ LinkHandle_REF(UIControl)\ LinkGroupHandle_REF(controlContentVerticalAlignment##symbol)\ \ _self.contentHorizontalAlignment = UIControlContentVerticalAlignment##symbol;\ return _self;\ };\ } lb_controlContentVerticalAlignment(Center) lb_controlContentVerticalAlignment(Top) lb_controlContentVerticalAlignment(Bottom) lb_controlContentVerticalAlignment(Fill) @end
{ "pile_set_name": "Github" }
# !/bin/env python3 # encoding: utf-8 """ Comparison Study of Recent Unsupervised Domain Adaptation Approaches on Digit Benchmark """ import torch from torch import nn import numpy as np from salad.datasets.da import toy from salad.utils import config from salad.datasets.da import NoiseLoader from salad.datasets.transforms import SaltAndPepper from salad.models.digits import DigitModel from salad.datasets.transforms import Augmentation class ComparisonConfig(config.DomainAdaptConfig): """ Configuration for the comparison study """ _algorithms = ['adv', 'vada', 'dann', 'assoc', 'coral', 'teach'] def _init(self): super()._init() self.add_argument('--seed', default=None, type=int, help="Random Seed") self.add_argument('--print', action='store_true') for arg in self._algorithms: self.add_argument('--{}'.format(arg), action='store_true', help="Enable {}".format(arg)) def print_experiments(): import itertools datasets = ['mnist', 'synth', 'svhn'] algos = ComparisonConfig._algorithms s = [] for algo, source, target in itertools.product(algos, datasets, datasets): if source == target: continue print('python3 {} --{} --source {} --target {} {}'.format( __file__, algo, source, target, '--epochs 10' )) def experiment_setup(args): """ Set default params and construct models for various experiments """ model = DigitModel() teacher = DigitModel() disc = nn.Linear(128, 1) kwargs = { 'n_epochs': args.epochs, 'multiclass': True, 'learningrate': 3e-4, 'gpu': None if args.cpu else args.gpu, 'savedir': 'log/noise-{}-{}'.format(args.source, args.target), 'dryrun': args.dryrun } return model, teacher, disc, kwargs if __name__ == '__main__': from torch.utils.data import TensorDataset, DataLoader from salad.datasets import DigitsLoader from salad import solver import sys parser = ComparisonConfig('Domain Adapt Comparison') args = parser.parse_args() if args.print: print_experiments() sys.exit(0) parser.print_config() dataset_names = [args.source, args.target] loader_plain = NoiseLoader('/tmp/data', args.source, collate = 'stack', noisemodels=[lambda x : x, SaltAndPepper(0.15)],batch_size = 32, shuffle = True, normalize=False) loader_augment = NoiseLoader('/tmp/data', args.source, collate = 'stack', noisemodels=[lambda x : x, SaltAndPepper(0.15)],batch_size = 32, shuffle = True, normalize=False,augment={1: 2}) if args.adv: model, teacher, disc, kwargs = experiment_setup(args) experiment = solver.AdversarialDropoutSolver(model, loader_plain, **kwargs) experiment.optimize() if args.vada: model, teacher, disc, kwargs = experiment_setup(args) experiment = solver.VADASolver(model, disc, loader_plain, **kwargs) experiment.optimize() if args.dann: model, teacher, disc, kwargs = experiment_setup(args) experiment = solver.DANNSolver(model, disc, loader_plain, **kwargs) experiment.optimize() if args.assoc: model, teacher, disc, kwargs = experiment_setup(args) experiment = solver.AssociativeSolver(model, loader_plain, **kwargs) experiment.optimize() if args.coral: model, teacher, disc, kwargs = experiment_setup(args) experiment = solver.DeepCoralSolver(model, loader_plain, **kwargs) experiment.optimize() if args.teach: model, teacher, disc, kwargs = experiment_setup(args) experiment = solver.SelfEnsemblingSolver(model, teacher, loader_augment, **kwargs) experiment.optimize()
{ "pile_set_name": "Github" }
a
{ "pile_set_name": "Github" }
// 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. package org.chromium.content.browser; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import java.util.List; /** * Factory to create a LocationProvider to allow us to inject * a mock for tests. */ public class LocationProviderFactory { private static LocationProviderFactory.LocationProvider sProviderImpl; /** * LocationProviderFactory.get() returns an instance of this interface. */ public interface LocationProvider { public void start(boolean enableHighAccuracy); public void stop(); public boolean isRunning(); } private LocationProviderFactory() { } @VisibleForTesting public static void setLocationProviderImpl(LocationProviderFactory.LocationProvider provider) { assert sProviderImpl == null; sProviderImpl = provider; } public static LocationProvider get(Context context) { if (sProviderImpl == null) { sProviderImpl = new LocationProviderImpl(context); } return sProviderImpl; } /** * This is the core of android location provider. It is a separate class for clarity * so that it can manage all processing completely in the UI thread. The container class * ensures that the start/stop calls into this class are done in the UI thread. */ private static class LocationProviderImpl implements LocationListener, LocationProviderFactory.LocationProvider { // Log tag private static final String TAG = "cr.LocationProvider"; private Context mContext; private LocationManager mLocationManager; private boolean mIsRunning; LocationProviderImpl(Context context) { mContext = context; } /** * Start listening for location updates. * @param enableHighAccuracy Whether or not to enable high accuracy location providers. */ @Override public void start(boolean enableHighAccuracy) { unregisterFromLocationUpdates(); registerForLocationUpdates(enableHighAccuracy); } /** * Stop listening for location updates. */ @Override public void stop() { unregisterFromLocationUpdates(); } /** * Returns true if we are currently listening for location updates, false if not. */ @Override public boolean isRunning() { return mIsRunning; } @Override public void onLocationChanged(Location location) { // Callbacks from the system location service are queued to this thread, so it's // possible that we receive callbacks after unregistering. At this point, the // native object will no longer exist. if (mIsRunning) { updateNewLocation(location); } } private void updateNewLocation(Location location) { LocationProviderAdapter.newLocationAvailable( location.getLatitude(), location.getLongitude(), location.getTime() / 1000.0, location.hasAltitude(), location.getAltitude(), location.hasAccuracy(), location.getAccuracy(), location.hasBearing(), location.getBearing(), location.hasSpeed(), location.getSpeed()); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } private void ensureLocationManagerCreated() { if (mLocationManager != null) return; mLocationManager = (LocationManager) mContext.getSystemService( Context.LOCATION_SERVICE); if (mLocationManager == null) { Log.e(TAG, "Could not get location manager."); } } /** * Registers this object with the location service. */ private void registerForLocationUpdates(boolean enableHighAccuracy) { ensureLocationManagerCreated(); if (usePassiveOneShotLocation()) return; assert !mIsRunning; mIsRunning = true; // We're running on the main thread. The C++ side is responsible to // bounce notifications to the Geolocation thread as they arrive in the mainLooper. try { Criteria criteria = new Criteria(); if (enableHighAccuracy) criteria.setAccuracy(Criteria.ACCURACY_FINE); mLocationManager.requestLocationUpdates(0, 0, criteria, this, ThreadUtils.getUiThreadLooper()); } catch (SecurityException e) { Log.e(TAG, "Caught security exception while registering for location updates " + "from the system. The application does not have sufficient geolocation " + "permissions."); unregisterFromLocationUpdates(); // Propagate an error to JavaScript, this can happen in case of WebView // when the embedding app does not have sufficient permissions. LocationProviderAdapter.newErrorAvailable("application does not have sufficient " + "geolocation permissions."); } catch (IllegalArgumentException e) { Log.e(TAG, "Caught IllegalArgumentException registering for location updates."); unregisterFromLocationUpdates(); assert false; } } /** * Unregisters this object from the location service. */ private void unregisterFromLocationUpdates() { if (mIsRunning) { mIsRunning = false; mLocationManager.removeUpdates(this); } } private boolean usePassiveOneShotLocation() { if (!isOnlyPassiveLocationProviderEnabled()) return false; // Do not request a location update if the only available location provider is // the passive one. Make use of the last known location and call // onLocationChanged directly. final Location location = mLocationManager.getLastKnownLocation( LocationManager.PASSIVE_PROVIDER); if (location != null) { ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { updateNewLocation(location); } }); } return true; } /* * Checks if the passive location provider is the only provider available * in the system. */ private boolean isOnlyPassiveLocationProviderEnabled() { List<String> providers = mLocationManager.getProviders(true); return providers != null && providers.size() == 1 && providers.get(0).equals(LocationManager.PASSIVE_PROVIDER); } } }
{ "pile_set_name": "Github" }
/////////////////////////////////////////////////////////////////////////////// // Name: src/gtk1/renderer.cpp // Purpose: implementation of wxRendererNative for wxGTK // Author: Vadim Zeitlin // Modified by: // Created: 20.07.2003 // Copyright: (c) 2003 Vadim Zeitlin <[email protected]> // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // for compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #include "wx/renderer.h" #ifndef WX_PRECOMP #include "wx/window.h" #include "wx/dc.h" #endif #include <gtk/gtk.h> #include "wx/gtk1/win_gtk.h" #include "wx/gtk1/dcclient.h" // RR: After a correction to the orientation of the sash // this doesn't seem to be required anymore and it // seems to confuse some themes so USE_ERASE_RECT=0 #define USE_ERASE_RECT 0 // ---------------------------------------------------------------------------- // wxRendererGTK: our wxRendererNative implementation // ---------------------------------------------------------------------------- class WXDLLEXPORT wxRendererGTK : public wxDelegateRendererNative { public: // draw the header control button (used by wxListCtrl) virtual int DrawHeaderButton(wxWindow *win, wxDC& dc, const wxRect& rect, int flags = 0, wxHeaderSortIconType sortArrow = wxHDR_SORT_ICON_NONE, wxHeaderButtonParams* params=NULL); virtual void DrawSplitterBorder(wxWindow *win, wxDC& dc, const wxRect& rect, int flags = 0); virtual void DrawSplitterSash(wxWindow *win, wxDC& dc, const wxSize& size, wxCoord position, wxOrientation orient, int flags = 0); virtual void DrawComboBoxDropButton(wxWindow *win, wxDC& dc, const wxRect& rect, int flags = 0); virtual void DrawDropArrow(wxWindow *win, wxDC& dc, const wxRect& rect, int flags = 0); virtual wxSplitterRenderParams GetSplitterParams(const wxWindow *win); private: // FIXME: shouldn't we destroy these windows somewhere? // used by DrawHeaderButton and DrawComboBoxDropButton static GtkWidget *GetButtonWidget(); }; // ============================================================================ // implementation // ============================================================================ /* static */ wxRendererNative& wxRendererNative::GetDefault() { static wxRendererGTK s_rendererGTK; return s_rendererGTK; } // ---------------------------------------------------------------------------- // helper functions // ---------------------------------------------------------------------------- GtkWidget * wxRendererGTK::GetButtonWidget() { static GtkWidget *s_button = NULL; static GtkWidget *s_window = NULL; if ( !s_button ) { s_window = gtk_window_new( GTK_WINDOW_POPUP ); gtk_widget_realize( s_window ); s_button = gtk_button_new(); gtk_container_add( GTK_CONTAINER(s_window), s_button ); gtk_widget_realize( s_button ); } return s_button; } // ---------------------------------------------------------------------------- // list/tree controls drawing // ---------------------------------------------------------------------------- int wxRendererGTK::DrawHeaderButton(wxWindow *win, wxDC& dc, const wxRect& rect, int flags, wxHeaderSortIconType WXUNUSED(sortArrow), wxHeaderButtonParams* WXUNUSED(params)) { GtkWidget *button = GetButtonWidget(); gtk_paint_box ( button->style, // FIXME: I suppose GTK_PIZZA(win->m_wxwindow)->bin_window doesn't work with wxMemoryDC. // Maybe use code similar as in DrawComboBoxDropButton below? GTK_PIZZA(win->m_wxwindow)->bin_window, flags & wxCONTROL_DISABLED ? GTK_STATE_INSENSITIVE : GTK_STATE_NORMAL, GTK_SHADOW_OUT, NULL, button, "button", dc.LogicalToDeviceX(rect.x) -1, rect.y -1, rect.width +2, rect.height +2 ); return rect.width + 2; } // ---------------------------------------------------------------------------- // splitter sash drawing // ---------------------------------------------------------------------------- // the full sash width (should be even) static const wxCoord SASH_SIZE = 8; // margin around the sash static const wxCoord SASH_MARGIN = 2; static int GetGtkSplitterFullSize() { return SASH_SIZE + SASH_MARGIN; } wxSplitterRenderParams wxRendererGTK::GetSplitterParams(const wxWindow *WXUNUSED(win)) { // we don't draw any border, hence 0 for the second field return wxSplitterRenderParams ( GetGtkSplitterFullSize(), 0, false // not ); } void wxRendererGTK::DrawSplitterBorder(wxWindow * WXUNUSED(win), wxDC& WXUNUSED(dc), const wxRect& WXUNUSED(rect), int WXUNUSED(flags)) { // nothing to do } void wxRendererGTK::DrawSplitterSash(wxWindow *win, wxDC& WXUNUSED(dc), const wxSize& size, wxCoord position, wxOrientation orient, int WXUNUSED(flags)) { if ( !win->m_wxwindow->window ) { // window not realized yet return; } wxCoord full_size = GetGtkSplitterFullSize(); // are we drawing vertical or horizontal splitter? const bool isVert = orient == wxVERTICAL; GdkRectangle rect; #if USE_ERASE_RECT GdkRectangle erase_rect; #endif if ( isVert ) { int h = win->GetClientSize().GetHeight(); rect.x = position; rect.y = 0; rect.width = full_size; rect.height = h; #if USE_ERASE_RECT erase_rect.x = position; erase_rect.y = 0; erase_rect.width = full_size; erase_rect.height = h; #endif } else // horz { int w = win->GetClientSize().GetWidth(); rect.x = 0; rect.y = position; rect.height = full_size; rect.width = w; #if USE_ERASE_RECT erase_rect.y = position; erase_rect.x = 0; erase_rect.height = full_size; erase_rect.width = w; #endif } #if USE_ERASE_RECT // we must erase everything first, otherwise the garbage // from the old sash is left when dragging it gtk_paint_flat_box ( win->m_wxwindow->style, GTK_PIZZA(win->m_wxwindow)->bin_window, GTK_STATE_NORMAL, GTK_SHADOW_NONE, NULL, win->m_wxwindow, (char *)"viewportbin", // const_cast erase_rect.x, erase_rect.y, erase_rect.width, erase_rect.height ); #endif // leave some margin before sash itself position += SASH_MARGIN / 2; // and finally draw it using GTK paint functions typedef void (*GtkPaintLineFunc)(GtkStyle *, GdkWindow *, GtkStateType, GdkRectangle *, GtkWidget *, gchar *, gint, gint, gint); GtkPaintLineFunc func = isVert ? gtk_paint_vline : gtk_paint_hline; (*func) ( win->m_wxwindow->style, GTK_PIZZA(win->m_wxwindow)->bin_window, GTK_STATE_NORMAL, NULL, win->m_wxwindow, (char *)"paned", // const_cast 0, isVert ? size.y : size.x, position + SASH_SIZE / 2 - 1 ); gtk_paint_box ( win->m_wxwindow->style, GTK_PIZZA(win->m_wxwindow)->bin_window, GTK_STATE_NORMAL, GTK_SHADOW_OUT, NULL, win->m_wxwindow, (char *)"paned", // const_cast isVert ? position : size.x - 2*SASH_SIZE, isVert ? size.y - 2*SASH_SIZE : position, SASH_SIZE, SASH_SIZE ); } void wxRendererGTK::DrawDropArrow(wxWindow *WXUNUSED(win), wxDC& dc, const wxRect& rect, int flags) { GtkWidget *button = GetButtonWidget(); // If we give GTK_PIZZA(win->m_wxwindow)->bin_window as // a window for gtk_paint_xxx function, then it won't // work for wxMemoryDC. So that is why we assume wxDC // is wxWindowDC (wxClientDC, wxMemoryDC and wxPaintDC // are derived from it) and use its m_window. wxWindowDCImpl * const impl = wxDynamicCast(dc.GetImpl(), wxWindowDCImpl); wxCHECK_RET( impl, "must have a window DC" ); GdkWindow* gdk_window = impl->GetGDKWindow(); // draw arrow so that there is even space horizontally // on both sides int arrowX = rect.width/4 + 1; int arrowWidth = rect.width - (arrowX*2); // scale arrow's height accoording to the width int arrowHeight = rect.width/3; int arrowY = (rect.height-arrowHeight)/2 + ((rect.height-arrowHeight) & 1); GtkStateType state; if ( flags & wxCONTROL_PRESSED ) state = GTK_STATE_ACTIVE; else if ( flags & wxCONTROL_DISABLED ) state = GTK_STATE_INSENSITIVE; else if ( flags & wxCONTROL_CURRENT ) state = GTK_STATE_PRELIGHT; else state = GTK_STATE_NORMAL; // draw arrow on button gtk_paint_arrow ( button->style, gdk_window, state, flags & wxCONTROL_PRESSED ? GTK_SHADOW_IN : GTK_SHADOW_OUT, NULL, button, "arrow", GTK_ARROW_DOWN, FALSE, rect.x + arrowX, rect.y + arrowY, arrowWidth, arrowHeight ); } void wxRendererGTK::DrawComboBoxDropButton(wxWindow *win, wxDC& dc, const wxRect& rect, int flags) { GtkWidget *button = GetButtonWidget(); // for reason why we do this, see DrawDropArrow wxWindowDCImpl * const impl = wxDynamicCast(dc.GetImpl(), wxWindowDCImpl); wxCHECK_RET( impl, "must have a window DC" ); GdkWindow* gdk_window = impl->GetGDKWindow(); // draw button GtkStateType state; if ( flags & wxCONTROL_PRESSED ) state = GTK_STATE_ACTIVE; else if ( flags & wxCONTROL_DISABLED ) state = GTK_STATE_INSENSITIVE; else if ( flags & wxCONTROL_CURRENT ) state = GTK_STATE_PRELIGHT; else state = GTK_STATE_NORMAL; gtk_paint_box ( button->style, gdk_window, state, flags & wxCONTROL_PRESSED ? GTK_SHADOW_IN : GTK_SHADOW_OUT, NULL, button, "button", rect.x, rect.y, rect.width, rect.height ); // draw arrow on button DrawDropArrow(win,dc,rect,flags); }
{ "pile_set_name": "Github" }
# $Id: loopback.py 38 2007-03-17 03:33:16Z dugsong $ """Platform-dependent loopback header.""" import dpkt, ethernet, ip, ip6 class Loopback(dpkt.Packet): __hdr__ = (('family', 'I', 0), ) __byte_order__ = '@' def unpack(self, buf): dpkt.Packet.unpack(self, buf) if self.family == 2: self.data = ip.IP(self.data) elif self.family == 0x02000000: self.family = 2 self.data = ip.IP(self.data) elif self.family in (24, 28, 30): self.data = ip6.IP6(self.data) elif self.family > 1500: self.data = ethernet.Ethernet(self.data)
{ "pile_set_name": "Github" }
'Duplicate assignment': null Templates: null 'Import theme': null 'Import succeeded!': null 'Import failed!': null 'Edit template: $1': null 'Set new name to': null 'Rename file': null 'Caching templates in:': null 'Caching templates finished': null 'Theme name': null 'Theme is assigned and can not be deleted': null 'Theme export was not successful. Check please that the server is not out of disk space.': null 'The theme can not be unassigned because it is in use by issues ($1) in this publication': null zip: null version: null uploaded: null updated: null 'or higher': null moved: null installed: null deleted: null 'You must select at least one template to perform an action.': null Upload: null 'Unassign theme': null 'Unassign successful': null Unassign: null 'Theme version': null 'Theme settings updated.': null 'Theme settings saved.': null 'Theme name / version': null 'Theme management': null 'Theme $1': null 'The file $1 is empty.': null 'Template object $1 was renamed to $2.': null 'Template object $1 was deleted.': null 'Template $1 was duplicated into $2.': null 'Template $1 $2.': null 'Something broke': null 'Section page template': null Saving..: null 'Saving settings failed.': null 'Save All': null 'Required Newscoop version': null Replace: null 'New template $1 created.': null 'New name': null 'Name cant be empty': null 'Last modified': null 'Issue page': null 'Go to parent': null 'Go to $1': null 'Geo Filtering': null 'Front page template': null 'File size': null 'File name': null 'File $1 was replaced.': null 'Failed unassigning theme': null Export: null 'Error page template': null 'Edit $1': null 'Done uploading': null 'Do you want to override $1?': null 'Directory is empty': null 'Directory $1 created.': null Design: null 'Delete theme': null 'Current directory:': null 'Create folder': null 'Create file': null 'Copy to available themes': null 'Copied successfully': null Compatibility: null 'Click to enlarge': null 'Choose destination': null 'Cant override directory $1.': null 'Cache Lifetime': null 'Browse for the theme': null 'Assigned successfully': null 'Article page template': null 'Article page': null 'Are you sure you want to unassign this theme?': null 'Are you sure you want to delete this theme?': null 'Add to publication': null '$1 is not writable': null '$1 $2': null '$1 files $2': null 'Available themes': null 'Update cached data': null 'Assigned templates': null 'Cached informations about theme playlists are not up to date!': null 'The theme''s configuration file does not contain information about the list of used featured articles.': null 'Below code should be placed into theme.xml (between ''theme'' nodes) file to make it work. This file is located in every theme''s main directory.': null
{ "pile_set_name": "Github" }
#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<map> #include<set> #include<vector> #include<utility> #include<queue> #include<stack> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); using namespace std; int k, N, n; string s, t, res, tmp; string process(string tmp){ string ret; int c1 = 0, c2 = 0; for(int i = 0; i < tmp.size(); i++){ if(tmp[i] == t[0]) c1++; else c2++; } // cout << c1 << " " << c2 << " " << t[0] << " " << t[1] << endl; if(c1 > 0 and c2 > 0){ if(c1 >= c2){ for(int i = 0; i < tmp.size(); i++){ if(tmp[i] == t[0]) ret += tmp[i]; } } else{ for(int i = 0; i < tmp.size(); i++){ if(tmp[i] != t[0]) ret += tmp[i]; } } return ret; } else{ return tmp; } } int main(){ cin >> s; N = s.length(); sd(k); for(int j = 0; j < k; j++){ cin >> t; n = s.length(); res = ""; for(int i = 0; i < n; i++){ if(s[i] != t[0] and s[i] != t[1]){ res += process(tmp); res += s[i]; tmp = ""; } else{ tmp += s[i]; } } if(tmp.length()){ res += process(tmp); tmp = ""; } s = res; // cout << s << endl; } cout << N - (s.length()) << endl; return 0; }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string msgid="4600421777120114993" name="abc_action_bar_home_description">"Nenda mwanzo"</string> <string msgid="1397052879051804371" name="abc_action_bar_home_description_format">"%1$s, %2$s"</string> <string msgid="6623331958280229229" name="abc_action_bar_home_subtitle_description_format">"%1$s, %2$s, %3$s"</string> <string msgid="1594238315039666878" name="abc_action_bar_up_description">"Nenda juu"</string> <string msgid="3588849162933574182" name="abc_action_menu_overflow_description">"Chaguo zaidi"</string> <string msgid="4076576682505996667" name="abc_action_mode_done">"Nimemaliza"</string> <string msgid="7468859129482906941" name="abc_activity_chooser_view_see_all">"Angalia zote"</string> <string msgid="2031811694353399454" name="abc_activitychooserview_choose_application">"Chagua programu"</string> <string msgid="121134116657445385" name="abc_capital_off">"IMEZIMWA"</string> <string msgid="3405795526292276155" name="abc_capital_on">"IMEWASHWA"</string> <string msgid="7723749260725869598" name="abc_search_hint">"Tafuta…"</string> <string msgid="3691816814315814921" name="abc_searchview_description_clear">"Futa hoja"</string> <string msgid="2550479030709304392" name="abc_searchview_description_query">"Hoja ya utafutaji"</string> <string msgid="8264924765203268293" name="abc_searchview_description_search">"Tafuta"</string> <string msgid="8928215447528550784" name="abc_searchview_description_submit">"Wasilisha hoja"</string> <string msgid="893419373245838918" name="abc_searchview_description_voice">"Tafuta kwa kutamka"</string> <string msgid="3421042268587513524" name="abc_shareactionprovider_share_with">"Shiriki na:"</string> <string msgid="7165123711973476752" name="abc_shareactionprovider_share_with_application">"Shiriki na %s"</string> <string msgid="1603543279005712093" name="abc_toolbar_collapse_description">"Kunja"</string> <string msgid="146198913615257606" name="search_menu_title">"Tafuta"</string> <string msgid="2869576371154716097" name="status_bar_notification_info_overflow">"999+"</string> </resources>
{ "pile_set_name": "Github" }
/** * Special options passed to Repository#save, Repository#insert and Repository#update methods. */ export interface SaveOptions { /** * Additional data to be passed with persist method. * This data can be used in subscribers then. */ data?: any; /** * Indicates if listeners and subscribers are called for this operation. * By default they are enabled, you can disable them by setting { listeners: false } in save/remove options. */ listeners?: boolean; /** * By default transactions are enabled and all queries in persistence operation are wrapped into the transaction. * You can disable this behaviour by setting { transaction: false } in the persistence options. */ transaction?: boolean; /** * Breaks save execution into chunks of a given size. * For example, if you want to save 100,000 objects but you have issues with saving them, * you can break them into 10 groups of 10,000 objects (by setting { chunk: 10000 }) and save each group separately. * This option is needed to perform very big insertions when you have issues with underlying driver parameter number limitation. */ chunk?: number; /** * Flag to determine whether the entity that is being persisted * should be reloaded during the persistence operation. * * It will work only on databases which does not support RETURNING / OUTPUT statement. * Enabled by default. */ reload?: boolean; }
{ "pile_set_name": "Github" }
package com.phauer.modernunittesting; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ModernUnitTestingApplication { public static void main(String[] args) { SpringApplication.run(ModernUnitTestingApplication.class, args); } }
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Paillave.Etl.Core.TraceContents { public interface ITraceContent { string Type { get; } TraceLevel Level { get; } string Message { get; } } }
{ "pile_set_name": "Github" }
%s:11 PhanUnreferencedUseConstant Possibly zero references to use statement for constant MAGIC_FUNCTION (\ast\flags\MAGIC_FUNCTION) %s:15 PhanTypeMissingReturnReal Method \test is declared to return string in its real type signature but has no return value %s:17 PhanTypeSuspiciousEcho Suspicious argument $globalVar of type null= for an echo/print statement
{ "pile_set_name": "Github" }
package fasthttp_test import ( "bufio" "fmt" "log" "time" "github.com/valyala/fasthttp" ) func ExampleRequestCtx_SetBodyStreamWriter() { // Start fasthttp server for streaming responses. if err := fasthttp.ListenAndServe(":8080", responseStreamHandler); err != nil { log.Fatalf("unexpected error in server: %s", err) } } func responseStreamHandler(ctx *fasthttp.RequestCtx) { // Send the response in chunks and wait for a second between each chunk. ctx.SetBodyStreamWriter(func(w *bufio.Writer) { for i := 0; i < 10; i++ { fmt.Fprintf(w, "this is a message number %d", i) // Do not forget flushing streamed data to the client. if err := w.Flush(); err != nil { return } time.Sleep(time.Second) } }) }
{ "pile_set_name": "Github" }
// Versatile string -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. /** @file ext/vstring.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ext/vstring.h} */ #ifndef _VSTRING_TCC #define _VSTRING_TCC 1 #pragma GCC system_header #include <bits/cxxabi_forced.h> namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> const typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>::npos; template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> void __versa_string<_CharT, _Traits, _Alloc, _Base>:: resize(size_type __n, _CharT __c) { const size_type __size = this->size(); if (__size < __n) this->append(__n - __size, __c); else if (__n < __size) this->_M_erase(__n, __size - __n); } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base>& __versa_string<_CharT, _Traits, _Alloc, _Base>:: _M_append(const _CharT* __s, size_type __n) { const size_type __len = __n + this->size(); if (__len <= this->capacity() && !this->_M_is_shared()) { if (__n) this->_S_copy(this->_M_data() + this->size(), __s, __n); } else this->_M_mutate(this->size(), size_type(0), __s, __n); this->_M_set_length(__len); return *this; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> template<typename _InputIterator> __versa_string<_CharT, _Traits, _Alloc, _Base>& __versa_string<_CharT, _Traits, _Alloc, _Base>:: _M_replace_dispatch(const_iterator __i1, const_iterator __i2, _InputIterator __k1, _InputIterator __k2, std::__false_type) { const __versa_string __s(__k1, __k2); const size_type __n1 = __i2 - __i1; return _M_replace(__i1 - _M_ibegin(), __n1, __s._M_data(), __s.size()); } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base>& __versa_string<_CharT, _Traits, _Alloc, _Base>:: _M_replace_aux(size_type __pos1, size_type __n1, size_type __n2, _CharT __c) { _M_check_length(__n1, __n2, "__versa_string::_M_replace_aux"); const size_type __old_size = this->size(); const size_type __new_size = __old_size + __n2 - __n1; if (__new_size <= this->capacity() && !this->_M_is_shared()) { _CharT* __p = this->_M_data() + __pos1; const size_type __how_much = __old_size - __pos1 - __n1; if (__how_much && __n1 != __n2) this->_S_move(__p + __n2, __p + __n1, __how_much); } else this->_M_mutate(__pos1, __n1, 0, __n2); if (__n2) this->_S_assign(this->_M_data() + __pos1, __n2, __c); this->_M_set_length(__new_size); return *this; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base>& __versa_string<_CharT, _Traits, _Alloc, _Base>:: _M_replace(size_type __pos, size_type __len1, const _CharT* __s, const size_type __len2) { _M_check_length(__len1, __len2, "__versa_string::_M_replace"); const size_type __old_size = this->size(); const size_type __new_size = __old_size + __len2 - __len1; if (__new_size <= this->capacity() && !this->_M_is_shared()) { _CharT* __p = this->_M_data() + __pos; const size_type __how_much = __old_size - __pos - __len1; if (_M_disjunct(__s)) { if (__how_much && __len1 != __len2) this->_S_move(__p + __len2, __p + __len1, __how_much); if (__len2) this->_S_copy(__p, __s, __len2); } else { // Work in-place. if (__len2 && __len2 <= __len1) this->_S_move(__p, __s, __len2); if (__how_much && __len1 != __len2) this->_S_move(__p + __len2, __p + __len1, __how_much); if (__len2 > __len1) { if (__s + __len2 <= __p + __len1) this->_S_move(__p, __s, __len2); else if (__s >= __p + __len1) this->_S_copy(__p, __s + __len2 - __len1, __len2); else { const size_type __nleft = (__p + __len1) - __s; this->_S_move(__p, __s, __nleft); this->_S_copy(__p + __nleft, __p + __len2, __len2 - __nleft); } } } } else this->_M_mutate(__pos, __len1, __s, __len2); this->_M_set_length(__new_size); return *this; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base> operator+(const __versa_string<_CharT, _Traits, _Alloc, _Base>& __lhs, const __versa_string<_CharT, _Traits, _Alloc, _Base>& __rhs) { __versa_string<_CharT, _Traits, _Alloc, _Base> __str; __str.reserve(__lhs.size() + __rhs.size()); __str.append(__lhs); __str.append(__rhs); return __str; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base> operator+(const _CharT* __lhs, const __versa_string<_CharT, _Traits, _Alloc, _Base>& __rhs) { __glibcxx_requires_string(__lhs); typedef __versa_string<_CharT, _Traits, _Alloc, _Base> __string_type; typedef typename __string_type::size_type __size_type; const __size_type __len = _Traits::length(__lhs); __string_type __str; __str.reserve(__len + __rhs.size()); __str.append(__lhs, __len); __str.append(__rhs); return __str; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base> operator+(_CharT __lhs, const __versa_string<_CharT, _Traits, _Alloc, _Base>& __rhs) { __versa_string<_CharT, _Traits, _Alloc, _Base> __str; __str.reserve(__rhs.size() + 1); __str.push_back(__lhs); __str.append(__rhs); return __str; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base> operator+(const __versa_string<_CharT, _Traits, _Alloc, _Base>& __lhs, const _CharT* __rhs) { __glibcxx_requires_string(__rhs); typedef __versa_string<_CharT, _Traits, _Alloc, _Base> __string_type; typedef typename __string_type::size_type __size_type; const __size_type __len = _Traits::length(__rhs); __string_type __str; __str.reserve(__lhs.size() + __len); __str.append(__lhs); __str.append(__rhs, __len); return __str; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base> operator+(const __versa_string<_CharT, _Traits, _Alloc, _Base>& __lhs, _CharT __rhs) { __versa_string<_CharT, _Traits, _Alloc, _Base> __str; __str.reserve(__lhs.size() + 1); __str.append(__lhs); __str.push_back(__rhs); return __str; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: copy(_CharT* __s, size_type __n, size_type __pos) const { _M_check(__pos, "__versa_string::copy"); __n = _M_limit(__pos, __n); __glibcxx_requires_string_len(__s, __n); if (__n) this->_S_copy(__s, this->_M_data() + __pos, __n); // 21.3.5.7 par 3: do not append null. (good.) return __n; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__s, __n); const size_type __size = this->size(); const _CharT* __data = this->_M_data(); if (__n == 0) return __pos <= __size ? __pos : npos; if (__n <= __size) { for (; __pos <= __size - __n; ++__pos) if (traits_type::eq(__data[__pos], __s[0]) && traits_type::compare(__data + __pos + 1, __s + 1, __n - 1) == 0) return __pos; } return npos; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { size_type __ret = npos; const size_type __size = this->size(); if (__pos < __size) { const _CharT* __data = this->_M_data(); const size_type __n = __size - __pos; const _CharT* __p = traits_type::find(__data + __pos, __n, __c); if (__p) __ret = __p - __data; } return __ret; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: rfind(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__s, __n); const size_type __size = this->size(); if (__n <= __size) { __pos = std::min(size_type(__size - __n), __pos); const _CharT* __data = this->_M_data(); do { if (traits_type::compare(__data + __pos, __s, __n) == 0) return __pos; } while (__pos-- > 0); } return npos; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: rfind(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { size_type __size = this->size(); if (__size) { if (--__size > __pos) __size = __pos; for (++__size; __size-- > 0; ) if (traits_type::eq(this->_M_data()[__size], __c)) return __size; } return npos; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find_first_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__s, __n); for (; __n && __pos < this->size(); ++__pos) { const _CharT* __p = traits_type::find(__s, __n, this->_M_data()[__pos]); if (__p) return __pos; } return npos; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find_last_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__s, __n); size_type __size = this->size(); if (__size && __n) { if (--__size > __pos) __size = __pos; do { if (traits_type::find(__s, __n, this->_M_data()[__size])) return __size; } while (__size-- != 0); } return npos; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__s, __n); for (; __pos < this->size(); ++__pos) if (!traits_type::find(__s, __n, this->_M_data()[__pos])) return __pos; return npos; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find_first_not_of(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { for (; __pos < this->size(); ++__pos) if (!traits_type::eq(this->_M_data()[__pos], __c)) return __pos; return npos; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find_last_not_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__s, __n); size_type __size = this->size(); if (__size) { if (--__size > __pos) __size = __pos; do { if (!traits_type::find(__s, __n, this->_M_data()[__size])) return __size; } while (__size--); } return npos; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find_last_not_of(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { size_type __size = this->size(); if (__size) { if (--__size > __pos) __size = __pos; do { if (!traits_type::eq(this->_M_data()[__size], __c)) return __size; } while (__size--); } return npos; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> int __versa_string<_CharT, _Traits, _Alloc, _Base>:: compare(size_type __pos, size_type __n, const __versa_string& __str) const { _M_check(__pos, "__versa_string::compare"); __n = _M_limit(__pos, __n); const size_type __osize = __str.size(); const size_type __len = std::min(__n, __osize); int __r = traits_type::compare(this->_M_data() + __pos, __str.data(), __len); if (!__r) __r = this->_S_compare(__n, __osize); return __r; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> int __versa_string<_CharT, _Traits, _Alloc, _Base>:: compare(size_type __pos1, size_type __n1, const __versa_string& __str, size_type __pos2, size_type __n2) const { _M_check(__pos1, "__versa_string::compare"); __str._M_check(__pos2, "__versa_string::compare"); __n1 = _M_limit(__pos1, __n1); __n2 = __str._M_limit(__pos2, __n2); const size_type __len = std::min(__n1, __n2); int __r = traits_type::compare(this->_M_data() + __pos1, __str.data() + __pos2, __len); if (!__r) __r = this->_S_compare(__n1, __n2); return __r; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> int __versa_string<_CharT, _Traits, _Alloc, _Base>:: compare(const _CharT* __s) const { __glibcxx_requires_string(__s); const size_type __size = this->size(); const size_type __osize = traits_type::length(__s); const size_type __len = std::min(__size, __osize); int __r = traits_type::compare(this->_M_data(), __s, __len); if (!__r) __r = this->_S_compare(__size, __osize); return __r; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> int __versa_string <_CharT, _Traits, _Alloc, _Base>:: compare(size_type __pos, size_type __n1, const _CharT* __s) const { __glibcxx_requires_string(__s); _M_check(__pos, "__versa_string::compare"); __n1 = _M_limit(__pos, __n1); const size_type __osize = traits_type::length(__s); const size_type __len = std::min(__n1, __osize); int __r = traits_type::compare(this->_M_data() + __pos, __s, __len); if (!__r) __r = this->_S_compare(__n1, __osize); return __r; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> int __versa_string <_CharT, _Traits, _Alloc, _Base>:: compare(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) const { __glibcxx_requires_string_len(__s, __n2); _M_check(__pos, "__versa_string::compare"); __n1 = _M_limit(__pos, __n1); const size_type __len = std::min(__n1, __n2); int __r = traits_type::compare(this->_M_data() + __pos, __s, __len); if (!__r) __r = this->_S_compare(__n1, __n2); return __r; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __in, __gnu_cxx::__versa_string<_CharT, _Traits, _Alloc, _Base>& __str) { typedef basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; typedef __gnu_cxx::__versa_string<_CharT, _Traits, _Alloc, _Base> __string_type; typedef typename __istream_type::int_type __int_type; typedef typename __string_type::size_type __size_type; typedef ctype<_CharT> __ctype_type; typedef typename __ctype_type::ctype_base __ctype_base; __size_type __extracted = 0; typename __ios_base::iostate __err = __ios_base::goodbit; typename __istream_type::sentry __cerb(__in, false); if (__cerb) { __try { // Avoid reallocation for common case. __str.erase(); _CharT __buf[128]; __size_type __len = 0; const streamsize __w = __in.width(); const __size_type __n = __w > 0 ? static_cast<__size_type>(__w) : __str.max_size(); const __ctype_type& __ct = use_facet<__ctype_type>(__in.getloc()); const __int_type __eof = _Traits::eof(); __int_type __c = __in.rdbuf()->sgetc(); while (__extracted < __n && !_Traits::eq_int_type(__c, __eof) && !__ct.is(__ctype_base::space, _Traits::to_char_type(__c))) { if (__len == sizeof(__buf) / sizeof(_CharT)) { __str.append(__buf, sizeof(__buf) / sizeof(_CharT)); __len = 0; } __buf[__len++] = _Traits::to_char_type(__c); ++__extracted; __c = __in.rdbuf()->snextc(); } __str.append(__buf, __len); if (_Traits::eq_int_type(__c, __eof)) __err |= __ios_base::eofbit; __in.width(0); } __catch(__cxxabiv1::__forced_unwind&) { __in._M_setstate(__ios_base::badbit); __throw_exception_again; } __catch(...) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 91. Description of operator>> and getline() for string<> // might cause endless loop __in._M_setstate(__ios_base::badbit); } } // 211. operator>>(istream&, string&) doesn't set failbit if (!__extracted) __err |= __ios_base::failbit; if (__err) __in.setstate(__err); return __in; } template<typename _CharT, typename _Traits, typename _Alloc, template <typename, typename, typename> class _Base> basic_istream<_CharT, _Traits>& getline(basic_istream<_CharT, _Traits>& __in, __gnu_cxx::__versa_string<_CharT, _Traits, _Alloc, _Base>& __str, _CharT __delim) { typedef basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; typedef __gnu_cxx::__versa_string<_CharT, _Traits, _Alloc, _Base> __string_type; typedef typename __istream_type::int_type __int_type; typedef typename __string_type::size_type __size_type; __size_type __extracted = 0; const __size_type __n = __str.max_size(); typename __ios_base::iostate __err = __ios_base::goodbit; typename __istream_type::sentry __cerb(__in, true); if (__cerb) { __try { // Avoid reallocation for common case. __str.erase(); _CharT __buf[128]; __size_type __len = 0; const __int_type __idelim = _Traits::to_int_type(__delim); const __int_type __eof = _Traits::eof(); __int_type __c = __in.rdbuf()->sgetc(); while (__extracted < __n && !_Traits::eq_int_type(__c, __eof) && !_Traits::eq_int_type(__c, __idelim)) { if (__len == sizeof(__buf) / sizeof(_CharT)) { __str.append(__buf, sizeof(__buf) / sizeof(_CharT)); __len = 0; } __buf[__len++] = _Traits::to_char_type(__c); ++__extracted; __c = __in.rdbuf()->snextc(); } __str.append(__buf, __len); if (_Traits::eq_int_type(__c, __eof)) __err |= __ios_base::eofbit; else if (_Traits::eq_int_type(__c, __idelim)) { ++__extracted; __in.rdbuf()->sbumpc(); } else __err |= __ios_base::failbit; } __catch(__cxxabiv1::__forced_unwind&) { __in._M_setstate(__ios_base::badbit); __throw_exception_again; } __catch(...) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 91. Description of operator>> and getline() for string<> // might cause endless loop __in._M_setstate(__ios_base::badbit); } } if (!__extracted) __err |= __ios_base::failbit; if (__err) __in.setstate(__err); return __in; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _VSTRING_TCC
{ "pile_set_name": "Github" }