prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>expanded-and-path-remap-80832.rs<|end_file_name|><|fim▁begin|>// Test for issue 80832 // // pretty-mode:expanded // pp-exact:expanded-and-path-remap-80832.pp<|fim▁hole|>fn main() {}<|fim▁end|>
// compile-flags: --remap-path-prefix {{src-base}}=the/src
<|file_name|>03_map.py<|end_file_name|><|fim▁begin|># Bug in 2.7 base64.py _b32alphabet = {<|fim▁hole|> 1: 'B', 10: 'K', 19: 'T', 28: '4', 2: 'C', 11: 'L', 20: 'U', 29: '5', 3: 'D', 12: 'M', 21: 'V', 30: '6', 4: 'E', 13: 'N', 22: 'W', 31: '7', 5: 'F', 14: 'O', 23: 'X', 6: 'G', 15: 'P', 24: 'Y', 7: 'H', 16: 'Q', 25: 'Z', 8: 'I', 17: 'R', 26: '2', }<|fim▁end|>
0: 'A', 9: 'J', 18: 'S', 27: '3',
<|file_name|>apprunner.py<|end_file_name|><|fim▁begin|># This file is part of the Enkel web programming library. # # Copyright (C) 2007 Espen Angell Kristiansen ([email protected]) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # 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 # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from unittest import TestCase from cStringIO import StringIO from sys import exc_info from enkel.wansgli.apprunner import run_app, AppError, Response from enkel.wansgli.testhelpers import unit_case_suite, run_suite HEAD = "HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\n" ERRHEAD = "HTTP/1.1 500 ERROR\r\ncontent-type: text/plain\r\n" def only_header_app(env, start_response): start_response("200 OK", [("Content-type", "text/plain")]) return list() # return empty list def simple_app(env, start_response): start_response("200 OK", [("Content-type", "text/plain")]) return ["Simple app"] def using_write_app(env, start_response): """ WSGI app for testing of the write function. """ write = start_response("200 OK", [("Content-type", "text/plain")]) write("Using write") return [] def mixing_write_app(env, start_response): """ WSGI app for tesing of mixing using the write function and iterator. """ write = start_response("200 OK", [("Content-type", "text/plain")]) write("Mixing write... ") return [" ...and iterator."] def double_response_error_app(env, start_response): """ WSGI app for testing the situation when an error occurs BEFORE HTTP headers are sent to the browser and a traceback IS NOT supplied. <|fim▁hole|> This should produce an error, and the same will happen if start_response is called after HTTP headers are sent. """ start_response("200 OK", [("Content-type", "text/plain")]) start_response("500 ERROR", [("Content-type", "text/plain")]) return list() # return empty list def double_response_ok_app(env, start_response): """ WSGI app for testing the situation when an error occurs BEFORE HTTP headers are sent to the browser and a traceback is supplied. Should work. """ start_response("200 OK", [("Content-type", "text/plain")]) try: int("jeje") except ValueError: start_response("500 ERROR", [("Content-type", "text/plain")], exc_info()) return list() # return empty list class DoubleResponseErrInResponse(object): """ WSGI app for testing the situation when an error occurs AFTER HTTP headers are sent to the browser and a traceback is supplied. Should re-raise the ValueError raised when "four" is sent to the int function. """ def __init__(self, env, start_response): start_response("200 OK", [("Content-type", "text/plain")]) self.it = [1, "2", 3, "four", 5, "6"].__iter__() self.start_response = start_response def __iter__(self): for d in self.it: try: yield str(int(d)) # will fail on "four" except ValueError: self.start_response("500 ERROR", [("Content-type", "text/plain")], exc_info()) def noiter_app(env, start_response): """ An app that does not return an iterator. This is an error, and should raise AppError. """ start_response("200 OK", [("Content-type", "text/plain")]) return 10 def override_defaultheader(env, start_response): """ An app that overrides the default HTTP header "server". This should result in only one "server" header with the new value. """ start_response("200 OK", [ ("Content-type", "text/plain"), ("Server", "xxx") ]) return [] class TestApprunner(TestCase): """ Tests the entire apprunner module. """ def setUp(self): self.buf = StringIO() self.env = dict(SERVER_PROTOCOL="HTTP/1.1") self.sr = Response(self.buf, self.env) def test_only_header(self): run_app(only_header_app, self.sr) b = self.buf.getvalue() self.assert_(b.startswith(HEAD)) def test_simple(self): run_app(simple_app, self.sr) b = self.buf.getvalue() self.assert_(b.startswith(HEAD)) self.assert_(b.endswith("Simple app")) def test_using_write(self): run_app(using_write_app, self.sr) b = self.buf.getvalue() self.assert_(b.startswith(HEAD)) self.assert_(b.endswith("Using write")) def test_mixing_write(self): run_app(mixing_write_app, self.sr) b = self.buf.getvalue() self.assert_(b.startswith(HEAD)) self.assert_(b.endswith("Mixing write... ...and iterator.")) def test_double_response_error(self): self.assertRaises(AppError, run_app, double_response_error_app, self.sr) def test_double_response_ok(self): run_app(double_response_ok_app, self.sr) b = self.buf.getvalue() self.assert_(b.startswith(ERRHEAD)) def testDoubleResponseErrInResponse(self): self.assertRaises(ValueError, run_app, DoubleResponseErrInResponse, self.sr) def test_noiter(self): self.assertRaises(AppError, run_app, noiter_app, self.sr) def suite(): return unit_case_suite(TestApprunner) if __name__ == '__main__': run_suite(suite())<|fim▁end|>
<|file_name|>package-info.java<|end_file_name|><|fim▁begin|>/**<|fim▁hole|> * @author Sergio Merino */ package assembler;<|fim▁end|>
* This package provides the necessary classes to slice and compose a file. *
<|file_name|>correspondence_estimation_backprojection.hpp<|end_file_name|><|fim▁begin|>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2012-, Open Perception, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR 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. * * $Id: correspondence_estimation_backprojection.hpp 7230 2012-09-21 06:31:19Z rusu $ * */ #ifndef PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_HPP_ #define PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_HPP_ #include <pcl/registration/correspondence_estimation_normal_shooting.h> /////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> bool pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::initCompute () { if (!source_normals_ || !target_normals_) { PCL_WARN ("[pcl::registration::%s::initCompute] Datasets containing normals for source/target have not been given!\n", getClassName ().c_str ()); return (false); } return (CorrespondenceEstimationBase<PointSource, PointTarget, Scalar>::initCompute ()); } /////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::rotatePointCloudNormals ( const pcl::PointCloud<NormalT> &cloud_in, pcl::PointCloud<NormalT> &cloud_out, const Eigen::Matrix<Scalar, 4, 4> &transform) { if (&cloud_in != &cloud_out) { // Note: could be replaced by cloud_out = cloud_in cloud_out.header = cloud_in.header; cloud_out.width = cloud_in.width; cloud_out.height = cloud_in.height; cloud_out.is_dense = cloud_in.is_dense; cloud_out.points.reserve (cloud_out.points.size ()); cloud_out.points.assign (cloud_in.points.begin (), cloud_in.points.end ()); } for (size_t i = 0; i < cloud_out.points.size (); ++i) { // Rotate normals (WARNING: transform.rotation () uses SVD internally!) Eigen::Matrix<Scalar, 3, 1> nt (cloud_in[i].normal_x, cloud_in[i].normal_y, cloud_in[i].normal_z); cloud_out[i].normal_x = static_cast<float> (transform (0, 0) * nt.coeffRef (0) + transform (0, 1) * nt.coeffRef (1) + transform (0, 2) * nt.coeffRef (2)); cloud_out[i].normal_y = static_cast<float> (transform (1, 0) * nt.coeffRef (0) + transform (1, 1) * nt.coeffRef (1) + transform (1, 2) * nt.coeffRef (2)); cloud_out[i].normal_z = static_cast<float> (transform (2, 0) * nt.coeffRef (0) + transform (2, 1) * nt.coeffRef (1) + transform (2, 2) * nt.coeffRef (2)); } } /////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::determineCorrespondences ( pcl::Correspondences &correspondences, double max_distance) { if (!initCompute ()) return; typedef typename pcl::traits::fieldList<PointTarget>::type FieldListTarget; correspondences.resize (indices_->size ()); std::vector<int> nn_indices (k_); std::vector<float> nn_dists (k_); float min_dist = std::numeric_limits<float>::max (); int min_index = 0; pcl::Correspondence corr; unsigned int nr_valid_correspondences = 0; // Check if the template types are the same. If true, avoid a copy. // Both point types MUST be registered using the POINT_CLOUD_REGISTER_POINT_STRUCT macro! if (isSamePointType<PointSource, PointTarget> ()) { PointTarget pt; // Iterate over the input set of source indices for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i) { tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists); // Among the K nearest neighbours find the one with minimum perpendicular distance to the normal min_dist = std::numeric_limits<float>::max (); // Find the best correspondence for (size_t j = 0; j < nn_indices.size (); j++) { float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x + source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y + source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ; float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle); if (dist < min_dist) { min_dist = dist; min_index = static_cast<int> (j); } } if (min_dist > max_distance) continue; corr.index_query = *idx_i; corr.index_match = nn_indices[min_index]; corr.distance = nn_dists[min_index];//min_dist; correspondences[nr_valid_correspondences++] = corr; } } else { PointTarget pt; // Iterate over the input set of source indices for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i) { tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists); // Among the K nearest neighbours find the one with minimum perpendicular distance to the normal min_dist = std::numeric_limits<float>::max (); // Find the best correspondence for (size_t j = 0; j < nn_indices.size (); j++) { PointSource pt_src; // Copy the source data to a target PointTarget format so we can search in the tree pcl::for_each_type <FieldListTarget> (pcl::NdConcatenateFunctor <PointSource, PointTarget> ( input_->points[*idx_i], pt_src)); float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x + source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y + source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ; float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle); if (dist < min_dist) { min_dist = dist; min_index = static_cast<int> (j); } } if (min_dist > max_distance) continue; corr.index_query = *idx_i; corr.index_match = nn_indices[min_index]; corr.distance = nn_dists[min_index];//min_dist; correspondences[nr_valid_correspondences++] = corr; } } correspondences.resize (nr_valid_correspondences); deinitCompute (); } /////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::determineReciprocalCorrespondences ( pcl::Correspondences &correspondences, double max_distance) {<|fim▁hole|> typedef typename pcl::traits::fieldList<PointTarget>::type FieldListTarget; typedef typename pcl::intersect<FieldListSource, FieldListTarget>::type FieldList; // setup tree for reciprocal search pcl::KdTreeFLANN<PointSource> tree_reciprocal; // Set the internal point representation of choice if (point_representation_) tree_reciprocal.setPointRepresentation (point_representation_); tree_reciprocal.setInputCloud (input_, indices_); correspondences.resize (indices_->size ()); std::vector<int> nn_indices (k_); std::vector<float> nn_dists (k_); std::vector<int> index_reciprocal (1); std::vector<float> distance_reciprocal (1); float min_dist = std::numeric_limits<float>::max (); int min_index = 0; pcl::Correspondence corr; unsigned int nr_valid_correspondences = 0; int target_idx = 0; // Check if the template types are the same. If true, avoid a copy. // Both point types MUST be registered using the POINT_CLOUD_REGISTER_POINT_STRUCT macro! if (isSamePointType<PointSource, PointTarget> ()) { PointTarget pt; // Iterate over the input set of source indices for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i) { tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists); // Among the K nearest neighbours find the one with minimum perpendicular distance to the normal min_dist = std::numeric_limits<float>::max (); // Find the best correspondence for (size_t j = 0; j < nn_indices.size (); j++) { float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x + source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y + source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ; float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle); if (dist < min_dist) { min_dist = dist; min_index = static_cast<int> (j); } } if (min_dist > max_distance) continue; // Check if the correspondence is reciprocal target_idx = nn_indices[min_index]; tree_reciprocal.nearestKSearch (target_->points[target_idx], 1, index_reciprocal, distance_reciprocal); if (*idx_i != index_reciprocal[0]) continue; corr.index_query = *idx_i; corr.index_match = nn_indices[min_index]; corr.distance = nn_dists[min_index];//min_dist; correspondences[nr_valid_correspondences++] = corr; } } else { PointTarget pt; // Iterate over the input set of source indices for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i) { tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists); // Among the K nearest neighbours find the one with minimum perpendicular distance to the normal min_dist = std::numeric_limits<float>::max (); // Find the best correspondence for (size_t j = 0; j < nn_indices.size (); j++) { PointSource pt_src; // Copy the source data to a target PointTarget format so we can search in the tree pcl::for_each_type <FieldListTarget> (pcl::NdConcatenateFunctor <PointSource, PointTarget> ( input_->points[*idx_i], pt_src)); float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x + source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y + source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ; float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle); if (dist < min_dist) { min_dist = dist; min_index = static_cast<int> (j); } } if (min_dist > max_distance) continue; // Check if the correspondence is reciprocal target_idx = nn_indices[min_index]; tree_reciprocal.nearestKSearch (target_->points[target_idx], 1, index_reciprocal, distance_reciprocal); if (*idx_i != index_reciprocal[0]) continue; corr.index_query = *idx_i; corr.index_match = nn_indices[min_index]; corr.distance = nn_dists[min_index];//min_dist; correspondences[nr_valid_correspondences++] = corr; } } correspondences.resize (nr_valid_correspondences); deinitCompute (); } #endif // PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_HPP_<|fim▁end|>
if (!initCompute ()) return; typedef typename pcl::traits::fieldList<PointSource>::type FieldListSource;
<|file_name|>parse.py<|end_file_name|><|fim▁begin|>import xmltodict def parseData(data): try: return xmltodict.parse(data) except: <|fim▁hole|> return None else: raise Exception('Invalid XML data', data)<|fim▁end|>
if len(data.split()) is 0:
<|file_name|>grove_slide_potentiometer.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # GrovePi Example for using the Grove Slide Potentiometer (http://www.seeedstudio.com/wiki/Grove_-_Slide_Potentiometer) # # The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi # # Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi # ''' ## License The MIT License (MIT) GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi. Copyright (C) 2015 Dexter Industries Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell<|fim▁hole|>copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import time import grovepi # Connect the Grove Slide Potentiometer to analog port A0 # OUT,LED,VCC,GND slide = 0 # pin 1 (yellow wire) # The device has an onboard LED accessible as pin 2 on port A0 # OUT,LED,VCC,GND led = 1 # pin 2 (white wire) grovepi.pinMode(slide,"INPUT") grovepi.pinMode(led,"OUTPUT") time.sleep(1) while True: try: # Read sensor value from potentiometer sensor_value = grovepi.analogRead(slide) # Illuminate onboard LED if sensor_value > 500: grovepi.digitalWrite(led,1) else: grovepi.digitalWrite(led,0) print("sensor_value =", sensor_value) except IOError: print ("Error")<|fim▁end|>
<|file_name|>DatabaseHelper.java<|end_file_name|><|fim▁begin|>/* Copyright (C) 2011 Lorenzo Bernardi ([email protected]) 2010 Ben Van Daele ([email protected]) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package be.bernardi.mvforandroid.data; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "mvforandroid.db"; private static final int SCHEMA_VERSION = 3; public final Usage usage; public final Credit credit; public final Topups topups; public final Msisdns msisdns; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, SCHEMA_VERSION); this.usage = new Usage(); this.credit = new Credit(); this.topups = new Topups(); this.msisdns = new Msisdns(); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS " + Usage.TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "timestamp INTEGER NOT NULL, " + "duration INTEGER, " + "type INTEGER, " + "incoming INTEGER, " + "contact TEXT, " + "cost REAL);"); db.execSQL("CREATE TABLE IF NOT EXISTS " + Topups.TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "amount REAL NOT NULL, " + "method TEXT NOT NULL, " + "executed_on INTEGER NOT NULL, " + "received_on INTEGER, " + "status TEXT NOT NULL);"); db.execSQL("CREATE TABLE IF NOT EXISTS " + Credit.TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "valid_until INTEGER NULL, " + "expired INTEGER NOT NULL, " + "sms INTEGER NOT NULL, " + "data INTEGER NOT NULL, " + "credits REAL NOT NULL, " + "price_plan TEXT NOT NULL, " + "sms_son INTEGER NOT NULL);"); db.execSQL("CREATE TABLE IF NOT EXISTS " + Msisdns.TABLE_NAME + " (msisdn TEXT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { switch(oldVersion) { case 1: if(newVersion < 2) { return; } case 2: { db.execSQL("DROP TABLE " + Topups.TABLE_NAME + ";"); db.execSQL("CREATE TABLE IF NOT EXISTS " + Topups.TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "amount REAL NOT NULL, " + "method TEXT NOT NULL, " + "executed_on INTEGER NOT NULL, " + "received_on INTEGER, " + "status TEXT NOT NULL);"); break; } } } private static SimpleDateFormat apiFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private static Date getDateFromAPI(String dateString) { try { return apiFormat.parse(dateString); } catch(ParseException e) { return null; } } public class Credit { private static final String TABLE_NAME = "credit"; public void update(JSONObject json, boolean data_only) throws JSONException, NumberFormatException { Cursor query = getWritableDatabase().query(TABLE_NAME, new String[] { "_id" }, null, null, null, null, null, null); ContentValues values = new ContentValues(); values.put("valid_until", getDateFromAPI(json.getString("valid_until")).getTime()); values.put("expired", (Boolean.parseBoolean(json.getString("is_expired")) ? 1 : 0)); if(Boolean.parseBoolean(json.getString("is_expired")) == true) { values.put("data", 0); values.put("credits", 0); } else { values.put("data", Long.parseLong(json.getString("data"))); } values.put("price_plan", json.getString("price_plan")); if(!data_only) { values.put("credits", Double.parseDouble(json.getString("credits"))); values.put("sms", Integer.parseInt(json.getString("sms"))); values.put("sms_son", Integer.parseInt(json.getString("sms_super_on_net"))); } else { values.put("credits", 0); values.put("sms", 0); values.put("sms_son", 0); } if(query.getCount() == 0) { // No credit info stored yet, insert a row getWritableDatabase().insert(TABLE_NAME, "valid_until", values); } else { // Credit info present already, so update it getWritableDatabase().update(TABLE_NAME, values, null, null); } query.close(); } public long getValidUntil() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); long result; if(c.moveToFirst()) result = c.getLong(1); else result = 0; c.close(); return result; } public boolean isExpired() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); boolean result; if(c.moveToFirst()) result = c.getLong(2) == 1; else result = true; c.close(); return result; } public int getRemainingSms() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); int result; if(c.moveToFirst()) result = c.getInt(3); else result = 0; c.close(); return result; } public long getRemainingData() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); long result;<|fim▁hole|> result = 0; c.close(); return result; } public double getRemainingCredit() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); double result; if(c.moveToFirst()) result = c.getDouble(5); else result = 0; c.close(); return result; } public int getPricePlan() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); int result; if(c.moveToFirst()) result = c.getInt(6); else result = 0; c.close(); return result; } public int getRemainingSmsSuperOnNet() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); int result; if(c.moveToFirst()) result = c.getInt(7); else result = 0; c.close(); return result; } } public class Usage { private static final String TABLE_NAME = "usage"; public static final int TYPE_DATA = 0; public static final int TYPE_SMS = 1; public static final int TYPE_VOICE = 2; public static final int TYPE_MMS = 3; public static final int ORDER_BY_DATE = 1; public void update(JSONArray jsonArray) throws JSONException { getWritableDatabase().delete(TABLE_NAME, null, null); getWritableDatabase().beginTransaction(); for(int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); insert(json); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); } public void insert(JSONObject json) throws JSONException { // "timestamp INTEGER NOT NULL, " + // "duration INTEGER NOT NULL, " + // "type INTEGER NOT NULL, " + // "incoming INTEGER NOT NULL, " + // "contact TEXT NOT NULL, " + // "cost REAL NOT NULL);"); ContentValues values = new ContentValues(); values.put("timestamp", getDateFromAPI(json.getString("start_timestamp")).getTime()); values.put("duration", json.getLong("duration_connection")); if(Boolean.parseBoolean(json.getString("is_data"))) values.put("type", TYPE_DATA); if(Boolean.parseBoolean(json.getString("is_sms"))) values.put("type", TYPE_SMS); if(Boolean.parseBoolean(json.getString("is_voice"))) values.put("type", TYPE_VOICE); if(Boolean.parseBoolean(json.getString("is_mms"))) values.put("type", TYPE_MMS); values.put("incoming", (Boolean.parseBoolean(json.getString("is_incoming")) ? 1 : 0)); values.put("contact", json.getString("to")); values.put("cost", Double.parseDouble(json.getString("price"))); getWritableDatabase().insert(TABLE_NAME, "timestamp", values); } public Cursor get(long id) { return getReadableDatabase().query(TABLE_NAME, null, "_id=" + id, null, null, null, null); } /** * Returns a cursor over the Usage table. * * @param isSearch * Whether to include usage records obtained by a search, or * (xor) those obtained through auto-updating. * @param order * The constant representing the field to order the cursor * by. * @param ascending * Whether the order should be ascending or descending. */ public Cursor get(int order, boolean ascending) { String orderBy = null; switch(order) { case ORDER_BY_DATE: orderBy = "timestamp " + (ascending ? "asc" : "desc"); } return getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, orderBy); } public long getTimestamp(Cursor c) { return c.getLong(1); } public long getduration(Cursor c) { return c.getLong(2); } public int getType(Cursor c) { return c.getInt(3); } public boolean isIncoming(Cursor c) { return c.getInt(4) == 1; } public String getContact(Cursor c) { return c.getString(5); } public double getCost(Cursor c) { return c.getDouble(6); } } public class Topups { private static final String TABLE_NAME = "topups"; public void update(JSONArray jsonArray, boolean b) throws JSONException { getWritableDatabase().delete(TABLE_NAME, null, null); for(int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); insert(json); } } private void insert(JSONObject json) throws JSONException { ContentValues values = new ContentValues(); values.put("amount", Double.parseDouble(json.getString("amount"))); values.put("method", json.getString("method")); values.put("executed_on", getDateFromAPI(json.getString("executed_on")).getTime()); Log.d("MVFA", json.getString("payment_received_on")); if(!json.getString("payment_received_on").equals("null")) values.put("received_on", getDateFromAPI(json.getString("payment_received_on")).getTime()); values.put("status", json.getString("status")); getWritableDatabase().insert(TABLE_NAME, "timestamp", values); } public Cursor getAll() { return getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); } public double getAmount(Cursor c) { return c.getDouble(1); } public String getMethod(Cursor c) { return c.getString(2); } public long getExecutedOn(Cursor c) { return c.getLong(3); } public long getReceivedOn(Cursor c) { return c.getLong(4); } public String getStatus(Cursor c) { return c.getString(5); } } public class Msisdns { private static final String TABLE_NAME = "msisdns"; public void update(JSONArray jsonArray) throws JSONException { getWritableDatabase().delete(TABLE_NAME, null, null); for(int i = 0; i < jsonArray.length(); i++) { String msisdn = jsonArray.getString(i); insert(msisdn); } } private void insert(String msisdn) throws JSONException { ContentValues values = new ContentValues(); values.put("msisdn", msisdn); getWritableDatabase().insert(TABLE_NAME, "msisdn", values); } public Cursor getAll() { return getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); } public String[] getMsisdnList() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); String[] result = null; int i = 0; if(c.moveToFirst()) { do { i++; } while(c.moveToNext()); result = new String[i]; c.moveToFirst(); i = 0; do { if(c.getString(0) != null) { result[i] = c.getString(0); i++; } } while(c.moveToNext()); } c.close(); return result; } } }<|fim▁end|>
if(c.moveToFirst()) result = c.getLong(4); else
<|file_name|>virtualmachinescalesetvms.go<|end_file_name|><|fim▁begin|>package compute // Copyright (c) Microsoft and contributors. 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // VirtualMachineScaleSetVMsClient is the compute Client type VirtualMachineScaleSetVMsClient struct { BaseClient } // NewVirtualMachineScaleSetVMsClient creates an instance of the VirtualMachineScaleSetVMsClient client. func NewVirtualMachineScaleSetVMsClient(subscriptionID string) VirtualMachineScaleSetVMsClient { return NewVirtualMachineScaleSetVMsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewVirtualMachineScaleSetVMsClientWithBaseURI creates an instance of the VirtualMachineScaleSetVMsClient client // using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign // clouds, Azure stack). func NewVirtualMachineScaleSetVMsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineScaleSetVMsClient { return VirtualMachineScaleSetVMsClient{NewWithBaseURI(baseURI, subscriptionID)} } // Deallocate deallocates a specific virtual machine in a VM scale set. Shuts down the virtual machine and releases the // compute resources it uses. You are not billed for the compute resources of this virtual machine once it is // deallocated. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) Deallocate(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsDeallocateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Deallocate") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.DeallocatePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", nil, "Failure preparing request") return } result, err = client.DeallocateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", nil, "Failure sending request") return } return } // DeallocatePreparer prepares the Deallocate request. func (client VirtualMachineScaleSetVMsClient) DeallocatePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/deallocate", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeallocateSender sends the Deallocate request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) DeallocateSender(req *http.Request) (future VirtualMachineScaleSetVMsDeallocateFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsDeallocateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsDeallocateFuture") return } ar.Response = future.Response() return } return } // DeallocateResponder handles the response to the Deallocate request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) DeallocateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Delete deletes a virtual machine from a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) Delete(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsDeleteFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Delete") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.DeletePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", nil, "Failure preparing request") return } result, err = client.DeleteSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", nil, "Failure sending request") return } return } // DeletePreparer prepares the Delete request. func (client VirtualMachineScaleSetVMsClient) DeletePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) DeleteSender(req *http.Request) (future VirtualMachineScaleSetVMsDeleteFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsDeleteFuture") return } ar.Response = future.Response() return } return } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // Get gets a virtual machine from a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. // expand - the expand expression to apply on the operation. func (client VirtualMachineScaleSetVMsClient) Get(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, expand InstanceViewTypes) (result VirtualMachineScaleSetVM, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID, expand) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", resp, "Failure responding to request") return } return } // GetPreparer prepares the Get request. func (client VirtualMachineScaleSetVMsClient) GetPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, expand InstanceViewTypes) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if len(string(expand)) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) GetResponder(resp *http.Response) (result VirtualMachineScaleSetVM, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // GetInstanceView gets the status of a virtual machine from a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) GetInstanceView(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMInstanceView, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.GetInstanceView") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetInstanceViewPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", nil, "Failure preparing request") return } resp, err := client.GetInstanceViewSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", resp, "Failure sending request") return } result, err = client.GetInstanceViewResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", resp, "Failure responding to request") return } return } // GetInstanceViewPreparer prepares the GetInstanceView request. func (client VirtualMachineScaleSetVMsClient) GetInstanceViewPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/instanceView", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetInstanceViewSender sends the GetInstanceView request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) GetInstanceViewSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetInstanceViewResponder handles the response to the GetInstanceView request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) GetInstanceViewResponder(resp *http.Response) (result VirtualMachineScaleSetVMInstanceView, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List gets a list of all virtual machines in a VM scale sets. // Parameters: // resourceGroupName - the name of the resource group. // virtualMachineScaleSetName - the name of the VM scale set. // filter - the filter to apply to the operation. Allowed values are 'startswith(instanceView/statuses/code, // 'PowerState') eq true', 'properties/latestModelApplied eq true', 'properties/latestModelApplied eq false'. // selectParameter - the list parameters. Allowed values are 'instanceView', 'instanceView/statuses'. // expand - the expand expression to apply to the operation. Allowed values are 'instanceView'. func (client VirtualMachineScaleSetVMsClient) List(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, filter string, selectParameter string, expand string) (result VirtualMachineScaleSetVMListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.List") defer func() { sc := -1 if result.vmssvlr.Response.Response != nil { sc = result.vmssvlr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, resourceGroupName, virtualMachineScaleSetName, filter, selectParameter, expand) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.vmssvlr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure sending request") return } result.vmssvlr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure responding to request") return } if result.vmssvlr.hasNextLink() && result.vmssvlr.IsEmpty() { err = result.NextWithContext(ctx) return } return } // ListPreparer prepares the List request. func (client VirtualMachineScaleSetVMsClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, filter string, selectParameter string, expand string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if len(filter) > 0 { queryParameters["$filter"] = autorest.Encode("query", filter) } if len(selectParameter) > 0 { queryParameters["$select"] = autorest.Encode("query", selectParameter) } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) ListResponder(resp *http.Response) (result VirtualMachineScaleSetVMListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client VirtualMachineScaleSetVMsClient) listNextResults(ctx context.Context, lastResults VirtualMachineScaleSetVMListResult) (result VirtualMachineScaleSetVMListResult, err error) { req, err := lastResults.virtualMachineScaleSetVMListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client VirtualMachineScaleSetVMsClient) ListComplete(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, filter string, selectParameter string, expand string) (result VirtualMachineScaleSetVMListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx, resourceGroupName, virtualMachineScaleSetName, filter, selectParameter, expand) return } // PerformMaintenance shuts down the virtual machine in a VMScaleSet, moves it to an already updated node, and powers // it back on during the self-service phase of planned maintenance. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) PerformMaintenance(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsPerformMaintenanceFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.PerformMaintenance") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.PerformMaintenancePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PerformMaintenance", nil, "Failure preparing request") return } result, err = client.PerformMaintenanceSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PerformMaintenance", nil, "Failure sending request") return } return } // PerformMaintenancePreparer prepares the PerformMaintenance request. func (client VirtualMachineScaleSetVMsClient) PerformMaintenancePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/performMaintenance", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // PerformMaintenanceSender sends the PerformMaintenance request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) PerformMaintenanceSender(req *http.Request) (future VirtualMachineScaleSetVMsPerformMaintenanceFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsPerformMaintenanceFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsPerformMaintenanceFuture") return } ar.Response = future.Response() return } return } // PerformMaintenanceResponder handles the response to the PerformMaintenance request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) PerformMaintenanceResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // PowerOff power off (stop) a virtual machine in a VM scale set. Note that resources are still attached and you are // getting charged for the resources. Instead, use deallocate to release resources and avoid charges. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. // skipShutdown - the parameter to request non-graceful VM shutdown. True value for this flag indicates // non-graceful shutdown whereas false indicates otherwise. Default value for this flag is false if not // specified func (client VirtualMachineScaleSetVMsClient) PowerOff(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, skipShutdown *bool) (result VirtualMachineScaleSetVMsPowerOffFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.PowerOff") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.PowerOffPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID, skipShutdown) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", nil, "Failure preparing request") return } result, err = client.PowerOffSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", nil, "Failure sending request") return } return } // PowerOffPreparer prepares the PowerOff request. func (client VirtualMachineScaleSetVMsClient) PowerOffPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, skipShutdown *bool) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if skipShutdown != nil { queryParameters["skipShutdown"] = autorest.Encode("query", *skipShutdown) } else { queryParameters["skipShutdown"] = autorest.Encode("query", false) } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/poweroff", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // PowerOffSender sends the PowerOff request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) PowerOffSender(req *http.Request) (future VirtualMachineScaleSetVMsPowerOffFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsPowerOffFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsPowerOffFuture") return } ar.Response = future.Response() return } return } // PowerOffResponder handles the response to the PowerOff request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) PowerOffResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Redeploy shuts down the virtual machine in the virtual machine scale set, moves it to a new node, and powers it back // on. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) Redeploy(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsRedeployFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Redeploy") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.RedeployPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Redeploy", nil, "Failure preparing request") return } result, err = client.RedeploySender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Redeploy", nil, "Failure sending request") return } return } // RedeployPreparer prepares the Redeploy request. func (client VirtualMachineScaleSetVMsClient) RedeployPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/redeploy", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // RedeploySender sends the Redeploy request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) RedeploySender(req *http.Request) (future VirtualMachineScaleSetVMsRedeployFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsRedeployFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsRedeployFuture") return } ar.Response = future.Response() return } return } // RedeployResponder handles the response to the Redeploy request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) RedeployResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Reimage reimages (upgrade the operating system) a specific virtual machine in a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. // VMScaleSetVMReimageInput - parameters for the Reimaging Virtual machine in ScaleSet. func (client VirtualMachineScaleSetVMsClient) Reimage(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, VMScaleSetVMReimageInput *VirtualMachineScaleSetVMReimageParameters) (result VirtualMachineScaleSetVMsReimageFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Reimage") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.ReimagePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID, VMScaleSetVMReimageInput) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", nil, "Failure preparing request") return } result, err = client.ReimageSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", nil, "Failure sending request") return } return } // ReimagePreparer prepares the Reimage request. func (client VirtualMachineScaleSetVMsClient) ReimagePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, VMScaleSetVMReimageInput *VirtualMachineScaleSetVMReimageParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/reimage", pathParameters), autorest.WithQueryParameters(queryParameters)) if VMScaleSetVMReimageInput != nil { preparer = autorest.DecoratePreparer(preparer, autorest.WithJSON(VMScaleSetVMReimageInput)) } return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ReimageSender sends the Reimage request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) ReimageSender(req *http.Request) (future VirtualMachineScaleSetVMsReimageFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsReimageFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsReimageFuture") return } ar.Response = future.Response() return } return } // ReimageResponder handles the response to the Reimage request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) ReimageResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // ReimageAll allows you to re-image all the disks ( including data disks ) in the a VM scale set instance. This // operation is only supported for managed disks. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) ReimageAll(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsReimageAllFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.ReimageAll") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.ReimageAllPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "ReimageAll", nil, "Failure preparing request") return } result, err = client.ReimageAllSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "ReimageAll", nil, "Failure sending request") return } return } // ReimageAllPreparer prepares the ReimageAll request. func (client VirtualMachineScaleSetVMsClient) ReimageAllPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/reimageall", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ReimageAllSender sends the ReimageAll request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) ReimageAllSender(req *http.Request) (future VirtualMachineScaleSetVMsReimageAllFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsReimageAllFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsReimageAllFuture") return } ar.Response = future.Response() return } return } // ReimageAllResponder handles the response to the ReimageAll request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) ReimageAllResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Restart restarts a virtual machine in a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) Restart(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsRestartFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Restart") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.RestartPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", nil, "Failure preparing request") return } result, err = client.RestartSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", nil, "Failure sending request") return } return } // RestartPreparer prepares the Restart request. func (client VirtualMachineScaleSetVMsClient) RestartPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/restart", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // RestartSender sends the Restart request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) RestartSender(req *http.Request) (future VirtualMachineScaleSetVMsRestartFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsRestartFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsRestartFuture") return } ar.Response = future.Response() return } return } // RestartResponder handles the response to the Restart request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // RunCommand run command on a virtual machine in a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. // parameters - parameters supplied to the Run command operation. func (client VirtualMachineScaleSetVMsClient) RunCommand(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters RunCommandInput) (result VirtualMachineScaleSetVMsRunCommandFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.RunCommand") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.CommandID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { return result, validation.NewError("compute.VirtualMachineScaleSetVMsClient", "RunCommand", err.Error()) } req, err := client.RunCommandPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID, parameters) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "RunCommand", nil, "Failure preparing request") return } result, err = client.RunCommandSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "RunCommand", nil, "Failure sending request") return } return } // RunCommandPreparer prepares the RunCommand request. func (client VirtualMachineScaleSetVMsClient) RunCommandPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters RunCommandInput) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/runCommand", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // RunCommandSender sends the RunCommand request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) RunCommandSender(req *http.Request) (future VirtualMachineScaleSetVMsRunCommandFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (rcr RunCommandResult, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsRunCommandFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsRunCommandFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if rcr.Response.Response, err = future.GetResult(sender); err == nil && rcr.Response.Response.StatusCode != http.StatusNoContent { rcr, err = client.RunCommandResponder(rcr.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsRunCommandFuture", "Result", rcr.Response.Response, "Failure responding to request") } } return } return } // RunCommandResponder handles the response to the RunCommand request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) RunCommandResponder(resp *http.Response) (result RunCommandResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Start starts a virtual machine in a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set. // instanceID - the instance ID of the virtual machine. func (client VirtualMachineScaleSetVMsClient) Start(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsStartFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Start") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode<|fim▁hole|> tracing.EndSpan(ctx, sc, err) }() } req, err := client.StartPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", nil, "Failure preparing request") return } result, err = client.StartSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", nil, "Failure sending request") return } return } // StartPreparer prepares the Start request. func (client VirtualMachineScaleSetVMsClient) StartPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/start", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // StartSender sends the Start request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) StartSender(req *http.Request) (future VirtualMachineScaleSetVMsStartFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsStartFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsStartFuture") return } ar.Response = future.Response() return } return } // StartResponder handles the response to the Start request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Update updates a virtual machine of a VM scale set. // Parameters: // resourceGroupName - the name of the resource group. // VMScaleSetName - the name of the VM scale set where the extension should be create or updated. // instanceID - the instance ID of the virtual machine. // parameters - parameters supplied to the Update Virtual Machine Scale Sets VM operation. func (client VirtualMachineScaleSetVMsClient) Update(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters VirtualMachineScaleSetVM) (result VirtualMachineScaleSetVMsUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Update") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.DiskEncryptionKey", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.DiskEncryptionKey.SecretURL", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.DiskEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, }}, {Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.KeyEncryptionKey", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.KeyEncryptionKey.KeyURL", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.KeyEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, }}, }}, }}, }}, }}}}}); err != nil { return result, validation.NewError("compute.VirtualMachineScaleSetVMsClient", "Update", err.Error()) } req, err := client.UpdatePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID, parameters) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Update", nil, "Failure preparing request") return } result, err = client.UpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Update", nil, "Failure sending request") return } return } // UpdatePreparer prepares the Update request. func (client VirtualMachineScaleSetVMsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters VirtualMachineScaleSetVM) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } const APIVersion = "2019-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } parameters.InstanceID = nil parameters.Sku = nil parameters.Resources = nil parameters.Zones = nil preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) UpdateSender(req *http.Request) (future VirtualMachineScaleSetVMsUpdateFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = func(client VirtualMachineScaleSetVMsClient) (vmssv VirtualMachineScaleSetVM, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if vmssv.Response.Response, err = future.GetResult(sender); err == nil && vmssv.Response.Response.StatusCode != http.StatusNoContent { vmssv, err = client.UpdateResponder(vmssv.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsUpdateFuture", "Result", vmssv.Response.Response, "Failure responding to request") } } return } return } // UpdateResponder handles the response to the Update request. The method always // closes the http.Response Body. func (client VirtualMachineScaleSetVMsClient) UpdateResponder(resp *http.Response) (result VirtualMachineScaleSetVM, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }<|fim▁end|>
}
<|file_name|>error.rs<|end_file_name|><|fim▁begin|>use solicit::client::ClientConnectError; use solicit::http::client::tls::TlsConnectError; use openssl::ssl::error::SslError;<|fim▁hole|>use std::error::Error; use std::fmt; #[derive(Debug)] pub enum ProviderError { ClientConnectError(String), SslError(String) } impl From<SslError> for ProviderError { fn from(e: SslError) -> ProviderError { ProviderError::SslError(format!("Error generating an SSL context: {}", e.description())) } } impl From<ClientConnectError<TlsConnectError>> for ProviderError { fn from(e: ClientConnectError<TlsConnectError>) -> ProviderError { ProviderError::ClientConnectError(format!("Error connecting to the APNs servers: {}", e.description())) } } impl Error for ProviderError { fn description(&self) -> &str { "APNs connection failed" } fn cause(&self) -> Option<&Error> { None } } impl fmt::Display for ProviderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } }<|fim▁end|>
<|file_name|>SimRepAnaligRMSD.py<|end_file_name|><|fim▁begin|>import MDAnalysis import matplotlib.pyplot as plt import numpy as np from MDAnalysis.analysis.align import * from MDAnalysis.analysis.rms import rmsd def ligRMSD(u,ref): """ This function produces RMSD data and plots for ligand. :input 1) Universe of Trajectory 2) reference universe :return 1) matplot object 2) array for RMSD data. """ RMSD_lig = [] ligand = u.select_atoms("(resid 142:146) and not name H*") ## include selection based on user description #current = u.select_atoms("segname BGLC and not name H*") reference = ref.select_atoms("(resid 142:146) and not name H*") for ts in u.trajectory: A = ligand.coordinates() B = reference.coordinates() C = rmsd(A,B) RMSD_lig.append((u.trajectory.frame, C)) RMSD_lig = np.array(RMSD_lig) #print RMSD_lig import matplotlib.pyplot as plt ax = plt.subplot(111) ax.plot(RMSD_lig[:,0], RMSD_lig[:,1], 'r--', lw=2, label=r"$R_G$") ax.set_xlabel("Frame") ax.set_ylabel(r"RMSD of ligand ($\AA$)") #ax.figure.savefig("RMSD_ligand.pdf") #plt.draw() handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels, loc = 'lower left') return ax, RMSD_lig if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='This function will plot RMSD for a given universe (trajectory).') parser.add_argument('-j', '--jobname', help='Enter your job name and it will appear as first coloumn in the result file', default='Test') parser.add_argument('-trj', '--trajectory', help='Filename of Trajecotry file.', required=True) parser.add_argument('-top', '--topology', help='Filename of psf/topology file', required=True) args = parser.parse_args() <|fim▁hole|> fig,ligandRMSD = ligRMSD(u,ref) #print caRMSD np.savetxt(args.jobname+"_ligRMSD.data", ligandRMSD) fig.figure.savefig(args.jobname+"_ligRMSD.pdf")<|fim▁end|>
u = MDAnalysis.Universe(args.topology, args.trajectory) ref = MDAnalysis.Universe(args.topology, args.trajectory) ligandRMSD = []
<|file_name|>parser.rs<|end_file_name|><|fim▁begin|>use std::{fmt, mem}; use std::sync::{Arc, Mutex}; use itertools::{Itertools, MultiPeek}; use unicode::{self, UString}; use lang::{Context, Filter}; use lang::context::PrecedenceGroup; use util::Labeled; #[derive(Debug)] pub enum ParseError { InvalidToken(char), MismatchedParens(Token, Tf), NotAllowed(Filter), NotFullyParsed(Vec<Tf>), UnbalancedParen(Token) } #[derive(Debug)] pub enum Token { /// An unrecognized character Invalid(char), /// An opening parenthesis `(` OpenParen, /// A closing parenthesis `)` CloseParen, /// The sequential execution operator `;;`, and all following code AndThen(Code), /// A sequence of one or more whitespace characters Whitespace } //#[derive(Debug)] // https://github.com/bluss/rust-itertools/issues/32 enum CodeVariant { Empty, UString { s: UString, peek_index: usize }, UStringIter(MultiPeek<unicode::IntoIter>), Mutation } impl fmt::Debug for CodeVariant { // https://github.com/bluss/rust-itertools/issues/32 fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { match *self { CodeVariant::Empty => try!(write!(w, "CodeVariant::Empty")), CodeVariant::UString { ref s, ref peek_index } => try!(write!(w, "CodeVariant::UString {{ s: {:?}, peek_index: {:?} }}", s, peek_index)), CodeVariant::UStringIter(_) => try!(write!(w, "CodeVariant::UStringIter(/* ... */)")), CodeVariant::Mutation => try!(write!(w, "CodeVariant::Mutation")) } Ok(()) } } #[derive(Debug)] pub struct Code(Mutex<CodeVariant>); impl Code { fn peek(&mut self) -> Option<char> { let mut lock = self.0.lock().unwrap(); match *&mut *lock { CodeVariant::Empty => None, CodeVariant::UString { ref s, ref mut peek_index } => { if *peek_index < s.len() { *peek_index += 1; Some(s[*peek_index - 1]) } else { None } } CodeVariant::UStringIter(ref mut it) => { it.peek().map(|&c| c) } CodeVariant::Mutation => panic!("code mutex has been emptied") } } } impl Default for Code { fn default() -> Code { Code(Mutex::new(CodeVariant::Empty)) } } impl<T: Into<UString>> From<T> for Code { fn from(code_string: T) -> Code { Code(Mutex::new(CodeVariant::UString { s: code_string.into(), peek_index: 0 })) } } impl Clone for Code { fn clone(&self) -> Code { let mut lock = self.0.lock().unwrap(); match *&mut *lock { CodeVariant::Empty => Code(Mutex::new(CodeVariant::Empty)), CodeVariant::UString { ref s, .. } => Code(Mutex::new(CodeVariant::UString { s: s.clone(), peek_index: 0 })), ref mut code_variant @ CodeVariant::UStringIter(_) => { if let CodeVariant::UStringIter(it) = mem::replace(code_variant, CodeVariant::Mutation) { let s = it.collect::<UString>(); *code_variant = CodeVariant::UString { s: s.clone(), peek_index: 0 }; Code(Mutex::new(CodeVariant::UString { s: s, peek_index: 0 })) } else { unreachable!() } } CodeVariant::Mutation => panic!("code mutex has been emptied") } } } impl Iterator for Code { type Item = char; fn next(&mut self) -> Option<char> { let mut lock = self.0.lock().unwrap(); match *&mut *lock { CodeVariant::Empty => None, ref mut code_variant @ CodeVariant::UString { .. } => { if let CodeVariant::UString { s, .. } = mem::replace(code_variant, CodeVariant::Mutation) { let mut iter = s.into_iter().multipeek(); let result = iter.next(); *code_variant = CodeVariant::UStringIter(iter); result } else { unreachable!() } } CodeVariant::UStringIter(ref mut iter) => iter.next(), CodeVariant::Mutation => panic!("code mutex has been emptied") } } } struct Tokens { code: Code, // context: Context } impl Tokens { fn new<T: Into<Code>>(code: T, _: Context) -> Tokens { Tokens { code: code.into(), // context: context } } } impl Iterator for Tokens { type Item = Token; fn next(&mut self) -> Option<Token> { use self::Token::*; match self.code.next() { Some('\t') | Some('\n') | Some('\r') | Some(' ') => Some(Whitespace), Some('#') => { while self.code.peek().map(|c| c != '\n').unwrap_or(false) { self.code.next(); // discard comment contents } Some(Whitespace) // comments are treated as whitespace } Some('(') => Some(OpenParen), Some(')') => Some(CloseParen), Some(';') => { if self.code.peek() == Some(';') { self.code.next(); // discard the second semicolon Some(AndThen(mem::replace(&mut self.code, Code::default()))) } else { Some(Invalid(';')) } } Some(c) => Some(Invalid(c)), None => None } } } /// A token or filter, used by the in-place parsing algorithm. #[derive(Debug)] pub enum Tf { Token(Token), Filter(Filter) } /// Convert a sequence of tokens into an executable filter. pub fn parse<T: Into<Code>>(code: T, context: Context) -> Result<Filter, ParseError> { parse_inner(Tokens::new(code, context.clone()).map(Tf::Token), context) } fn parse_inner<I: IntoIterator<Item = Tf>>(tf_iter: I, context: Context) -> Result<Filter, ParseError> { let mut tf = tf_iter.into_iter().collect::<Vec<_>>(); // the list of tokens and filters on which the in-place parsing algorithm operates // error if any invalid token is found if let Some(pos) = tf.iter().position(|i| if let Tf::Token(Token::Invalid(_)) = *i { true } else { false }) { if let Tf::Token(Token::Invalid(c)) = tf[pos] { return Err(ParseError::InvalidToken(c)); } else { unreachable!(); } } // define the macro used for testing if filters are allowed macro_rules! try_filter { ($f:expr) => { match $f { f => { if (context.filter_allowed)(&f) { f } else { return Err(ParseError::NotAllowed(f)); } } } } } // remove leading and trailing whitespace as it is semantically irrelevant while let Some(&Tf::Token(Token::Whitespace)) = tf.first() { tf.remove(0); } while let Some(&Tf::Token(Token::Whitespace)) = tf.last() { tf.pop(); } // return an empty filter if the token list is empty if tf.len() == 0 { return Ok(try_filter!(Filter::Empty)); } // parse operators in decreasing precedence for (_, precedence_group) in context.operators.clone().into_iter().rev() { // iterate from highest to lowest precedence match precedence_group { PrecedenceGroup::AndThen => { let mut found = None; // flag any AndThen tokens and remember their contents for idx in (0..tf.len()).rev() { // iterate right-to-left for in-place manipulation if let Some(remaining_code) = mem::replace(&mut found, None) { if let Tf::Token(Token::Whitespace) = tf[idx] { // ignore whitespace between `;;` and its left operand tf.remove(idx); continue; } tf[idx] = Tf::Filter(try_filter!(Filter::AndThen { lhs: Box::new(if let Tf::Filter(ref lhs) = tf[idx] { lhs.clone() } else { try_filter!(Filter::Empty) }), remaining_code: remaining_code })); } else { match tf.remove(idx) { Tf::Token(Token::AndThen(remaining_code)) => { found = Some(remaining_code); // found an AndThen (`;;`), will be merged into a syntax tree with the element to its left } tf_item => { tf.insert(idx, tf_item); } } } } if let Some(remaining_code) = found { // the code begins with an `;;` tf.insert(0, Tf::Filter(try_filter!(Filter::AndThen { lhs: Box::new(try_filter!(Filter::Empty)), remaining_code: remaining_code }))); } } PrecedenceGroup::Circumfix => { let mut paren_balance = 0; // how many closing parens have not been matched by opening parens let mut paren_start = None; // the index of the outermost closing paren for idx in (0..tf.len()).rev() { // iterate right-to-left for in-place manipulation match tf[idx] { Tf::Token(Token::CloseParen) => { if paren_balance == 0 { paren_start = Some(idx); } paren_balance += 1; } Tf::Token(Token::OpenParen) => { paren_balance -= 1; if paren_balance < 0 { return Err(ParseError::UnbalancedParen(Token::OpenParen)); } else if paren_balance == 0 { if let Some(paren_start) = paren_start { if let Tf::Token(Token::CloseParen) = tf[paren_start] { tf.remove(paren_start); //let inner = tf.drain(idx + 1..paren_start).collect::<Vec<_>>(); //TODO use this when stabilized let mut inner = vec![]; for _ in idx + 1..paren_start { inner.push(tf.remove(idx + 1)); } tf[idx] = Tf::Filter(try_filter!(Filter::Custom { attributes: vec![try!(parse_inner(inner, context.clone()))],<|fim▁hole|> attrs[0].run(input, output) }))) })); } else { return Err(ParseError::MismatchedParens(Token::OpenParen, tf.remove(paren_start))); } } else { unreachable!(); } paren_start = None; } } _ => { continue; } } } if paren_balance > 0 { if let Some(paren_start) = paren_start { if let Tf::Token(Token::CloseParen) = tf[paren_start] { return Err(ParseError::UnbalancedParen(Token::CloseParen)); } else { unreachable!(); } } else { unreachable!(); } } } } } if tf.len() == 1 { match tf.pop() { Some(Tf::Filter(result)) => Ok(result), Some(Tf::Token(token)) => Err(ParseError::NotFullyParsed(vec![Tf::Token(token)])), None => unreachable!() } } else { Err(ParseError::NotFullyParsed(tf)) } }<|fim▁end|>
run: Box::new(Labeled::new("<filter group (α)>", Arc::new(|attrs, input, output| { assert_eq!(attrs.len(), 1);
<|file_name|>winusb.rs<|end_file_name|><|fim▁begin|>// Copyright © 2016-2017 winapi-rs developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms. //! FFI bindings to winusb. use shared::minwindef::{BOOL, LPDWORD, PUCHAR, PULONG, UCHAR, ULONG, USHORT}; use shared::usb::PUSBD_ISO_PACKET_DESCRIPTOR; use shared::usbspec::PUSB_CONFIGURATION_DESCRIPTOR; use shared::winusbio::{PWINUSB_PIPE_INFORMATION, PWINUSB_PIPE_INFORMATION_EX}; use um::minwinbase::LPOVERLAPPED; use um::winnt::{HANDLE, LARGE_INTEGER, LONG, PVOID}; pub type WINUSB_INTERFACE_HANDLE = PVOID; pub type PWINUSB_INTERFACE_HANDLE = *mut PVOID; pub type WINUSB_ISOCH_BUFFER_HANDLE = PVOID; pub type PWINUSB_ISOCH_BUFFER_HANDLE = *mut PVOID; STRUCT!{#[repr(packed)] struct WINUSB_SETUP_PACKET { RequestType: UCHAR, Request: UCHAR, Value: USHORT, Index: USHORT, Length: USHORT, }} pub type PWINUSB_SETUP_PACKET = *mut WINUSB_SETUP_PACKET; extern "system" { pub fn WinUsb_Initialize( DeviceHandle: HANDLE, InterfaceHandle: PWINUSB_INTERFACE_HANDLE, ) -> BOOL; pub fn WinUsb_Free( InterfaceHandle: WINUSB_INTERFACE_HANDLE, ) -> BOOL; pub fn WinUsb_GetAssociatedInterface( InterfaceHandle: WINUSB_INTERFACE_HANDLE, AssociatedInterfaceIndex: UCHAR, AssociatedInterfaceHandle: PWINUSB_INTERFACE_HANDLE, ) -> BOOL; pub fn WinUsb_GetDescriptor( InterfaceHandle: WINUSB_INTERFACE_HANDLE, DescriptorType: UCHAR, Index: UCHAR, LanguageID: USHORT, Buffer: PUCHAR, BufferLength: ULONG, LengthTransferred: PULONG, ) -> BOOL; pub fn WinUsb_QueryInterfaceSettings( InterfaceHandle: WINUSB_INTERFACE_HANDLE, AlternateInterfaceNumber: UCHAR, UsbAltInterfaceDescriptor: PUSB_INTERFACE_DESCRIPTOR, ) -> BOOL; pub fn WinUsb_QueryDeviceInformation( InterfaceHandle: WINUSB_INTERFACE_HANDLE, InformationType: ULONG, BufferLength: PULONG, Buffer: PVOID, ) -> BOOL; pub fn WinUsb_SetCurrentAlternateSetting( InterfaceHandle: WINUSB_INTERFACE_HANDLE, SettingNumber: UCHAR, ) -> BOOL; pub fn WinUsb_GetCurrentAlternateSetting( InterfaceHandle: WINUSB_INTERFACE_HANDLE, SettingNumber: PUCHAR, ) -> BOOL; pub fn WinUsb_QueryPipe( InterfaceHandle: WINUSB_INTERFACE_HANDLE, AlternateInterfaceNumber: UCHAR, PipeIndex: UCHAR, PipeInformationEx: PWINUSB_PIPE_INFORMATION, ) -> BOOL; pub fn WinUsb_QueryPipeEx( InterfaceHandle: WINUSB_INTERFACE_HANDLE, AlternateInterfaceNumber: UCHAR, PipeIndex: UCHAR, PipeInformationEx: PWINUSB_PIPE_INFORMATION_EX, ) -> BOOL; pub fn WinUsb_SetPipePolicy( InterfaceHandle: WINUSB_INTERFACE_HANDLE, PipeID: UCHAR, PolicyType: ULONG, ValueLength: ULONG, Value: PVOID, ) -> BOOL; pub fn WinUsb_GetPipePolicy( InterfaceHandle: WINUSB_INTERFACE_HANDLE, PipeID: UCHAR, PolicyType: ULONG, ValueLength: PULONG, Value: PVOID, ) -> BOOL; pub fn WinUsb_ReadPipe( InterfaceHandle: WINUSB_INTERFACE_HANDLE, PipeID: UCHAR, Buffer: PUCHAR, BufferLength: ULONG, LengthTransferred: PULONG, Overlapped: LPOVERLAPPED, ) -> BOOL; pub fn WinUsb_WritePipe( InterfaceHandle: WINUSB_INTERFACE_HANDLE, PipeID: UCHAR, Buffer: PUCHAR, BufferLength: ULONG, LengthTransferred: PULONG, Overlapped: LPOVERLAPPED, ) -> BOOL; pub fn WinUsb_ControlTransfer( InterfaceHandle: WINUSB_INTERFACE_HANDLE, SetupPacket: WINUSB_SETUP_PACKET, Buffer: PUCHAR, BufferLength: ULONG, LengthTransferred: PULONG, Overlapped: LPOVERLAPPED, ) -> BOOL; pub fn WinUsb_ResetPipe( InterfaceHandle: WINUSB_INTERFACE_HANDLE, PipeID: UCHAR, ) -> BOOL; pub fn WinUsb_AbortPipe( InterfaceHandle: WINUSB_INTERFACE_HANDLE, PipeID: UCHAR, ) -> BOOL; pub fn WinUsb_FlushPipe( InterfaceHandle: WINUSB_INTERFACE_HANDLE, PipeID: UCHAR, ) -> BOOL; pub fn WinUsb_SetPowerPolicy( InterfaceHandle: WINUSB_INTERFACE_HANDLE, PolicyType: ULONG, ValueLength: ULONG, Value: PVOID, ) -> BOOL; pub fn WinUsb_GetPowerPolicy( InterfaceHandle: WINUSB_INTERFACE_HANDLE, PolicyType: ULONG, ValueLength: PULONG, Value: PVOID, ) -> BOOL; pub fn WinUsb_GetOverlappedResult( InterfaceHandle: WINUSB_INTERFACE_HANDLE, lpOverlapped: LPOVERLAPPED, lpNumberOfBytesTransferred: LPDWORD, bWait: BOOL, ) -> BOOL;<|fim▁hole|> AlternateSetting: LONG, InterfaceClass: LONG, InterfaceSubClass: LONG, InterfaceProtocol: LONG, ) -> BOOL; pub fn WinUsb_ParseDescriptors( DescriptorBuffer: PVOID, TotalLength: ULONG, StartPosition: PVOID, DescriptorType: LONG, ) -> BOOL; pub fn WinUsb_GetCurrentFrameNumber( InterfaceHandle: WINUSB_INTERFACE_HANDLE, CurrentFrameNumber: PULONG, TimeStamp: *mut LARGE_INTEGER, ) -> BOOL; pub fn WinUsb_GetAdjustedFrameNumber( CurrentFrameNumber: PULONG, TimeStamp: LARGE_INTEGER, ) -> BOOL; pub fn WinUsb_RegisterIsochBuffer( InterfaceHandle: WINUSB_INTERFACE_HANDLE, PipeID: UCHAR, Buffer: PUCHAR, BufferLength: ULONG, IsochBufferHandle: PWINUSB_ISOCH_BUFFER_HANDLE, ) -> BOOL; pub fn WinUsb_UnregisterIsochBuffer( IsochBufferHandle: WINUSB_ISOCH_BUFFER_HANDLE, ) -> BOOL; pub fn WinUsb_WriteIsochPipe( BufferHandle: WINUSB_ISOCH_BUFFER_HANDLE, Offset: ULONG, Length: ULONG, FrameNumber: PULONG, Overlapped: LPOVERLAPPED, ) -> BOOL; pub fn WinUsb_ReadIsochPipe( BufferHandle: WINUSB_ISOCH_BUFFER_HANDLE, Offset: ULONG, Length: ULONG, FrameNumber: PULONG, NumberOfPackets: ULONG, IsoPacketDescriptors: PUSBD_ISO_PACKET_DESCRIPTOR, Overlapped: LPOVERLAPPED, ) -> BOOL; pub fn WinUsb_WriteIsochPipeAsap( BufferHandle: WINUSB_ISOCH_BUFFER_HANDLE, Offset: ULONG, Length: ULONG, ContinueStream: BOOL, Overlapped: LPOVERLAPPED, ) -> BOOL; pub fn WinUsb_ReadIsochPipeAsap( BufferHandle: WINUSB_ISOCH_BUFFER_HANDLE, Offset: ULONG, Length: ULONG, ContinueStream: BOOL, NumberOfPackets: ULONG, IsoPacketDescriptors: PUSBD_ISO_PACKET_DESCRIPTOR, Overlapped: LPOVERLAPPED, ) -> BOOL; } STRUCT!{struct USB_INTERFACE_DESCRIPTOR { bLength: UCHAR, bDescriptorType: UCHAR, bInterfaceNumber: UCHAR, bAlternateSetting: UCHAR, bNumEndpoints: UCHAR, bInterfaceClass: UCHAR, bInterfaceSubClass: UCHAR, bInterfaceProtocol: UCHAR, iInterface: UCHAR, }} pub type PUSB_INTERFACE_DESCRIPTOR = *mut USB_INTERFACE_DESCRIPTOR;<|fim▁end|>
pub fn WinUsb_ParseConfigurationDescriptor( ConfigurationDescriptor: PUSB_CONFIGURATION_DESCRIPTOR, StartPosition: PVOID, InterfaceNumber: LONG,
<|file_name|>unboxed-closures-drop.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // A battery of tests to ensure destructors of unboxed closure environments // run at the right times. #![feature(unboxed_closures)] static mut DROP_COUNT: usize = 0; fn drop_count() -> usize { unsafe { DROP_COUNT } } struct Droppable { x: isize, } impl Droppable { fn new() -> Droppable { Droppable { x: 1 } } } impl Drop for Droppable { fn drop(&mut self) { unsafe { DROP_COUNT += 1 } } } fn a<F:Fn(isize, isize) -> isize>(f: F) -> isize { f(1, 2) } fn b<F:FnMut(isize, isize) -> isize>(mut f: F) -> isize { f(3, 4) } fn c<F:FnOnce(isize, isize) -> isize>(f: F) -> isize { f(5, 6) } fn test_fn() { { a(move |a: isize, b| { a + b }); } assert_eq!(drop_count(), 0); { let z = &Droppable::new(); a(move |a: isize, b| { z; a + b }); assert_eq!(drop_count(), 0); } assert_eq!(drop_count(), 1); { let z = &Droppable::new(); let zz = &Droppable::new(); a(move |a: isize, b| { z; zz; a + b }); assert_eq!(drop_count(), 1); } assert_eq!(drop_count(), 3); } fn test_fn_mut() { {<|fim▁hole|> { let z = &Droppable::new(); b(move |a: isize, b| { z; a + b }); assert_eq!(drop_count(), 3); } assert_eq!(drop_count(), 4); { let z = &Droppable::new(); let zz = &Droppable::new(); b(move |a: isize, b| { z; zz; a + b }); assert_eq!(drop_count(), 4); } assert_eq!(drop_count(), 6); } fn test_fn_once() { { c(move |a: isize, b| { a + b }); } assert_eq!(drop_count(), 6); { let z = Droppable::new(); c(move |a: isize, b| { z; a + b }); assert_eq!(drop_count(), 7); } assert_eq!(drop_count(), 7); { let z = Droppable::new(); let zz = Droppable::new(); c(move |a: isize, b| { z; zz; a + b }); assert_eq!(drop_count(), 9); } assert_eq!(drop_count(), 9); } fn main() { test_fn(); test_fn_mut(); test_fn_once(); }<|fim▁end|>
b(move |a: isize, b| { a + b }); } assert_eq!(drop_count(), 3);
<|file_name|>UUID.js<|end_file_name|><|fim▁begin|>// Private array of chars to use var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); var ID = {}; ID.uuid = function (len, radix) { var chars = CHARS, uuid = [], i; radix = radix || chars.length; if (len) { // Compact form for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix]; } else { // rfc4122, version 4 form var r; // rfc4122 requires these characters uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'; uuid[14] = '4'; // Fill in random data. At i==19 set the high bits of clock sequence as // per rfc4122, sec. 4.1.5 for (i = 0; i < 36; i++) { if (!uuid[i]) { r = 0 | Math.random()*16; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; } } } return uuid.join(''); }; // A more performant, but slightly bulkier, RFC4122v4 solution. We boost performance // by minimizing calls to random() ID.uuidFast = function() { var chars = CHARS, uuid = new Array(36), rnd=0, r; for (var i = 0; i < 36; i++) { if (i==8 || i==13 || i==18 || i==23) { uuid[i] = '-'; } else if (i==14) { uuid[i] = '4'; } else { if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0; r = rnd & 0xf; rnd = rnd >> 4; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; } } return uuid.join(''); };<|fim▁hole|>ID.uuidCompact = function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); }; module.exports = ID;<|fim▁end|>
// A more compact, but less performant, RFC4122v4 solution:
<|file_name|>bitcoin_pl.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="pl" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="14"/> <source>About Forcoin</source> <translation>O Forcoin</translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="53"/> <source>&lt;b&gt;Forcoin&lt;/b&gt; version</source> <translation>Wersja &lt;b&gt;Forcoin&lt;/b&gt;</translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="97"/> <source>Copyright © 2009-2012 Forcoin Developers This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file license.txt or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation>Copyright © 2009-2012 Forcoin Developers Oprogramowanie eksperymentalne. Distributed under the MIT/X11 software license, see the accompanying file license.txt or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard. Pomóż w tłumaczeniu: www.transifex.net/projects/p/bitcoin/</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="14"/> <source>Address Book</source> <translation>Książka Adresowa</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="20"/> <source>These are your Forcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Tutaj znajdują się twoje adresy Forcoin do odbioru płatności. Możesz nadać oddzielne adresy dla każdego z wysyłających monety, żeby śledzić oddzielnie ich opłaty.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="36"/> <source>Double-click to edit address or label</source> <translation>Kliknij dwukrotnie, aby edytować adres lub etykietę</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="63"/> <source>Create a new address</source> <translation>Utwórz nowy adres</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="77"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Skopiuj aktualnie wybrany adres do schowka</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="66"/> <source>&amp;New Address</source> <translation>&amp;Nowy Adres</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="80"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="91"/> <source>Show &amp;QR Code</source> <translation>Pokaż Kod &amp;QR</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="102"/> <source>Sign a message to prove you own this address</source> <translation>Podpisz wiadomość aby dowieść, że ten adres jest twój</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="105"/> <source>&amp;Sign Message</source> <translation>Podpi&amp;sz Wiadomość</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="116"/> <source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source> <translation>Usuń aktualnie wybrany adres z listy. Tylko adresy nadawcze mogą być usunięte.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="119"/> <source>&amp;Delete</source> <translation>&amp;Usuń</translation> </message> <message> <location filename="../addressbookpage.cpp" line="63"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="65"/> <source>&amp;Edit</source> <translation>&amp;Edytuj</translation> </message> <message> <location filename="../addressbookpage.cpp" line="292"/> <source>Export Address Book Data</source> <translation>Eksportuj książkę adresową</translation> </message> <message> <location filename="../addressbookpage.cpp" line="293"/> <source>Comma separated file (*.csv)</source> <translation>Plik *.CSV (rozdzielany przecinkami)</translation> </message> <message> <location filename="../addressbookpage.cpp" line="306"/> <source>Error exporting</source> <translation>Błąd podczas eksportowania</translation> </message> <message> <location filename="../addressbookpage.cpp" line="306"/> <source>Could not write to file %1.</source> <translation>Błąd zapisu do pliku %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="142"/> <source>Label</source> <translation>Etykieta</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="142"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="178"/> <source>(no label)</source> <translation>(bez etykiety)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="47"/> <source>Enter passphrase</source> <translation>Wpisz hasło</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="61"/> <source>New passphrase</source> <translation>Nowe hasło</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="75"/> <source>Repeat new passphrase</source> <translation>Powtórz nowe hasło</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Wprowadź nowe hasło dla portfela.&lt;br/&gt;Proszę użyć hasła składającego się z &lt;b&gt;10 lub więcej losowych znaków&lt;/b&gt; lub &lt;b&gt;ośmiu lub więcej słów&lt;/b&gt;.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="34"/> <source>Encrypt wallet</source> <translation>Zaszyfruj portfel</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="37"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ta operacja wymaga hasła do portfela ażeby odblokować portfel.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="42"/> <source>Unlock wallet</source> <translation>Odblokuj portfel</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="45"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ta operacja wymaga hasła do portfela ażeby odszyfrować portfel.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="50"/> <source>Decrypt wallet</source> <translation>Odszyfruj portfel</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="53"/> <source>Change passphrase</source> <translation>Zmień hasło</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="54"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Podaj stare i nowe hasło do portfela.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="100"/> <source>Confirm wallet encryption</source> <translation>Potwierdź szyfrowanie portfela</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="101"/> <source>WARNING: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;! Are you sure you wish to encrypt your wallet?</source> <translation>OSTRZEŻENIE: Jeśli zaszyfrujesz portfel i zgubisz hasło, wtedy &lt;b&gt;STRACISZ WSZYSTKIE SWOJE BITMONETY&lt;/b&gt; Czy na pewno chcesz zaszyfrować swój portfel?</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="110"/> <location filename="../askpassphrasedialog.cpp" line="159"/> <source>Wallet encrypted</source> <translation>Portfel zaszyfrowany</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="111"/> <source>Forcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source> <translation>Program Forcoin zamknie się aby dokończyć proces szyfrowania. Pamiętaj, że szyfrowanie portfela nie zabezpiecza w pełni Twoich bitcoinów przed kradzieżą przez wirusy lub trojany mogące zainfekować Twój komputer.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="207"/> <location filename="../askpassphrasedialog.cpp" line="231"/> <source>Warning: The Caps Lock key is on.</source> <translation>Ostrzeżenie: Caps Lock jest włączony.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="116"/> <location filename="../askpassphrasedialog.cpp" line="123"/> <location filename="../askpassphrasedialog.cpp" line="165"/> <location filename="../askpassphrasedialog.cpp" line="171"/> <source>Wallet encryption failed</source> <translation>Szyfrowanie portfela nie powiodło się</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="117"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Szyfrowanie portfela nie powiodło się z powodu wewnętrznego błędu. Twój portfel nie został zaszyfrowany.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="124"/> <location filename="../askpassphrasedialog.cpp" line="172"/> <source>The supplied passphrases do not match.</source> <translation>Podane hasła nie są takie same.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="135"/> <source>Wallet unlock failed</source> <translation>Odblokowanie portfela nie powiodło się</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="136"/> <location filename="../askpassphrasedialog.cpp" line="147"/> <location filename="../askpassphrasedialog.cpp" line="166"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Wprowadzone hasło do odszyfrowania portfela jest niepoprawne.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="146"/> <source>Wallet decryption failed</source> <translation>Odszyfrowywanie portfela nie powiodło się</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="160"/> <source>Wallet passphrase was succesfully changed.</source> <translation>Hasło do portfela zostało pomyślnie zmienione.</translation> </message> </context> <context> <name>ForcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="73"/> <source>Forcoin Wallet</source> <translation>Portfel Forcoin</translation> </message> <message> <location filename="../bitcoingui.cpp" line="215"/> <source>Sign &amp;message...</source> <translation>Podpisz wiado&amp;mość...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="248"/> <source>Show/Hide &amp;Forcoin</source> <translation>Pokaż/Ukryj &amp;Forcoin</translation> </message> <message> <location filename="../bitcoingui.cpp" line="515"/> <source>Synchronizing with network...</source> <translation>Synchronizacja z siecią...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="185"/> <source>&amp;Overview</source> <translation>P&amp;odsumowanie</translation> </message> <message> <location filename="../bitcoingui.cpp" line="186"/> <source>Show general overview of wallet</source> <translation>Pokazuje ogólny zarys portfela</translation> </message> <message> <location filename="../bitcoingui.cpp" line="191"/> <source>&amp;Transactions</source> <translation>&amp;Transakcje</translation> </message> <message> <location filename="../bitcoingui.cpp" line="192"/> <source>Browse transaction history</source> <translation>Przeglądaj historię transakcji</translation> </message> <message> <location filename="../bitcoingui.cpp" line="197"/> <source>&amp;Address Book</source> <translation>Książka &amp;adresowa</translation> </message> <message> <location filename="../bitcoingui.cpp" line="198"/> <source>Edit the list of stored addresses and labels</source> <translation>Edytuj listę zapisanych adresów i i etykiet</translation> </message> <message> <location filename="../bitcoingui.cpp" line="203"/> <source>&amp;Receive coins</source> <translation>Odbie&amp;rz monety</translation> </message> <message> <location filename="../bitcoingui.cpp" line="204"/> <source>Show the list of addresses for receiving payments</source> <translation>Pokaż listę adresów do otrzymywania płatności</translation> </message> <message> <location filename="../bitcoingui.cpp" line="209"/> <source>&amp;Send coins</source> <translation>Wy&amp;syłka monet</translation> </message> <message> <location filename="../bitcoingui.cpp" line="216"/> <source>Prove you control an address</source> <translation>Udowodnij, że kontrolujesz adres</translation> </message> <message> <location filename="../bitcoingui.cpp" line="235"/> <source>E&amp;xit</source> <translation>&amp;Zakończ</translation> </message> <message> <location filename="../bitcoingui.cpp" line="236"/> <source>Quit application</source> <translation>Zamknij program</translation> </message> <message> <location filename="../bitcoingui.cpp" line="239"/> <source>&amp;About %1</source> <translation>&amp;O %1</translation> </message> <message> <location filename="../bitcoingui.cpp" line="240"/> <source>Show information about Forcoin</source> <translation>Pokaż informację o Forcoin</translation> </message> <message> <location filename="../bitcoingui.cpp" line="242"/> <source>About &amp;Qt</source> <translation>O &amp;Qt</translation> </message> <message> <location filename="../bitcoingui.cpp" line="243"/> <source>Show information about Qt</source> <translation>Pokazuje informacje o Qt</translation> </message> <message> <location filename="../bitcoingui.cpp" line="245"/> <source>&amp;Options...</source> <translation>&amp;Opcje...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="252"/> <source>&amp;Encrypt Wallet...</source> <translation>Zaszyfruj Portf&amp;el</translation> </message> <message> <location filename="../bitcoingui.cpp" line="255"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="257"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="517"/> <source>~%n block(s) remaining</source> <translation><numerusform>pozostał ~%n blok</numerusform><numerusform>pozostało ~%n bloki</numerusform><numerusform>pozostało ~%n bloków</numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="528"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="250"/> <source>&amp;Export...</source> <translation>&amp;Eksportuj...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="210"/> <source>Send coins to a Forcoin address</source> <translation>Wyślij monety na adres Forcoin</translation> </message> <message> <location filename="../bitcoingui.cpp" line="246"/> <source>Modify configuration options for Forcoin</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="249"/> <source>Show or hide the Forcoin window</source> <translation>Pokaż lub ukryj okno Forcoin</translation> </message> <message> <location filename="../bitcoingui.cpp" line="251"/> <source>Export the data in the current tab to a file</source> <translation>Eksportuj dane z aktywnej karty do pliku</translation> </message> <message> <location filename="../bitcoingui.cpp" line="253"/> <source>Encrypt or decrypt wallet</source> <translation>Zaszyfruj lub odszyfruj portfel</translation> </message> <message> <location filename="../bitcoingui.cpp" line="256"/> <source>Backup wallet to another location</source> <translation>Zapasowy portfel w innej lokalizacji</translation> </message> <message> <location filename="../bitcoingui.cpp" line="258"/> <source>Change the passphrase used for wallet encryption</source> <translation>Zmień hasło użyte do szyfrowania portfela</translation> </message> <message> <location filename="../bitcoingui.cpp" line="259"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="260"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="261"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="262"/> <source>Verify a message signature</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="286"/> <source>&amp;File</source> <translation>&amp;Plik</translation> </message> <message> <location filename="../bitcoingui.cpp" line="296"/> <source>&amp;Settings</source> <translation>P&amp;referencje</translation> </message> <message> <location filename="../bitcoingui.cpp" line="302"/> <source>&amp;Help</source> <translation>Pomo&amp;c</translation> </message> <message> <location filename="../bitcoingui.cpp" line="311"/> <source>Tabs toolbar</source> <translation>Pasek zakładek</translation> </message> <message> <location filename="../bitcoingui.cpp" line="322"/> <source>Actions toolbar</source> <translation>Pasek akcji</translation> </message> <message> <location filename="../bitcoingui.cpp" line="334"/> <location filename="../bitcoingui.cpp" line="343"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location filename="../bitcoingui.cpp" line="343"/> <location filename="../bitcoingui.cpp" line="399"/> <source>Forcoin client</source> <translation>Forcoin klient</translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="492"/> <source>%n active connection(s) to Forcoin network</source> <translation><numerusform>%n aktywne połączenie do sieci Forcoin</numerusform><numerusform>%n aktywne połączenia do sieci Forcoin</numerusform><numerusform>%n aktywnych połączeń do sieci Anoncoin</numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="540"/> <source>Downloaded %1 blocks of transaction history.</source> <translation>Pobrano %1 bloków z historią transakcji.</translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="555"/> <source>%n second(s) ago</source> <translation><numerusform>%n sekundę temu</numerusform><numerusform>%n sekundy temu</numerusform><numerusform>%n sekund temu</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="559"/> <source>%n minute(s) ago</source> <translation><numerusform>%n minutę temu</numerusform><numerusform>%n minuty temu</numerusform><numerusform>%n minut temu</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="563"/> <source>%n hour(s) ago</source> <translation><numerusform>%n godzinę temu</numerusform><numerusform>%n godziny temu</numerusform><numerusform>%n godzin temu</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="567"/> <source>%n day(s) ago</source> <translation><numerusform>%n dzień temu</numerusform><numerusform>%n dni temu</numerusform><numerusform>%n dni temu</numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="573"/> <source>Up to date</source> <translation>Aktualny</translation> </message> <message> <location filename="../bitcoingui.cpp" line="580"/> <source>Catching up...</source> <translation>Łapanie bloków...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="590"/> <source>Last received block was generated %1.</source> <translation>Ostatnio otrzymany blok została wygenerowany %1.</translation> </message> <message> <location filename="../bitcoingui.cpp" line="649"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Transakcja przekracza limit. Możesz wysłać ją płacąc prowizję %1, która zostaje przekazana do węzłów, które ją prześlą i pomoże wspierać sieć Forcoin. Czy chcesz zapłacić prowizję?</translation> </message> <message> <location filename="../bitcoingui.cpp" line="654"/> <source>Confirm transaction fee</source> <translation>Potwierdź prowizję transakcyjną</translation> </message> <message> <location filename="../bitcoingui.cpp" line="681"/> <source>Sent transaction</source> <translation>Transakcja wysłana</translation> </message> <message> <location filename="../bitcoingui.cpp" line="682"/> <source>Incoming transaction</source> <translation>Transakcja przychodząca</translation> </message> <message> <location filename="../bitcoingui.cpp" line="683"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Kwota: %2 Typ: %3 Adres: %4 </translation> </message> <message> <location filename="../bitcoingui.cpp" line="804"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Portfel jest &lt;b&gt;zaszyfrowany&lt;/b&gt; i obecnie &lt;b&gt;niezablokowany&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoingui.cpp" line="812"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Portfel jest &lt;b&gt;zaszyfrowany&lt;/b&gt; i obecnie &lt;b&gt;zablokowany&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoingui.cpp" line="835"/> <source>Backup Wallet</source> <translation>Kopia Zapasowa Portfela</translation> </message> <message> <location filename="../bitcoingui.cpp" line="835"/> <source>Wallet Data (*.dat)</source> <translation>Dane Portfela (*.dat)</translation> </message> <message> <location filename="../bitcoingui.cpp" line="838"/> <source>Backup Failed</source> <translation>Kopia Zapasowa Nie Została Wykonana</translation> </message> <message> <location filename="../bitcoingui.cpp" line="838"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Wystąpił błąd podczas próby zapisu portfela do nowej lokalizacji.</translation> </message> <message> <location filename="../bitcoin.cpp" line="112"/> <source>A fatal error occured. Forcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="84"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>DisplayOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="246"/> <source>Display</source> <translation>Wyświetlanie</translation> </message> <message> <location filename="../optionsdialog.cpp" line="257"/> <source>default</source> <translation>domyślny</translation> </message> <message> <location filename="../optionsdialog.cpp" line="263"/> <source>The user interface language can be set here. This setting will only take effect after restarting Forcoin.</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="252"/> <source>User Interface &amp;Language:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="273"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="277"/> <source>Choose the default subdivision unit to show in the interface, and when sending coins</source> <translation>Wybierz podział jednostki pokazywany w interfejsie oraz podczas wysyłania monet</translation> </message> <message> <location filename="../optionsdialog.cpp" line="284"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="285"/> <source>Whether to show Forcoin addresses in the transaction list</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="303"/> <source>Warning</source> <translation>Ostrzeżenie</translation> </message> <message> <location filename="../optionsdialog.cpp" line="303"/> <source>This setting will take effect after restarting Forcoin.</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="14"/> <source>Edit Address</source> <translation>Edytuj adres</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="25"/> <source>&amp;Label</source> <translation>&amp;Etykieta</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="35"/> <source>The label associated with this address book entry</source> <translation>Etykieta skojarzona z tym wpisem w książce adresowej</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="42"/> <source>&amp;Address</source> <translation>&amp;Adres</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="52"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Ten adres jest skojarzony z wpisem w książce adresowej. Może być zmodyfikowany jedynie dla adresów wysyłających.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="20"/> <source>New receiving address</source> <translation>Nowy adres odbiorczy</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="24"/> <source>New sending address</source> <translation>Nowy adres wysyłania</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="27"/> <source>Edit receiving address</source> <translation>Edytuj adres odbioru</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="31"/> <source>Edit sending address</source> <translation>Edytuj adres wysyłania</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="91"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Wprowadzony adres &quot;%1&quot; już istnieje w książce adresowej.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="96"/> <source>The entered address &quot;%1&quot; is not a valid Forcoin address.</source> <translation>Wprowadzony adres &quot;%1&quot; nie jest poprawnym adresem Forcoin.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="101"/> <source>Could not unlock wallet.</source> <translation>Nie można było odblokować portfela.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="106"/> <source>New key generation failed.</source> <translation>Tworzenie nowego klucza nie powiodło się.</translation> </message> </context> <context> <name>HelpMessageBox</name> <message> <location filename="../bitcoin.cpp" line="133"/> <location filename="../bitcoin.cpp" line="143"/> <source>Forcoin-Qt</source> <translation>Forcoin-Qt</translation> </message> <message> <location filename="../bitcoin.cpp" line="133"/> <source>version</source> <translation>wersja</translation> </message> <message> <location filename="../bitcoin.cpp" line="135"/> <source>Usage:</source> <translation>Użycie:</translation> </message> <message> <location filename="../bitcoin.cpp" line="136"/> <source>options</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="138"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="139"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Ustaw Język, na przykład &quot;pl_PL&quot; (domyślnie: systemowy)</translation> </message> <message> <location filename="../bitcoin.cpp" line="140"/> <source>Start minimized</source> <translation>Uruchom zminimalizowany</translation> </message> <message> <location filename="../bitcoin.cpp" line="141"/> <source>Show splash screen on startup (default: 1)</source> <translation>Pokazuj okno powitalne przy starcie (domyślnie: 1)</translation> </message> </context> <context> <name>MainOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="227"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="212"/> <source>Pay transaction &amp;fee</source> <translation>Płać prowizję za t&amp;ransakcje</translation> </message> <message> <location filename="../optionsdialog.cpp" line="204"/> <source>Main</source> <translation>Główny</translation> </message> <message> <location filename="../optionsdialog.cpp" line="206"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation>Opcjonalna prowizja za transakcje za kB, wspomaga ona szybkość przebiegu transakcji. Większość transakcji jest 1 kB. Zalecana prowizja 0.01 .</translation> </message> <message> <location filename="../optionsdialog.cpp" line="222"/> <source>&amp;Start Forcoin on system login</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="223"/> <source>Automatically start Forcoin after logging in to the system</source> <translation>Automatycznie uruchom Forcoin po zalogowaniu do systemu</translation> </message> <message> <location filename="../optionsdialog.cpp" line="226"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> </context> <context> <name>MessagePage</name> <message> <location filename="../forms/messagepage.ui" line="14"/> <source>Sign Message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="20"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Możesz podpisywać wiadomości swoimi adresami aby udowodnić, że jesteś ich właścicielem. Uważaj, aby nie podpisywać niczego co wzbudza Twoje podejrzenia, ponieważ ktoś może stosować phishing próbując nakłonić Cię do ich podpisania. Akceptuj i podpisuj tylko w pełni zrozumiałe komunikaty i wiadomości.</translation> </message> <message> <location filename="../forms/messagepage.ui" line="38"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="48"/> <source>Choose adress from address book</source> <translation>Wybierz adres z książki adresowej</translation> </message> <message> <location filename="../forms/messagepage.ui" line="58"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location filename="../forms/messagepage.ui" line="71"/> <source>Paste address from clipboard</source> <translation>Wklej adres ze schowka</translation> </message> <message> <location filename="../forms/messagepage.ui" line="81"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location filename="../forms/messagepage.ui" line="93"/> <source>Enter the message you want to sign here</source> <translation>Wprowadź wiadomość, którą chcesz podpisać, tutaj</translation> </message> <message> <location filename="../forms/messagepage.ui" line="128"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="131"/> <source>&amp;Copy Signature</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="142"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="145"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="31"/> <source>Click &quot;Sign Message&quot; to get signature</source> <translation>Kliknij &quot;Podpisz Wiadomość&quot; żeby uzyskać podpis</translation> </message> <message> <location filename="../forms/messagepage.ui" line="114"/> <source>Sign a message to prove you own this address</source> <translation>Podpisz wiadomość aby dowieść, że ten adres jest twój</translation> </message> <message> <location filename="../forms/messagepage.ui" line="117"/> <source>&amp;Sign Message</source> <translation>Podpi&amp;sz Wiadomość</translation> </message> <message> <location filename="../messagepage.cpp" line="30"/> <source>Enter a Forcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Wprowadź adres Forcoin (np. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location filename="../messagepage.cpp" line="83"/> <location filename="../messagepage.cpp" line="90"/> <location filename="../messagepage.cpp" line="105"/> <location filename="../messagepage.cpp" line="117"/> <source>Error signing</source> <translation>Błąd podpisywania</translation> </message> <message> <location filename="../messagepage.cpp" line="83"/> <source>%1 is not a valid address.</source> <translation>%1 nie jest poprawnym adresem.</translation> </message> <message> <location filename="../messagepage.cpp" line="90"/> <source>%1 does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="105"/> <source>Private key for %1 is not available.</source> <translation>Klucz prywatny dla %1 jest niedostępny.</translation> </message> <message> <location filename="../messagepage.cpp" line="117"/> <source>Sign failed</source> <translation>Podpisywanie nie powiodło się.</translation> </message> </context> <context> <name>NetworkOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="345"/> <source>Network</source> <translation>Sieć</translation> </message> <message> <location filename="../optionsdialog.cpp" line="347"/> <source>Map port using &amp;UPnP</source> <translation>Mapuj port używając &amp;UPnP</translation> </message> <message> <location filename="../optionsdialog.cpp" line="348"/> <source>Automatically open the Forcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automatycznie otwiera port klienta Forcoin na routerze. Ta opcja dzieła tylko jeśli twój router wspiera UPnP i jest ono włączone.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="351"/> <source>&amp;Connect through SOCKS4 proxy:</source> <translation>Połącz przez proxy SO&amp;CKS4:</translation> </message> <message> <location filename="../optionsdialog.cpp" line="352"/> <source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source> <translation>Łączy się z siecią Forcoin przez proxy SOCKS4 (np. kiedy łączysz się przez Tor)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="357"/> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP: </translation> </message> <message> <location filename="../optionsdialog.cpp" line="366"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="363"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Adres IP serwera proxy (np. 127.0.0.1)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="372"/> <source>Port of the proxy (e.g. 1234)</source> <translation>Port proxy (np. 1234)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../optionsdialog.cpp" line="135"/> <source>Options</source> <translation>Opcje</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="14"/> <source>Form</source> <translation>Formularz</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="47"/> <location filename="../forms/overviewpage.ui" line="204"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Forcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/overviewpage.ui" line="89"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="147"/> <source>Number of transactions:</source> <translation>Liczba transakcji:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="118"/> <source>Unconfirmed:</source> <translation>Niepotwierdzony:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="40"/> <source>Wallet</source> <translation>Portfel</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="197"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Ostatnie transakcje&lt;/b&gt;</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="105"/> <source>Your current balance</source> <translation>Twoje obecne saldo</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="134"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Suma transakcji, które nie zostały jeszcze potwierdzone, i które nie zostały wliczone do twojego obecnego salda</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="154"/> <source>Total number of transactions in wallet</source> <translation>Całkowita liczba transakcji w portfelu</translation> </message> <message> <location filename="../overviewpage.cpp" line="110"/> <location filename="../overviewpage.cpp" line="111"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="14"/> <source>QR Code Dialog</source> <translation>Okno Dialogowe Kodu QR</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="32"/> <source>QR Code</source> <translation>Kod QR</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="55"/> <source>Request Payment</source> <translation>Prośba o płatność</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="70"/> <source>Amount:</source> <translation>Kwota:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="105"/> <source>BTC</source> <translation>BTC</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="121"/> <source>Label:</source> <translation>Etykieta:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="144"/> <source>Message:</source> <translation>Wiadomość:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="186"/> <source>&amp;Save As...</source> <translation>Zapi&amp;sz jako...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="45"/> <source>Error encoding URI into QR Code.</source> <translation>Błąd kodowania URI w Kodzie QR.</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="63"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="120"/> <source>Save QR Code</source> <translation>Zapisz Kod QR</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="120"/> <source>PNG Images (*.png)</source> <translation>Obraz PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="14"/> <source>Forcoin debug window</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="46"/> <source>Client name</source> <translation>Nazwa klienta</translation> </message> <message> <location filename="../forms/rpcconsole.ui" line="56"/> <location filename="../forms/rpcconsole.ui" line="79"/> <location filename="../forms/rpcconsole.ui" line="102"/> <location filename="../forms/rpcconsole.ui" line="125"/> <location filename="../forms/rpcconsole.ui" line="161"/> <location filename="../forms/rpcconsole.ui" line="214"/> <location filename="../forms/rpcconsole.ui" line="237"/> <location filename="../forms/rpcconsole.ui" line="260"/> <location filename="../rpcconsole.cpp" line="245"/> <source>N/A</source> <translation>NIEDOSTĘPNE</translation> </message> <message> <location filename="../forms/rpcconsole.ui" line="69"/> <source>Client version</source> <translation>Wersja klienta</translation> </message> <message> <location filename="../forms/rpcconsole.ui" line="24"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="39"/> <source>Client</source> <translation>Klient</translation> </message> <message> <location filename="../forms/rpcconsole.ui" line="115"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="144"/> <source>Network</source> <translation>Sieć</translation> </message> <message> <location filename="../forms/rpcconsole.ui" line="151"/> <source>Number of connections</source> <translation>Liczba połączeń</translation> </message> <message> <location filename="../forms/rpcconsole.ui" line="174"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="197"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="204"/> <source>Current number of blocks</source> <translation>Aktualna liczba bloków</translation> </message> <message> <location filename="../forms/rpcconsole.ui" line="227"/> <source>Estimated total blocks</source> <translation>Szacowana ilość bloków</translation> </message> <message> <location filename="../forms/rpcconsole.ui" line="250"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="292"/> <source>Debug logfile</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="299"/> <source>Open the Forcoin debug logfile from the current data directory. This can take a few seconds for large logfiles.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="302"/> <source>&amp;Open</source> <translation>&amp;Otwórz</translation> </message> <message> <location filename="../forms/rpcconsole.ui" line="323"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="92"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="372"/> <source>Clear console</source> <translation>Wyczyść konsole</translation> </message> <message> <location filename="../rpcconsole.cpp" line="212"/> <source>Welcome to the Forcoin RPC console.</source> <translation>Witam w konsoli Forcoin RPC</translation> </message> <message> <location filename="../rpcconsole.cpp" line="213"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="214"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="14"/> <location filename="../sendcoinsdialog.cpp" line="122"/> <location filename="../sendcoinsdialog.cpp" line="127"/> <location filename="../sendcoinsdialog.cpp" line="132"/> <location filename="../sendcoinsdialog.cpp" line="137"/> <location filename="../sendcoinsdialog.cpp" line="143"/> <location filename="../sendcoinsdialog.cpp" line="148"/> <location filename="../sendcoinsdialog.cpp" line="153"/> <source>Send Coins</source> <translation>Wyślij płatność</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="64"/> <source>Send to multiple recipients at once</source> <translation>Wyślij do wielu odbiorców na raz</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="67"/> <source>&amp;Add Recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="84"/> <source>Remove all transaction fields</source> <translation>Wyczyść wszystkie pola transakcji</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="87"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="106"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="113"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="144"/> <source>Confirm the send action</source> <translation>Potwierdź akcję wysyłania</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="147"/> <source>&amp;Send</source> <translation>Wy&amp;syłka</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="94"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; do %2 (%3)</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="99"/> <source>Confirm send coins</source> <translation>Potwierdź wysyłanie monet</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source>Are you sure you want to send %1?</source> <translation>Czy na pewno chcesz wysłać %1?</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source> and </source> <translation> i </translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="123"/> <source>The recepient address is not valid, please recheck.</source> <translation>Adres odbiorcy jest niepoprawny, proszę go sprawdzić.</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="128"/> <source>The amount to pay must be larger than 0.</source> <translation>Kwota do zapłacenie musi być większa od 0.</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="133"/> <source>The amount exceeds your balance.</source> <translation>Kwota przekracza twoje saldo.</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="138"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="144"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="149"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="154"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="14"/> <source>Form</source> <translation>Formularz</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="29"/> <source>A&amp;mount:</source> <translation>Su&amp;ma:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="42"/> <source>Pay &amp;To:</source> <translation>Płać &amp;Do:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="66"/> <location filename="../sendcoinsentry.cpp" line="25"/> <source>Enter a label for this address to add it to your address book</source> <translation>Wprowadź etykietę dla tego adresu by dodać go do książki adresowej</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="75"/> <source>&amp;Label:</source> <translation>&amp;Etykieta:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="93"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Adres do wysłania należności do (np. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="103"/> <source>Choose address from address book</source> <translation>Wybierz adres z książki adresowej</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="113"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="120"/> <source>Paste address from clipboard</source> <translation>Wklej adres ze schowka</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="130"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="137"/> <source>Remove this recipient</source> <translation>Usuń tego odbiorce</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="26"/> <source>Enter a Forcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Wprowadź adres Forcoin (np. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="21"/> <source>Open for %1 blocks</source> <translation>Otwórz dla %1 bloków</translation> </message> <message> <location filename="../transactiondesc.cpp" line="23"/> <source>Open until %1</source> <translation>Otwórz do %1</translation> </message> <message> <location filename="../transactiondesc.cpp" line="29"/> <source>%1/offline?</source> <translation>%1/offline?</translation> </message> <message> <location filename="../transactiondesc.cpp" line="31"/> <source>%1/unconfirmed</source> <translation>%1/niezatwierdzone</translation> </message> <message> <location filename="../transactiondesc.cpp" line="33"/> <source>%1 confirmations</source> <translation>%1 potwierdzeń</translation> </message> <message> <location filename="../transactiondesc.cpp" line="51"/> <source>&lt;b&gt;Status:&lt;/b&gt; </source> <translation>&lt;b&gt;Status:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="56"/> <source>, has not been successfully broadcast yet</source> <translation>, nie został jeszcze pomyślnie wyemitowany</translation> </message> <message> <location filename="../transactiondesc.cpp" line="58"/> <source>, broadcast through %1 node</source> <translation>, emitowany przez %1 węzeł</translation> </message> <message> <location filename="../transactiondesc.cpp" line="60"/> <source>, broadcast through %1 nodes</source> <translation>, emitowany przez %1 węzły</translation> </message> <message> <location filename="../transactiondesc.cpp" line="64"/> <source>&lt;b&gt;Date:&lt;/b&gt; </source> <translation>&lt;b&gt;Data:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="71"/> <source>&lt;b&gt;Source:&lt;/b&gt; Generated&lt;br&gt;</source> <translation>&lt;b&gt;Źródło:&lt;/b&gt; Wygenerowano&lt;br&gt;</translation> </message> <message> <location filename="../transactiondesc.cpp" line="77"/> <location filename="../transactiondesc.cpp" line="94"/> <source>&lt;b&gt;From:&lt;/b&gt; </source> <translation>&lt;b&gt;Od:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="94"/> <source>unknown</source> <translation>nieznany</translation> </message> <message> <location filename="../transactiondesc.cpp" line="95"/> <location filename="../transactiondesc.cpp" line="118"/> <location filename="../transactiondesc.cpp" line="178"/> <source>&lt;b&gt;To:&lt;/b&gt; </source> <translation>&lt;b&gt;Do:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="98"/> <source> (yours, label: </source> <translation> (twoje, etykieta: </translation> </message> <message> <location filename="../transactiondesc.cpp" line="100"/> <source> (yours)</source> <translation> (twoje)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="136"/> <location filename="../transactiondesc.cpp" line="150"/> <location filename="../transactiondesc.cpp" line="195"/> <location filename="../transactiondesc.cpp" line="212"/> <source>&lt;b&gt;Credit:&lt;/b&gt; </source> <translation>&lt;b&gt;Przypisy:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="138"/> <source>(%1 matures in %2 more blocks)</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="142"/> <source>(not accepted)</source> <translation>(niezaakceptowane)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="186"/> <location filename="../transactiondesc.cpp" line="194"/> <location filename="../transactiondesc.cpp" line="209"/> <source>&lt;b&gt;Debit:&lt;/b&gt; </source> <translation>&lt;b&gt;Debet:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="200"/> <source>&lt;b&gt;Transaction fee:&lt;/b&gt; </source> <translation>&lt;b&gt;Prowizja transakcyjna:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="216"/> <source>&lt;b&gt;Net amount:&lt;/b&gt; </source> <translation>&lt;b&gt;Kwota netto:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="222"/> <source>Message:</source> <translation>Wiadomość:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="224"/> <source>Comment:</source> <translation>Komentarz:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="226"/> <source>Transaction ID:</source> <translation>ID transakcji:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="229"/> <source>Generated coins must wait 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, it will change to &quot;not accepted&quot; and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Wygenerowane monety muszą zaczekać 120 bloków zanim będzie można je wydać. Kiedy wygenerowałeś ten blok, został on wyemitowany do sieci, aby dodać go do łańcucha bloków. Jeśli to się nie powiedzie nie zostanie on zaakceptowany i wygenerowanych monet nie będzie można wysyłać. Może się to czasami zdarzyć jeśli inny węzeł wygeneruje blok tuż przed tobą.</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="14"/> <source>Transaction details</source> <translation>Szczegóły transakcji</translation> </message> <message> <location filename="../forms/transactiondescdialog.ui" line="20"/> <source>This pane shows a detailed description of the transaction</source> <translation>Ten panel pokazuje szczegółowy opis transakcji</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Date</source> <translation>Data</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Amount</source> <translation>Kwota</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="281"/> <source>Open for %n block(s)</source> <translation><numerusform>Otwórz dla %n bloku</numerusform><numerusform>Otwórz dla %n bloków</numerusform><numerusform>Otwórz dla %n bloków</numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="284"/> <source>Open until %1</source> <translation>Otwórz do %1</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="287"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 potwierdzeń)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="290"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Niezatwierdzony (%1 z %2 potwierdzeń)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="293"/> <source>Confirmed (%1 confirmations)</source> <translation>Zatwierdzony (%1 potwierdzeń)</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="301"/> <source>Mined balance will be available in %n more blocks</source> <translation><numerusform>Wydobyta kwota będzie dostępna za %n blok</numerusform><numerusform>Wydobyta kwota będzie dostępna za %n bloków</numerusform><numerusform>Wydobyta kwota będzie dostępna za %n bloki</numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="307"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Ten blok nie został odebrany przez jakikolwiek inny węzeł i prawdopodobnie nie zostanie zaakceptowany!</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="310"/> <source>Generated but not accepted</source> <translation>Wygenerowano ale nie zaakceptowano</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="353"/> <source>Received with</source> <translation>Otrzymane przez</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="355"/> <source>Received from</source> <translation>Odebrano od</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="358"/> <source>Sent to</source> <translation>Wysłano do</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="360"/> <source>Payment to yourself</source> <translation>Płatność do siebie</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="362"/> <source>Mined</source> <translation>Wydobyto</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="400"/> <source>(n/a)</source> <translation>(brak)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="599"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Status transakcji. Najedź na pole, aby zobaczyć liczbę potwierdzeń.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="601"/> <source>Date and time that the transaction was received.</source> <translation>Data i czas odebrania transakcji.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="603"/> <source>Type of transaction.</source> <translation>Rodzaj transakcji.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="605"/> <source>Destination address of transaction.</source> <translation>Adres docelowy transakcji.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="607"/> <source>Amount removed from or added to balance.</source> <translation>Kwota usunięta z lub dodana do konta.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="55"/> <location filename="../transactionview.cpp" line="71"/> <source>All</source> <translation>Wszystko</translation> </message> <message> <location filename="../transactionview.cpp" line="56"/> <source>Today</source> <translation>Dzisiaj</translation> </message> <message> <location filename="../transactionview.cpp" line="57"/> <source>This week</source> <translation>W tym tygodniu</translation> </message> <message> <location filename="../transactionview.cpp" line="58"/> <source>This month</source> <translation>W tym miesiącu</translation> </message> <message> <location filename="../transactionview.cpp" line="59"/> <source>Last month</source> <translation>W zeszłym miesiącu</translation> </message> <message> <location filename="../transactionview.cpp" line="60"/> <source>This year</source> <translation>W tym roku</translation> </message> <message> <location filename="../transactionview.cpp" line="61"/> <source>Range...</source> <translation>Zakres...</translation> </message> <message> <location filename="../transactionview.cpp" line="72"/> <source>Received with</source> <translation>Otrzymane przez</translation> </message> <message> <location filename="../transactionview.cpp" line="74"/> <source>Sent to</source> <translation>Wysłano do</translation> </message> <message> <location filename="../transactionview.cpp" line="76"/> <source>To yourself</source> <translation>Do siebie</translation> </message> <message> <location filename="../transactionview.cpp" line="77"/> <source>Mined</source> <translation>Wydobyto</translation> </message> <message> <location filename="../transactionview.cpp" line="78"/> <source>Other</source> <translation>Inne</translation> </message> <message> <location filename="../transactionview.cpp" line="85"/> <source>Enter address or label to search</source> <translation>Wprowadź adres albo etykietę żeby wyszukać</translation> </message> <message> <location filename="../transactionview.cpp" line="92"/> <source>Min amount</source> <translation>Min suma</translation> </message> <message> <location filename="../transactionview.cpp" line="126"/> <source>Copy address</source> <translation>Kopiuj adres</translation> </message> <message> <location filename="../transactionview.cpp" line="127"/> <source>Copy label</source> <translation>Kopiuj etykietę</translation> </message> <message> <location filename="../transactionview.cpp" line="128"/> <source>Copy amount</source> <translation>Kopiuj kwotę</translation> </message> <message> <location filename="../transactionview.cpp" line="129"/> <source>Edit label</source> <translation>Edytuj etykietę</translation> </message> <message> <location filename="../transactionview.cpp" line="130"/> <source>Show transaction details</source> <translation>Pokaż szczegóły transakcji</translation> </message> <message> <location filename="../transactionview.cpp" line="270"/> <source>Export Transaction Data</source> <translation>Eksportuj Dane Transakcyjne</translation> </message> <message> <location filename="../transactionview.cpp" line="271"/> <source>Comma separated file (*.csv)</source> <translation>CSV (rozdzielany przecinkami)</translation> </message> <message> <location filename="../transactionview.cpp" line="279"/> <source>Confirmed</source> <translation>Potwierdzony</translation> </message> <message> <location filename="../transactionview.cpp" line="280"/> <source>Date</source> <translation>Data</translation> </message> <message> <location filename="../transactionview.cpp" line="281"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location filename="../transactionview.cpp" line="282"/> <source>Label</source> <translation>Etykieta</translation> </message> <message> <location filename="../transactionview.cpp" line="283"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location filename="../transactionview.cpp" line="284"/> <source>Amount</source> <translation>Kwota</translation> </message> <message> <location filename="../transactionview.cpp" line="285"/> <source>ID</source> <translation>ID</translation> </message> <message> <location filename="../transactionview.cpp" line="289"/> <source>Error exporting</source> <translation>Błąd podczas eksportowania</translation> </message> <message> <location filename="../transactionview.cpp" line="289"/> <source>Could not write to file %1.</source> <translation>Błąd zapisu do pliku %1.</translation> </message> <message> <location filename="../transactionview.cpp" line="384"/> <source>Range:</source> <translation>Zakres:</translation> </message> <message> <location filename="../transactionview.cpp" line="392"/> <source>to</source> <translation>do</translation> </message> </context> <context> <name>VerifyMessageDialog</name> <message> <location filename="../forms/verifymessagedialog.ui" line="14"/> <source>Verify Signed Message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="20"/> <source>Enter the message and signature below (be careful to correctly copy newlines, spaces, tabs and other invisible characters) to obtain the Forcoin address used to sign the message.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="62"/> <source>Verify a message and obtain the Forcoin address used to sign the message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="65"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="79"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Skopiuj aktualnie wybrany adres do schowka</translation> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="82"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="93"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="96"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="28"/> <source>Enter Forcoin signature</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="29"/> <source>Click &quot;Verify Message&quot; to obtain address</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="55"/> <location filename="../verifymessagedialog.cpp" line="62"/> <source>Invalid Signature</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="55"/> <source>The signature could not be decoded. Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="62"/> <source>The signature did not match the message digest. Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="72"/> <source>Address not found in address book.</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="72"/> <source>Address found in address book: %1</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="158"/> <source>Sending...</source> <translation>Wysyłanie...</translation> </message> </context> <context> <name>WindowOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="313"/> <source>Window</source> <translation>Okno</translation> </message> <message> <location filename="../optionsdialog.cpp" line="316"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimalizuj do paska przy zegarku zamiast do paska zadań</translation> </message> <message> <location filename="../optionsdialog.cpp" line="317"/> <source>Show only a tray icon after minimizing the window</source> <translation>Pokazuje tylko ikonę przy zegarku po zminimalizowaniu okna</translation> </message> <message> <location filename="../optionsdialog.cpp" line="320"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimalizuj przy zamknięciu</translation> </message> <message> <location filename="../optionsdialog.cpp" line="321"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimalizuje zamiast zakończyć działanie programu przy zamykaniu okna. Kiedy ta opcja jest włączona, program zakończy działanie po wybieraniu Zamknij w menu.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="43"/> <source>Forcoin version</source> <translation>Wersja Forcoin</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="44"/> <source>Usage:</source> <translation>Użycie:</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="45"/> <source>Send command to -server or bitcoind</source> <translation>Wyślij polecenie do -server lub bitcoind</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="46"/> <source>List commands</source> <translation>Lista poleceń</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="47"/> <source>Get help for a command</source> <translation>Uzyskaj pomoc do polecenia</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="49"/> <source>Options:</source> <translation>Opcje:</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="50"/> <source>Specify configuration file (default: bitcoin.conf)</source> <translation>Wskaż plik konfiguracyjny (domyślnie: bitcoin.conf)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="51"/> <source>Specify pid file (default: bitcoind.pid)</source> <translation>Wskaż plik pid (domyślnie: bitcoin.pid)</translation> </message> <message><|fim▁hole|> <source>Generate coins</source> <translation>Generuj monety</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="53"/> <source>Don&apos;t generate coins</source> <translation>Nie generuj monet</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="54"/> <source>Specify data directory</source> <translation>Wskaż folder danych</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="55"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="56"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="57"/> <source>Specify connection timeout (in milliseconds)</source> <translation>Wskaż czas oczekiwania bezczynności połączenia (w milisekundach)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="63"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>Nasłuchuj połączeń na &lt;port&gt; (domyślnie: 8333 lub testnet: 18333)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="64"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Utrzymuj maksymalnie &lt;n&gt; połączeń z peerami (domyślnie: 125)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="66"/> <source>Connect only to the specified node</source> <translation>Łącz tylko do wskazanego węzła</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="67"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="68"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="69"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4 or IPv6)</source> <translation>Łącz tylko z węzłami w sieci &lt;net&gt; (IPv4 lub IPv6)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="70"/> <source>Try to discover public IP address (default: 1)</source> <translation>Próbuj odkryć publiczny adres IP (domyślnie: 1)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="73"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="75"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="76"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="79"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation>Maksymalny bufor odbioru na połączenie, &lt;n&gt;*1000 bajtów (domyślnie: 10000)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="80"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation>Maksymalny bufor wysyłu na połączenie, &lt;n&gt;*1000 bajtów (domyślnie: 10000)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="83"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="86"/> <source>Accept command line and JSON-RPC commands</source> <translation>Akceptuj linię poleceń oraz polecenia JSON-RPC</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="87"/> <source>Run in the background as a daemon and accept commands</source> <translation>Uruchom w tle jako daemon i przyjmuj polecenia</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="88"/> <source>Use the test network</source> <translation>Użyj sieci testowej</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="89"/> <source>Output extra debugging information</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="90"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="91"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Wyślij informację/raport do konsoli zamiast do pliku debug.log.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="92"/> <source>Send trace/debug info to debugger</source> <translation>Wyślij informację/raport do debuggera.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="93"/> <source>Username for JSON-RPC connections</source> <translation>Nazwa użytkownika dla połączeń JSON-RPC</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="94"/> <source>Password for JSON-RPC connections</source> <translation>Hasło do połączeń JSON-RPC</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="95"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332)</source> <translation>Nasłuchuj połączeń JSON-RPC na &lt;port&gt; (domyślnie: 8332)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="96"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Przyjmuj połączenia JSON-RPC ze wskazanego adresu IP</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="97"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Wysyłaj polecenia do węzła działającego na &lt;ip&gt; (domyślnie: 127.0.0.1)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="98"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="101"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="102"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Ustaw rozmiar puli kluczy na &lt;n&gt; (domyślnie: 100)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="103"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Przeskanuj blok łańcuchów żeby znaleźć zaginione transakcje portfela</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="104"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="105"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="106"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="108"/> <source> SSL options: (see the Forcoin Wiki for SSL setup instructions)</source> <translation> opcje SSL: (sprawdź Forcoin Wiki dla instrukcje konfiguracji SSL)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="111"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Użyj OpenSSL (https) do połączeń JSON-RPC</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="112"/> <source>Server certificate file (default: server.cert)</source> <translation>Plik certyfikatu serwera (domyślnie: server.cert)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="113"/> <source>Server private key (default: server.pem)</source> <translation>Klucz prywatny serwera (domyślnie: server.pem)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="114"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Aceptowalne szyfry (domyślnie: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="145"/> <source>Warning: Disk space is low</source> <translation>Ostrzeżenie: mało miejsca na dysku</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="107"/> <source>This help message</source> <translation>Ta wiadomość pomocy</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="121"/> <source>Cannot obtain a lock on data directory %s. Forcoin is probably already running.</source> <translation>Nie można zablokować folderu danych %s. Forcoin prawdopodobnie już działa.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="48"/> <source>Forcoin</source> <translation>Forcoin</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="30"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="58"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="59"/> <source>Select the version of socks proxy to use (4 or 5, 5 is default)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="60"/> <source>Do not use proxy for connections to network &lt;net&gt; (IPv4 or IPv6)</source> <translation>Nie używaj proxy do połączeń z siecią &lt;net&gt; (IPv4 lub IPv6)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="61"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="62"/> <source>Pass DNS requests to (SOCKS5) proxy</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="142"/> <source>Loading addresses...</source> <translation>Wczytywanie adresów...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="132"/> <source>Error loading blkindex.dat</source> <translation>Błąd ładownia blkindex.dat</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="134"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Błąd ładowania wallet.dat: Uszkodzony portfel</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="135"/> <source>Error loading wallet.dat: Wallet requires newer version of Forcoin</source> <translation>Błąd ładowania wallet.dat: Portfel wymaga nowszej wersji Forcoin</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="136"/> <source>Wallet needed to be rewritten: restart Forcoin to complete</source> <translation>Portfel wymaga przepisania: zrestartuj Forcoina żeby ukończyć</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="137"/> <source>Error loading wallet.dat</source> <translation>Błąd ładowania wallet.dat</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="124"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="125"/> <source>Unknown network specified in -noproxy: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="127"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="126"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="128"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="129"/> <source>Not listening on any port</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="130"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="117"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Nieprawidłowa kwota dla -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="143"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="31"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="32"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="35"/> <source>Error: Transaction creation failed </source> <translation>Błąd: Tworzenie transakcji nie powiodło się </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="36"/> <source>Sending...</source> <translation>Wysyłanie...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="37"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Błąd: transakcja została odrzucona. Może się to zdarzyć, gdy monety z Twojego portfela zostały już wydane, na przykład gdy używałeś kopii wallet.dat i bitcoiny które tam wydałeś nie zostały jeszcze odjęte z portfela z którego teraz korzystasz.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="41"/> <source>Invalid amount</source> <translation>Nieprawidłowa kwota</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="42"/> <source>Insufficient funds</source> <translation>Niewystarczające środki</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="131"/> <source>Loading block index...</source> <translation>Ładowanie indeksu bloku...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="65"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="28"/> <source>Unable to bind to %s on this computer. Forcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="71"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="72"/> <source>Accept connections from outside (default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="74"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="81"/> <source>Use Universal Plug and Play to map the listening port (default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="82"/> <source>Use Universal Plug and Play to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="85"/> <source>Fee per KB to add to transactions you send</source> <translation> </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="118"/> <source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="133"/> <source>Loading wallet...</source> <translation>Wczytywanie portfela...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="138"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="139"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="140"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="141"/> <source>Rescanning...</source> <translation>Ponowne skanowanie...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="144"/> <source>Done loading</source> <translation>Wczytywanie zakończone</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="8"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="9"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitcoinrpc rpcpassword=%s (you do not need to remember this password) If the file does not exist, create it with owner-readable-only file permissions. </source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="18"/> <source>Error</source> <translation>Błąd</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="19"/> <source>An error occured while setting up the RPC port %i for listening: %s</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="20"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="25"/> <source>Warning: Please check that your computer&apos;s date and time are correct. If your clock is wrong Forcoin will not work properly.</source> <translation>Ostrzeżenie: Proszę sprawdzić poprawność czasu i daty na tym komputerze. Jeśli czas jest zły Forcoin może nie działać prawidłowo.</translation> </message> </context> </TS><|fim▁end|>
<location filename="../bitcoinstrings.cpp" line="52"/>
<|file_name|>CollapsibleMultilineText.py<|end_file_name|><|fim▁begin|>import qt class CollapsibleMultilineText(qt.QTextEdit): """Text field that expands when it gets the focus and remain collapsed otherwise""" def __init__(self): super(CollapsibleMultilineText, self).__init__() self.minHeight = 20 self.maxHeight = 50 self.setFixedHeight(self.minHeight) def focusInEvent(self, event): # super(MyLineEdit, self).focusInEvent(event) self.setFixedHeight(self.maxHeight) <|fim▁hole|> def focusOutEvent(self, event): # super(MyLineEdit, self).focusOutEvent(event) self.setFixedHeight(self.minHeight)<|fim▁end|>
<|file_name|>consts.py<|end_file_name|><|fim▁begin|>import sys from rpython.rlib.unroll import unrolling_iterable SEND_EFFECT = 0xFF ARRAY_EFFECT = 0xFE BLOCK_EFFECT = 0xFD UNPACK_EFFECT = 0xFC # Name, number of arguments, stack effect BYTECODES = [ ("LOAD_SELF", 0, +1), ("LOAD_SCOPE", 0, +1), ("LOAD_BLOCK", 0, +1), ("LOAD_CODE", 0, +1), ("LOAD_CONST", 1, +1), ("LOAD_DEREF", 1, +1), ("STORE_DEREF", 1, 0), ("LOAD_CLOSURE", 1, +1), ("LOAD_CONSTANT", 1, 0), ("STORE_CONSTANT", 1, 0), ("DEFINED_CONSTANT", 1, 0), ("LOAD_LOCAL_CONSTANT", 1, +1), ("DEFINED_LOCAL_CONSTANT", 1, 0), ("LOAD_INSTANCE_VAR", 1, 0), ("STORE_INSTANCE_VAR", 1, -1), ("DEFINED_INSTANCE_VAR", 1, 0), ("LOAD_CLASS_VAR", 1, 0), ("STORE_CLASS_VAR", 1, -1), ("DEFINED_CLASS_VAR", 1, 0), ("LOAD_GLOBAL", 1, +1), ("STORE_GLOBAL", 1, 0), ("DEFINED_GLOBAL", 1, +1), ("BUILD_ARRAY", 1, ARRAY_EFFECT), ("BUILD_ARRAY_SPLAT", 1, ARRAY_EFFECT), ("BUILD_STRING", 1, ARRAY_EFFECT), ("BUILD_HASH", 0, +1), ("BUILD_RANGE", 0, -1), ("BUILD_RANGE_EXCLUSIVE", 0, -1), ("BUILD_FUNCTION", 0, -1), ("BUILD_BLOCK", 1, BLOCK_EFFECT), ("BUILD_LAMBDA", 0, 0), ("BUILD_CLASS", 0, -2), ("BUILD_MODULE", 0, -1), ("BUILD_REGEXP", 0, -1), ("COERCE_ARRAY", 1, 0), ("COERCE_BLOCK", 0, 0), ("COERCE_STRING", 0, 0), ("UNPACK_SEQUENCE", 1, UNPACK_EFFECT), ("UNPACK_SEQUENCE_SPLAT", 2, UNPACK_EFFECT), ("DEFINE_FUNCTION", 0, -2), ("ATTACH_FUNCTION", 0, -2), ("EVALUATE_MODULE", 0, -1),<|fim▁hole|> ("SEND", 2, SEND_EFFECT), ("SEND_BLOCK", 2, SEND_EFFECT), ("SEND_SPLAT", 2, SEND_EFFECT), ("SEND_BLOCK_SPLAT", 2, SEND_EFFECT), ("DEFINED_METHOD", 1, 0), ("SEND_SUPER_BLOCK", 2, SEND_EFFECT), ("SEND_SUPER_BLOCK_SPLAT", 2, SEND_EFFECT), ("DEFINED_SUPER", 1, 0), ("SETUP_LOOP", 1, 0), ("SETUP_EXCEPT", 1, 0), ("SETUP_FINALLY", 1, 0), ("END_FINALLY", 0, -2), ("POP_BLOCK", 0, 0), ("JUMP", 1, 0), ("JUMP_IF_TRUE", 1, -1), ("JUMP_IF_FALSE", 1, -1), ("DISCARD_TOP", 0, -1), ("DUP_TOP", 0, +1), ("DUP_TWO", 0, +2), ("ROT_TWO", 0, 0), ("ROT_THREE", 0, 0), ("YIELD", 1, ARRAY_EFFECT), ("YIELD_SPLAT", 1, SEND_EFFECT), ("DEFINED_YIELD", 0, +1), ("RETURN", 0, -1), ("RAISE_RETURN", 0, -1), ("CONTINUE_LOOP", 1, -1), ("BREAK_LOOP", 0, -1), ("RAISE_BREAK", 0, -1), ] BYTECODE_NAMES = [] BYTECODE_NUM_ARGS = [] BYTECODE_STACK_EFFECT = [] module = sys.modules[__name__] for i, (name, num_args, stack_effect) in enumerate(BYTECODES): setattr(module, name, i) BYTECODE_NAMES.append(name) BYTECODE_NUM_ARGS.append(num_args) BYTECODE_STACK_EFFECT.append(stack_effect) UNROLLING_BYTECODES = unrolling_iterable(enumerate(BYTECODE_NAMES))<|fim▁end|>
("LOAD_SINGLETON_CLASS", 0, 0),
<|file_name|>Gruntfile.js<|end_file_name|><|fim▁begin|>module.exports = function (grunt) { 'use strict'; // Project configuration. grunt.initConfig({ jshint: { options: { "expr": true, "laxcomma": true, "smarttabs": true, "curly": true, "eqeqeq": false, "immed": true, "latedef": true, "newcap": true, "noarg": true, "sub": true, "es5": true, "undef": true, "eqnull": true, "browser": true, "regexdash": true, "loopfunc": true, "mootools": true, "node": true, globals: { "Mousetrap": true, "Modernizr": true, "mootools": true, "nsUtil": true, "resource": true, "define": true, "debugMode": true, "rendererModel": true, "viewMode": true, "WixGoogleAnalytics": true, "siteHeader": true, "editorModel": true, "siteId": true, "LOG": true, "PHASES": true, "wixLogLegend": true, "wixEvents": true, "WixLogger": true, "wixErrors": true, "WixBILogger": true, "managers": true, "classDefinition": true, "Utils": true, "UtilsClass": true, "WClass": true, "W": true, "e": true, "l": true, "s": true, "m": true, "g": true, "d": true, "f": true, "t": true, "after": true, "unescape": true, "alert": true, "missingItems": true, "hex_sha256": true, "XDomainRequest": true, "_userAnalyticsAccount": true, "getCookieInfo": true, "creationSource": true, "ActiveXObject": true, "Test": true, "main": true, "Async": true, "console": true, "Request": true, "getAsyncExpects": true, "fail": true, "pageTracker": true, "_gat": true, "Constants": true, "expect": true, "describe": true, "beforeEach": true, "it": true, "waits": true, "runs": true, "waitsFor": true, "afterEach": true, "spyOn": true, "sleep": true, "jasmine": true, "getPlayGround": true, "Element": true, "typeOf": true, "getSpy": true, "MockBuilder": true, "Define": true, "instanceOf": true, "xdescribe": true, "merge": true, "clone": true } }, all: [ 'Gruntfile.js', 'tasks/**/*.js', 'test/javascript/**/*.js' ] }, jasmine_node: { specNameMatcher: "spec", projectRoot: ".", requirejs: false, forceExit: true,<|fim▁hole|> consolidate: true } }, aggregate: { "ordered-list": { src: "test/resources/ordered-list.json", manifest: "target/ordered-list.json" }, main: { src: "test/resources/aggregations.json", manifest: "target/manifest.json" }, 'no-min': { src: "test/resources/no-min.json", manifest: 'target/no-min.json', min: false }, 'no-copy': { src: "test/resources/no-copy.json", manifest: 'target/no-copy.json', copy: false }, list: { src: "test/resources/list.json", manifest: 'target/list.json', manifestCopy: 'target/list.copy.json', min: false, copy: false }, exclude: { src: "test/resources/exclude.json", manifest: 'target/exclude.json', manifestCopy: 'target/exclude.copy.json' }, css: { src: "test/resources/css.json", manifest: 'target/css.json' }, manymin: { src: "test/resources/manymin.json", manifest: "target/manymin.json", min: false, manymin: true, copy: false } }, modify: { json: { base: 'test/resources', src: ['dir*/**/*.json'], dest: 'target/mod', modifier: function (name, content) { return { name: name.search('subdir1_2') !== -1 ? 'genereated.name.json' : name, content: '[' + content + ']' }; } } }, clean: { test: "target" }, copy: { target: { files: { 'target/aggregations/greatescape/escaped.js': ['test/greatescape/original.js'] } } }, greatescape: { all: 'target/aggregations/greatescape/escaped.js' } }); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-jshint'); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // By default, lint and run all tests. grunt.registerTask('default', ['clean', 'jshint', 'modify', 'aggregate']); };<|fim▁end|>
jUnit: { report: false, savePath: "./build/reports/jasmine/", useDotNotation: true,
<|file_name|>base.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import abc import typing import pkg_resources import google.auth # type: ignore from google.api_core import gapic_v1 from google.auth import credentials as ga_credentials # type: ignore from google.ads.googleads.v9.resources.types import geo_target_constant from google.ads.googleads.v9.services.types import geo_target_constant_service try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-ads",).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() class GeoTargetConstantServiceTransport(metaclass=abc.ABCMeta): """Abstract transport class for GeoTargetConstantService.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/adwords",) def __init__( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with<|fim▁hole|> """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: host += ":443" self._host = host # If no credentials are provided, then determine the appropriate # defaults. if credentials is None: credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES) # Save the credentials. self._credentials = credentials # Lifted into its own function so it can be stubbed out during tests. self._prep_wrapped_messages(client_info) def _prep_wrapped_messages(self, client_info): # Precomputed wrapped methods self._wrapped_methods = { self.get_geo_target_constant: gapic_v1.method.wrap_method( self.get_geo_target_constant, default_timeout=None, client_info=client_info, ), self.suggest_geo_target_constants: gapic_v1.method.wrap_method( self.suggest_geo_target_constants, default_timeout=None, client_info=client_info, ), } def close(self): """Closes resources associated with the transport. .. warning:: Only call this method if the transport is NOT shared with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property def get_geo_target_constant( self, ) -> typing.Callable[ [geo_target_constant_service.GetGeoTargetConstantRequest], geo_target_constant.GeoTargetConstant, ]: raise NotImplementedError @property def suggest_geo_target_constants( self, ) -> typing.Callable[ [geo_target_constant_service.SuggestGeoTargetConstantsRequest], geo_target_constant_service.SuggestGeoTargetConstantsResponse, ]: raise NotImplementedError __all__ = ("GeoTargetConstantServiceTransport",)<|fim▁end|>
API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library.
<|file_name|>hello_world.rs<|end_file_name|><|fim▁begin|>// [Ref](http://kmcallister.github.io/talks/rust/2015-contributing-to-rust/slides.html) // rustc -Z time-passes hello_world.rs fn main() { println!("Hello World!");<|fim▁hole|><|fim▁end|>
}
<|file_name|>server3.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import server import time from Sensoria.stereotypes.TimeControlData import TimeControlData from Sensoria.stereotypes.InstantMessageData import InstantMessageData class TemperatureSensor (server.TemperatureSensor): def __init__ (self): super (TemperatureSensor, self).__init__ ("HD", "Heater Temperature") class HeaterController (server.ControlledRelayActuator): def __init__ (self): super (HeaterController, self).__init__ ("HC", "Heater Controller") #TL1:10 TL2:18 TL3:21 class HeaterTimer (server.TimedActuator): def __init__ (self): super (HeaterTimer, self).__init__ ("HT", "Heater Timer") initData = TimeControlData () initData.unmarshal ("PMO:000000001000000003222110 PTU:000000001000000003222110 PWE:000000001000000003222110 PTH:000000001000000003222110 PFR:000000001000000003222111 PSA:000000000322222222222211 PSU:000000000322222222222210") ok, msg = self.write (initData) print msg assert ok class HeaterSettings (server.ValueSetActuator): def __init__ (self): super (HeaterSettings, self).__init__ ("HS", "Heater Settings") self.levels = [10, 18, 21] @property def values (self): return self.levels @values.setter def values (self, v): self.levels = v[0:3] hd = TemperatureSensor () hc = HeaterController () ht = HeaterTimer () hs = HeaterSettings () listener = server.CommandListener ("HeatingSystem") listener.register_sensor (hd) listener.register_sensor (hc) listener.register_sensor (ht) listener.register_sensor (hs) listener.start ()<|fim▁hole|><|fim▁end|>
while True: time.sleep (1)
<|file_name|>mac_securityd.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*-<|fim▁hole|># # Copyright 2014 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Formatter for ASL securityd log file.""" from plaso.formatters import interface class MacSecuritydLogFormatter(interface.ConditionalEventFormatter): """Formatter for ASL Securityd file.""" DATA_TYPE = 'mac:asl:securityd:line' FORMAT_STRING_PIECES = [ u'Sender: {sender}', u'({sender_pid})', u'Level: {level}', u'Facility: {facility}', u'Text: {message}'] FORMAT_STRING_SHORT_PIECES = [u'Text: {message}'] SOURCE_LONG = 'Mac ASL Securityd Log' SOURCE_SHORT = 'LOG'<|fim▁end|>
<|file_name|>macros.rs<|end_file_name|><|fim▁begin|>#[macro_export] macro_rules! hash_test ( ($inp:expr, $out_b:expr, $out_s:expr) => (<|fim▁hole|> HashTestCase { input: $inp, output: $out_b, output_str: $out_s } ) );<|fim▁end|>
<|file_name|>UniqueOperationTypesRule.ts<|end_file_name|><|fim▁begin|>import { GraphQLError } from '../../error/GraphQLError'; import type { SchemaDefinitionNode, SchemaExtensionNode, } from '../../language/ast'; import type { ASTVisitor } from '../../language/visitor'; import type { SDLValidationContext } from '../ValidationContext'; /** * Unique operation types * * A GraphQL document is only valid if it has only one type per operation. */ export function UniqueOperationTypesRule( context: SDLValidationContext, ): ASTVisitor { const schema = context.getSchema(); const definedOperationTypes = Object.create(null); const existingOperationTypes = schema ? { query: schema.getQueryType(), mutation: schema.getMutationType(), subscription: schema.getSubscriptionType(), } : {}; return { SchemaDefinition: checkOperationTypes, SchemaExtension: checkOperationTypes, };<|fim▁hole|> function checkOperationTypes( node: SchemaDefinitionNode | SchemaExtensionNode, ) { // See: https://github.com/graphql/graphql-js/issues/2203 /* c8 ignore next */ const operationTypesNodes = node.operationTypes ?? []; for (const operationType of operationTypesNodes) { const operation = operationType.operation; const alreadyDefinedOperationType = definedOperationTypes[operation]; if (existingOperationTypes[operation]) { context.reportError( new GraphQLError( `Type for ${operation} already defined in the schema. It cannot be redefined.`, operationType, ), ); } else if (alreadyDefinedOperationType) { context.reportError( new GraphQLError( `There can be only one ${operation} type in schema.`, [alreadyDefinedOperationType, operationType], ), ); } else { definedOperationTypes[operation] = operationType; } } return false; } }<|fim▁end|>
<|file_name|>credentials.py<|end_file_name|><|fim▁begin|># encoding: utf-8 # module samba.credentials # from /usr/lib/python2.7/dist-packages/samba/credentials.so # by generator 1.135 """ Credentials management. """ # imports import talloc as __talloc # Variables with simple values AUTO_KRB_FORWARDABLE = 0 AUTO_USE_KERBEROS = 0 DONT_USE_KERBEROS = 1 FORCE_KRB_FORWARDABLE = 2 MUST_USE_KERBEROS = 2 NO_KRB_FORWARDABLE = 1 # no functions # classes class CredentialCacheContainer(__talloc.Object): # no doc def __init__(self, *args, **kwargs): # real signature unknown pass class Credentials(__talloc.Object): # no doc def authentication_requested(self, *args, **kwargs): # real signature unknown pass def get_bind_dn(self): # real signature unknown; restored from __doc__ """ S.get_bind_dn() -> bind dn Obtain bind DN. """ pass def get_domain(self): # real signature unknown; restored from __doc__ """ S.get_domain() -> domain Obtain domain name. """ pass def get_gensec_features(self, *args, **kwargs): # real signature unknown pass def get_named_ccache(self, *args, **kwargs): # real signature unknown pass def get_nt_hash(self, *args, **kwargs): # real signature unknown pass def get_password(self): # real signature unknown; restored from __doc__ """ S.get_password() -> password Obtain password. """ pass def get_realm(self): # real signature unknown; restored from __doc__ """ S.get_realm() -> realm Obtain realm name. """ pass def get_username(self): # real signature unknown; restored from __doc__ """ S.get_username() -> username Obtain username. """ pass def get_workstation(self, *args, **kwargs): # real signature unknown pass def guess(self, *args, **kwargs): # real signature unknown pass def is_anonymous(self, *args, **kwargs): # real signature unknown pass def parse_string(self, text, obtained=None): # real signature unknown; restored from __doc__ """ S.parse_string(text, obtained=CRED_SPECIFIED) -> None Parse credentials string. """ pass def set_anonymous(self): # real signature unknown; restored from __doc__ """ S.set_anonymous() -> None Use anonymous credentials. """ pass def set_bind_dn(self, bind_dn): # real signature unknown; restored from __doc__ """ S.set_bind_dn(bind_dn) -> None Change bind DN. """ pass def set_cmdline_callbacks(self): # real signature unknown; restored from __doc__ """ S.set_cmdline_callbacks() -> bool Use command-line to obtain credentials not explicitly set. """ return False def set_domain(self, domain, obtained=None): # real signature unknown; restored from __doc__ """ S.set_domain(domain, obtained=CRED_SPECIFIED) -> None<|fim▁hole|> """ pass def set_gensec_features(self, *args, **kwargs): # real signature unknown pass def set_kerberos_state(self, *args, **kwargs): # real signature unknown pass def set_krb_forwardable(self, *args, **kwargs): # real signature unknown pass def set_machine_account(self, *args, **kwargs): # real signature unknown pass def set_password(self, password, obtained=None): # real signature unknown; restored from __doc__ """ S.set_password(password, obtained=CRED_SPECIFIED) -> None Change password. """ pass def set_realm(self, realm, obtained=None): # real signature unknown; restored from __doc__ """ S.set_realm(realm, obtained=CRED_SPECIFIED) -> None Change realm name. """ pass def set_username(self, name, obtained=None): # real signature unknown; restored from __doc__ """ S.set_username(name, obtained=CRED_SPECIFIED) -> None Change username. """ pass def set_workstation(self, *args, **kwargs): # real signature unknown pass def wrong_password(self): # real signature unknown; restored from __doc__ """ S.wrong_password() -> bool Indicate the returned password was incorrect. """ return False def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass<|fim▁end|>
Change domain name.
<|file_name|>desaturate.py<|end_file_name|><|fim▁begin|>from os.path import dirname, join from pystacia import lena dest = join(dirname(__file__), '../_static/generated') <|fim▁hole|><|fim▁end|>
image = lena(256) image.desaturate() image.write(join(dest, 'lena_desaturate.jpg')) image.close()
<|file_name|>modal.js<|end_file_name|><|fim▁begin|>// Get the modal var modal = document.getElementById('myModal'); // Get the image and insert it inside the modal - use its "alt" text as a caption var img = document.getElementById('myImg'); var modalImg = document.getElementById("img01"); var captionText = document.getElementById("caption"); img.onclick = function(){ modal.style.display = "block";<|fim▁hole|>} // Get the <span> element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; }<|fim▁end|>
modalImg.src = this.src; modalImg.alt = this.alt; captionText.innerHTML = this.alt;
<|file_name|>contactgetrequests.js<|end_file_name|><|fim▁begin|>const R = require('aws-response'); const f = require('../contactGetRequests/index'); <|fim▁hole|><|fim▁end|>
exports.handler = R(f);
<|file_name|>NPWidgetService.java<|end_file_name|><|fim▁begin|>package com.networkprofiles.widget; /** Service to refresh the widget **/ import android.app.Service; import android.appwidget.AppWidgetManager; import android.content.Intent; import android.graphics.Color; import android.os.IBinder; import android.provider.Settings; import android.widget.RemoteViews; import com.networkprofiles.R; import com.networkprofiles.utils.MyNetControll; public class NPWidgetService extends Service { private Boolean mobile; private Boolean cell; private Boolean gps; private Boolean display; private Boolean sound; private int [] widgetIds; private RemoteViews rv; private AppWidgetManager wm; private MyNetControll myController; public void onCreate() { wm = AppWidgetManager.getInstance(NPWidgetService.this);//this.getApplicationContext() myController = new MyNetControll(NPWidgetService.this); myController.myStart(); //rv = new RemoteViews(getPackageName(), R.layout.npwidgetwifi); } public int onStartCommand(Intent intent, int flags, int startId) { // /** Check the state of the network devices and set the text for the text fields **/ // //set the TextView for 3G data // if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED || telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTING) { // rv.setTextViewText(R.id.textMobile, "3G data is ON"); // } // if(telephonyManager.getDataState() == TelephonyManager.DATA_DISCONNECTED) { // rv.setTextViewText(R.id.textMobile, "3G data is OFF"); // } // //set the TextView for WiFi // if(wifim.getWifiState() == WifiManager.WIFI_STATE_ENABLED || wifim.getWifiState() == WifiManager.WIFI_STATE_ENABLING) { // rv.setTextViewText(R.id.textWifi, "Wifi is ON"); // } // if(wifim.getWifiState() == WifiManager.WIFI_STATE_DISABLED || wifim.getWifiState() == WifiManager.WIFI_STATE_DISABLING) { // rv.setTextViewText(R.id.textWifi, "Wifi is OFF"); // } // //set the TextView for Bluetooth // if(myBluetooth.getState() == BluetoothAdapter.STATE_ON || myBluetooth.getState() == BluetoothAdapter.STATE_TURNING_ON) { // rv.setTextViewText(R.id.textBluetooth, "Bluetooth is ON"); // } // if(myBluetooth.getState() == BluetoothAdapter.STATE_OFF || myBluetooth.getState() == BluetoothAdapter.STATE_TURNING_OFF) { // rv.setTextViewText(R.id.textBluetooth, "Bluetooth is Off"); // } // //set the TextView for Cell voice // if(Settings.System.getInt(NPWidgetService.this.getContentResolver(), // Settings.System.AIRPLANE_MODE_ON, 0) == 0) { // rv.setTextViewText(R.id.textCell, "Cell is ON"); // } else { // rv.setTextViewText(R.id.textCell, "Cell is OFF"); // } // //set the TextView for GPS // locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); // if(locationProviders.contains("gps")) { // rv.setTextViewText(R.id.textGps, "GPS is ON"); // } else { // rv.setTextViewText(R.id.textGps, "GPS is OFF"); // } /** Check which textView was clicked and switch the state of the corresponding device **/ widgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); mobile = intent.getBooleanExtra("mobile", false); cell = intent.getBooleanExtra("cell", false); gps = intent.getBooleanExtra("gps", false); display = intent.getBooleanExtra("display", false); sound = intent.getBooleanExtra("sound", false); if(widgetIds.length > 0) { if(mobile) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetmobiledata); rv.setTextColor(R.id.textWidgetMobileData, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textWidgetMobileData, Color.WHITE); myController.mobileOnOff(); } if(cell) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetcell); rv.setTextColor(R.id.textWidgetCell, Color.GREEN); if(Settings.System.getInt(NPWidgetService.this.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 0) { myController.cellOff(); } else { myController.cellOn(); } if(Settings.System.getInt(NPWidgetService.this.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 0) { rv.setTextViewText(R.id.textWidgetCell, "Cell ON"); } else { rv.setTextViewText(R.id.textWidgetCell, "Cell OFF"); } updateWidgets(); rv.setTextColor(R.id.textWidgetCell, Color.WHITE); } if(gps) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetgps); rv.setTextColor(R.id.textWidgetGps, Color.GREEN); updateWidgets();<|fim▁hole|> myController.gpsOnOff(); } if(display) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetdisplay); rv.setTextColor(R.id.textWidgetDisplay, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textWidgetDisplay, Color.WHITE); myController.displayOnOff(); } if(sound) { rv = new RemoteViews(getPackageName(), R.layout.npwidgetsound); rv.setTextColor(R.id.textViewWidgetSound, Color.GREEN); updateWidgets(); rv.setTextColor(R.id.textViewWidgetSound, Color.WHITE); myController.soundSettings(); } } updateWidgets(); stopSelf(); return 1; } public void onStart(Intent intent, int startId) { } public IBinder onBind(Intent arg0) { return null; } private void updateWidgets() { for(int id : widgetIds) { wm.updateAppWidget(id, rv); } } }//close class NPWidgetService<|fim▁end|>
rv.setTextColor(R.id.textWidgetGps, Color.WHITE);
<|file_name|>LeadForm.js<|end_file_name|><|fim▁begin|>import React, { Component } from 'react' import PropTypes from 'prop-types' import themed from '@rentpath/react-themed' import clsx from 'clsx' import isEqual from 'lodash/isEqual' import { randomId } from '@rentpath/react-ui-utils' import SubmitButton from './SubmitButton' import Header from './Header' import { Form, Field, Name, Message, Email, Phone, RadioGroup, OptInNewsLetter, TermsOfService, } from '../Form' const FIELD_MAPPING = { header: Header, name: Name, message: Message, email: Email, phone: Phone, tos: TermsOfService, submit: SubmitButton, opt_in_newsletter: OptInNewsLetter, terms_of_service: TermsOfService, } const FIELDS = [ { name: 'header' }, { name: 'message' }, { name: 'name' }, { name: 'email' }, { name: 'phone' }, { name: 'submit' }, { name: 'opt_in_newsletter' }, { name: 'terms_of_service' }, ] @themed(/^(LeadForm|Field)/) export default class LeadForm extends Component { static propTypes = { theme: PropTypes.object, className: PropTypes.string, fields: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string, field: PropTypes.oneOfType([ PropTypes.func, PropTypes.node, ]), }), ), children: PropTypes.node, } static defaultProps = { theme: {}, fields: FIELDS, } constructor(props) { super(props) this.generateRandomId() } componentWillReceiveProps() { this.generateRandomId() } shouldComponentUpdate(nextProps) { return !isEqual(this.props.fields, nextProps.fields) } get fields() { const { fields } = this.props return fields.map(fieldComposition => { const { field, className, ...props } = fieldComposition const name = props.name const FormField = field || FIELD_MAPPING[name] || this.fallbackField(props.type) <|fim▁hole|> return ( <FormField data-tid={`lead-form-${name}`} key={`${this.id}-${name}`} {...props} /> ) }) } generateRandomId() { this.id = randomId('leadform') } fallbackField(type) { return type === 'radiogroup' ? RadioGroup : Field } render() { const { className, theme, fields, children, ...props } = this.props return ( <Form className={clsx( theme.LeadForm, className, )} {...props} > {this.fields} {children} </Form> ) } }<|fim▁end|>
<|file_name|>boundaryMeasurements.C<|end_file_name|><|fim▁begin|>/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2016-2021 hyStrath \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of hyStrath, a derivative work of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class boundaryMeasurements Description \*----------------------------------------------------------------------------*/ #include "boundaryMeasurements.H" #include "processorPolyPatch.H" #include "cyclicPolyPatch.H" #include "wallPolyPatch.H" #include "dsmcCloud.H" namespace Foam { // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // void boundaryMeasurements::writenStuckParticles() { tmp<volScalarField> tnStuckParticles ( new volScalarField ( IOobject ( "nStuckParticles", mesh_.time().timeName(), mesh_, IOobject::NO_READ, IOobject::NO_WRITE ), mesh_, dimensionedScalar("nStuckParticles", dimless, 0.0) ) ); volScalarField& nStuckParticles = tnStuckParticles.ref(); nStuckParticles.boundaryFieldRef() = nParticlesOnStickingBoundaries_; nStuckParticles.write(); } void boundaryMeasurements::writenAbsorbedParticles() { tmp<volScalarField> tnAbsorbedParticles ( new volScalarField ( IOobject ( "nAbsorbedParticles", mesh_.time().timeName(), mesh_, IOobject::NO_READ, IOobject::NO_WRITE ), mesh_, dimensionedScalar("nAbsorbedParticles", dimless, 0.0) ) ); volScalarField& nAbsorbedParticles = tnAbsorbedParticles.ref(); nAbsorbedParticles.boundaryFieldRef() = nAbsorbedParticles_; nAbsorbedParticles.write(); } void boundaryMeasurements::writePatchFields() { //- Temperature field tmp<volScalarField> tboundaryT ( new volScalarField ( IOobject ( "boundaryT", mesh_.time().timeName(), mesh_, IOobject::NO_READ, IOobject::NO_WRITE ), mesh_, dimensionedScalar("boundaryT", dimTemperature, 0.0) ) ); volScalarField& boundaryT = tboundaryT.ref(); boundaryT.boundaryFieldRef() = boundaryT_; boundaryT.write(); //- Velocity field tmp<volVectorField> tboundaryU ( new volVectorField ( IOobject ( "boundaryU", mesh_.time().timeName(), mesh_, IOobject::NO_READ, IOobject::NO_WRITE ), mesh_, dimensionedVector("boundaryU", dimVelocity, vector::zero) ) ); volVectorField& boundaryU = tboundaryU.ref(); boundaryU.boundaryFieldRef() = boundaryU_; boundaryU.write(); } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // // Construct from mesh and cloud boundaryMeasurements::boundaryMeasurements ( const polyMesh& mesh, dsmcCloud& cloud ) : mesh_(refCast<const fvMesh>(mesh)), cloud_(cloud), nParticlesOnStickingBoundaries_ ( mesh_.boundary(), mesh_.V(), calculatedFvPatchScalarField::typeName<|fim▁hole|> nAbsorbedParticles_ ( mesh_.boundary(), mesh_.V(), calculatedFvPatchScalarField::typeName ), boundaryT_ ( mesh_.boundary(), mesh_.V(), calculatedFvPatchScalarField::typeName ), boundaryU_ ( mesh_.boundary(), mesh_.C(), calculatedFvPatchVectorField::typeName ) { nParticlesOnStickingBoundaries_ = 0.0; nAbsorbedParticles_ = 0.0; } //- Construct from mesh, cloud and boolean (dsmcFoam) boundaryMeasurements::boundaryMeasurements ( const polyMesh& mesh, dsmcCloud& cloud, const bool& dummy ) : mesh_(refCast<const fvMesh>(mesh)), cloud_(cloud), typeIds_(cloud_.typeIdList().size(), -1), speciesRhoNIntBF_(), speciesRhoNElecBF_(), speciesRhoNBF_(), speciesRhoMBF_(), speciesLinearKEBF_(), speciesMccBF_(), speciesMomentumBF_(), speciesUMeanBF_(), speciesErotBF_(), speciesZetaRotBF_(), speciesEvibBF_(), speciesEelecBF_(), speciesqBF_(), speciesfDBF_(), speciesEvibModBF_(), nParticlesOnStickingBoundaries_ ( mesh_.boundary(), mesh_.V(), calculatedFvPatchScalarField::typeName ), nAbsorbedParticles_ ( mesh_.boundary(), mesh_.V(), calculatedFvPatchScalarField::typeName ), boundaryT_ ( mesh_.boundary(), mesh_.V(), calculatedFvPatchScalarField::typeName ), boundaryU_ ( mesh_.boundary(), mesh_.C(), calculatedFvPatchVectorField::typeName ) { nParticlesOnStickingBoundaries_ = 0.0; nAbsorbedParticles_ = 0.0; } // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * // boundaryMeasurements::~boundaryMeasurements() {} // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // void boundaryMeasurements::updatenStuckParticlesOnPatch ( const label patchi, const scalarList& pnStuckParticles ) { forAll(pnStuckParticles, facei) { nParticlesOnStickingBoundaries_[patchi][facei] = pnStuckParticles[facei]; } } void boundaryMeasurements::updatenAbsorbedParticlesOnPatch ( const label patchi, const label facei, const scalar nAbsorbedParticles ) { nAbsorbedParticles_[patchi][facei] += nAbsorbedParticles; } void boundaryMeasurements::setBoundaryT ( const label patchi, const scalarList& pboundaryT ) { forAll(pboundaryT, facei) { boundaryT_[patchi][facei] = pboundaryT[facei]; } } void boundaryMeasurements::setBoundaryU ( const label patchi, const vectorList& pboundaryU ) { forAll(pboundaryU, facei) { boundaryU_[patchi][facei] = pboundaryU[facei]; } } void boundaryMeasurements::setBoundarynStuckParticles ( const label patchi, const scalarList& pnStuckParticles ) { forAll(pnStuckParticles, facei) { nParticlesOnStickingBoundaries_[patchi][facei] = pnStuckParticles[facei]; } } void boundaryMeasurements::setBoundarynAbsorbedParticles ( const label patchi, const scalarList& pnAbsorbedParticles ) { forAll(pnAbsorbedParticles, facei) { nAbsorbedParticles_[patchi][facei] = pnAbsorbedParticles[facei]; } } void boundaryMeasurements::outputResults() { if (mesh_.time().outputTime()) { if (cloud_.boundaries().isAStickingPatch()) { writenStuckParticles(); } if (cloud_.boundaries().isAAbsorbingPatch()) { writenAbsorbedParticles(); } if (cloud_.boundaries().isAFieldPatch()) { writePatchFields(); } } } void boundaryMeasurements::setInitialConfig() { forAll(typeIds_, i) { typeIds_[i] = i; } reset(); } void boundaryMeasurements::clean() { //- clean geometric fields forAll(typeIds_, i) { forAll(speciesRhoNBF_[i], j) { speciesRhoNIntBF_[i][j] = 0.0; speciesRhoNElecBF_[i][j] = 0.0; speciesRhoNBF_[i][j] = 0.0; speciesRhoMBF_[i][j] = 0.0; speciesLinearKEBF_[i][j] = 0.0; speciesMccBF_[i][j] = 0.0; speciesMomentumBF_[i][j] = vector::zero; speciesUMeanBF_[i][j] = vector::zero; speciesErotBF_[i][j] = 0.0; speciesZetaRotBF_[i][j] = 0.0; speciesEvibBF_[i][j] = 0.0; speciesEelecBF_[i][j] = 0.0; speciesqBF_[i][j] = 0.0; speciesfDBF_[i][j] = vector::zero; } forAll(speciesEvibModBF_[i], mod) { forAll(speciesEvibModBF_[i][mod], j) { speciesEvibModBF_[i][mod][j] = 0.0; } } } forAll(nParticlesOnStickingBoundaries_, j) { nParticlesOnStickingBoundaries_[j] = 0.0; } } void boundaryMeasurements::reset() { //- reset sizes of the fields after mesh is changed const label nSpecies = typeIds_.size(); const label nPatches = mesh_.boundaryMesh().size(); speciesRhoNIntBF_.setSize(nSpecies); speciesRhoNElecBF_.setSize(nSpecies); speciesRhoNBF_.setSize(nSpecies); speciesRhoMBF_.setSize(nSpecies); speciesLinearKEBF_.setSize(nSpecies); speciesMccBF_.setSize(nSpecies); speciesMomentumBF_.setSize(nSpecies); speciesUMeanBF_.setSize(nSpecies); speciesErotBF_.setSize(nSpecies); speciesZetaRotBF_.setSize(nSpecies); speciesEvibBF_.setSize(nSpecies); speciesEelecBF_.setSize(nSpecies); speciesqBF_.setSize(nSpecies); speciesfDBF_.setSize(nSpecies); speciesEvibModBF_.setSize(nSpecies); forAll(typeIds_, i) { const label spId = typeIds_[i]; const label nVibMod = cloud_.constProps(spId).nVibrationalModes(); speciesRhoNIntBF_[i].setSize(nPatches); speciesRhoNElecBF_[i].setSize(nPatches); speciesRhoNBF_[i].setSize(nPatches); speciesRhoMBF_[i].setSize(nPatches); speciesLinearKEBF_[i].setSize(nPatches); speciesMccBF_[i].setSize(nPatches); speciesMomentumBF_[i].setSize(nPatches); speciesUMeanBF_[i].setSize(nPatches); speciesErotBF_[i].setSize(nPatches); speciesZetaRotBF_[i].setSize(nPatches); speciesEvibBF_[i].setSize(nPatches); speciesEelecBF_[i].setSize(nPatches); speciesqBF_[i].setSize(nPatches); speciesfDBF_[i].setSize(nPatches); speciesEvibModBF_[i].setSize(nVibMod); forAll(speciesEvibModBF_[i], mod) { speciesEvibModBF_[i][mod].setSize(nPatches); } forAll(speciesRhoNBF_[i], j) { const label nFaces = mesh_.boundaryMesh()[j].size(); speciesRhoNIntBF_[i][j].setSize(nFaces, 0.0); speciesRhoNElecBF_[i][j].setSize(nFaces, 0.0); speciesRhoNBF_[i][j].setSize(nFaces, 0.0); speciesRhoMBF_[i][j].setSize(nFaces, 0.0); speciesLinearKEBF_[i][j].setSize(nFaces, 0.0); speciesMccBF_[i][j].setSize(nFaces, 0.0); speciesMomentumBF_[i][j].setSize(nFaces, vector::zero); speciesUMeanBF_[i][j].setSize(nFaces, vector::zero); speciesErotBF_[i][j].setSize(nFaces, 0.0); speciesZetaRotBF_[i][j].setSize(nFaces, 0.0); speciesEvibBF_[i][j].setSize(nFaces, 0.0); speciesEelecBF_[i][j].setSize(nFaces, 0.0); speciesqBF_[i][j].setSize(nFaces, 0.0); speciesfDBF_[i][j].setSize(nFaces, vector::zero); } forAll(speciesEvibModBF_[i], mod) { forAll(speciesEvibModBF_[i][mod], j) { const label nFaces = mesh_.boundaryMesh()[j].size(); speciesEvibModBF_[i][mod][j].setSize(nFaces, 0.0); } } } nParticlesOnStickingBoundaries_.setSize(nPatches); nAbsorbedParticles_.setSize(nPatches); boundaryT_.setSize(nPatches); boundaryU_.setSize(nPatches); forAll(mesh_.boundaryMesh(), j) { const label nFaces = mesh_.boundaryMesh()[j].size(); nParticlesOnStickingBoundaries_[j].setSize(nFaces, 0.0); nAbsorbedParticles_[j].setSize(nFaces, 0.0); boundaryT_[j].setSize(nFaces, 0.0); boundaryU_[j].setSize(nFaces, vector::zero); } } void boundaryMeasurements::updateFields(dsmcParcel& p) {} } // End namespace Foam // ************************************************************************* //<|fim▁end|>
),
<|file_name|>gelk.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) 2015-2019 Bitergia # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Authors: # Alvaro del Castillo San Felix <[email protected]> # import argparse import logging from datetime import datetime from os import sys from perceval.backends.bugzilla import Bugzilla from perceval.backends.gerrit import Gerrit from perceval.backends.github import GitHub <|fim▁hole|>from grimoire_elk.enriched.bugzilla import BugzillaEnrich from grimoire_elk.enriched.gerrit import GerritEnrich from grimoire_elk.enriched.github import GitHubEnrich from grimoire_elk.enriched.sortinghat_gelk import SortingHat from grimoire_elk.raw.bugzilla import BugzillaOcean from grimoire_elk.raw.elastic import ElasticOcean from grimoire_elk.raw.gerrit import GerritOcean from grimoire_elk.raw.github import GitHubOcean def get_connector_from_name(name, connectors): found = None for connector in connectors: backend = connector[0] if backend.get_name() == name: found = connector return found if __name__ == '__main__': """Gelk: perceval2ocean and ocean2kibana""" connectors = [[Bugzilla, BugzillaOcean, BugzillaEnrich], [GitHub, GitHubOcean, GitHubEnrich], [Gerrit, GerritOcean, GerritEnrich]] # Will come from Registry parser = argparse.ArgumentParser() ElasticOcean.add_params(parser) subparsers = parser.add_subparsers(dest='backend', help='perceval backend') for connector in connectors: name = connector[0].get_name() subparser = subparsers.add_parser(name, help='gelk %s -h' % name) # We need params for feed connector[0].add_params(subparser) args = parser.parse_args() app_init = datetime.now() backend_name = args.backend if not backend_name: parser.print_help() sys.exit(0) if 'debug' in args and args.debug: logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s') logging.debug("Debug mode activated") else: logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') logging.getLogger("urllib3").setLevel(logging.WARNING) logging.getLogger("requests").setLevel(logging.WARNING) connector = get_connector_from_name(backend_name, connectors) backend = connector[0](**vars(args)) ocean_backend = connector[1](backend, **vars(args)) enrich_backend = connector[2](backend, **vars(args)) es_index = backend.get_name() + "_" + backend.get_id() clean = args.no_incremental if args.cache: clean = True try: # Ocean elastic_state = ElasticSearch(args.elastic_url, es_index, ocean_backend.get_elastic_mappings(), clean) # Enriched ocean enrich_index = es_index + "_enrich" elastic = ElasticSearch(args.elastic_url, enrich_index, enrich_backend.get_elastic_mappings(), clean) except ElasticConnectException: logging.error("Can't connect to Elastic Search. Is it running?") sys.exit(1) ocean_backend.set_elastic(elastic_state) enrich_backend.set_elastic(elastic) try: # First feed the item in Ocean to use it later logging.info("Adding data to %s" % (ocean_backend.elastic.index_url)) ocean_backend.feed() if backend_name == "github": GitHub.users = enrich_backend.users_from_es() logging.info("Adding enrichment data to %s" % (enrich_backend.elastic.index_url)) items = [] new_identities = [] items_count = 0 for item in ocean_backend: # print("%s %s" % (item['url'], item['lastUpdated_date'])) if len(items) >= elastic.max_items_bulk: enrich_backend.enrich_items(items) items = [] items.append(item) # Get identities from new items to be added to SortingHat identities = ocean_backend.get_identities(item) if not identities: identities = [] for identity in identities: if identity not in new_identities: new_identities.append(identity) items_count += 1 enrich_backend.enrich_items(items) logging.info("Total items enriched %i " % items_count) logging.info("Total new identities to be checked %i" % len(new_identities)) merged_identities = SortingHat.add_identities(new_identities, backend_name) # Redo enrich for items with new merged identities except KeyboardInterrupt: logging.info("\n\nReceived Ctrl-C or other break signal. Exiting.\n") logging.debug("Recovering cache") backend.cache.recover() sys.exit(0) total_time_min = (datetime.now() - app_init).total_seconds() / 60 logging.info("Finished in %.2f min" % (total_time_min))<|fim▁end|>
from grimoire_elk.elastic import ElasticConnectException from grimoire_elk.elastic import ElasticSearch
<|file_name|>bitcoin_de.ts<|end_file_name|><|fim▁begin|><TS language="de" version="2.0"> <context> <name>AboutDialog</name> <message> <source>About sherlockcoin Core</source> <translation>Über sherlockcoin Core</translation> </message> <message> <source>&lt;b&gt;sherlockcoin Core&lt;/b&gt; version</source> <translation>&lt;b&gt;&quot;sherlockcoin Core&quot;&lt;/b&gt;-Version</translation> </message> <message> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> Dies ist experimentelle Software. Veröffentlicht unter der MIT/X11-Softwarelizenz, siehe beiligende Datei COPYING oder http://www.opensource.org/licenses/mit-license.php. Dieses Produkt enthält Software, die vom OpenSSL-Projekt zur Verwendung im OpenSSL-Toolkit (https://www.openssl.org) entwickelt wird, sowie von Eric Young ([email protected]) geschriebene kryptographische Software und von Thomas Bernard geschriebene UPnP-Software.</translation> </message> <message> <source>Copyright</source> <translation>Urheberrecht</translation> </message> <message> <source>The sherlockcoin Core developers</source> <translation>Die &quot;sherlockcoin Core&quot;-Entwickler</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-Bit)</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <source>Double-click to edit address or label</source> <translation>Doppelklick zum Bearbeiten der Adresse oder der Bezeichnung</translation> </message> <message> <source>Create a new address</source> <translation>Eine neue Adresse erstellen</translation> </message> <message> <source>&amp;New</source> <translation>&amp;Neu</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Ausgewählte Adresse in die Zwischenablage kopieren</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Kopieren</translation> </message> <message> <source>C&amp;lose</source> <translation>&amp;Schließen</translation> </message> <message> <source>&amp;Copy Address</source> <translation>Adresse &amp;kopieren</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Ausgewählte Adresse aus der Liste entfernen</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Daten der aktuellen Ansicht in eine Datei exportieren</translation> </message> <message> <source>&amp;Export</source> <translation>E&amp;xportieren</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Löschen</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Wählen Sie die Adresse aus, an die Sie sherlockcoins überweisen möchten</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Wählen Sie die Adresse aus, über die Sie sherlockcoins empfangen wollen</translation> </message> <message> <source>C&amp;hoose</source> <translation>&amp;Auswählen</translation> </message> <message> <source>Very sending addresses</source> <translation>Zahlungsadressen</translation> </message> <message> <source>Much receiving addresses</source> <translation>Empfangsadressen</translation> </message> <message> <source>These are your sherlockcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Dies sind ihre sherlockcoin-Adressen zum Tätigen von Überweisungen. Bitte prüfen Sie den Betrag und die Empfangsadresse, bevor Sie sherlockcoins überweisen.</translation> </message> <message> <source>These are your sherlockcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>Dies sind ihre sherlockcoin-Adressen zum Empfangen von Zahlungen. Es wird empfohlen für jede Transaktion eine neue Empfangsadresse zu verwenden.</translation> </message> <message> <source>Copy &amp;Label</source> <translation>&amp;Bezeichnung kopieren</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Editieren</translation> </message> <message> <source>Export Address List</source> <translation>Addressliste exportieren</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommagetrennte-Datei (*.csv)</translation> </message> <message> <source>Exporting Failed</source> <translation>Exportieren fehlgeschlagen</translation> </message> <message> <source>There was an error trying to save the address list to %1.</source> <translation>Beim Speichern der Adressliste nach %1 ist ein Fehler aufgetreten.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Bezeichnung</translation> </message> <message> <source>Address</source> <translation>Adresse</translation> </message> <message> <source>(no label)</source> <translation>(keine Bezeichnung)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Passphrasendialog</translation> </message> <message> <source>Enter passphrase</source> <translation>Passphrase eingeben</translation> </message> <message> <source>New passphrase</source> <translation>Neue Passphrase</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Neue Passphrase wiederholen</translation> </message> <message> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Geben Sie die neue Passphrase für die Brieftasche ein.&lt;br&gt;Bitte benutzen Sie eine Passphrase bestehend aus &lt;b&gt;10 oder mehr zufälligen Zeichen&lt;/b&gt; oder &lt;b&gt;8 oder mehr Wörtern&lt;/b&gt;.</translation> </message> <message> <source>Encrypt wallet</source> <translation>Brieftasche verschlüsseln</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Dieser Vorgang benötigt ihre Passphrase, um die Brieftasche zu entsperren.</translation> </message> <message> <source>Unlock wallet</source> <translation>Brieftasche entsperren</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Dieser Vorgang benötigt ihre Passphrase, um die Brieftasche zu entschlüsseln.</translation> </message> <message> <source>Decrypt wallet</source> <translation>Brieftasche entschlüsseln</translation> </message> <message> <source>Change passphrase</source> <translation>Passphrase ändern</translation> </message> <message> <source>Enter the old and new passphrase to the wallet.</source> <translation>Geben Sie die alte und neue Passphrase für die Brieftasche ein.</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Verschlüsselung der Brieftasche bestätigen</translation> </message> <message> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR sherlockcoinS&lt;/b&gt;!</source> <translation>Warnung: Wenn Sie ihre Brieftasche verschlüsseln und ihre Passphrase verlieren, werden Sie &lt;b&gt;alle ihre sherlockcoins verlieren&lt;/b&gt;!</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Sind Sie sich sicher, dass Sie ihre Brieftasche verschlüsseln möchten?</translation> </message> <message> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>WICHTIG: Alle vorherigen Brieftaschen-Sicherungen sollten durch die neu erzeugte, verschlüsselte Brieftasche ersetzt werden. Aus Sicherheitsgründen werden vorherige Sicherungen der unverschlüsselten Brieftasche nutzlos, sobald Sie die neue, verschlüsselte Brieftasche verwenden.</translation> </message> <message> <source>Warning: The Caps Lock key is on!</source> <translation>Warnung: Die Feststelltaste ist aktiviert!</translation> </message> <message> <source>Wallet encrypted</source> <translation>Brieftasche verschlüsselt</translation> </message> <message> <source>sherlockcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your sherlockcoins from being stolen by malware infecting your computer.</source> <translation>sherlockcoin wird jetzt beendet, um den Verschlüsselungsprozess abzuschließen. Bitte beachten Sie, dass die Verschlüsselung der Brieftasche nicht vollständig vor Diebstahl ihrer sherlockcoins durch Schadsoftware schützt, die ihren Computer befällt.</translation> </message> <message> <source>Wallet encryption failed</source> <translation>Verschlüsselung der Brieftasche fehlgeschlagen</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Die Verschlüsselung der Brieftasche ist aufgrund eines internen Fehlers fehlgeschlagen. Ihre Brieftasche wurde nicht verschlüsselt.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>Die eingegebenen Passphrasen stimmen nicht überein.</translation> </message> <message> <source>Wallet unlock failed</source> <translation>Entsperrung der Brieftasche fehlgeschlagen</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Die eingegebene Passphrase zur Entschlüsselung der Brieftasche war nicht korrekt.</translation> </message> <message> <source>Wallet decryption failed</source> <translation>Entschlüsselung der Brieftasche fehlgeschlagen</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>Die Passphrase der Brieftasche wurde erfolgreich geändert.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>Nachricht s&amp;ignieren...</translation> </message> <message> <source>Synchronizing with network...</source> <translation>Synchronisiere mit Netzwerk...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Übersicht</translation> </message> <message> <source>Node</source> <translation>Knoten</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Allgemeine Übersicht über die Brieftasche anzeigen</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transaktionen</translation> </message> <message> <source>Browse transaction history</source> <translation>Transaktionsverlauf durchsehen</translation> </message> <message> <source>E&amp;xit</source> <translation>&amp;Beenden</translation> </message> <message> <source>Quit application</source> <translation>Anwendung beenden</translation> </message> <message> <source>Show information about sherlockcoin</source> <translation>Informationen über sherlockcoin anzeigen</translation> </message> <message> <source>About &amp;Qt</source> <translation>Über &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Informationen über Qt anzeigen</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Konfiguration...</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>Brieftasche &amp;verschlüsseln...</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>Brieftasche &amp;sichern...</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>Passphrase &amp;ändern...</translation> </message> <message> <source>Very &amp;sending addresses...</source> <translation>&amp;Zahlungsadressen...</translation> </message> <message> <source>Much &amp;receiving addresses...</source> <translation>&amp;Empfangsadressen...</translation> </message> <message> <source>Open &amp;URI...</source> <translation>&amp;URI öffnen...</translation> </message> <message> <source>Importing blocks from disk...</source> <translation>Importiere Blöcke von Datenträger...</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>Reindiziere Blöcke auf Datenträger...</translation> </message> <message> <source>Send coins to a sherlockcoin address</source> <translation>sherlockcoins an eine sherlockcoin-Adresse überweisen</translation> </message> <message> <source>Modify configuration options for sherlockcoin Core</source> <translation>Die Konfiguration des Clients bearbeiten</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Eine Sicherungskopie der Brieftasche erstellen und abspeichern</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Ändert die Passphrase, die für die Verschlüsselung der Brieftasche benutzt wird</translation> </message> <message> <source>&amp;Debug window</source> <translation>&amp;Debugfenster</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Debugging- und Diagnosekonsole öffnen</translation> </message> <message> <source>&amp;Verify message...</source> <translation>Nachricht &amp;verifizieren...</translation> </message> <message> <source>sherlockcoin</source> <translation>sherlockcoin</translation> </message> <message> <source>Wallet</source> <translation>Brieftasche</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Überweisen</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Empfangen</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Anzeigen / Verstecken</translation> </message> <message> <source>Show or hide the main Window</source> <translation>Das Hauptfenster anzeigen oder verstecken</translation> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation>Verschlüsselt die zu ihrer Brieftasche gehörenden privaten Schlüssel</translation> </message> <message> <source>Sign messages with your sherlockcoin addresses to prove you own them</source> <translation>Nachrichten signieren, um den Besitz ihrer sherlockcoin-Adressen zu beweisen</translation> </message> <message> <source>Verify messages to ensure they were signed with specified sherlockcoin addresses</source> <translation>Nachrichten verifizieren, um sicherzustellen, dass diese mit den angegebenen sherlockcoin-Adressen signiert wurden</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Datei</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Einstellungen</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Hilfe</translation> </message> <message> <source>Tabs toolbar</source> <translation>Registerkartenleiste</translation> </message> <message> <source>[testnet]</source> <translation>[Testnetz]</translation> </message> <message> <source>sherlockcoin Core</source> <translation>sherlockcoin Core</translation> </message> <message> <source>Request payments (generates QR codes and sherlockcoin: URIs)</source> <translation>Zahlungen anfordern (erzeugt QR-Codes und &quot;sherlockcoin:&quot;-URIs)</translation> </message> <message> <source>&amp;About sherlockcoin Core</source> <translation>&amp;Über sherlockcoin Core</translation> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation>Liste verwendeter Zahlungsadressen und Bezeichnungen anzeigen</translation> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation>Liste verwendeter Empfangsadressen und Bezeichnungen anzeigen</translation> </message> <message> <source>Open a sherlockcoin: URI or payment request</source> <translation>Eine &quot;sherlockcoin:&quot;-URI oder Zahlungsanforderung öffnen</translation> </message> <message> <source>&amp;Command-line options</source> <translation>&amp;Kommandozeilenoptionen</translation> </message> <message> <source>Show the sherlockcoin Core help message to get a list with possible command-line options</source> <translation>Zeige den &quot;sherlockcoin Core&quot;-Hilfetext, um eine Liste mit möglichen Kommandozeilenoptionen zu erhalten</translation> </message> <message> <source>sherlockcoin client</source> <translation>sherlockcoin-Client</translation> </message> <message numerus="yes"> <source>%n active connection(s) to sherlockcoin network</source> <translation><numerusform>%n aktive Verbindung zum sherlockcoin-Netzwerk</numerusform><numerusform>%n aktive Verbindungen zum sherlockcoin-Netzwerk</numerusform></translation> </message> <message> <source>No block source available...</source> <translation>Keine Blockquelle verfügbar...</translation> </message> <message> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>%1 von (geschätzten) %2 Blöcken des Transaktionsverlaufs verarbeitet.</translation> </message> <message> <source>Processed %1 blocks of transaction history.</source> <translation>%1 Blöcke des Transaktionsverlaufs verarbeitet.</translation> </message> <message numerus="yes"> <source>%n hour(s)</source> <translation><numerusform>%n Stunde</numerusform><numerusform>%n Stunden</numerusform></translation> </message> <message numerus="yes"> <source>%n day(s)</source> <translation><numerusform>%n Tag</numerusform><numerusform>%n Tage</numerusform></translation> </message> <message numerus="yes"> <source>%n week(s)</source> <translation><numerusform>%n Woche</numerusform><numerusform>%n Wochen</numerusform></translation> </message> <message> <source>%1 and %2</source> <translation>%1 und %2</translation> </message> <message numerus="yes"> <source>%n year(s)</source> <translation><numerusform>%n Jahr</numerusform><numerusform>%n Jahre</numerusform></translation> </message> <message> <source>%1 behind</source> <translation>%1 im Rückstand</translation> </message> <message> <source>Last received block was generated %1 ago.</source> <translation>Der letzte empfangene Block ist %1 alt.</translation> </message> <message> <source>Transactions after this will not yet be visible.</source> <translation>Transaktionen hiernach werden noch nicht angezeigt.</translation> </message> <message> <source>Error</source> <translation>Fehler</translation> </message> <message> <source>Warning</source> <translation>Warnung</translation> </message> <message> <source>Information</source> <translation>Hinweis</translation> </message> <message> <source>Up to date</source> <translation>Auf aktuellem Stand</translation> </message> <message> <source>Catching up...</source> <translation>Hole auf...</translation> </message> <message> <source>Sent transaction</source> <translation>Gesendete Transaktion</translation> </message> <message> <source>Incoming transaction</source> <translation>Eingehende Transaktion</translation> </message> <message> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum: %1 Betrag: %2 Typ: %3 Adresse: %4</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Brieftasche ist &lt;b&gt;verschlüsselt&lt;/b&gt; und aktuell &lt;b&gt;entsperrt&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Brieftasche ist &lt;b&gt;verschlüsselt&lt;/b&gt; und aktuell &lt;b&gt;gesperrt&lt;/b&gt;</translation> </message> <message> <source>A fatal error occurred. sherlockcoin can no longer continue safely and will quit.</source> <translation>Ein schwerer Fehler ist aufgetreten. sherlockcoin kann nicht stabil weiter ausgeführt werden und wird beendet.</translation> </message> </context> <context> <name>ClientModel</name> <message> <source>Network Alert</source> <translation>Netzwerkalarm</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Control Address Selection</source> <translation>&quot;Coin Control&quot;-Adressauswahl</translation> </message> <message> <source>Quantity:</source> <translation>Anzahl:</translation> </message> <message> <source>Bytes:</source> <translation>Byte:</translation> </message> <message> <source>Amount:</source> <translation>Betrag:</translation> </message> <message> <source>Priority:</source> <translation>Priorität:</translation> </message> <message> <source>Fee:</source> <translation>Gebühr:</translation> </message> <message> <source>Low Output:</source> <translation>Zu geringer Ausgabebetrag:</translation> </message> <message> <source>After Fee:</source> <translation>Abzüglich Gebühr:</translation> </message> <message> <source>Change:</source> <translation>Wechselgeld:</translation> </message> <message> <source>(un)select all</source> <translation>Alles (de)selektieren</translation> </message> <message> <source>Tree mode</source> <translation>Baumansicht</translation> </message> <message> <source>List mode</source> <translation>Listenansicht</translation> </message> <message> <source>Amount</source> <translation>Betrag</translation> </message> <message> <source>Label</source> <translation type="unfinished"/> </message> <message> <source>Address</source> <translation>Adresse</translation><|fim▁hole|> </message> <message> <source>Confirmations</source> <translation>Bestätigungen</translation> </message> <message> <source>Confirmed</source> <translation>Bestätigt</translation> </message> <message> <source>Priority</source> <translation>Priorität</translation> </message> <message> <source>Copy address</source> <translation>Adresse kopieren</translation> </message> <message> <source>Copy label</source> <translation>Bezeichnung kopieren</translation> </message> <message> <source>Copy amount</source> <translation>Betrag kopieren</translation> </message> <message> <source>Copy transaction ID</source> <translation>Transaktions-ID kopieren</translation> </message> <message> <source>Lock unspent</source> <translation>Nicht ausgegebenen Betrag sperren</translation> </message> <message> <source>Unlock unspent</source> <translation>Nicht ausgegebenen Betrag entsperren</translation> </message> <message> <source>Copy quantity</source> <translation>Anzahl kopieren</translation> </message> <message> <source>Copy fee</source> <translation>Gebühr kopieren</translation> </message> <message> <source>Copy after fee</source> <translation>Abzüglich Gebühr kopieren</translation> </message> <message> <source>Copy bytes</source> <translation>Byte kopieren</translation> </message> <message> <source>Copy priority</source> <translation>Priorität kopieren</translation> </message> <message> <source>Copy low output</source> <translation>Zu geringen Ausgabebetrag kopieren</translation> </message> <message> <source>Copy change</source> <translation>Wechselgeld kopieren</translation> </message> <message> <source>highest</source> <translation>am höchsten</translation> </message> <message> <source>higher</source> <translation>höher</translation> </message> <message> <source>high</source> <translation>hoch</translation> </message> <message> <source>medium-high</source> <translation>mittel-hoch</translation> </message> <message> <source>medium</source> <translation>mittel</translation> </message> <message> <source>low-medium</source> <translation>niedrig-mittel</translation> </message> <message> <source>low</source> <translation>niedrig</translation> </message> <message> <source>lower</source> <translation>niedriger</translation> </message> <message> <source>lowest</source> <translation>am niedrigsten</translation> </message> <message> <source>(%1 locked)</source> <translation>(%1 gesperrt)</translation> </message> <message> <source>none</source> <translation>keine</translation> </message> <message> <source>Dust</source> <translation>&quot;Dust&quot;</translation> </message> <message> <source>yes</source> <translation>ja</translation> </message> <message> <source>no</source> <translation>nein</translation> </message> <message> <source>This label turns red, if the transaction size is greater than 1000 bytes.</source> <translation>Diese Bezeichnung wird rot, wenn die Transaktion größer als 1000 Byte ist.</translation> </message> <message> <source>This means a fee of at least %1 per kB is required.</source> <translation>Das bedeutet, dass eine Gebühr von mindestens %1 pro kB erforderlich ist.</translation> </message> <message> <source>Can vary +/- 1 byte per input.</source> <translation>Kann um +/- 1 Byte pro Eingabe variieren.</translation> </message> <message> <source>Transactions with higher priority are more likely to get included into a block.</source> <translation>Transaktionen mit höherer Priorität haben eine größere Chance in einen Block aufgenommen zu werden.</translation> </message> <message> <source>This label turns red, if the priority is smaller than &quot;medium&quot;.</source> <translation>Diese Bezeichnung wird rot, wenn die Priorität niedriger als &quot;mittel&quot; ist.</translation> </message> <message> <source>This label turns red, if any recipient receives an amount smaller than %1.</source> <translation>Diese Bezeichnung wird rot, wenn irgendein Empfänger einen Betrag kleiner als %1 erhält.</translation> </message> <message> <source>This means a fee of at least %1 is required.</source> <translation>Das bedeutet, dass eine Gebühr von mindestens %1 erforderlich ist.</translation> </message> <message> <source>Amounts below 0.546 times the minimum relay fee are shown as dust.</source> <translation>Beträge kleiner als das 0,546-fache der niedrigsten Vermittlungsgebühr werden als &quot;Dust&quot; angezeigt.</translation> </message> <message> <source>This label turns red, if the change is smaller than %1.</source> <translation>Diese Bezeichnung wird rot, wenn das Wechselgeld weniger als %1 ist.</translation> </message> <message> <source>(no label)</source> <translation>(keine Bezeichnung)</translation> </message> <message> <source>change from %1 (%2)</source> <translation>Wechselgeld von %1 (%2)</translation> </message> <message> <source>(change)</source> <translation>(Wechselgeld)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Adresse bearbeiten</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Bezeichnung</translation> </message> <message> <source>The label associated with this address list entry</source> <translation>Bezeichnung, die dem Adresslisteneintrag zugeordnet ist.</translation> </message> <message> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation>Adresse, die dem Adresslisteneintrag zugeordnet ist. Diese kann nur bei Zahlungsadressen verändert werden.</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Adresse</translation> </message> <message> <source>New receiving address</source> <translation>Neue Empfangsadresse</translation> </message> <message> <source>New sending address</source> <translation>Neue Zahlungsadresse</translation> </message> <message> <source>Edit receiving address</source> <translation>Empfangsadresse bearbeiten</translation> </message> <message> <source>Edit sending address</source> <translation>Zahlungsadresse bearbeiten</translation> </message> <message> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Die eingegebene Adresse &quot;%1&quot; befindet sich bereits im Adressbuch.</translation> </message> <message> <source>The entered address &quot;%1&quot; is not a valid sherlockcoin address.</source> <translation>Die eingegebene Adresse &quot;%1&quot; ist keine gültige sherlockcoin-Adresse.</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>Brieftasche konnte nicht entsperrt werden.</translation> </message> <message> <source>New key generation failed.</source> <translation>Erzeugung eines neuen Schlüssels fehlgeschlagen.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>A new data directory will be created.</source> <translation>Es wird ein neues Datenverzeichnis angelegt.</translation> </message> <message> <source>name</source> <translation>Name</translation> </message> <message> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>Verzeichnis existiert bereits. Fügen Sie %1 an, wenn Sie beabsichtigen hier ein neues Verzeichnis anzulegen.</translation> </message> <message> <source>Path already exists, and is not a directory.</source> <translation>Pfad existiert bereits und ist kein Verzeichnis.</translation> </message> <message> <source>Cannot create data directory here.</source> <translation>Datenverzeichnis kann hier nicht angelegt werden.</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>sherlockcoin Core - Command-line options</source> <translation>sherlockcoin Core - Kommandozeilenoptionen</translation> </message> <message> <source>sherlockcoin Core</source> <translation>sherlockcoin Core</translation> </message> <message> <source>version</source> <translation>Version</translation> </message> <message> <source>Usage:</source> <translation>Benutzung:</translation> </message> <message> <source>command-line options</source> <translation>Kommandozeilenoptionen</translation> </message> <message> <source>UI options</source> <translation>UI-Optionen</translation> </message> <message> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Sprache festlegen, z.B. &quot;de_DE&quot; (Standard: Systemstandard)</translation> </message> <message> <source>Start minimized</source> <translation>Minimiert starten</translation> </message> <message> <source>Set SSL root certificates for payment request (default: -system-)</source> <translation>SSL-Wurzelzertifikate für Zahlungsanforderungen festlegen (Standard: Systemstandard)</translation> </message> <message> <source>Show splash screen on startup (default: 1)</source> <translation>Startbildschirm beim Starten anzeigen (Standard: 1)</translation> </message> <message> <source>Choose data directory on startup (default: 0)</source> <translation>Datenverzeichnis beim Starten auswählen (Standard: 0)</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>Willkommen</translation> </message> <message> <source>Welcome to sherlockcoin Core.</source> <translation>Willkommen zu sherlockcoin Core.</translation> </message> <message> <source>As this is the first time the program is launched, you can choose where sherlockcoin Core will store its data.</source> <translation>Da Sie das Programm gerade zum ersten Mal starten, können Sie nun auswählen wo sherlockcoin Core seine Daten ablegen soll.</translation> </message> <message> <source>sherlockcoin Core will download and store a copy of the sherlockcoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation>sherlockcoin Core wird eine Kopie der Blockkette herunterladen und speichern. Mindestens %1GB Daten werden in diesem Verzeichnis abgelegt und die Datenmenge wächst über die Zeit an. Auch die Brieftasche wird in diesem Verzeichnis abgelegt.</translation> </message> <message> <source>Use the default data directory</source> <translation>Standard-Datenverzeichnis verwenden</translation> </message> <message> <source>Use a custom data directory:</source> <translation>Ein benutzerdefiniertes Datenverzeichnis verwenden:</translation> </message> <message> <source>sherlockcoin</source> <translation>sherlockcoin</translation> </message> <message> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation>Fehler: Angegebenes Datenverzeichnis &quot;%1&quot; kann nicht angelegt werden.</translation> </message> <message> <source>Error</source> <translation>Fehler</translation> </message> <message> <source>GB of free space available</source> <translation>GB freier Speicherplatz verfügbar</translation> </message> <message> <source>(of %1GB needed)</source> <translation>(von benötigten %1GB)</translation> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation>URI öffnen</translation> </message> <message> <source>Open payment request from URI or file</source> <translation>Zahlungsanforderung über URI oder aus Datei öffnen</translation> </message> <message> <source>URI:</source> <translation>URI:</translation> </message> <message> <source>Select payment request file</source> <translation>Zahlungsanforderungsdatei auswählen</translation> </message> <message> <source>Select payment request file to open</source> <translation>Zu öffnende Zahlungsanforderungsdatei auswählen</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Konfiguration</translation> </message> <message> <source>&amp;Main</source> <translation>&amp;Allgemein</translation> </message> <message> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>Optionale Transaktionsgebühr pro kB, die sicherstellt, dass ihre Transaktionen schnell bearbeitet werden. Die meisten Transaktionen sind 1 kB groß.</translation> </message> <message> <source>Pay transaction &amp;fee</source> <translation>Transaktions&amp;gebühr bezahlen</translation> </message> <message> <source>Automatically start sherlockcoin Core after logging in to the system.</source> <translation>sherlockcoin nach der Anmeldung am System automatisch ausführen.</translation> </message> <message> <source>&amp;Start sherlockcoin Core on system login</source> <translation>&amp;Starte sherlockcoin nach Systemanmeldung</translation> </message> <message> <source>Size of &amp;database cache</source> <translation>Größe des &amp;Datenbankcaches</translation> </message> <message> <source>MB</source> <translation>MB</translation> </message> <message> <source>Number of script &amp;verification threads</source> <translation>Anzahl an Skript-&amp;Verifizierungs-Threads</translation> </message> <message> <source>Connect to the sherlockcoin network through a SOCKS proxy.</source> <translation>Über einen SOCKS-Proxy mit dem sherlockcoin-Netzwerk verbinden.</translation> </message> <message> <source>&amp;Connect through SOCKS proxy (default proxy):</source> <translation>Über einen SOCKS-Proxy &amp;verbinden (Standardproxy):</translation> </message> <message> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation>IP-Adresse des Proxies (z.B. IPv4: 127.0.0.1 / IPv6: ::1)</translation> </message> <message> <source>Active command-line options that override above options:</source> <translation>Aktive Kommandozeilenoptionen, die obige Konfiguration überschreiben:</translation> </message> <message> <source>Reset all client options to default.</source> <translation>Setzt die Clientkonfiguration auf Standardwerte zurück.</translation> </message> <message> <source>&amp;Reset Options</source> <translation>Konfiguration &amp;zurücksetzen</translation> </message> <message> <source>&amp;Network</source> <translation>&amp;Netzwerk</translation> </message> <message> <source>(0 = auto, &lt;0 = leave that many cores free)</source> <translation>(0 = automatisch, &lt;0 = so viele Kerne frei lassen)</translation> </message> <message> <source>W&amp;allet</source> <translation>W&amp;allet</translation> </message> <message> <source>Expert</source> <translation>Erweiterte Optionen der Brieftasche</translation> </message> <message> <source>Enable coin &amp;control features</source> <translation>&quot;&amp;Coin Control&quot;-Funktionen aktivieren</translation> </message> <message> <source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source> <translation>Wenn Sie das Ausgeben von unbestätigtem Wechselgeld deaktivieren, kann das Wechselgeld einer Transaktion nicht verwendet werden, bis es mindestens eine Bestätigung erhalten hat. Dies wirkt sich auf die Berechnung des Kontostands aus.</translation> </message> <message> <source>&amp;Spend unconfirmed change</source> <translation>&amp;Unbestätigtes Wechselgeld darf ausgegeben werden</translation> </message> <message> <source>Automatically open the sherlockcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automatisch den sherlockcoin-Clientport auf dem Router öffnen. Dies funktioniert nur, wenn ihr Router UPnP unterstützt und dies aktiviert ist.</translation> </message> <message> <source>Map port using &amp;UPnP</source> <translation>Portweiterleitung via &amp;UPnP</translation> </message> <message> <source>Proxy &amp;IP:</source> <translation>Proxy-&amp;IP:</translation> </message> <message> <source>&amp;Port:</source> <translation>&amp;Port:</translation> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation>Port des Proxies (z.B. 9050)</translation> </message> <message> <source>SOCKS &amp;Version:</source> <translation>SOCKS-&amp;Version:</translation> </message> <message> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>SOCKS-Version des Proxies (z.B. 5)</translation> </message> <message> <source>&amp;Window</source> <translation>&amp;Programmfenster</translation> </message> <message> <source>Show only a tray icon after minimizing the window.</source> <translation>Nur ein Symbol im Infobereich anzeigen, nachdem das Programmfenster minimiert wurde.</translation> </message> <message> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>In den Infobereich anstatt in die Taskleiste &amp;minimieren</translation> </message> <message> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimiert die Anwendung anstatt sie zu beenden wenn das Fenster geschlossen wird. Wenn dies aktiviert ist, müssen Sie das Programm über &quot;Beenden&quot; im Menü schließen.</translation> </message> <message> <source>M&amp;inimize on close</source> <translation>Beim Schließen m&amp;inimieren</translation> </message> <message> <source>&amp;Display</source> <translation>Anzei&amp;ge</translation> </message> <message> <source>User Interface &amp;language:</source> <translation>&amp;Sprache der Benutzeroberfläche:</translation> </message> <message> <source>The user interface language can be set here. This setting will take effect after restarting sherlockcoin Core.</source> <translation>Legt die Sprache der Benutzeroberfläche fest. Diese Einstellung wird erst nach einem Neustart von sherlockcoin aktiv.</translation> </message> <message> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Einheit der Beträge:</translation> </message> <message> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Wählen Sie die standardmäßige Untereinheit, die in der Benutzeroberfläche und beim Überweisen von sherlockcoins angezeigt werden soll.</translation> </message> <message> <source>Whether to show sherlockcoin addresses in the transaction list or not.</source> <translation>Legt fest, ob sherlockcoin-Adressen im Transaktionsverlauf angezeigt werden.</translation> </message> <message> <source>&amp;Display addresses in transaction list</source> <translation>Adressen im Transaktionsverlauf &amp;anzeigen</translation> </message> <message> <source>Whether to show coin control features or not.</source> <translation>Legt fest, ob die &quot;Coin Control&quot;-Funktionen angezeigt werden.</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <source>&amp;Cancel</source> <translation>A&amp;bbrechen</translation> </message> <message> <source>default</source> <translation>Standard</translation> </message> <message> <source>none</source> <translation>keine</translation> </message> <message> <source>Confirm options reset</source> <translation>Zurücksetzen der Konfiguration bestätigen</translation> </message> <message> <source>Client restart required to activate changes.</source> <translation>Clientneustart nötig, um die Änderungen zu aktivieren.</translation> </message> <message> <source>Client will be shutdown, do you want to proceed?</source> <translation>Client wird beendet, wollen Sie fortfahren?</translation> </message> <message> <source>This change would require a client restart.</source> <translation>Diese Änderung würde einen Clientneustart benötigen.</translation> </message> <message> <source>The supplied proxy address is invalid.</source> <translation>Die eingegebene Proxyadresse ist ungültig.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Formular</translation> </message> <message> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the sherlockcoin network after a connection is established, but this process has not completed yet.</source> <translation>Die angezeigten Informationen sind möglicherweise nicht mehr aktuell. Ihre Brieftasche wird automatisch synchronisiert, nachdem eine Verbindung zum sherlockcoin-Netzwerk hergestellt wurde. Dieser Prozess ist jedoch derzeit noch nicht abgeschlossen.</translation> </message> <message> <source>Wallet</source> <translation>Brieftasche</translation> </message> <message> <source>Available:</source> <translation>Verfügbar:</translation> </message> <message> <source>Your current spendable balance</source> <translation>Ihr aktuell verfügbarer Kontostand</translation> </message> <message> <source>Pending:</source> <translation>Ausstehend:</translation> </message> <message> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>Betrag aus unbestätigten Transaktionen, der noch nicht im aktuell verfügbaren Kontostand enthalten ist</translation> </message> <message> <source>Immature:</source> <translation>Unreif:</translation> </message> <message> <source>Mined balance that has not yet matured</source> <translation>Erarbeiteter Betrag der noch nicht gereift ist</translation> </message> <message> <source>Total:</source> <translation>Gesamtbetrag:</translation> </message> <message> <source>Your current total balance</source> <translation>Aktueller Gesamtbetrag aus obigen Kategorien</translation> </message> <message> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Letzte Transaktionen&lt;/b&gt;</translation> </message> <message> <source>out of sync</source> <translation>nicht synchron</translation> </message> </context> <context> <name>PaymentServer</name> <message> <source>URI handling</source> <translation>URI-Verarbeitung</translation> </message> <message> <source>URI can not be parsed! This can be caused by an invalid sherlockcoin address or malformed URI parameters.</source> <translation>URI kann nicht analysiert werden! Dies kann durch eine ungültige sherlockcoin-Adresse oder fehlerhafte URI-Parameter verursacht werden.</translation> </message> <message> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation>Angeforderter Zahlungsbetrag in Höhe von %1 ist zu niedrig und wurde als &quot;Dust&quot; eingestuft.</translation> </message> <message> <source>Payment request error</source> <translation>fehlerhafte Zahlungsanforderung</translation> </message> <message> <source>Cannot start sherlockcoin: click-to-pay handler</source> <translation>&quot;sherlockcoin: Klicken-zum-Bezahlen&quot;-Handler konnte nicht gestartet werden</translation> </message> <message> <source>Net manager warning</source> <translation>Netzwerkmanager-Warnung</translation> </message> <message> <source>Your active proxy doesn&apos;t support SOCKS5, which is required for payment requests via proxy.</source> <translation>Ihr aktiver Proxy unterstützt kein SOCKS5, dies wird jedoch für Zahlungsanforderungen über einen Proxy benötigt.</translation> </message> <message> <source>Payment request fetch URL is invalid: %1</source> <translation>Abruf-URL der Zahlungsanforderung ist ungültig: %1</translation> </message> <message> <source>Payment request file handling</source> <translation>Zahlungsanforderungsdatei-Verarbeitung</translation> </message> <message> <source>Payment request file can not be read or processed! This can be caused by an invalid payment request file.</source> <translation>Zahlungsanforderungsdatei kann nicht gelesen oder verarbeitet werden! Dies kann durch eine ungültige Zahlungsanforderungsdatei verursacht werden.</translation> </message> <message> <source>Unverified payment requests to custom payment scripts are unsupported.</source> <translation>Unverifizierte Zahlungsanforderungen an benutzerdefinierte Zahlungsskripte werden nicht unterstützt.</translation> </message> <message> <source>Refund from %1</source> <translation>Rücküberweisung von %1</translation> </message> <message> <source>Error communicating with %1: %2</source> <translation>Kommunikationsfehler mit %1: %2</translation> </message> <message> <source>Payment request can not be parsed or processed!</source> <translation>Zahlungsanforderung kann nicht analysiert oder verarbeitet werden!</translation> </message> <message> <source>Bad response from server %1</source> <translation>Fehlerhafte Antwort vom Server: %1</translation> </message> <message> <source>Payment acknowledged</source> <translation>Zahlung bestätigt</translation> </message> <message> <source>Network request error</source> <translation>fehlerhafte Netzwerkanfrage</translation> </message> </context> <context> <name>QObject</name> <message> <source>sherlockcoin</source> <translation>sherlockcoin</translation> </message> <message> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation>Fehler: Angegebenes Datenverzeichnis &quot;%1&quot; existiert nicht.</translation> </message> <message> <source>Error: Cannot parse configuration file: %1. Only use key=value syntax.</source> <translation>Fehler: Konfigurationsdatei kann nicht analysiert werden: %1. Bitte nur &quot;Schlüssel=Wert&quot;-Syntax verwenden.</translation> </message> <message> <source>Error: Invalid combination of -regtest and -testnet.</source> <translation>Fehler: Ungültige Kombination von -regtest und -testnet.</translation> </message> <message> <source>sherlockcoin Core did&apos;t yet exit safely...</source> <translation>sherlockcoin Core wurde noch nicht sicher beendet...</translation> </message> <message> <source>Enter a sherlockcoin address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation>sherlockcoin-Adresse eingeben (z.B. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation> </message> </context> <context> <name>QRImageWidget</name> <message> <source>&amp;Save Image...</source> <translation>Grafik &amp;speichern...</translation> </message> <message> <source>&amp;Copy Image</source> <translation>Grafik &amp;kopieren</translation> </message> <message> <source>Save QR Code</source> <translation>QR-Code speichern</translation> </message> <message> <source>PNG Image (*.png)</source> <translation>PNG-Grafik (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <source>Client name</source> <translation>Clientname</translation> </message> <message> <source>N/A</source> <translation>k.A.</translation> </message> <message> <source>Client version</source> <translation>Clientversion</translation> </message> <message> <source>&amp;Information</source> <translation>&amp;Information</translation> </message> <message> <source>Debug window</source> <translation>Debugfenster</translation> </message> <message> <source>General</source> <translation>Allgemein</translation> </message> <message> <source>Using OpenSSL version</source> <translation>Verwendete OpenSSL-Version</translation> </message> <message> <source>Startup time</source> <translation>Startzeit</translation> </message> <message> <source>Network</source> <translation>Netzwerk</translation> </message> <message> <source>Name</source> <translation>Name</translation> </message> <message> <source>Number of connections</source> <translation>Anzahl Verbindungen</translation> </message> <message> <source>Block chain</source> <translation>Blockkette</translation> </message> <message> <source>Current number of blocks</source> <translation>Aktuelle Anzahl Blöcke</translation> </message> <message> <source>Estimated total blocks</source> <translation>Geschätzte Gesamtzahl Blöcke</translation> </message> <message> <source>Last block time</source> <translation>Letzte Blockzeit</translation> </message> <message> <source>&amp;Open</source> <translation>&amp;Öffnen</translation> </message> <message> <source>&amp;Console</source> <translation>&amp;Konsole</translation> </message> <message> <source>&amp;Network Traffic</source> <translation>&amp;Netzwerkauslastung</translation> </message> <message> <source>&amp;Clear</source> <translation>&amp;Zurücksetzen</translation> </message> <message> <source>Totals</source> <translation>Summen</translation> </message> <message> <source>In:</source> <translation>eingehend:</translation> </message> <message> <source>Out:</source> <translation>ausgehend:</translation> </message> <message> <source>Build date</source> <translation>Erstellungsdatum</translation> </message> <message> <source>Debug log file</source> <translation>Debugprotokolldatei</translation> </message> <message> <source>Open the sherlockcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Öffnet die sherlockcoin-Debugprotokolldatei aus dem aktuellen Datenverzeichnis. Dies kann bei großen Protokolldateien einige Sekunden dauern.</translation> </message> <message> <source>Clear console</source> <translation>Konsole zurücksetzen</translation> </message> <message> <source>Welcome to the sherlockcoin RPC console.</source> <translation>Willkommen in der sherlockcoin-RPC-Konsole.</translation> </message> <message> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Pfeiltaste hoch und runter, um den Verlauf durchzublättern und &lt;b&gt;Strg-L&lt;/b&gt;, um die Konsole zurückzusetzen.</translation> </message> <message> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Bitte &lt;b&gt;help&lt;/b&gt; eingeben, um eine Übersicht verfügbarer Befehle zu erhalten.</translation> </message> <message> <source>%1 B</source> <translation>%1 B</translation> </message> <message> <source>%1 KB</source> <translation>%1 KB</translation> </message> <message> <source>%1 MB</source> <translation>%1 MB</translation> </message> <message> <source>%1 GB</source> <translation>%1 GB</translation> </message> <message> <source>%1 m</source> <translation>%1 m</translation> </message> <message> <source>%1 h</source> <translation>%1 h</translation> </message> <message> <source>%1 h %2 m</source> <translation>%1 h %2 m</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>&amp;Betrag:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Bezeichnung:</translation> </message> <message> <source>&amp;Message:</source> <translation>&amp;Nachricht:</translation> </message> <message> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation>Eine der bereits verwendeten Empfangsadressen wiederverwenden. Addressen wiederzuverwenden birgt Sicherheits- und Datenschutzrisiken. Außer zum Neuerstellen einer bereits erzeugten Zahlungsanforderung sollten Sie dies nicht nutzen.</translation> </message> <message> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation>Vorhandene Empfangsadresse &amp;wiederverwenden (nicht empfohlen)</translation> </message> <message> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the sherlockcoin network.</source> <translation>Eine optionale Nachricht, die an die Zahlungsanforderung angehängt wird. Sie wird angezeigt, wenn die Anforderung geöffnet wird. Hinweis: Diese Nachricht wird nicht mit der Zahlung über das sherlockcoin-Netzwerk gesendet.</translation> </message> <message> <source>An optional label to associate with the new receiving address.</source> <translation>Eine optionale Bezeichnung, die der neuen Empfangsadresse zugeordnet wird.</translation> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation>Verwenden Sie dieses Formular, um Zahlungen anzufordern. Alle Felder sind &lt;b&gt;optional&lt;/b&gt;.</translation> </message> <message> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation>Ein optional angeforderte Betrag. Lassen Sie dieses Feld leer oder setzen Sie es auf 0, um keinen spezifischen Betrag anzufordern.</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Alle Formularfelder zurücksetzen.</translation> </message> <message> <source>Clear</source> <translation>Zurücksetzen</translation> </message> <message> <source>Requested payments history</source> <translation>Verlauf der angeforderten Zahlungen</translation> </message> <message> <source>&amp;Request payment</source> <translation>&amp;Zahlung anfordern</translation> </message> <message> <source>Show the selected request (does the same as double clicking an entry)</source> <translation>Ausgewählte Zahlungsanforderungen anzeigen (entspricht einem Doppelklick auf einen Eintrag)</translation> </message> <message> <source>Show</source> <translation>Anzeigen</translation> </message> <message> <source>Remove the selected entries from the list</source> <translation>Ausgewählte Einträge aus der Liste entfernen</translation> </message> <message> <source>Remove</source> <translation>Entfernen</translation> </message> <message> <source>Copy label</source> <translation>Bezeichnung kopieren</translation> </message> <message> <source>Copy message</source> <translation>Nachricht kopieren</translation> </message> <message> <source>Copy amount</source> <translation>Betrag kopieren</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation>QR-Code</translation> </message> <message> <source>Copy &amp;URI</source> <translation>&amp;URI kopieren</translation> </message> <message> <source>Copy &amp;Address</source> <translation>&amp;Addresse kopieren</translation> </message> <message> <source>&amp;Save Image...</source> <translation>Grafik &amp;speichern...</translation> </message> <message> <source>Request payment to %1</source> <translation>Zahlung anfordern an %1</translation> </message> <message> <source>Payment information</source> <translation>Zahlungsinformationen</translation> </message> <message> <source>URI</source> <translation>URI</translation> </message> <message> <source>Address</source> <translation>Adresse</translation> </message> <message> <source>Amount</source> <translation>Betrag</translation> </message> <message> <source>Label</source> <translation>Bezeichnung</translation> </message> <message> <source>Message</source> <translation>Nachricht</translation> </message> <message> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Resultierende URI ist zu lang, bitte den Text für Bezeichnung/Nachricht kürzen.</translation> </message> <message> <source>Error encoding URI into QR Code.</source> <translation>Beim Enkodieren der URI in den QR-Code ist ein Fehler aufgetreten.</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Label</source> <translation>Bezeichnung</translation> </message> <message> <source>Message</source> <translation>Nachricht</translation> </message> <message> <source>Amount</source> <translation>Betrag</translation> </message> <message> <source>(no label)</source> <translation>(keine Bezeichnung)</translation> </message> <message> <source>(no message)</source> <translation>(keine Nachricht)</translation> </message> <message> <source>(no amount)</source> <translation>(kein Betrag)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>sherlockcoins überweisen</translation> </message> <message> <source>Coin Control Features</source> <translation>&quot;Coin Control&quot;-Funktionen</translation> </message> <message> <source>Inputs...</source> <translation>Eingaben...</translation> </message> <message> <source>automatically selected</source> <translation>automatisch ausgewählt</translation> </message> <message> <source>Insufficient funds!</source> <translation>Unzureichender Kontostand!</translation> </message> <message> <source>Quantity:</source> <translation>Anzahl:</translation> </message> <message> <source>Bytes:</source> <translation>Byte:</translation> </message> <message> <source>Amount:</source> <translation>Betrag:</translation> </message> <message> <source>Priority:</source> <translation>Priorität:</translation> </message> <message> <source>Fee:</source> <translation>Gebühr:</translation> </message> <message> <source>Low Output:</source> <translation>Zu geringer Ausgabebetrag:</translation> </message> <message> <source>After Fee:</source> <translation>Abzüglich Gebühr:</translation> </message> <message> <source>Change:</source> <translation>Wechselgeld:</translation> </message> <message> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation>Wenn dies aktivert, und die Wechselgeld-Adresse leer oder ungültig ist, wird das Wechselgeld einer neu erzeugten Adresse gutgeschrieben.</translation> </message> <message> <source>Custom change address</source> <translation>Benutzerdefinierte Wechselgeld-Adresse</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>An mehrere Empfänger auf einmal überweisen</translation> </message> <message> <source>Add &amp;Recipient</source> <translation>Empfänger &amp;hinzufügen</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Alle Formularfelder zurücksetzen.</translation> </message> <message> <source>Clear &amp;All</source> <translation>&amp;Zurücksetzen</translation> </message> <message> <source>Balance:</source> <translation>Kontostand:</translation> </message> <message> <source>Confirm the send action</source> <translation>Überweisung bestätigen</translation> </message> <message> <source>S&amp;end</source> <translation>&amp;Überweisen</translation> </message> <message> <source>Confirm send coins</source> <translation>Überweisung bestätigen</translation> </message> <message> <source>%1 to %2</source> <translation>%1 an %2</translation> </message> <message> <source>Copy quantity</source> <translation>Anzahl kopieren</translation> </message> <message> <source>Copy amount</source> <translation>Betrag kopieren</translation> </message> <message> <source>Copy fee</source> <translation>Gebühr kopieren</translation> </message> <message> <source>Copy after fee</source> <translation>Abzüglich Gebühr kopieren</translation> </message> <message> <source>Copy bytes</source> <translation>Byte kopieren</translation> </message> <message> <source>Copy priority</source> <translation>Priorität kopieren</translation> </message> <message> <source>Copy low output</source> <translation>Zu geringen Ausgabebetrag kopieren</translation> </message> <message> <source>Copy change</source> <translation>Wechselgeld kopieren</translation> </message> <message> <source>Total Amount %1 (= %2)</source> <translation>Gesamtbetrag %1 (= %2)</translation> </message> <message> <source>or</source> <translation>oder</translation> </message> <message> <source>The recipient address is not valid, please recheck.</source> <translation>Die Zahlungsadresse ist ungültig, bitte nochmals überprüfen.</translation> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation>Der zu zahlende Betrag muss größer als 0 sein.</translation> </message> <message> <source>The amount exceeds your balance.</source> <translation>Der angegebene Betrag übersteigt ihren Kontostand.</translation> </message> <message> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Der angegebene Betrag übersteigt aufgrund der Transaktionsgebühr in Höhe von %1 ihren Kontostand.</translation> </message> <message> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Doppelte Zahlungsadresse gefunden, pro Überweisung kann an jede Adresse nur einmalig etwas überwiesen werden.</translation> </message> <message> <source>Transaction creation failed!</source> <translation>Transaktionserstellung fehlgeschlagen!</translation> </message> <message> <source>The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Die Transaktion wurde abgelehnt! Dies kann passieren, wenn einige sherlockcoins aus ihrer Brieftasche bereits ausgegeben wurden. Beispielsweise weil Sie eine Kopie ihrer wallet.dat genutzt, die sherlockcoins dort ausgegeben haben und dies daher in der derzeit aktiven Brieftasche nicht vermerkt ist.</translation> </message> <message> <source>Warning: Invalid sherlockcoin address</source> <translation>Warnung: Ungültige sherlockcoin-Adresse</translation> </message> <message> <source>(no label)</source> <translation>(keine Bezeichnung)</translation> </message> <message> <source>Warning: Unknown change address</source> <translation>Warnung: Unbekannte Wechselgeld-Adresse</translation> </message> <message> <source>Are you sure you want to send?</source> <translation>Wollen Sie die Überweisung ausführen?</translation> </message> <message> <source>added as transaction fee</source> <translation>als Transaktionsgebühr hinzugefügt</translation> </message> <message> <source>Payment request expired</source> <translation>Zahlungsanforderung abgelaufen</translation> </message> <message> <source>Invalid payment address %1</source> <translation>Ungültige Zahlungsadresse %1</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>Betra&amp;g:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>E&amp;mpfänger:</translation> </message> <message> <source>The address to send the payment to (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation>Die Zahlungsadresse der Überweisung (z.B. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation> </message> <message> <source>Enter a label for this address to add it to your address book</source> <translation>Adressbezeichnung eingeben (diese wird zusammen mit der Adresse dem Adressbuch hinzugefügt)</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Bezeichnung:</translation> </message> <message> <source>Choose previously used address</source> <translation>Bereits verwendete Adresse auswählen</translation> </message> <message> <source>This is a normal payment.</source> <translation>Dies ist eine normale Überweisung.</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Adresse aus der Zwischenablage einfügen</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this entry</source> <translation>Diesen Eintrag entfernen</translation> </message> <message> <source>Message:</source> <translation>Nachricht:</translation> </message> <message> <source>This is a verified payment request.</source> <translation>Dies is eine verifizierte Zahlungsanforderung.</translation> </message> <message> <source>Enter a label for this address to add it to the list of used addresses</source> <translation>Adressbezeichnung eingeben, die dann zusammen mit der Adresse der Liste bereits verwendeter Adressen hinzugefügt wird.</translation> </message> <message> <source>A message that was attached to the sherlockcoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the sherlockcoin network.</source> <translation>Eine an die &quot;sherlockcoin:&quot;-URI angefügte Nachricht, die zusammen mit der Transaktion gespeichert wird. Hinweis: Diese Nachricht wird nicht über das sherlockcoin-Netzwerk gesendet.</translation> </message> <message> <source>This is an unverified payment request.</source> <translation>Dies is eine unverifizierte Zahlungsanforderung.</translation> </message> <message> <source>Pay To:</source> <translation>Empfänger:</translation> </message> <message> <source>Memo:</source> <translation>Memo:</translation> </message> </context> <context> <name>ShutdownWindow</name> <message> <source>sherlockcoin Core is shutting down...</source> <translation>sherlockcoin Core wird beendet...</translation> </message> <message> <source>Do not shut down the computer until this window disappears.</source> <translation>Fahren Sie den Computer nicht herunter, bevor dieses Fenster verschwindet.</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Signatures - Sign / Verify a Message</source> <translation>Signaturen - eine Nachricht signieren / verifizieren</translation> </message> <message> <source>&amp;Sign Message</source> <translation>Nachricht &amp;signieren</translation> </message> <message> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Sie können Nachrichten mit ihren Adressen signieren, um den Besitz dieser Adressen zu beweisen. Bitte nutzen Sie diese Funktion mit Vorsicht und nehmen Sie sich vor Phishingangriffen in Acht. Signieren Sie nur Nachrichten, mit denen Sie vollständig einverstanden sind.</translation> </message> <message> <source>The address to sign the message with (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation>Die Adresse mit der die Nachricht signiert wird (z.B. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation> </message> <message> <source>Choose previously used address</source> <translation>Bereits verwendete Adresse auswählen</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Adresse aus der Zwischenablage einfügen</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Enter the message you want to sign here</source> <translation>Zu signierende Nachricht hier eingeben</translation> </message> <message> <source>Signature</source> <translation>Signatur</translation> </message> <message> <source>Copy the current signature to the system clipboard</source> <translation>Aktuelle Signatur in die Zwischenablage kopieren</translation> </message> <message> <source>Sign the message to prove you own this sherlockcoin address</source> <translation>Die Nachricht signieren, um den Besitz dieser sherlockcoin-Adresse zu beweisen</translation> </message> <message> <source>Sign &amp;Message</source> <translation>&amp;Nachricht signieren</translation> </message> <message> <source>Reset all sign message fields</source> <translation>Alle &quot;Nachricht signieren&quot;-Felder zurücksetzen</translation> </message> <message> <source>Clear &amp;All</source> <translation>&amp;Zurücksetzen</translation> </message> <message> <source>&amp;Verify Message</source> <translation>Nachricht &amp;verifizieren</translation> </message> <message> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Geben Sie die signierende Adresse, Nachricht (achten Sie darauf Zeilenumbrüche, Leerzeichen, Tabulatoren usw. exakt zu kopieren) und Signatur unten ein, um die Nachricht zu verifizieren. Vorsicht, interpretieren Sie nicht mehr in die Signatur hinein, als in der signierten Nachricht selber enthalten ist, um nicht von einem Man-in-the-middle-Angriff hinters Licht geführt zu werden.</translation> </message> <message> <source>The address the message was signed with (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation>Die Adresse mit der die Nachricht signiert wurde (z.B. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation> </message> <message> <source>Verify the message to ensure it was signed with the specified sherlockcoin address</source> <translation>Die Nachricht verifizieren, um sicherzustellen, dass diese mit der angegebenen sherlockcoin-Adresse signiert wurde</translation> </message> <message> <source>Verify &amp;Message</source> <translation>&amp;Nachricht verifizieren</translation> </message> <message> <source>Reset all verify message fields</source> <translation>Alle &quot;Nachricht verifizieren&quot;-Felder zurücksetzen</translation> </message> <message> <source>Enter a sherlockcoin address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation>sherlockcoin-Adresse eingeben (z.B. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation> </message> <message> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Auf &quot;Nachricht signieren&quot; klicken, um die Signatur zu erzeugen</translation> </message> <message> <source>The entered address is invalid.</source> <translation>Die eingegebene Adresse ist ungültig.</translation> </message> <message> <source>Please check the address and try again.</source> <translation>Bitte überprüfen Sie die Adresse und versuchen Sie es erneut.</translation> </message> <message> <source>The entered address does not refer to a key.</source> <translation>Die eingegebene Adresse verweist nicht auf einen Schlüssel.</translation> </message> <message> <source>Wallet unlock was cancelled.</source> <translation>Entsperrung der Brieftaschewurde abgebrochen.</translation> </message> <message> <source>Private key for the entered address is not available.</source> <translation>Privater Schlüssel zur eingegebenen Adresse ist nicht verfügbar.</translation> </message> <message> <source>Message signing failed.</source> <translation>Signierung der Nachricht fehlgeschlagen.</translation> </message> <message> <source>Message signed.</source> <translation>Nachricht signiert.</translation> </message> <message> <source>The signature could not be decoded.</source> <translation>Die Signatur konnte nicht dekodiert werden.</translation> </message> <message> <source>Please check the signature and try again.</source> <translation>Bitte überprüfen Sie die Signatur und versuchen Sie es erneut.</translation> </message> <message> <source>The signature did not match the message digest.</source> <translation>Die Signatur entspricht nicht dem &quot;Message Digest&quot;.</translation> </message> <message> <source>Message verification failed.</source> <translation>Verifikation der Nachricht fehlgeschlagen.</translation> </message> <message> <source>Message verified.</source> <translation>Nachricht verifiziert.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>sherlockcoin Core</source> <translation>sherlockcoin Core</translation> </message> <message> <source>The sherlockcoin Core developers</source> <translation>Die &quot;sherlockcoin Core&quot;-Entwickler</translation> </message> <message> <source>[testnet]</source> <translation>[Testnetz]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <source>KB/s</source> <translation>KB/s</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <source>Open until %1</source> <translation>Offen bis %1</translation> </message> <message> <source>conflicted</source> <translation>in Konflikt stehend</translation> </message> <message> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <source>%1/unconfirmed</source> <translation>%1/unbestätigt</translation> </message> <message> <source>%1 confirmations</source> <translation>%1 Bestätigungen</translation> </message> <message> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <source>, broadcast through %n node(s)</source> <translation><numerusform>, über %n Knoten übertragen</numerusform><numerusform>, über %n Knoten übertragen</numerusform></translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Source</source> <translation>Quelle</translation> </message> <message> <source>Generated</source> <translation>Erzeugt</translation> </message> <message> <source>From</source> <translation>Von</translation> </message> <message> <source>To</source> <translation>An</translation> </message> <message> <source>own address</source> <translation>eigene Adresse</translation> </message> <message> <source>label</source> <translation>Bezeichnung</translation> </message> <message> <source>Credit</source> <translation>Gutschrift</translation> </message> <message numerus="yes"> <source>matures in %n more block(s)</source> <translation><numerusform>reift noch %n weiteren Block</numerusform><numerusform>reift noch %n weitere Blöcke</numerusform></translation> </message> <message> <source>not accepted</source> <translation>nicht angenommen</translation> </message> <message> <source>Debit</source> <translation>Belastung</translation> </message> <message> <source>Transaction fee</source> <translation>Transaktionsgebühr</translation> </message> <message> <source>Net amount</source> <translation>Nettobetrag</translation> </message> <message> <source>Message</source> <translation>Nachricht</translation> </message> <message> <source>Comment</source> <translation>Kommentar</translation> </message> <message> <source>Transaction ID</source> <translation>Transaktions-ID</translation> </message> <message> <source>Merchant</source> <translation>Händler</translation> </message> <message> <source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Erzeugte sherlockcoins müssen %1 Blöcke lang reifen, bevor sie ausgegeben werden können. Als Sie diesen Block erzeugten, wurde er an das Netzwerk übertragen, um ihn der Blockkette hinzuzufügen. Falls dies fehlschlägt wird der Status in &quot;nicht angenommen&quot; geändert und Sie werden keine sherlockcoins gutgeschrieben bekommen. Das kann gelegentlich passieren, wenn ein anderer Knoten einen Block fast zeitgleich erzeugt.</translation> </message> <message> <source>Debug information</source> <translation>Debuginformationen</translation> </message> <message> <source>Transaction</source> <translation>Transaktion</translation> </message> <message> <source>Inputs</source> <translation>Eingaben</translation> </message> <message> <source>Amount</source> <translation>Betrag</translation> </message> <message> <source>true</source> <translation>wahr</translation> </message> <message> <source>false</source> <translation>falsch</translation> </message> <message> <source>, has not been successfully broadcast yet</source> <translation>, wurde noch nicht erfolgreich übertragen</translation> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation><numerusform>Offen für %n weiteren Block</numerusform><numerusform>Offen für %n weitere Blöcke</numerusform></translation> </message> <message> <source>unknown</source> <translation>unbekannt</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>Transaction details</source> <translation>Transaktionsdetails</translation> </message> <message> <source>This pane shows a detailed description of the transaction</source> <translation>Dieser Bereich zeigt eine detaillierte Beschreibung der Transaktion an</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Type</source> <translation>Typ</translation> </message> <message> <source>Address</source> <translation>Adresse</translation> </message> <message> <source>Amount</source> <translation>Betrag</translation> </message> <message> <source>Immature (%1 confirmations, will be available after %2)</source> <translation>Unreif (%1 Bestätigungen, wird verfügbar sein nach %2)</translation> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation><numerusform>Offen für %n weiteren Block</numerusform><numerusform>Offen für %n weitere Blöcke</numerusform></translation> </message> <message> <source>Open until %1</source> <translation>Offen bis %1</translation> </message> <message> <source>Confirmed (%1 confirmations)</source> <translation>Bestätigt (%1 Bestätigungen)</translation> </message> <message> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Dieser Block wurde von keinem anderen Knoten empfangen und wird wahrscheinlich nicht angenommen werden!</translation> </message> <message> <source>Generated but not accepted</source> <translation>Erzeugt, jedoch nicht angenommen</translation> </message> <message> <source>Offline</source> <translation>Offline</translation> </message> <message> <source>Unconfirmed</source> <translation>Unbestätigt</translation> </message> <message> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation>Wird bestätigt (%1 von %2 empfohlenen Bestätigungen)</translation> </message> <message> <source>Conflicted</source> <translation>in Konflikt stehend</translation> </message> <message> <source>Received with</source> <translation>Empfangen über</translation> </message> <message> <source>Received from</source> <translation>Empfangen von</translation> </message> <message> <source>Sent to</source> <translation>Überwiesen an</translation> </message> <message> <source>Payment to yourself</source> <translation>Eigenüberweisung</translation> </message> <message> <source>Mined</source> <translation>Erarbeitet</translation> </message> <message> <source>(n/a)</source> <translation>(k.A.)</translation> </message> <message> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Transaktionsstatus, fahren Sie mit der Maus über dieses Feld, um die Anzahl der Bestätigungen zu sehen.</translation> </message> <message> <source>Date and time that the transaction was received.</source> <translation>Datum und Uhrzeit zu der die Transaktion empfangen wurde.</translation> </message> <message> <source>Type of transaction.</source> <translation>Art der Transaktion</translation> </message> <message> <source>Destination address of transaction.</source> <translation>Zieladresse der Transaktion</translation> </message> <message> <source>Amount removed from or added to balance.</source> <translation>Der Betrag, der dem Kontostand abgezogen oder hinzugefügt wurde.</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>Alle</translation> </message> <message> <source>Today</source> <translation>Heute</translation> </message> <message> <source>This week</source> <translation>Diese Woche</translation> </message> <message> <source>This month</source> <translation>Diesen Monat</translation> </message> <message> <source>Last month</source> <translation>Letzten Monat</translation> </message> <message> <source>This year</source> <translation>Dieses Jahr</translation> </message> <message> <source>Range...</source> <translation>Zeitraum...</translation> </message> <message> <source>Received with</source> <translation>Empfangen über</translation> </message> <message> <source>Sent to</source> <translation>Überwiesen an</translation> </message> <message> <source>To yourself</source> <translation>Eigenüberweisung</translation> </message> <message> <source>Mined</source> <translation>Erarbeitet</translation> </message> <message> <source>Other</source> <translation>Andere</translation> </message> <message> <source>Enter address or label to search</source> <translation>Zu suchende Adresse oder Bezeichnung eingeben</translation> </message> <message> <source>Min amount</source> <translation>Minimaler Betrag</translation> </message> <message> <source>Copy address</source> <translation>Adresse kopieren</translation> </message> <message> <source>Copy label</source> <translation>Bezeichnung kopieren</translation> </message> <message> <source>Copy amount</source> <translation>Betrag kopieren</translation> </message> <message> <source>Copy transaction ID</source> <translation>Transaktions-ID kopieren</translation> </message> <message> <source>Edit label</source> <translation>Bezeichnung bearbeiten</translation> </message> <message> <source>Show transaction details</source> <translation>Transaktionsdetails anzeigen</translation> </message> <message> <source>Export Transaction History</source> <translation>Transaktionsverlauf exportieren</translation> </message> <message> <source>Exporting Failed</source> <translation>Exportieren fehlgeschlagen</translation> </message> <message> <source>There was an error trying to save the transaction history to %1.</source> <translation>Beim Speichern des Transaktionsverlaufs nach %1 ist ein Fehler aufgetreten.</translation> </message> <message> <source>Exporting Successful</source> <translation>Exportieren erfolgreich</translation> </message> <message> <source>The transaction history was successfully saved to %1.</source> <translation>Speichern des Transaktionsverlaufs nach %1 war erfolgreich.</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommagetrennte-Datei (*.csv)</translation> </message> <message> <source>Confirmed</source> <translation>Bestätigt</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Type</source> <translation>Typ</translation> </message> <message> <source>Label</source> <translation>Bezeichnung</translation> </message> <message> <source>Address</source> <translation>Adresse</translation> </message> <message> <source>Amount</source> <translation>Betrag</translation> </message> <message> <source>ID</source> <translation>ID</translation> </message> <message> <source>Range:</source> <translation>Zeitraum:</translation> </message> <message> <source>to</source> <translation>bis</translation> </message> </context> <context> <name>WalletFrame</name> <message> <source>No wallet has been loaded.</source> <translation>Es wurde keine Brieftasche geladen.</translation> </message> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>sherlockcoins überweisen</translation> </message> </context> <context> <name>WalletView</name> <message> <source>&amp;Export</source> <translation>E&amp;xportieren</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Daten der aktuellen Ansicht in eine Datei exportieren</translation> </message> <message> <source>Backup Wallet</source> <translation>Brieftasche sichern</translation> </message> <message> <source>Wallet Data (*.dat)</source> <translation>Brieftaschen-Daten (*.dat)</translation> </message> <message> <source>Backup Failed</source> <translation>Sicherung fehlgeschlagen</translation> </message> <message> <source>There was an error trying to save the wallet data to %1.</source> <translation>Beim Speichern der Brieftaschen-Daten nach %1 ist ein Fehler aufgetreten.</translation> </message> <message> <source>The wallet data was successfully saved to %1.</source> <translation>Speichern der Brieftaschen-Daten nach %1 war erfolgreich.</translation> </message> <message> <source>Backup Successful</source> <translation>Sicherung erfolgreich</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <source>Usage:</source> <translation>Benutzung:</translation> </message> <message> <source>List commands</source> <translation>Befehle auflisten</translation> </message> <message> <source>Get help for a command</source> <translation>Hilfe zu einem Befehl erhalten</translation> </message> <message> <source>Options:</source> <translation>Optionen:</translation> </message> <message> <source>Specify configuration file (default: sherlockcoin.conf)</source> <translation>Konfigurationsdatei festlegen (Standard: sherlockcoin.conf)</translation> </message> <message> <source>Specify pid file (default: bitcoind.pid)</source> <translation>PID-Datei festlegen (Standard: bitcoind.pid)</translation> </message> <message> <source>Specify data directory</source> <translation>Datenverzeichnis festlegen</translation> </message> <message> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>&lt;port&gt; nach Verbindungen abhören (Standard: 8333 oder Testnetz: 18333)</translation> </message> <message> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Maximal &lt;n&gt; Verbindungen zu Gegenstellen aufrechterhalten (Standard: 125)</translation> </message> <message> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Mit dem angegebenen Knoten verbinden, um Adressen von Gegenstellen abzufragen, danach trennen</translation> </message> <message> <source>Specify your own public address</source> <translation>Die eigene öffentliche Adresse angeben</translation> </message> <message> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Schwellenwert, um Verbindungen zu sich nicht konform verhaltenden Gegenstellen zu beenden (Standard: 100)</translation> </message> <message> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Anzahl Sekunden, während denen sich nicht konform verhaltenden Gegenstellen die Wiederverbindung verweigert wird (Standard: 86400)</translation> </message> <message> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Beim Einrichten des RPC-Ports %u zum Abhören von IPv4 ist ein Fehler aufgetreten: %s</translation> </message> <message> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation>&lt;port&gt; nach JSON-RPC-Verbindungen abhören (Standard: 8332 oder Testnetz: 18332)</translation> </message> <message> <source>Accept command line and JSON-RPC commands</source> <translation>Kommandozeilen- und JSON-RPC-Befehle annehmen</translation> </message> <message> <source>sherlockcoin Core RPC client version</source> <translation>&quot;sherlockcoin Core&quot;-RPC-Client-Version</translation> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation>Als Hintergrunddienst ausführen und Befehle annehmen</translation> </message> <message> <source>Use the test network</source> <translation>Das Testnetz verwenden</translation> </message> <message> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Eingehende Verbindungen annehmen (Standard: 1, wenn nicht -proxy oder -connect)</translation> </message> <message> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;sherlockcoin Alert&quot; [email protected] </source> <translation>%s, Sie müssen den Wert rpcpasswort in dieser Konfigurationsdatei angeben: %s Es wird empfohlen das folgende Zufallspasswort zu verwenden: rpcuser=bitcoinrpc rpcpassword=%s (Sie müssen sich dieses Passwort nicht merken!) Der Benutzername und das Passwort dürfen NICHT identisch sein. Falls die Konfigurationsdatei nicht existiert, erzeugen Sie diese bitte mit Leserechten nur für den Dateibesitzer. Es wird ebenfalls empfohlen alertnotify anzugeben, um im Problemfall benachrichtig zu werden; zum Beispiel: alertnotify=echo %%s | mail -s \&quot;sherlockcoin Alert\&quot; [email protected] </translation> </message> <message> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation>Zulässige Chiffren (Standard: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</translation> </message> <message> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Beim Einrichten des RPC-Ports %u zum Abhören von IPv6 ist ein Fehler aufgetreten, es wird auf IPv4 zurückgegriffen: %s</translation> </message> <message> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>An die angegebene Adresse binden und immer abhören. Für IPv6 &quot;[Host]:Port&quot;-Schreibweise verwenden</translation> </message> <message> <source>Continuously rate-limit free transactions to &lt;n&gt;*1000 bytes per minute (default:15)</source> <translation>Anzahl der freien Transaktionen auf &lt;n&gt; * 1000 Byte pro Minute begrenzen (Standard: 15)</translation> </message> <message> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation>Regressionstest-Modus aktivieren, der eine spezielle Blockkette nutzt, in der Blöcke sofort gelöst werden können. Dies ist für Regressionstest-Tools und Anwendungsentwicklung gedacht.</translation> </message> <message> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source> <translation>Regressionstest-Modus aktivieren, der eine spezielle Blockkette nutzt, in der Blöcke sofort gelöst werden können.</translation> </message> <message> <source>Error: Listening for incoming connections failed (listen returned error %d)</source> <translation>Fehler: Abhören nach eingehenden Verbindungen fehlgeschlagen (Fehler %d)</translation> </message> <message> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Fehler: Die Transaktion wurde abgelehnt! Dies kann passieren, wenn einige sherlockcoins aus ihrer Wallet bereits ausgegeben wurden. Beispielsweise weil Sie eine Kopie ihrer wallet.dat genutzt, die sherlockcoins dort ausgegeben haben und dies daher in der derzeit aktiven Brieftasche nicht vermerkt ist.</translation> </message> <message> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>Fehler: Diese Transaktion benötigt aufgrund ihres Betrags, ihrer Komplexität oder der Nutzung erst kürzlich erhaltener Zahlungen eine Transaktionsgebühr in Höhe von mindestens %s!</translation> </message> <message> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Befehl ausführen wenn sich eine Transaktion in der Brieftasche verändert (%s im Befehl wird durch die TxID ersetzt)</translation> </message> <message> <source>Fees smaller than this are considered zero fee (for transaction creation) (default:</source> <translation>Niedrigere Gebühren als diese werden als gebührenfrei angesehen (bei der Transaktionserstellung) (Standard:</translation> </message> <message> <source>Flush database activity from memory pool to disk log every &lt;n&gt; megabytes (default: 100)</source> <translation>Datenbankaktivitäten vom Arbeitsspeicher-Pool alle &lt;n&gt; Megabyte auf den Datenträger schreiben (Standard: 100)</translation> </message> <message> <source>How thorough the block verification of -checkblocks is (0-4, default: 3)</source> <translation>Legt fest, wie gründlich die Blockverifikation von -checkblocks ist (0-4, Standard: 3)</translation> </message> <message> <source>In this mode -genproclimit controls how many blocks are generated immediately.</source> <translation>In diesem Modus legt -genproclimit fest, wie viele Blöcke sofort erzeugt werden.</translation> </message> <message> <source>Set the number of script verification threads (%u to %d, 0 = auto, &lt;0 = leave that many cores free, default: %d)</source> <translation>Maximale Anzahl an Skript-Verifizierungs-Threads festlegen (%u bis %d, 0 = automatisch, &lt;0 = so viele Kerne frei lassen, Standard: %d)</translation> </message> <message> <source>Set the processor limit for when generation is on (-1 = unlimited, default: -1)</source> <translation>Legt ein Prozessor-/CPU-Kernlimit fest, wenn CPU-Mining aktiviert ist (-1 = unbegrenzt, Standard: -1)</translation> </message> <message> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Dies ist eine Vorab-Testversion - Verwendung auf eigene Gefahr - nicht für Mining- oder Handelsanwendungen nutzen!</translation> </message> <message> <source>Unable to bind to %s on this computer. sherlockcoin Core is probably already running.</source> <translation>Kann auf diesem Computer nicht an %s binden, da sherlockcoin Core wahrscheinlich bereits gestartet wurde.</translation> </message> <message> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)</source> <translation>Separaten SOCKS5-Proxy verwenden, um Gegenstellen über versteckte Tor-Dienste zu erreichen (Standard: -proxy)</translation> </message> <message> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Warnung: -paytxfee ist auf einen sehr hohen Wert festgelegt! Dies ist die Gebühr die beim Senden einer Transaktion fällig wird.</translation> </message> <message> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong sherlockcoin will not work properly.</source> <translation>Warnung: Bitte korrigieren Sie die Datums- und Uhrzeiteinstellungen ihres Computers, da sherlockcoin ansonsten nicht ordnungsgemäß funktionieren wird!</translation> </message> <message> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation>Warnung: Das Netzwerk scheint nicht vollständig übereinzustimmen! Einige Miner scheinen Probleme zu haben.</translation> </message> <message> <source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Warnung: Wir scheinen nicht vollständig mit unseren Gegenstellen übereinzustimmen! Sie oder die anderen Knoten müssen unter Umständen ihre Client-Software aktualisieren.</translation> </message> <message> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Warnung: Lesen von wallet.dat fehlgeschlagen! Alle Schlüssel wurden korrekt gelesen, Transaktionsdaten bzw. Adressbucheinträge fehlen aber möglicherweise oder sind inkorrekt.</translation> </message> <message> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Warnung: wallet.dat beschädigt, Datenrettung erfolgreich! Original wallet.dat wurde als wallet.{Zeitstempel}.dat in %s gespeichert. Falls ihr Kontostand oder Transaktionen nicht korrekt sind, sollten Sie von einer Datensicherung wiederherstellen.</translation> </message> <message> <source>(default: 1)</source> <translation>(Standard: 1)</translation> </message> <message> <source>(default: wallet.dat)</source> <translation>(Standard: wallet.dat)</translation> </message> <message> <source>&lt;category&gt; can be:</source> <translation>&lt;category&gt; kann sein:</translation> </message> <message> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Versuchen, private Schlüssel aus einer beschädigten wallet.dat wiederherzustellen</translation> </message> <message> <source>sherlockcoin Core Daemon</source> <translation>&quot;sherlockcoin Core&quot;-Hintergrunddienst</translation> </message> <message> <source>Block creation options:</source> <translation>Blockerzeugungsoptionen:</translation> </message> <message> <source>Clear list of wallet transactions (diagnostic tool; implies -rescan)</source> <translation>Liste der Transaktionen der Brieftasche zurücksetzen (Diagnosetool; beinhaltet -rescan)</translation> </message> <message> <source>Connect only to the specified node(s)</source> <translation>Mit nur dem oder den angegebenen Knoten verbinden</translation> </message> <message> <source>Connect through SOCKS proxy</source> <translation>Über einen SOCKS-Proxy verbinden</translation> </message> <message> <source>Connect to JSON-RPC on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation>Mit JSON-RPC auf &lt;port&gt; verbinden (Standard: 8332 oder Testnetz: 18332)</translation> </message> <message> <source>Connection options:</source> <translation>Verbindungsoptionen:</translation> </message> <message> <source>Corrupted block database detected</source> <translation>Beschädigte Blockdatenbank erkannt</translation> </message> <message> <source>Debugging/Testing options:</source> <translation>Debugging-/Testoptionen:</translation> </message> <message> <source>Disable safemode, override a real safe mode event (default: 0)</source> <translation>Sicherheitsmodus deaktivieren, übergeht ein echtes Sicherheitsmodusereignis (Standard: 0)</translation> </message> <message> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Eigene IP-Adresse erkennen (Standard: 1, wenn abgehört wird und nicht -externalip)</translation> </message> <message> <source>Do not load the wallet and disable wallet RPC calls</source> <translation>Die Brieftasche nicht laden und Brieftaschen-RPC-Aufrufe deaktivieren</translation> </message> <message> <source>Do you want to rebuild the block database now?</source> <translation>Möchten Sie die Blockdatenbank jetzt neu aufbauen?</translation> </message> <message> <source>Error initializing block database</source> <translation>Fehler beim Initialisieren der Blockdatenbank</translation> </message> <message> <source>Error initializing wallet database environment %s!</source> <translation>Fehler beim Initialisieren der Brieftaschen-Datenbankumgebung %s!</translation> </message> <message> <source>Error loading block database</source> <translation>Fehler beim Laden der Blockdatenbank</translation> </message> <message> <source>Error opening block database</source> <translation>Fehler beim Öffnen der Blockdatenbank</translation> </message> <message> <source>Error: Disk space is low!</source> <translation>Fehler: Zu wenig freier Speicherplatz auf dem Datenträger!</translation> </message> <message> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Fehler: Brieftasche gesperrt, Transaktion kann nicht erstellt werden!</translation> </message> <message> <source>Error: system error: </source> <translation>Fehler: Systemfehler: </translation> </message> <message> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Fehler, es konnte kein Port abgehört werden. Wenn dies so gewünscht wird -listen=0 verwenden.</translation> </message> <message> <source>Failed to read block info</source> <translation>Lesen der Blockinformationen fehlgeschlagen</translation> </message> <message> <source>Failed to read block</source> <translation>Lesen des Blocks fehlgeschlagen</translation> </message> <message> <source>Failed to sync block index</source> <translation>Synchronisation des Blockindex fehlgeschlagen</translation> </message> <message> <source>Failed to write block index</source> <translation>Schreiben des Blockindex fehlgeschlagen</translation> </message> <message> <source>Failed to write block info</source> <translation>Schreiben der Blockinformationen fehlgeschlagen</translation> </message> <message> <source>Failed to write block</source> <translation>Schreiben des Blocks fehlgeschlagen</translation> </message> <message> <source>Failed to write file info</source> <translation>Schreiben der Dateiinformationen fehlgeschlagen</translation> </message> <message> <source>Failed to write to coin database</source> <translation>Schreiben in die Münzendatenbank fehlgeschlagen</translation> </message> <message> <source>Failed to write transaction index</source> <translation>Schreiben des Transaktionsindex fehlgeschlagen</translation> </message> <message> <source>Failed to write undo data</source> <translation>Schreiben der Rücksetzdaten fehlgeschlagen</translation> </message> <message> <source>Fee per kB to add to transactions you send</source> <translation>Gebühr pro kB, die gesendeten Transaktionen hinzugefügt wird</translation> </message> <message> <source>Fees smaller than this are considered zero fee (for relaying) (default:</source> <translation>Niedrigere Gebühren als diese werden als gebührenfrei angesehen (bei der Vermittlung) (Standard:</translation> </message> <message> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Gegenstellen via DNS-Abfrage finden (Standard: 1, außer bei -connect)</translation> </message> <message> <source>Force safe mode (default: 0)</source> <translation>Sicherheitsmodus erzwingen (Standard: 0)</translation> </message> <message> <source>Generate coins (default: 0)</source> <translation>sherlockcoins erzeugen (Standard: 0)</translation> </message> <message> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Wieviele Blöcke beim Starten geprüft werden sollen (Standard: 288, 0 = alle)</translation> </message> <message> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation>Wenn &lt;category&gt; nicht angegeben wird, jegliche Debugginginformationen ausgeben.</translation> </message> <message> <source>Importing...</source> <translation>Importiere...</translation> </message> <message> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation>Fehlerhafter oder kein Genesis-Block gefunden. Falsches Datenverzeichnis für das Netzwerk?</translation> </message> <message> <source>Invalid -onion address: &apos;%s&apos;</source> <translation>Ungültige &quot;-onion&quot;-Adresse: &apos;%s&apos;</translation> </message> <message> <source>Not enough file descriptors available.</source> <translation>Nicht genügend Datei-Deskriptoren verfügbar.</translation> </message> <message> <source>Prepend debug output with timestamp (default: 1)</source> <translation>Debugausgaben einen Zeitstempel voranstellen (Standard: 1)</translation> </message> <message> <source>RPC client options:</source> <translation>RPC-Client-Optionen:</translation> </message> <message> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Blockkettenindex aus aktuellen Dateien blk000??.dat wiederaufbauen</translation> </message> <message> <source>Select SOCKS version for -proxy (4 or 5, default: 5)</source> <translation>SOCKS-Version des Proxies wählen (4 oder 5, Standard: 5)</translation> </message> <message> <source>Set database cache size in megabytes (%d to %d, default: %d)</source> <translation>Größe des Datenbankcaches in Megabyte festlegen (%d bis %d, Standard: %d)</translation> </message> <message> <source>Set maximum block size in bytes (default: %d)</source> <translation>Maximale Blockgröße in Byte festlegen (Standard: %d)</translation> </message> <message> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Maximale Anzahl an Threads zur Verarbeitung von RPC-Anfragen festlegen (Standard: 4)</translation> </message> <message> <source>Specify wallet file (within data directory)</source> <translation>Brieftaschen-Datei angeben (innerhalb des Datenverzeichnisses)</translation> </message> <message> <source>Spend unconfirmed change when sending transactions (default: 1)</source> <translation>Unbestätigtes Wechselgeld beim Senden von Transaktionen ausgeben (Standard: 1)</translation> </message> <message> <source>This is intended for regression testing tools and app development.</source> <translation>Dies ist für Regressionstest-Tools und Anwendungsentwicklung gedacht.</translation> </message> <message> <source>Usage (deprecated, use sherlockcoin-cli):</source> <translation>Benutzung (veraltet, bitte sherlockcoin-cli verwenden):</translation> </message> <message> <source>Verifying blocks...</source> <translation>Verifiziere Blöcke...</translation> </message> <message> <source>Verifying wallet...</source> <translation>Verifiziere Brieftasche...</translation> </message> <message> <source>Wait for RPC server to start</source> <translation>Warten, bis der RPC-Server gestartet ist</translation> </message> <message> <source>Wallet %s resides outside data directory %s</source> <translation>Brieftasche %s liegt außerhalb des Datenverzeichnisses %s</translation> </message> <message> <source>Wallet options:</source> <translation>Brieftaschen-Optionen:</translation> </message> <message> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation>Warnung: Veraltetes Argument -debugnet gefunden, bitte -debug=net verwenden</translation> </message> <message> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation>Sie müssen die Datenbank mit Hilfe von -reindex neu aufbauen, um -txindex zu verändern</translation> </message> <message> <source>Imports blocks from external blk000??.dat file</source> <translation>Blöcke aus externer Datei blk000??.dat importieren</translation> </message> <message> <source>Cannot obtain a lock on data directory %s. sherlockcoin Core is probably already running.</source> <translation>Datenverzeichnis %s kann nicht gesperrt werden, da sherlockcoin Core wahrscheinlich bereits gestartet wurde.</translation> </message> <message> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation>Befehl ausführen wenn ein relevanter Alarm empfangen wird oder wir einen wirklich langen Fork entdecken (%s im Befehl wird durch die Nachricht ersetzt)</translation> </message> <message> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation>Debugginginformationen ausgeben (Standard: 0, &lt;category&gt; anzugeben ist optional)</translation> </message> <message> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation>Maximale Größe in Byte von Transaktionen hoher Priorität/mit niedrigen Gebühren festlegen (Standard: %d)</translation> </message> <message> <source>Information</source> <translation>Hinweis</translation> </message> <message> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ungültiger Betrag für -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ungültiger Betrag für -mintxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <source>Limit size of signature cache to &lt;n&gt; entries (default: 50000)</source> <translation>Größe des Signaturcaches auf &lt;n&gt; Einträge begrenzen (Standard: 50000)</translation> </message> <message> <source>Log transaction priority and fee per kB when mining blocks (default: 0)</source> <translation>Transaktionspriorität und Gebühr pro kB beim Erzeugen von Blöcken protokollieren (Standard: 0)</translation> </message> <message> <source>Maintain a full transaction index (default: 0)</source> <translation>Einen vollständigen Transaktionsindex führen (Standard: 0)</translation> </message> <message> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maximale Größe des Empfangspuffers pro Verbindung, &lt;n&gt; * 1000 Byte (Standard: 5000)</translation> </message> <message> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maximale Größe des Sendepuffers pro Verbindung, &lt;n&gt; * 1000 Byte (Standard: 1000)</translation> </message> <message> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Blockkette nur als gültig ansehen, wenn sie mit den integrierten Prüfpunkten übereinstimmt (Standard: 1)</translation> </message> <message> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Verbinde nur zu Knoten des Netztyps &lt;net&gt; (IPv4, IPv6 oder Tor)</translation> </message> <message> <source>Print block on startup, if found in block index</source> <translation>Block beim Starten ausgeben, wenn dieser im Blockindex gefunden wurde.</translation> </message> <message> <source>Print block tree on startup (default: 0)</source> <translation>Blockbaum beim Starten ausgeben (Standard: 0)</translation> </message> <message> <source>RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>RPC-SSL-Optionen (siehe Bitcoin-Wiki für SSL-Einrichtung):</translation> </message> <message> <source>RPC server options:</source> <translation>RPC-Serveroptionen:</translation> </message> <message> <source>Randomly drop 1 of every &lt;n&gt; network messages</source> <translation>Zufällig eine von &lt;n&gt; Netzwerknachrichten verwerfen</translation> </message> <message> <source>Randomly fuzz 1 of every &lt;n&gt; network messages</source> <translation>Zufällig eine von &lt;n&gt; Netzwerknachrichten verwürfeln</translation> </message> <message> <source>Run a thread to flush wallet periodically (default: 1)</source> <translation>Einen Thread starten, der periodisch die Brieftasche sicher auf den Datenträger schreibt (Standard: 1)</translation> </message> <message> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>SSL-Optionen (siehe Bitcoin-Wiki für SSL-Einrichtungssanweisungen):</translation> </message> <message> <source>Send command to sherlockcoin Core</source> <translation>Befehl an sherlockcoin Core senden</translation> </message> <message> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Rückverfolgungs- und Debuginformationen an die Konsole senden, anstatt sie in debug.log zu schreiben</translation> </message> <message> <source>Set minimum block size in bytes (default: 0)</source> <translation>Minimale Blockgröße in Byte festlegen (Standard: 0)</translation> </message> <message> <source>Sets the DB_PRIVATE flag in the wallet db environment (default: 1)</source> <translation>DB_PRIVATE-Flag in der Brieftaschen-Datenbankumgebung setzen (Standard: 1)</translation> </message> <message> <source>Show all debugging options (usage: --help -help-debug)</source> <translation>Zeige alle Debuggingoptionen (Benutzung: --help -help-debug)</translation> </message> <message> <source>Show benchmark information (default: 0)</source> <translation>Zeige Benchmarkinformationen (Standard: 0)</translation> </message> <message> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Protokolldatei debug.log beim Starten des Clients kürzen (Standard: 1, wenn kein -debug)</translation> </message> <message> <source>Signing transaction failed</source> <translation>Signierung der Transaktion fehlgeschlagen</translation> </message> <message> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Verbindungzeitüberschreitung in Millisekunden festlegen (Standard: 5000)</translation> </message> <message> <source>Start sherlockcoin Core Daemon</source> <translation>&quot;sherlockcoin Core&quot;-Hintergrunddienst starten</translation> </message> <message> <source>System error: </source> <translation>Systemfehler: </translation> </message> <message> <source>Transaction amount too small</source> <translation>Transaktionsbetrag zu niedrig</translation> </message> <message> <source>Transaction amounts must be positive</source> <translation>Transaktionsbeträge müssen positiv sein</translation> </message> <message> <source>Transaction too large</source> <translation>Transaktion zu groß</translation> </message> <message> <source>Use UPnP to map the listening port (default: 0)</source> <translation>UPnP verwenden, um eine Portweiterleitung einzurichten (Standard: 0)</translation> </message> <message> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>UPnP verwenden, um eine Portweiterleitung einzurichten (Standard: 1, wenn abgehört wird)</translation> </message> <message> <source>Username for JSON-RPC connections</source> <translation>Benutzername für JSON-RPC-Verbindungen</translation> </message> <message> <source>Warning</source> <translation>Warnung</translation> </message> <message> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Warnung: Diese Version is veraltet, Aktualisierung erforderlich!</translation> </message> <message> <source>Zapping all transactions from wallet...</source> <translation>Lösche alle Transaktionen aus Brieftasche...</translation> </message> <message> <source>on startup</source> <translation>beim Starten</translation> </message> <message> <source>version</source> <translation>Version</translation> </message> <message> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat beschädigt, Datenrettung fehlgeschlagen</translation> </message> <message> <source>Password for JSON-RPC connections</source> <translation>Passwort für JSON-RPC-Verbindungen</translation> </message> <message> <source>Allow JSON-RPC connections from specified IP address</source> <translation>JSON-RPC-Verbindungen von der angegebenen IP-Adresse erlauben</translation> </message> <message> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Sende Befehle an Knoten &lt;ip&gt; (Standard: 127.0.0.1)</translation> </message> <message> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Befehl ausführen wenn der beste Block wechselt (%s im Befehl wird durch den Hash des Blocks ersetzt)</translation> </message> <message> <source>Upgrade wallet to latest format</source> <translation>Brieftasche auf das neueste Format aktualisieren</translation> </message> <message> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Größe des Schlüsselpools festlegen auf &lt;n&gt; (Standard: 100)</translation> </message> <message> <source>Rescan the block chain for missing wallet transactions</source> <translation>Blockkette erneut nach fehlenden Transaktionen der Brieftasche durchsuchen</translation> </message> <message> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>OpenSSL (https) für JSON-RPC-Verbindungen verwenden</translation> </message> <message> <source>Server certificate file (default: server.cert)</source> <translation>Serverzertifikat (Standard: server.cert)</translation> </message> <message> <source>Server private key (default: server.pem)</source> <translation>Privater Serverschlüssel (Standard: server.pem)</translation> </message> <message> <source>This help message</source> <translation>Dieser Hilfetext</translation> </message> <message> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Kann auf diesem Computer nicht an %s binden (von bind zurückgegebener Fehler %d, %s)</translation> </message> <message> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Erlaube DNS-Abfragen für -addnode, -seednode und -connect</translation> </message> <message> <source>Loading addresses...</source> <translation>Lade Adressen...</translation> </message> <message> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Fehler beim Laden von wallet.dat: Brieftasche beschädigt</translation> </message> <message> <source>Error loading wallet.dat: Wallet requires newer version of sherlockcoin</source> <translation>Fehler beim Laden von wallet.dat: Brieftasche benötigt neuere Version von sherlockcoin</translation> </message> <message> <source>Wallet needed to be rewritten: restart sherlockcoin to complete</source> <translation>Brieftasche musste neu geschrieben werden: starten Sie sherlockcoin zur Fertigstellung neu</translation> </message> <message> <source>Error loading wallet.dat</source> <translation>Fehler beim Laden von wallet.dat</translation> </message> <message> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Ungültige Adresse in -proxy: &apos;%s&apos;</translation> </message> <message> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Unbekannter Netztyp in -onlynet angegeben: &apos;%s&apos;</translation> </message> <message> <source>Unknown -socks proxy version requested: %i</source> <translation>Unbekannte Proxyversion in -socks angefordert: %i</translation> </message> <message> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Kann Adresse in -bind nicht auflösen: &apos;%s&apos;</translation> </message> <message> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Kann Adresse in -externalip nicht auflösen: &apos;%s&apos;</translation> </message> <message> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ungültiger Betrag für -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <source>Invalid amount</source> <translation>Ungültiger Betrag</translation> </message> <message> <source>Insufficient funds</source> <translation>Unzureichender Kontostand</translation> </message> <message> <source>Loading block index...</source> <translation>Lade Blockindex...</translation> </message> <message> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Mit dem angegebenen Knoten verbinden und versuchen die Verbindung aufrecht zu erhalten</translation> </message> <message> <source>Loading wallet...</source> <translation>Lade Brieftasche...</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation>Brieftasche kann nicht auf eine ältere Version herabgestuft werden</translation> </message> <message> <source>Cannot write default address</source> <translation>Standardadresse kann nicht geschrieben werden</translation> </message> <message> <source>Rescanning...</source> <translation>Durchsuche erneut...</translation> </message> <message> <source>Done loading</source> <translation>Laden abgeschlossen</translation> </message> <message> <source>To use the %s option</source> <translation>Zur Nutzung der %s-Option</translation> </message> <message> <source>Error</source> <translation>Fehler</translation> </message> <message> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Sie müssen den Wert rpcpassword=&lt;passwort&gt; in der Konfigurationsdatei angeben: %s Falls die Konfigurationsdatei nicht existiert, erzeugen Sie diese bitte mit Leserechten nur für den Dateibesitzer.</translation> </message> </context> </TS><|fim▁end|>
</message> <message> <source>Date</source> <translation>Datum</translation>
<|file_name|>Union.cpp<|end_file_name|><|fim▁begin|><|fim▁hole|> for (auto&& figure : figures) if (figure->contains(point)) return true; return false; } Figure* Union::createCopy() const { return new Union(*this); } std::ostream &operator<<(std::ostream& os, const Union* un) { return un->serializeFigures(os); } std::istream &operator>>(std::istream& is, Union*& un) { std::vector<Figure*> figures = FigureGroup::unserializeFigures(is); un = new Union(figures); return is; }<|fim▁end|>
#include "Union.h" bool Union::contains(const Vector2D& point) const {
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>from dateutil.relativedelta import relativedelta from script.models import Script, ScriptProgress from rapidsms.models import Connection import datetime from rapidsms.models import Contact from rapidsms.contrib.locations.models import Location from poll.models import Poll from script.models import ScriptStep from django.db.models import Count from django.conf import settings from education.scheduling import schedule_at, at def is_holiday(date1, holidays = getattr(settings, 'SCHOOL_HOLIDAYS', [])): for date_start, date_end in holidays: if isinstance(date_end, str): if date1.date() == date_start.date(): return True elif date1.date() >= date_start.date() and date1.date() <= date_end.date(): return True return False def is_empty(arg): """ Generalizes 'empty' checks on Strings, sequences, and dicts. Returns 'True' for None, empty strings, strings with just white-space, and sequences with len == 0 """ if arg is None: return True if isinstance(arg, basestring): arg = arg.strip() try: if not len(arg): return True except TypeError: # wasn't a sequence pass return False def previous_calendar_week(t=None): """ To education monitoring, a week runs between Thursdays, Thursday marks the beginning of a new week of data submission Data for a new week is accepted until Wednesday evening of the following week """ d = t or datetime.datetime.now() if not d.weekday() == 3: # last Thursday == next Thursday minus 7 days. last_thursday = d + (datetime.timedelta((3-d.weekday())%7) - (datetime.timedelta(days=7))) else: last_thursday = d end_date = last_thursday + datetime.timedelta(days=6) return (last_thursday.date(), end_date) def _this_thursday(sp=None, get_time=datetime.datetime.now, time_set=None, holidays=getattr(settings, 'SCHOOL_HOLIDAYS', [])): """ This Thursday of the week which is not a school holiday. """ schedule = time_set or get_time() d = sp.time if sp else schedule d = d + datetime.timedelta((3 - d.weekday()) % 7) while(is_holiday(d, holidays)): d = d + datetime.timedelta(1) # try next day return at(d.date(), 10) def get_polls(**kwargs): script_polls = ScriptStep.objects.values_list('poll', flat=True).exclude(poll=None) return Poll.objects.exclude(pk__in=script_polls).annotate(Count('responses')) def compute_average_percentage(list_of_percentages): """ Average percentage -> this is also a handly tool to compute averages generally while sanitizing """ sanitize = [] try: for i in list_of_percentages: if isinstance(float(i), float): sanitize.append(float(i)) else: pass except ValueError: print "non-numeric characters used" pass if len(sanitize) <= 0: return 0 return sum(sanitize) / float(len(sanitize)) def list_poll_responses(poll, **kwargs): """ pass a poll queryset and you get yourself a dict with locations vs responses (quite handy for the charts) dependecies: Contact and Location must be in your module; this lists all Poll responses by district """ #forceful import from poll.models import Poll to_ret = {} """ narrowed down to 3 districts (and up to 14 districts) """ DISTRICT = ['Kaabong', 'Kabarole', 'Kyegegwa', 'Kotido'] if not kwargs: # if no other arguments are provided for location in Location.objects.filter(name__in=DISTRICT): to_ret[location.__unicode__()] = compute_average_percentage([msg.message.text for msg in poll.responses.filter(contact__in=Contact.objects.filter(reporting_location=location))]) return to_ret else: # filter by number of weeks #TODO more elegant solution to coincide with actual school term weeks date_filter = kwargs['weeks'] #give the date in weeks date_now = datetime.datetime.now() date_diff = date_now - datetime.timedelta(weeks=date_filter) all_emis_reports = EmisReporter.objects.filter(reporting_location__in=[loc for loc in Locations.objects.filter(name__in=DISTRICT)]) for location in Location.objects.filter(name__in=DISTRICT): to_ret[location.__unicode__()] = compute_average_percentage([msg.message.text for msg in poll.responses.filter(date__gte=date_diff, contact__in=Contact.objects.filter(reporting_location=location))]) return to_ret themes = { 1.1 : "Name and location of our Sub-county/Division", 1.2 : 'Physical features of our Sub-County/Division', 1.3 : 'People in our Sub-county/Division', 2.1 : 'Occupations of people in our Sub-county/Division and their importance', 2.2 : 'Social Services and their importance', 2.3 : 'Challenges in social services and their possible solutions', 3.1 : 'Soil', 3.2 : 'Natural causes of changes in the environment', 3.3 : 'Changes in the environment through human activities', 4.1 : 'Air and the Sun', 4.2 : 'Water', 4.3 : 'Managing Water', 5.1 : 'Living things', 5.2 : 'Birds and Insects', 5.3 : 'Care for insects, birds and animals', 6.1 : 'Plants and their habitat', 6.2 : 'Parts of a flowering plant and their uses', 6.3 : 'Crop-growing practices', 7.1 : 'Saving resources', 7.2 : 'Spending resources', 7.3 : 'Projects', 8.1 : 'Living in peace with others', 8.2 : 'Child rights, needs and their importance', 8.3 : 'Child responsibility', 9.1 : 'Customs in our sub-county/division', 9.2 : 'Gender', 9.3 : 'Ways of promoting and preserving culture', 10.1: 'Disease vectors', 10.2: 'Diseases spread by vectors',<|fim▁hole|> 11.3: 'Making things from artificial materials', 12.1: 'Sources of energy', 12.2: 'Ways of saving energy', 12.3: 'Dangers of energy and ways of avoiding them' } ## {{{ http://code.activestate.com/recipes/409413/ (r2) """ Descriptive statistical analysis tool. """ class StatisticsException(Exception): """Statistics Exception class.""" pass class Statistics(object): """Class for descriptive statistical analysis. Behavior: Computes numerical statistics for a given data set. Available public methods: None Available instance attributes: N: total number of elements in the data set sum: sum of all values (n) in the data set min: smallest value of the data set max: largest value of the data set mode: value(s) that appear(s) most often in the data set mean: arithmetic average of the data set range: difference between the largest and smallest value in the data set median: value which is in the exact middle of the data set variance: measure of the spread of the data set about the mean stddev: standard deviation - measure of the dispersion of the data set based on variance identification: Instance ID Raised Exceptions: StatisticsException Bases Classes: object (builtin) Example Usage: x = [ -1, 0, 1 ] try: stats = Statistics(x) except StatisticsException, mesg: <handle exception> print "N: %s" % stats.N print "SUM: %s" % stats.sum print "MIN: %s" % stats.min print "MAX: %s" % stats.max print "MODE: %s" % stats.mode print "MEAN: %0.2f" % stats.mean print "RANGE: %s" % stats.range print "MEDIAN: %0.2f" % stats.median print "VARIANCE: %0.5f" % stats.variance print "STDDEV: %0.5f" % stats.stddev print "DATA LIST: %s" % stats.sample """ def __init__(self, sample=[], population=False): """Statistics class initializer method.""" # Raise an exception if the data set is empty. if (not sample): raise StatisticsException, "Empty data set!: %s" % sample # The data set (a list). self.sample = sample # Sample/Population variance determination flag. self.population = population self.N = len(self.sample) self.sum = float(sum(self.sample)) self.min = min(self.sample) self.max = max(self.sample) self.range = self.max - self.min self.mean = self.sum/self.N # Inplace sort (list is now in ascending order). self.sample.sort() self.__getMode() # Instance identification attribute. self.identification = id(self) def __getMode(self): """Determine the most repeated value(s) in the data set.""" # Initialize a dictionary to store frequency data. frequency = {} # Build dictionary: key - data set values; item - data frequency. for x in self.sample: if (x in frequency): frequency[x] += 1 else: frequency[x] = 1 # Create a new list containing the values of the frequency dict. Convert # the list, which may have duplicate elements, into a set. This will # remove duplicate elements. Convert the set back into a sorted list # (in descending order). The first element of the new list now contains # the frequency of the most repeated values(s) in the data set. # mode = sorted(list(set(frequency.values())), reverse=True)[0] # Or use the builtin - max(), which returns the largest item of a # non-empty sequence. mode = max(frequency.values()) # If the value of mode is 1, there is no mode for the given data set. if (mode == 1): self.mode = [] return # Step through the frequency dictionary, looking for values equaling # the current value of mode. If found, append the value and its # associated key to the self.mode list. self.mode = [(x, mode) for x in frequency if (mode == frequency[x])] def __getVariance(self): """Determine the measure of the spread of the data set about the mean. Sample variance is determined by default; population variance can be determined by setting population attribute to True. """ x = 0 # Summation variable. # Subtract the mean from each data item and square the difference. # Sum all the squared deviations. for item in self.sample: x += (item - self.mean)**2.0 try: if (not self.population): # Divide sum of squares by N-1 (sample variance). self.variance = x/(self.N-1) else: # Divide sum of squares by N (population variance). self.variance = x/self.N except: self.variance = 0 def __getStandardDeviation(self): """Determine the measure of the dispersion of the data set based on the variance. """ from math import sqrt # Mathematical functions. # Take the square root of the variance. self.stddev = sqrt(self.variance) def extract_key_count(list, key=None): """ A utility function written to count the number of times a `key` would appear in, for example, a categorized poll. Examples: >>> extract_key_count('yes', """ if list and key: # go through a list of dictionaries for dict in list: if dict.get('category__name') == key: return dict.get('value') else: return 0 def get_week_count(reference_date, d): week_count = 0 while(reference_date.date() <= d.date()): d = d - datetime.timedelta(days=7) week_count = week_count + 1 return week_count def get_months(start_date,end_date): to_ret = [] first_day = start_date while start_date < end_date: last_day = start_date + relativedelta(day=1, months=+1, days=-1,hour=23,minute=59) start_date += relativedelta(months=1) to_ret.append([ datetime.datetime(first_day.year, first_day.month, first_day.day,first_day.hour,first_day.minute), datetime.datetime(last_day.year, last_day.month, last_day.day,last_day.hour,last_day.minute)]) first_day = start_date + relativedelta(day=1,hour=00,minute=00) to_ret.append([ datetime.datetime(first_day.year, first_day.month, first_day.day,first_day.hour,first_day.minute), datetime.datetime(end_date.year, end_date.month, end_date.day,end_date.hour,end_date.minute)]) return to_ret<|fim▁end|>
10.3: 'HIV/AIDS', 11.1: 'Concept of technology', 11.2: 'Processing and making things from natural materials',
<|file_name|>md5.rs<|end_file_name|><|fim▁begin|>use digest::Digest; use utils::buffer::{ FixedBuffer64, FixedBuffer, StandardPadding }; use byteorder::{ WriteBytesExt, ReadBytesExt, LittleEndian<|fim▁hole|>}; #[derive(Debug)] struct MD5State { s0: u32, s1: u32, s2: u32, s3: u32 } impl MD5State { fn new() -> Self { MD5State { s0: 0x67452301, s1: 0xefcdab89, s2: 0x98badcfe, s3: 0x10325476 } } fn process_block(&mut self, mut input: &[u8]) { fn f(u: u32, v: u32, w: u32) -> u32 { (u & v) | (!u & w) } fn g(u: u32, v: u32, w: u32) -> u32 { (u & w) | (v & !w) } fn h(u: u32, v: u32, w: u32) -> u32 { u ^ v ^ w } fn i(u: u32, v: u32, w: u32) -> u32 { v ^ (u | !w) } fn op_f(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { w.wrapping_add(f(x, y, z)).wrapping_add(m).rotate_left(s).wrapping_add(x) } fn op_g(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { w.wrapping_add(g(x, y, z)).wrapping_add(m).rotate_left(s).wrapping_add(x) } fn op_h(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { w.wrapping_add(h(x, y, z)).wrapping_add(m).rotate_left(s).wrapping_add(x) } fn op_i(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { w.wrapping_add(i(x, y, z)).wrapping_add(m).rotate_left(s).wrapping_add(x) } let mut a = self.s0; let mut b = self.s1; let mut c = self.s2; let mut d = self.s3; let mut i = 0; let mut data = [0u32; 16]; while let Ok(val) = input.read_u32::<LittleEndian>() { data[i] = val; i += 1; } // round 1 for i in (0..4) { let i = i * 4; a = op_f(a, b, c, d, data[i].wrapping_add(C1[i]), 7); d = op_f(d, a, b, c, data[i + 1].wrapping_add(C1[i + 1]), 12); c = op_f(c, d, a, b, data[i + 2].wrapping_add(C1[i + 2]), 17); b = op_f(b, c, d, a, data[i + 3].wrapping_add(C1[i + 3]), 22); } // round 2 let mut t = 1; for i in (0..4) { let i = i * 4; a = op_g(a, b, c, d, data[t & 0x0f].wrapping_add(C2[i]), 5); d = op_g(d, a, b, c, data[(t + 5) & 0x0f].wrapping_add(C2[i + 1]), 9); c = op_g(c, d, a, b, data[(t + 10) & 0x0f].wrapping_add(C2[i + 2]), 14); b = op_g(b, c, d, a, data[(t + 15) & 0x0f].wrapping_add(C2[i + 3]), 20); t += 20; } // round 3 t = 5; for i in (0..4) { let i = i * 4; a = op_h(a, b, c, d, data[t & 0x0f].wrapping_add(C3[i]), 4); d = op_h(d, a, b, c, data[(t + 3) & 0x0f].wrapping_add(C3[i + 1]), 11); c = op_h(c, d, a, b, data[(t + 6) & 0x0f].wrapping_add(C3[i + 2]), 16); b = op_h(b, c, d, a, data[(t + 9) & 0x0f].wrapping_add(C3[i + 3]), 23); t += 12; } // round 4 t = 0; for i in (0..4) { let i = i * 4; a = op_i(a, b, c, d, data[t & 0x0f].wrapping_add(C4[i]), 6); d = op_i(d, a, b, c, data[(t + 7) & 0x0f].wrapping_add(C4[i + 1]), 10); c = op_i(c, d, a, b, data[(t + 14) & 0x0f].wrapping_add(C4[i + 2]), 15); b = op_i(b, c, d, a, data[(t + 21) & 0x0f].wrapping_add(C4[i + 3]), 21); t += 28; } self.s0 = self.s0.wrapping_add(a); self.s1 = self.s1.wrapping_add(b); self.s2 = self.s2.wrapping_add(c); self.s3 = self.s3.wrapping_add(d); } } // Round 1 constants static C1: [u32; 16] = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 ]; // Round 2 constants static C2: [u32; 16] = [ 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a ]; // Round 3 constants static C3: [u32; 16] = [ 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665 ]; // Round 4 constants static C4: [u32; 16] = [ 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 ]; pub struct MD5 { state: MD5State, length: u64, buffer: FixedBuffer64, } impl Default for MD5 { fn default() -> Self { MD5 { state: MD5State::new(), length: 0, buffer: FixedBuffer64::new(), } } } impl Digest for MD5 { fn update<T>(&mut self, input: T) where T: AsRef<[u8]> { let input = input.as_ref(); self.length += input.len() as u64; let state = &mut self.state; self.buffer.input(&input[..], |d| state.process_block(d)); } fn output_bits() -> usize { 128 } fn block_size() -> usize { 64 } fn result<T: AsMut<[u8]>>(mut self, mut out: T) { let state = &mut self.state; self.buffer.standard_padding(8, |d| state.process_block(d)); self.buffer.next(4).write_u32::<LittleEndian>((self.length << 3) as u32).unwrap(); self.buffer.next(4).write_u32::<LittleEndian>((self.length >> 29) as u32).unwrap(); state.process_block(self.buffer.full_buffer()); let mut out = out.as_mut(); assert!(out.len() >= Self::output_bytes()); out.write_u32::<LittleEndian>(state.s0).unwrap(); out.write_u32::<LittleEndian>(state.s1).unwrap(); out.write_u32::<LittleEndian>(state.s2).unwrap(); out.write_u32::<LittleEndian>(state.s3).unwrap(); } } #[cfg(test)] mod tests { use digest::Digest; use digest::test::Test; use super::MD5; const TESTS: [Test<'static>; 7] = [ Test { input: "", output: "d41d8cd98f00b204e9800998ecf8427e" }, Test { input: "a", output: "0cc175b9c0f1b6a831c399e269772661" }, Test { input: "abc", output: "900150983cd24fb0d6963f7d28e17f72" }, Test { input: "message digest", output: "f96b697d7cb7938d525a2f31aaf161d0" }, Test { input: "abcdefghijklmnopqrstuvwxyz", output: "c3fcd3d76192e4007dfb496cca67e13b" }, Test { input: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", output: "d174ab98d277d9f5a5611c2c9f419d9f" }, Test { input: "12345678901234567890123456789012345678901234567890123456789012345678901234567890", output: "57edf4a22be3c955ac49da2e2107b67a" }, ]; #[test] fn test_md5() { // Examples from wikipedia // Test that it works when accepting the message all at once for test in &TESTS { test.test(MD5::new()); } } }<|fim▁end|>
<|file_name|>launch_suite.js<|end_file_name|><|fim▁begin|>;(function($){ var page_container, current_select = null; $(document).ready(function(){ page_container = $('#launch_suite_pages'); $('#funnel_select').change(function(){ if(parseInt($('#funnel_id').val()) > 0){ if($(this).val() != $('#funnel_id').val()){ document.location.href = OptimizePress.launch_suite_url.replace(/&amp;/g, '&')+$(this).val(); } } }).trigger('change'); <|fim▁hole|> items:'> div.section-stage', handle:'div.show-hide-panel', axis: 'y', update: refresh_titles }); page_container.find('.panel-controlx').iButton().end().delegate('select.value_page','change',function(e){ var url = OptimizePress.launch_page_urls[$(this).val()] || ''; //console.log($(this).val()); var title = $(this).find('option:selected').text(); var $value_page = $(this).parent().siblings('.tab-navigation_text').find('.active-link-text'); if ($.trim($value_page.val())=='') $value_page.val(title); if ($.trim($value_page.val())=='(Select Page...)') $value_page.val(''); $(this).parent().find('input.value_page_url').val(url).end().find('input.value_page_access_url').val(add_key(url)); }).delegate('div.tab-delete_stage button','click',function(){ $(this).closest('.section-stage').remove(); refresh_titles(); }); // open cart on, removes hide cart and sets it to false $('input[name="op[funnel_pages][sales][page_setup][open_sales_cart]"]').change(function(e){ if($(this).is(':checked')){ $('input[name="op[funnel_pages][sales][page_setup][hide_cart]"]').removeAttr('checked').trigger('change'); $('#hide_cart').hide(); } else { $('#hide_cart').show(); } }).trigger('change'); $('#launch_suite_sales select.value_page').change(function(){ var url = OptimizePress.launch_page_urls[$(this).val()] || ''; $(this).parent().find('input.value_page_url').val(url).end().find('input.value_page_access_url').val(add_key(url)); }).trigger('change'); $('#op_launch_settings_gateway_key_key').change(function(){ page_container.find('select.value_page').trigger('change'); }); $('#op_gateway_key_enabled').change(function(){ page_container.find('select.value_page').trigger('change'); var cl1 = '.gateway_off', cl2 = '.gateway_on'; if($(this).is(':checked')){ cl1 = '.gateway_on'; cl2 = '.gateway_off'; } page_container.add('#launch_suite_sales').find(cl1).css('display','block').end().find(cl2).css('display','none'); }).trigger('change'); var selected_class = 'op-bsw-grey-panel-tabs-selected'; $('#launch_suite_add_section').click(function(e){ e.preventDefault(); var tmpl = $('#launch_suite_new_item').html(), elcount = page_container.find('div.section-stage').length+1; tmpl = tmpl.replace(/9999/g,elcount).replace(/# TITLE #/ig,OptimizePress.launch_section_title.replace(/%1\$s/,elcount)); page_container.append(tmpl).find('div.section-stage:last').find('ul.op-bsw-grey-panel-tabs').op_tabs().end().find('.panel-controlx').iButton().end().find('select.value_page').trigger('change'); $('#op_gateway_key_enabled').trigger('change'); add_page_link(); bind_content_sliders(); }); add_page_link(); init_funnel_switch(); bind_content_sliders(); }); function add_page_link(){ $('#launch_suite_pages .add-new-page,#launch_suite_sales .add-new-page').click(function(e){ e.preventDefault(); current_select = $(this).prev(); $('#toplevel_page_optimizepress a[href$="page=optimizepress-page-builder"]').trigger('click'); }); }; function init_funnel_switch(){ $('#funnel_delete').click(function(e) { var funnel_id = $('#funnel_select').val(); if (!confirm('Are you sure you want to delete this funnel?')) { return false; } $.post( OptimizePress.ajaxurl, { action: OptimizePress.SN + '-launch-suite-delete', _wpnonce: $('#_wpnonce').val(), funnel_id: funnel_id }, function(response) { document.location.replace(document.location.href.replace('&funnel_id=' + funnel_id, '')); } ); return false; }); $('#funnel_switch_create_new').click(function(e){ e.preventDefault(); $('#launch_funnel_select:visible').fadeOut('fast',function(){ $('#launch_funnel_new').fadeIn('fast'); }); }); $('#funnel_switch_select').click(function(e){ e.preventDefault(); $('#launch_funnel_new:visible').fadeOut('fast',function(){ $('#launch_funnel_select').fadeIn('fast'); }); }); $('#add_new_funnel').click(function(e){ e.preventDefault(); var waiting = $(this).next().find('img').fadeIn('fast'), name = $('#new_funnel').val(), data = { action: OptimizePress.SN+'-launch-suite-create', _wpnonce: $('#_wpnonce').val(), funnel_name: name }; $.post(OptimizePress.ajaxurl,data,function(resp){ waiting.fadeOut('fast'); if(typeof resp.error != 'undefined'){ alert(resp.error); } else { $('#funnel_select').html(resp.html).trigger('change'); document.location.reload(); } },'json'); }); }; function refresh_titles(){ var counter = 1; page_container.find('> div.section-stage > div.op-bsw-grey-panel-header > h3 > a').each(function(){ $(this).text(OptimizePress.launch_section_title.replace(/%1\$s/,counter)); counter++; }); }; function add_key(url){ if(url == ''){ return ''; } if($('#op_gateway_key_enabled').is(':checked')){ return add_param(url,'gw',$('#op_launch_settings_gateway_key_key').val()); } return url; }; function add_param(url,name,value){ return url + (url.indexOf('?') != -1 ? '&' : '?') + name+'='+encodeURIComponent(value); }; window.op_launch_suite_update_selects = function(page_id){ var data = { action: OptimizePress.SN+'-launch-suite-refresh_dropdown', _wpnonce: $('#_wpnonce').val(), funnel_id: $('#funnel_id').val() }; $.post(OptimizePress.ajaxurl,data,function(resp){ if(typeof resp.error != 'undefined'){ alert(resp.error); } else { $('.landing_page,.value_page,#launch_suite_sales select,#launch_suite_new_item select').each(function(){ var curv = $(this).val(); //console.log(resp.html); $(this).html(resp.html).val(curv); }); if(current_select !== null){ current_select.val(page_id); } } },'json'); }; function bind_content_sliders(){ var $btns = $('.op-content-slider-button'); //Get all the content slider buttons //Loop through each one $btns.each(function(index, value){ var $target = $(this).parent().prev('.op-content-slider'); //Get the target of the current button (the content slider) var $cur_btn = $(this); //Used later on in the script for callbacks //Initialize the show action on click of the show gallery button $(this).unbind('click').click(function(e){ var scrollY = window.pageYOffset; //Get the current position of the viewport $target.show().animate({top:scrollY},400); //Scroll the box to the viewport e.preventDefault(); }); //Initialize the close button $target.find('.hide-the-panda').unbind('click').click(function(e){ var scrollY = window.pageYOffset; //Get the current position of the viewport //Scroll the box to the viewport $target.animate({top:-(scrollY)},400, function(){ $(this).hide(); //Hide the box after it is out of sight }); e.preventDefault(); }); //Init the click handlers for the images inside the content box $target.delegate('ul.op-image-slider-content li a','click',function(e){ var $input = $cur_btn.next('input.op-gallery-value'); //Grab ahold of the hidden input for the gallery var $preview = $input.next('.file-preview').find('.content'); //Get ahold of the preview area var src = $(this).find('img').attr('src'); //Get ahold of the image src //Create the html for the preview area var html = '<a class="preview-image" target="_blank" href="' + src + '"><img alt="uploaded-image" src="' + src + '"></a><a class="remove-file button" href="#remove">Remove Image</a>'; //Put the image source into the hidden input for form submission $input.val(src); //Navigate through the DOM to the uploader preview image and value and set accordingly $input.parent().next('.op-file-uploader').find('.file-preview .content').empty().html(html).find('.remove-file').click(function(){ $(this).parent().empty().parent('.file-preview').prev('.op-uploader-value').val(''); }).parent().parent('.file-preview').prev('.op-uploader-value').val(src); //Animate the box off of the screen and hide it $target.animate({top:-700},400, function(){ $(this).hide(); }); e.preventDefault(); }); }); } }(opjq));<|fim▁end|>
page_container.sortable({
<|file_name|>borrowck-univariant-enum.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(managed_boxes)] use std::cell::Cell; enum newtype { newtype(int) } pub fn main() { <|fim▁hole|> // Test that borrowck treats enums with a single variant // specially. let x = @Cell::new(5); let y = @Cell::new(newtype(3)); let z = match y.get() { newtype(b) => { x.set(x.get() + 1); x.get() * b } }; assert_eq!(z, 18); }<|fim▁end|>
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>""" Represents protected content """ from django.conf.urls import url<|fim▁hole|>def testview(request): return HttpResponse() urlpatterns = [url(r"^$", testview, name="test_url_content")]<|fim▁end|>
from django.http import HttpResponse
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[macro_use] extern crate libproto; #[macro_use] extern crate cita_logger as logger; #[macro_use] extern crate serde_derive; #[macro_use] extern crate util;<|fim▁hole|>extern crate cita_database as cita_db; extern crate common_types as types; pub mod filters; pub mod libchain; pub use crate::types::*;<|fim▁end|>
#[cfg(test)] extern crate cita_crypto;
<|file_name|>swap.rs<|end_file_name|><|fim▁begin|>#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::atomic::AtomicUsize; use core::atomic::Ordering::{Relaxed, Release, Acquire, AcqRel, SeqCst}; use std::sync::Arc; use std::thread; // pub struct AtomicUsize { // v: UnsafeCell<usize>, // } // impl Default for AtomicUsize { // fn default() -> Self { // Self::new(Default::default()) // } // } // unsafe impl Sync for AtomicUsize {} // #[derive(Copy, Clone)] // pub enum Ordering { // /// No ordering constraints, only atomic operations. // #[stable(feature = "rust1", since = "1.0.0")] // Relaxed, // /// When coupled with a store, all previous writes become visible // /// to another thread that performs a load with `Acquire` ordering // /// on the same value. // #[stable(feature = "rust1", since = "1.0.0")] // Release, // /// When coupled with a load, all subsequent loads will see data // /// written before a store with `Release` ordering on the same value // /// in another thread. // #[stable(feature = "rust1", since = "1.0.0")] // Acquire, // /// When coupled with a load, uses `Acquire` ordering, and with a store // /// `Release` ordering. // #[stable(feature = "rust1", since = "1.0.0")] // AcqRel, // /// Like `AcqRel` with the additional guarantee that all threads see all // /// sequentially consistent operations in the same order. // #[stable(feature = "rust1", since = "1.0.0")] // SeqCst, // } // impl AtomicUsize { // /// Creates a new `AtomicUsize`. // /// // /// # Examples // /// // /// ``` // /// use std::sync::atomic::AtomicUsize; // /// // /// let atomic_forty_two = AtomicUsize::new(42); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub const fn new(v: usize) -> AtomicUsize { // AtomicUsize { v: UnsafeCell::new(v) } // } // // /// Loads a value from the usize. // /// // /// `load` takes an `Ordering` argument which describes the memory ordering of this operation. // /// // /// # Panics // /// // /// Panics if `order` is `Release` or `AcqRel`. // /// // /// # Examples // /// // /// ``` // /// use std::sync::atomic::{AtomicUsize, Ordering}; // /// // /// let some_usize = AtomicUsize::new(5); // /// // /// assert_eq!(some_usize.load(Ordering::Relaxed), 5); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn load(&self, order: Ordering) -> usize { // unsafe { atomic_load(self.v.get(), order) } // } // // /// Stores a value into the usize. // /// // /// `store` takes an `Ordering` argument which describes the memory ordering of this operation. // /// // /// # Examples // /// // /// ``` // /// use std::sync::atomic::{AtomicUsize, Ordering}; // /// // /// let some_usize = AtomicUsize::new(5); // /// // /// some_usize.store(10, Ordering::Relaxed); // /// assert_eq!(some_usize.load(Ordering::Relaxed), 10); // /// ``` // /// // /// # Panics // /// // /// Panics if `order` is `Acquire` or `AcqRel`. // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn store(&self, val: usize, order: Ordering) { // unsafe { atomic_store(self.v.get(), val, order); } // } // // /// Stores a value into the usize, returning the old value. // /// // /// `swap` takes an `Ordering` argument which describes the memory ordering of this operation. // /// // /// # Examples // /// // /// ``` // /// use std::sync::atomic::{AtomicUsize, Ordering}; // /// // /// let some_usize= AtomicUsize::new(5); // /// // /// assert_eq!(some_usize.swap(10, Ordering::Relaxed), 5); // /// assert_eq!(some_usize.load(Ordering::Relaxed), 10); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn swap(&self, val: usize, order: Ordering) -> usize { // unsafe { atomic_swap(self.v.get(), val, order) } // } // // /// Stores a value into the `usize` if the current value is the same as the `current` value. // /// // /// The return value is always the previous value. If it is equal to `current`, then the value // /// was updated. // /// // /// `compare_and_swap` also takes an `Ordering` argument which describes the memory ordering of // /// this operation. // /// // /// # Examples // /// // /// ``` // /// use std::sync::atomic::{AtomicUsize, Ordering}; // /// // /// let some_usize = AtomicUsize::new(5); // /// // /// assert_eq!(some_usize.compare_and_swap(5, 10, Ordering::Relaxed), 5); // /// assert_eq!(some_usize.load(Ordering::Relaxed), 10); // /// // /// assert_eq!(some_usize.compare_and_swap(6, 12, Ordering::Relaxed), 10); // /// assert_eq!(some_usize.load(Ordering::Relaxed), 10); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn compare_and_swap(&self, current: usize, new: usize, order: Ordering) -> usize { // unsafe { atomic_compare_and_swap(self.v.get(), current, new, order) } // } // // /// Add to the current usize, returning the previous value. // /// // /// # Examples // /// // /// ``` // /// use std::sync::atomic::{AtomicUsize, Ordering}; // /// // /// let foo = AtomicUsize::new(0); // /// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0); // /// assert_eq!(foo.load(Ordering::SeqCst), 10); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn fetch_add(&self, val: usize, order: Ordering) -> usize { // unsafe { atomic_add(self.v.get(), val, order) } // } // // /// Subtract from the current usize, returning the previous value. // /// // /// # Examples // /// // /// ``` // /// use std::sync::atomic::{AtomicUsize, Ordering}; // /// // /// let foo = AtomicUsize::new(10); // /// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 10); // /// assert_eq!(foo.load(Ordering::SeqCst), 0); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn fetch_sub(&self, val: usize, order: Ordering) -> usize { // unsafe { atomic_sub(self.v.get(), val, order) } // } // // /// Bitwise and with the current usize, returning the previous value. // /// // /// # Examples // /// // /// ``` // /// use std::sync::atomic::{AtomicUsize, Ordering}; // /// // /// let foo = AtomicUsize::new(0b101101); // /// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101); // /// assert_eq!(foo.load(Ordering::SeqCst), 0b100001); // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn fetch_and(&self, val: usize, order: Ordering) -> usize { // unsafe { atomic_and(self.v.get(), val, order) } // } // // /// Bitwise or with the current usize, returning the previous value.<|fim▁hole|> // /// // /// ``` // /// use std::sync::atomic::{AtomicUsize, Ordering}; // /// // /// let foo = AtomicUsize::new(0b101101); // /// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101); // /// assert_eq!(foo.load(Ordering::SeqCst), 0b111111); // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn fetch_or(&self, val: usize, order: Ordering) -> usize { // unsafe { atomic_or(self.v.get(), val, order) } // } // // /// Bitwise xor with the current usize, returning the previous value. // /// // /// # Examples // /// // /// ``` // /// use std::sync::atomic::{AtomicUsize, Ordering}; // /// // /// let foo = AtomicUsize::new(0b101101); // /// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101); // /// assert_eq!(foo.load(Ordering::SeqCst), 0b011110); // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn fetch_xor(&self, val: usize, order: Ordering) -> usize { // unsafe { atomic_xor(self.v.get(), val, order) } // } // } // // impl<T> AtomicPtr<T> { // /// Creates a new `AtomicPtr`. // /// // /// # Examples // /// // /// ``` // /// use std::sync::atomic::AtomicPtr; // /// // /// let ptr = &mut 5; // /// let atomic_ptr = AtomicPtr::new(ptr); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub const fn new(p: *mut T) -> AtomicPtr<T> { // AtomicPtr { p: UnsafeCell::new(p) } // } // // /// Loads a value from the pointer. // /// // /// `load` takes an `Ordering` argument which describes the memory ordering of this operation. // /// // /// # Panics // /// // /// Panics if `order` is `Release` or `AcqRel`. // /// // /// # Examples // /// // /// ``` // /// use std::sync::atomic::{AtomicPtr, Ordering}; // /// // /// let ptr = &mut 5; // /// let some_ptr = AtomicPtr::new(ptr); // /// // /// let value = some_ptr.load(Ordering::Relaxed); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn load(&self, order: Ordering) -> *mut T { // unsafe { // atomic_load(self.p.get() as *mut usize, order) as *mut T // } // } // // /// Stores a value into the pointer. // /// // /// `store` takes an `Ordering` argument which describes the memory ordering of this operation. // /// // /// # Examples // /// // /// ``` // /// use std::sync::atomic::{AtomicPtr, Ordering}; // /// // /// let ptr = &mut 5; // /// let some_ptr = AtomicPtr::new(ptr); // /// // /// let other_ptr = &mut 10; // /// // /// some_ptr.store(other_ptr, Ordering::Relaxed); // /// ``` // /// // /// # Panics // /// // /// Panics if `order` is `Acquire` or `AcqRel`. // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn store(&self, ptr: *mut T, order: Ordering) { // unsafe { atomic_store(self.p.get() as *mut usize, ptr as usize, order); } // } // // /// Stores a value into the pointer, returning the old value. // /// // /// `swap` takes an `Ordering` argument which describes the memory ordering of this operation. // /// // /// # Examples // /// // /// ``` // /// use std::sync::atomic::{AtomicPtr, Ordering}; // /// // /// let ptr = &mut 5; // /// let some_ptr = AtomicPtr::new(ptr); // /// // /// let other_ptr = &mut 10; // /// // /// let value = some_ptr.swap(other_ptr, Ordering::Relaxed); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T { // unsafe { atomic_swap(self.p.get() as *mut usize, ptr as usize, order) as *mut T } // } // // /// Stores a value into the pointer if the current value is the same as the `current` value. // /// // /// The return value is always the previous value. If it is equal to `current`, then the value // /// was updated. // /// // /// `compare_and_swap` also takes an `Ordering` argument which describes the memory ordering of // /// this operation. // /// // /// # Examples // /// // /// ``` // /// use std::sync::atomic::{AtomicPtr, Ordering}; // /// // /// let ptr = &mut 5; // /// let some_ptr = AtomicPtr::new(ptr); // /// // /// let other_ptr = &mut 10; // /// let another_ptr = &mut 10; // /// // /// let value = some_ptr.compare_and_swap(other_ptr, another_ptr, Ordering::Relaxed); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn compare_and_swap(&self, current: *mut T, new: *mut T, order: Ordering) -> *mut T { // unsafe { // atomic_compare_and_swap(self.p.get() as *mut usize, current as usize, // new as usize, order) as *mut T // } // } // } // pub const ATOMIC_USIZE_INIT: AtomicUsize = AtomicUsize::new(0); macro_rules! swap_test { ($($order:ident)*) => ($({ let atomicusize: AtomicUsize = AtomicUsize::default(); let result: usize = atomicusize.load(Relaxed); assert_eq!(result, 0); let data: Arc<AtomicUsize> = Arc::<AtomicUsize>::new(atomicusize); let clone: Arc<AtomicUsize> = data.clone(); let result: usize = clone.load(Relaxed); assert_eq!(result, 0); thread::spawn(move || { let val: usize = 68; let result: usize = clone.load(Relaxed); assert_eq!(result, 0); let old: usize = clone.swap(val, $order); assert_eq!(old, 0); }); thread::sleep_ms(10); let result: usize = data.load(Relaxed); assert_eq!(result, 68); })*) } #[test] fn swap_test1() { swap_test!( Relaxed Release Acquire AcqRel SeqCst ); } }<|fim▁end|>
// /// // /// # Examples
<|file_name|>TextureDummy.js<|end_file_name|><|fim▁begin|>/** * Copyright (c) 2015, Alexander Orzechowski. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Currently in beta stage. Changes can and will be made to the core mechanic * making this not backwards compatible. * * Github: https://github.com/Need4Speed402/tessellator */ Tessellator.TextureDummy = function (ready){ this.super(null); <|fim▁hole|>}; Tessellator.extend(Tessellator.TextureDummy, Tessellator.Texture); Tessellator.TextureDummy.prototype.configure = Tessellator.EMPTY_FUNC; Tessellator.TextureDummy.prototype.bind = Tessellator.EMPTY_FUNC;<|fim▁end|>
if (ready){ this.setReady(); };
<|file_name|>bls.rs<|end_file_name|><|fim▁begin|>/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use super::ecp::ECP; use super::ecp2::ECP2; use std::str; //use super::fp12::FP12; use super::big; use super::big::BIG; use super::pair; use super::rom; use rand::RAND; use sha3::SHA3; use sha3::SHAKE256; /* BLS API Functions */ pub const BFS: usize = big::MODBYTES as usize; pub const BGS: usize = big::MODBYTES as usize; pub const BLS_OK: isize = 0; pub const BLS_FAIL: isize = -1; /* hash a message to an ECP point, using SHA3 */ #[allow(non_snake_case)] pub fn bls_hashit(m: &str) -> ECP { let mut sh = SHA3::new(SHAKE256); let mut hm: [u8; BFS] = [0; BFS]; let t = m.as_bytes(); for i in 0..m.len() { sh.process(t[i]); } sh.shake(&mut hm, BFS); let P = ECP::mapit(&hm); return P; } /* generate key pair, private key s, public key w */ pub fn key_pair_generate(mut rng: &mut RAND, s: &mut [u8], w: &mut [u8]) -> isize { let q = BIG::new_ints(&rom::CURVE_ORDER); let g = ECP2::generator(); let mut sc = BIG::randomnum(&q, &mut rng); sc.tobytes(s); pair::g2mul(&g, &mut sc).tobytes(w); return BLS_OK; } /* Sign message m using private key s to produce signature sig */ pub fn sign(sig: &mut [u8], m: &str, s: &[u8]) -> isize { let d = bls_hashit(m); let mut sc = BIG::frombytes(&s); pair::g1mul(&d, &mut sc).tobytes(sig, true); return BLS_OK; } /* Verify signature given message m, the signature sig, and the public key w */ pub fn verify(sig: &[u8], m: &str, w: &[u8]) -> isize { let hm = bls_hashit(m); let mut d = ECP::frombytes(&sig); let g = ECP2::generator(); let pk = ECP2::frombytes(&w); d.neg(); // Use new multi-pairing mechanism let mut r = pair::initmp(); pair::another(&mut r, &g, &d); pair::another(&mut r, &pk, &hm); let mut v = pair::miller(&r); //.. or alternatively<|fim▁hole|> v = pair::fexp(&v); if v.isunity() { return BLS_OK; } return BLS_FAIL; }<|fim▁end|>
// let mut v = pair::ate2(&g, &d, &pk, &hm);
<|file_name|>ex12.py<|end_file_name|><|fim▁begin|>#import factorial #import square x = int(raw_input("What is 'x'?\n")) y = int(raw_input("What is y?\n")) # question0 = str(raw_input("Define a y value? (y/n)\n")) # if (question0 == "y","Y","yes","Yes"): # y = int(raw_input("What will 'y' be?\n")) # elif (y == "n","N","no","No"): # question2 = str(raw_input("Is y = 10 ok?\n")) # if (question2 == "y","Y","yes","Yes"): # y = 10 # elif (question2 == "n","N","no","No"): # y = int(raw_input("What will 'y' be?\n")) # else: # print "Please insert and interger" # else: # print "Please insert an interger." print "Using that information, we can do some mathematical equations." if x > y: #is not None: print "x, %d, is greater than y, %d." % (x, y) elif x == y: #is not None: print "x, %d, is equal to y, %d." % (x, y) elif x < y: #is not None: print "x, %d, is less than y, %d." % (x, y) elif x is not int: print "x should be a interger, you put it as %d" % (x) elif x is None: print "Please rerun the code." else: print "Something went wrong!" add = (x + y) sub = (x - y) mult = (x * y) div = (x / y) rem = (x % y) xeven = (x % 2 == 0) xodd = (x % 2 != 0) yeven = (y % 2 == 0) yodd = (y % 2 != 0) # xfact = (factorial(x)) # yfact = (factorial(y)) print "If you add x and y, you'll get %s." % add print "If you subtract x and y, you'll get %s." % sub print "If you multiply x and y, you'll get %s." % mult print "If you divide x and y, you'll get %s, with a remainder of %s." % (div, rem) if (x % 2 == 0): print "x is even." if (x % 2 != 0): print "x is odd." if (y % 2 == 0): print "y is even." if (y % 2 != 0): print "y is odd." print "If you square x, you get %s, and y squared is %s." % ((x^2),(y^2)) print "If you cube x, you get %s, and y cubed is %s." % ((x^3), (y^3)) #print "If you take x factorial, you get %s, and y factorial is %s." % ((xfact), (yfact)) #print "The square root of x is %s, and the square root of y is %s." % (square(x), square(y)) print "" <|fim▁hole|># import random # value = (1,2,3,4,5,6) # roll, string = argv # def choice(roll): # random.choice(dice) # return choice # choice(roll) # dice = choice(value)<|fim▁end|>
# from sys import argv
<|file_name|>author.service.ts<|end_file_name|><|fim▁begin|>import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Author } from '../entities/author'; @Injectable() export class AuthorService { private baseUrl: string = 'https://api.github.com'; constructor(private http: Http) { } getAuthor(name: string): Promise<Author> { return this.http .get(`${this.baseUrl}/users/${name}`) .toPromise() .then(this.mapAuthor) .catch(this.handleError); } private mapAuthor(response: Response): Author { const res = response.json(); let url = ''; if (res.blog !== undefined && res.blog !== null && res.blog !== '') { url = res.blog; } else { url = res.html_url; } const author = <Author>({ userName: res.login, name: res.name, avatarUrl: res.avatar_url, homepage: url, company: res.company, location: res.location, email: res.email, bio: res.bio }); return author; } private handleError(error: any): Promise<any> { console.error('An error occurred', error); return Promise.reject(error.message || error); }<|fim▁hole|><|fim▁end|>
}
<|file_name|>widget_medialist.js<|end_file_name|><|fim▁begin|>/* FTUI Plugin * Copyright (c) 2016 Mario Stephan <[email protected]> * Under MIT License (http://www.opensource.org/licenses/mit-license.php) */ /* global ftui:true, Modul_widget:true */ "use strict"; var Modul_medialist = function () { $('head').append('<link rel="stylesheet" href="' + ftui.config.dir + '/../css/ftui_medialist.css" type="text/css" />'); function changedCurrent(elem, pos) { elem.find('.media').each(function (index) { $(this).removeClass('current'); }); var idx = elem.hasClass('index1') ? pos - 1 : pos; var currentElem = elem.find('.media').eq(idx); if (currentElem.length > 0) { currentElem.addClass("current"); if (elem.hasClass("autoscroll")) { elem.scrollTop(currentElem.offset().top - elem.offset().top + elem.scrollTop()); } } } function init_attr(elem) { elem.initData('get', 'STATE'); elem.initData('set', 'play'); elem.initData('pos', 'Pos'); elem.initData('cmd', 'set'); elem.initData('color', ftui.getClassColor(elem) || ftui.getStyle('.' + me.widgetname, 'color') || '#222'); elem.initData('background-color', ftui.getStyle('.' + me.widgetname, 'background-color') || 'transparent'); elem.initData('text-color', ftui.getStyle('.' + me.widgetname, 'text-color') || '#ddd'); elem.initData('width', '90%'); elem.initData('height', '80%'); me.addReading(elem, 'get'); me.addReading(elem, 'pos'); } function init_ui(elem) { // prepare container element var width = elem.data('width'); var widthUnit = ($.isNumeric(width)) ? 'px' : ''; var height = elem.data('height'); var heightUnit = ($.isNumeric(height)) ? 'px' : ''; elem.html('') .addClass('media-list') .css({ width: width + widthUnit, maxWidth: width + widthUnit, height: height + heightUnit, color: elem.mappedColor('text-color'), backgroundColor: elem.mappedColor('background-color'), }); elem.on('click', '.media', function (index) { elem.data('value', elem.hasClass('index1') ? $(this).index() + 1 : $(this).index()); elem.transmitCommand(); }); } function update(dev, par) { // update medialist reading me.elements.filterDeviceReading('get', dev, par) .each(function (index) { var elem = $(this); var list = elem.getReading('get').val; var pos = elem.getReading('pos').val; if (ftui.isValid(list)) { elem.html(''); var text = ''; try { var collection = JSON.parse(list); for (var idx in collection) { var media = collection[idx]; text += '<div class="media">'; text += '<div class="media-image">'; text += '<img class="cover" src="' + media.Cover + '"/>'; text += '</div>'; text += '<div class="media-text">'; text += '<div class="title" data-track="' + media.Track + '">' + media.Title + '</div>'; text += '<div class="artist">' + media.Artist + '</div>'; text += '<div class="duration">' + ftui.durationFromSeconds(media.Time) + '</div>'; text += '</div></div>'; } } catch (e) { ftui.log(1, 'widget-' + me.widgetname + ': error:' + e); ftui.log(1, list); ftui.toast('<b>widget-' + me.widgetname + '</b><br>' + e, 'error'); } elem.append(text).fadeIn(); } if (pos) {<|fim▁hole|> //extra reading for current position me.elements.filterDeviceReading('pos', dev, par) .each(function (idx) { var elem = $(this); var pos = elem.getReading('pos').val; if (ftui.isValid(pos)){ changedCurrent(elem, pos); } }); } // public // inherit members from base class var me = $.extend(new Modul_widget(), { //override members widgetname: 'medialist', init_attr: init_attr, init_ui: init_ui, update: update, }); return me; };<|fim▁end|>
changedCurrent(elem, pos); } });
<|file_name|>core.py<|end_file_name|><|fim▁begin|># Copyright 2017 Erik Tollerud # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function, unicode_literals # just in case, for py2 to be py3-ish import pkgutil, io import numpy as np from matplotlib import image, cm from matplotlib import pyplot as plt __all__ = ['get_cat_num', 'n_cats', 'catter'] # N_cats x 72 x 72, 0 is transparent, 1 is full-cat _CAT_DATA = np.load(io.BytesIO(pkgutil.get_data('catterplot', 'data/cats.npy'))) def get_cat_num(i): return _CAT_DATA[i] def n_cats(): return len(_CAT_DATA) def catter(x, y, s=40, c=None, cat='random', alpha=1, ax=None, cmap=None, aspects='auto'): """ A catter plot (scatter plot with cats). Most arguments are interpreted the same as the matplotlib `scatter` function, except that ``s`` is the *data* size of the symbol (not pixel). Additional kwargs include: ``cat`` can be: * int : the index of the cat symbol to use - you can use ``catterplot.n_cats()`` to get the number of cats available * a squence of ints : must match the data, but otherwise interpreted as for a scalar * 'random'/'rand' : random cats ``ax`` can be: * None: use the current default (pyplot) axes * an `Axes` : random cats ``aspects`` can be: * 'auto': the cats length-to-width is set to be square given the spread of inputs * a float: the height/width of the cats. If not 1, ``s`` is interpreted as the geometric mean of the sizes * a sequence of floats: much match data, gives height/width """ if ax is None: ax = plt.gca() if c is not None: if cmap is None: cmap = plt.rcParams['image.cmap'] smap = cm.ScalarMappable(cmap=cmap) rgba = smap.to_rgba(c) else: rgba = np.ones((len(x), 4)) rgba[:, 3] *= alpha if np.isscalar(s) or s.shape==tuple(): s = np.ones(len(x))*s # otherwise assume shapes match if cat in ('rand', 'random'): cats = np.random.randint(n_cats(), size=len(x)) else: try: cats = np.ones(len(x)) * cat except TypeError as e: raise TypeError('`cat` argument needs to be "random", a scalar, or match the input.', e) if aspects == 'auto': <|fim▁hole|> ims = [] for xi, yi, si, ci, cati, aspecti in zip(x, y, s, rgba, cats, aspects): data = get_cat_num(cati) offsetx = si * aspecti**-0.5 / (2 * data.shape[0]) offsety = si * aspecti**0.5 / (2 * data.shape[1]) im = image.AxesImage(ax, extent=(xi - offsetx, xi + offsetx, yi - offsety, yi + offsety)) if c is None: # defaults to fading "black" cdata = 1-data else: # leave just the alpha to control the fading cdata = np.ones(data.shape) imarr = np.transpose([cdata*ci[0], cdata*ci[1], cdata*ci[2], data*ci[3]], (1, 2, 0)) im.set_data(imarr) ims.append(im) for im in ims: ax.add_image(im) #ax.autoscale_view() # for some reason autoscaling fails for images. So we'll just force it via # scatter... sc = plt.scatter(x, y) sc.remove() return ims<|fim▁end|>
aspects = np.ptp(y)/np.ptp(x) if np.isscalar(aspects) or aspects.shape==tuple(): aspects = np.ones(len(x)) * aspects
<|file_name|>instr_vpcmpuw.rs<|end_file_name|><|fim▁begin|>use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn vpcmpuw_1() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPUW, operand1: Some(Direct(K3)), operand2: Some(Direct(XMM7)), operand3: Some(Direct(XMM1)), operand4: Some(Literal8(53)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 243, 197, 15, 62, 217, 53], OperandSize::Dword) } #[test] fn vpcmpuw_2() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPUW, operand1: Some(Direct(K1)), operand2: Some(Direct(XMM5)), operand3: Some(IndirectScaledDisplaced(EDX, Eight, 2144732023, Some(OperandSize::Xmmword), None)), operand4: Some(Literal8(108)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K4), broadcast: None }, &[98, 243, 213, 12, 62, 12, 213, 119, 3, 214, 127, 108], OperandSize::Dword) } #[test] fn vpcmpuw_3() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPUW, operand1: Some(Direct(K4)), operand2: Some(Direct(XMM10)), operand3: Some(Direct(XMM23)), operand4: Some(Literal8(92)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 179, 173, 15, 62, 231, 92], OperandSize::Qword) } #[test] fn vpcmpuw_4() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPUW, operand1: Some(Direct(K6)), operand2: Some(Direct(XMM24)), operand3: Some(IndirectScaledIndexed(RSI, RSI, Four, Some(OperandSize::Xmmword), None)), operand4: Some(Literal8(25)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 243, 189, 1, 62, 52, 182, 25], OperandSize::Qword) } #[test] fn vpcmpuw_5() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPUW, operand1: Some(Direct(K2)), operand2: Some(Direct(YMM1)), operand3: Some(Direct(YMM6)), operand4: Some(Literal8(79)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 243, 245, 42, 62, 214, 79], OperandSize::Dword) } #[test] fn vpcmpuw_6() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPUW, operand1: Some(Direct(K1)), operand2: Some(Direct(YMM6)), operand3: Some(IndirectDisplaced(EAX, 2036232406, Some(OperandSize::Ymmword), None)), operand4: Some(Literal8(113)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K6), broadcast: None }, &[98, 243, 205, 46, 62, 136, 214, 112, 94, 121, 113], OperandSize::Dword) } #[test] fn vpcmpuw_7() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPUW, operand1: Some(Direct(K1)), operand2: Some(Direct(YMM2)), operand3: Some(Direct(YMM29)), operand4: Some(Literal8(93)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 147, 237, 47, 62, 205, 93], OperandSize::Qword) } #[test] fn vpcmpuw_8() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPUW, operand1: Some(Direct(K1)), operand2: Some(Direct(YMM16)), operand3: Some(IndirectScaledDisplaced(RCX, Eight, 1518565530, Some(OperandSize::Ymmword), None)), operand4: Some(Literal8(111)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 243, 253, 33, 62, 12, 205, 154, 120, 131, 90, 111], OperandSize::Qword) } #[test] fn vpcmpuw_9() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPUW, operand1: Some(Direct(K5)), operand2: Some(Direct(ZMM0)), operand3: Some(Direct(ZMM6)), operand4: Some(Literal8(62)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K6), broadcast: None }, &[98, 243, 253, 78, 62, 238, 62], OperandSize::Dword) } #[test] fn vpcmpuw_10() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPUW, operand1: Some(Direct(K6)), operand2: Some(Direct(ZMM7)), operand3: Some(IndirectScaledDisplaced(ESI, Eight, 1681212595, Some(OperandSize::Zmmword), None)), operand4: Some(Literal8(102)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 243, 197, 79, 62, 52, 245, 179, 68, 53, 100, 102], OperandSize::Dword) } <|fim▁hole|>} #[test] fn vpcmpuw_12() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPUW, operand1: Some(Direct(K1)), operand2: Some(Direct(ZMM11)), operand3: Some(IndirectScaledDisplaced(RDX, Four, 1742436219, Some(OperandSize::Zmmword), None)), operand4: Some(Literal8(81)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 243, 165, 74, 62, 12, 149, 123, 119, 219, 103, 81], OperandSize::Qword) }<|fim▁end|>
#[test] fn vpcmpuw_11() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPUW, operand1: Some(Direct(K2)), operand2: Some(Direct(ZMM12)), operand3: Some(Direct(ZMM15)), operand4: Some(Literal8(113)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 211, 157, 74, 62, 215, 113], OperandSize::Qword)
<|file_name|>protocol-buffers-schema-tests.ts<|end_file_name|><|fim▁begin|>import schema from "protocol-buffers-schema"; <|fim▁hole|> required int32 y=2; optional string label = 3; } message Line { required Point start = 1; required Point end = 2; optional string label = 3; }`; // pass a buffer or string to schema.parse const sch = schema.parse(proto); // will print out the schema as a javascript object console.log(sch);<|fim▁end|>
const proto = `syntax = "proto2"; message Point { required int32 x = 1;
<|file_name|>draw.C<|end_file_name|><|fim▁begin|>void draw(){ TString histoFileName = "data0/histo.root"; TFile* histoFile = TFile::Open(histoFileName); TH3D* hDetEventTime = (TH3D*) histoFile->Get("hDetEventTime"); printf("Nentries:%i\n",hDetEventTime->GetEntries()); for (Int_t det=1;det<=6;det++){ TCanvas* c1 = new TCanvas(Form("c1_det%i",det),Form("c1_det%i",det),800,500); gPad->SetRightMargin(0.02); gPad->SetLeftMargin(0.12); gPad->SetLogy(); TH1D* hTime = hDetEventTime->ProjectionZ(Form("StsEvent%i",det),det,det,1,1000); hTime->SetStats(0); hTime->SetLineColor(kBlue); hTime->SetLineWidth(2); if (det==1) hTime->SetTitle("STS @ 30 cm; time, ns;Entries"); if (det==2) hTime->SetTitle("STS @ 100 cm; time, ns;Entries"); if (det==3) hTime->SetTitle("MuCh @ 130 cm; time, ns;Entries"); if (det==4) hTime->SetTitle("MuCh @ 315 cm; time, ns;Entries"); if (det==5) hTime->SetTitle("TOF @ 1000 cm; time, ns;Entries"); if (det==6) hTime->SetTitle("TRD @ 948 cm; time, ns;Entries"); hTime->Draw(); c1->Print(".png"); } TCanvas* c2 = new TCanvas("c2","Primary tracks distribution",800,500); gPad->SetRightMargin(0.04); // c2->Divide(2,1); // TH1D* hNPrimaryTracks = (TH1D*) histoFile->Get("hNPrimaryTracks"); TH1D* hNPrimaryTracksInAcceptance = (TH1D*) histoFile->Get("hNPrimaryTracksInAcceptance"); hNPrimaryTracksInAcceptance->SetLineColor(kBlue); // c2->cd(1); // hNPrimaryTracks->Draw(); // c2->cd(2); hNPrimaryTracksInAcceptance->SetTitle(";Number of primary tracks in CBM acceptance;Entries"); hNPrimaryTracksInAcceptance->Draw(); // gPad->Print(".png"); TCanvas* c3 = new TCanvas("c3","tau",800,500); gPad->SetRightMargin(0.04); gPad->SetRightMargin(0.12); TF1* f1 = new TF1("time","(1-exp(-x/[0]))",0,600); f1->SetParameter(0,100); f1->SetLineColor(kBlue); f1->Draw(); f1->SetTitle(";time, ns;Probability"); TH1D* hStsPointsZ = (TH1D*) histoFile->Get("hStsPointsZ"); TH1D* hTrdPointsZ = (TH1D*) histoFile->Get("hTrdPointsZ"); TH1D* hTofPointsZ = (TH1D*) histoFile->Get("hTofPointsZ"); TH1D* hMuchPointsZ = (TH1D*) histoFile->Get("hMuchPointsZ"); TCanvas* c4 = new TCanvas("c4","z position",1000,800); c4->Divide(2,2); c4->cd(1); hStsPointsZ->Draw(); c4->cd(2); hTrdPointsZ->Draw(); c4->cd(3); <|fim▁hole|> c4->cd(4); hMuchPointsZ->Draw(); }<|fim▁end|>
hTofPointsZ->Draw();
<|file_name|>app.js<|end_file_name|><|fim▁begin|>var path = require('path'); var fs = require('fs') var http = require('http') var url = require('url') var mime = require('./mime').types var config = require("./config"); var zlib = require("zlib") var utils = require("./utils") var port = 8089; var server = http.createServer(function(request, response){ var pathname = url.parse(request.url).pathname; var realpath = path.join("assets", path.normalize(pathname.replace(/\.\./g, ""))) var ext = path.extname(realpath) ext = ext ? ext.slice(1):"unknown" var contentType = mime[ext] || "text/plain" fs.exists(realpath, function(exists) { if (!exists) { response.writeHead(404, { 'Content-Type': 'text/plain' }) response.write("This request URL " + pathname + "was not found on this server"); response.end(); } else { response.setHeader("Content-Type",contentType); var stats = fs.statSync(realpath); if (request.headers["range"]) { var range = utils.parseRange(request.headers["range"], stats.size); if (range) { response.setHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + stats.size); response.setHeader("Content-Length", (range.end - range.start + 1)); var stream = fs.createReadStream(realpath, { "start": range.start, "end": range.end }); response.writeHead('206', "Partial Content"); stream.pipe(response); } else { response.removeHeader("Content-Length"); response.writeHead(416, "Request Range Not Satisfiable"); response.end(); } } else { var stream = fs.createReadStream(realpath); response.writeHead('200', "Partial Content"); stream.pipe(response); } } })<|fim▁hole|>}) server.listen(port)<|fim▁end|>
<|file_name|>KanalanschlussPropertyConstants.java<|end_file_name|><|fim▁begin|>/*************************************************** * * cismet GmbH, Saarbruecken, Germany<|fim▁hole|>* ... and it just works. * ****************************************************/ /* * Copyright (C) 2011 jruiz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.cismet.verdis.commons.constants; /** * DOCUMENT ME! * * @author jruiz * @version $Revision$, $Date$ */ public final class KanalanschlussPropertyConstants extends PropertyConstants { //~ Static fields/initializers --------------------------------------------- public static final String BEFREIUNGENUNDERLAUBNISSE = "befreiungenunderlaubnisse"; //~ Constructors ----------------------------------------------------------- /** * Creates a new KanalanschlussPropertyConstants object. */ KanalanschlussPropertyConstants() { } }<|fim▁end|>
*
<|file_name|>__openerp__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Partners Persons Management', 'version': '1.0', 'category': 'Tools', 'sequence': 14, 'summary': '', 'description': """ Partners Persons Management ===========================<|fim▁hole|> Openerp consider a person those partners that have not "is_company" as true, now, those partners can have: ---------------------------------------------------------------------------------------------------------- * First Name and Last Name * Birthdate * Sex * Mother and Father * Childs * Age (functional field) * Nationality * Husband/Wife * National Identity * Passport * Marital Status It also adds a configuration menu for choosing which fields do you wanna see. """, 'author': 'ADHOC SA', 'website': 'www.adhoc.com.ar', 'images': [ ], 'depends': [ 'base', ], 'data': [ 'res_partner_view.xml', 'res_config_view.xml', 'security/partner_person_security.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<|fim▁end|>
<|file_name|>errors.py<|end_file_name|><|fim▁begin|>from flask import render_template from . import main @main.app_errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @main.app_errorhandler(500)<|fim▁hole|><|fim▁end|>
def internal_server_error(e): return render_template('500.html'), 500
<|file_name|>const-bound.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license<|fim▁hole|>// except according to those terms. // run-pass #![allow(dead_code)] // Make sure const bounds work on things, and test that a few types // are const. // pretty-expanded FIXME #23616 fn foo<T: Sync>(x: T) -> T { x } struct F { field: isize } pub fn main() { /*foo(1); foo("hi".to_string()); foo(vec![1, 2, 3]); foo(F{field: 42}); foo((1, 2)); foo(@1);*/ foo(Box::new(1)); }<|fim▁end|>
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
<|file_name|>cleanfilecache.py<|end_file_name|><|fim▁begin|>import os from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.core.exceptions import ImproperlyConfigured from cacheops.simple import file_cache, FILE_CACHE_DIR class Command(BaseCommand):<|fim▁hole|> os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % FILE_CACHE_DIR)<|fim▁end|>
help = 'Clean filebased cache' def handle(self, **options):
<|file_name|>test_tasks.py<|end_file_name|><|fim▁begin|>from django.test import TestCase from django.test.utils import override_settings from django.utils import timezone from django.core import mail from ovp.apps.users.tests.fixture import UserFactory from ovp.apps.organizations.tests.fixture import OrganizationFactory from ovp.apps.projects.models import Project, Apply, Job, Work from ovp.apps.core.helpers import get_email_subject from server.celery_tasks import app @override_settings(DEFAULT_SEND_EMAIL='sync', CELERY_TASK_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_TASK_ALWAYS_EAGER=True) class TestEmailTriggers(TestCase): def setUp(self): self.user = UserFactory.create( email='[email protected]', password='test_returned', object_channel='default' ) self.organization = OrganizationFactory.create( name='test org', owner=self.user, type=0, object_channel='default' ) self.project = Project.objects.create( name='test project', slug='test-slug', details='abc', description='abc', owner=self.user, organization=self.organization, published=False, object_channel='default' ) self.project.published = True self.project.save() app.control.purge() def test_applying_schedules_interaction_confirmation_email(self): """ Assert cellery task to ask about interaction is created when user applies to project """ mail.outbox = [] Apply.objects.create(user=self.user, project=self.project, object_channel='default') self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].subject, get_email_subject( 'default', 'atados-askProjectInteractionConfirmation-toVolunteer', 'Ask project confirmation' )) self.assertIn('vaga test project', mail.outbox[0].body) def test_applying_schedules_reminder_email(self): """<|fim▁hole|> Job.objects.create( start_date=timezone.now(), end_date=timezone.now(), project=self.project, object_channel='default' ) Apply.objects.create(user=self.user, project=self.project, object_channel='default') self.assertEqual(len(mail.outbox), 4) self.assertEqual(mail.outbox[1].subject, 'Uma ação está chegando... estamos ansiosos para te ver.') self.assertIn('test project', mail.outbox[1].body) def test_applying_schedules_ask_about_project_experience_to_volunteer(self): """ Assert cellery task to ask volunteer about project experience is created when user applies to project """ mail.outbox = [] work = Work.objects.create(project=self.project, object_channel='default') Apply.objects.create(user=self.user, project=self.project, object_channel='default') self.assertEqual(len(mail.outbox), 3) self.assertEqual(mail.outbox[1].subject, 'Conta pra gente como foi sua experiência?') self.assertIn('>test project<', mail.outbox[1].alternatives[0][0]) mail.outbox = [] work.delete() Job.objects.create( start_date=timezone.now(), end_date=timezone.now(), project=self.project, object_channel='default' ) Apply.objects.create(user=self.user, project=self.project, object_channel='default') self.assertEqual(mail.outbox[2].subject, 'Conta pra gente como foi sua experiência?') self.assertIn('>test project<', mail.outbox[2].alternatives[0][0]) def test_publishing_project_schedules_ask_about_experience_to_organization(self): """ Assert cellery task to ask organization about project experience is created when user project is published """ mail.outbox = [] project = Project.objects.create( name='test project', slug='test-slug', details='abc', description='abc', owner=self.user, published=False, organization=self.organization, object_channel='default' ) Work.objects.create(project=project, object_channel='default') project.published = True project.save() self.assertEqual(len(mail.outbox), 3) self.assertEqual(mail.outbox[2].subject, 'Tá na hora de contar pra gente como foi') self.assertIn('>test project<', mail.outbox[2].alternatives[0][0])<|fim▁end|>
Assert cellery task to remind volunteer is created when user applies to project """ mail.outbox = []
<|file_name|>test_rnaseq.py<|end_file_name|><|fim▁begin|>import pytest<|fim▁hole|> @pytest.yield_fixture def ericscript_run(mocker): yield mocker.patch('bcbio.pipeline.rnaseq.ericscript.run', autospec=True) @pytest.fixture def sample(): return { 'config': { 'algorithm': { 'fusion_mode': True, 'fusion_caller': 'ericscript' } } } def test_detect_fusion_callers_calls_for_each_sample(ericscript_run, sample): samples = [[sample], [sample]] rnaseq.detect_fusions(samples) assert ericscript_run.call_count == len(samples) def test_detect_fusions_returns_updated_samples(ericscript_run, sample): samples = [[sample]] result = rnaseq.detect_fusions(samples) assert result == [[ericscript_run.return_value]] def test_detect_fusions_calls_caller_with_sample_dict(ericscript_run, sample): samples = [[sample]] rnaseq.detect_fusions(samples) ericscript_run.assert_called_once_with(sample)<|fim▁end|>
from bcbio.pipeline import rnaseq
<|file_name|>development.js<|end_file_name|><|fim▁begin|>// Note: You must restart bin/webpack-watcher for changes to take effect const merge = require('webpack-merge') const sharedConfig = require('./shared.js')<|fim▁hole|> stats: { errorDetails: true }, output: { pathinfo: true } })<|fim▁end|>
module.exports = merge(sharedConfig, { devtool: 'sourcemap',
<|file_name|>getlyrics.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- u"""歌詞コーパスの取得 """ import argparse import requests import logging import urllib, urllib2 import re import time from BeautifulSoup import BeautifulSoup verbose = False logger = None def init_logger(): global logger logger = logging.getLogger('GetLyrics') logger.setLevel(logging.DEBUG) log_fmt = '%(asctime)s/%(name)s[%(levelname)s]: %(message)s' logging.basicConfig(format=log_fmt) def getSimilarArtist(artist): u"""類似アーティストのリストを取得 Last.fm APIを使用 """ params = {"method":"artist.getSimilar", "artist":artist, "api_key":"1d4a537bc937e81b88719933eed12ea0"} r = requests.get("http://ws.audioscrobbler.com/2.0/", params=params) soup = BeautifulSoup(r.content) artist_list = soup("name") p = re.compile(r"<[^>]*?>") for i, v in enumerate(artist_list): artist_list[i] = p.sub("", str(v)) if verbose: logger.info("Retrieved " + str(len(artist_list)) \ + " similar artists") return artist_list def getArtistId(artist): u"""j-lyrics.netでのアーティストのIDを取得 """ params = {"ka": artist,} baseurl = "http://search.j-lyric.net/index.php" r = requests.get(baseurl, params=params) soup = BeautifulSoup(r.content) urls = soup.find("div", id="lyricList").findAll("a") r = re.compile(r'http://j-lyric.net/artist/\w+/') for url in urls: href = url.get("href") if href.startswith("http://j-lyric.net/artist/"): return href.split("/")[-2] if verbose: logger.warning(artist + ": Not found") return None <|fim▁hole|> j-lyrics.net """ artist_id = getArtistId(artist) baseurl = "http://j-lyric.net/artist/" + artist_id + "/" r = requests.get(baseurl) soup = BeautifulSoup(r.content) a_tags = soup.find("div", id="lyricList").findAll("a") urls = map(lambda t: (t.string, t.get("href")), a_tags) # 歌詞以外のリンクを除く urls = filter(lambda t: t[1].startswith('/artist/'), urls) urls = map(lambda url: (url[0], "http://j-lyric.net" + url[1]), urls) return urls def getLyricText(url): u"""歌詞を取得して返す """ r = requests.get(url) soup = BeautifulSoup(r.content) # TODO: refactoring text = str(soup.find("p", id="lyricBody")) text = text.replace('<p id="lyricBody">', '').replace('</p>', '') text = text.replace('\r', '').replace('\n', '') return text.replace('\n', '').replace('<br />', '<BR>') def printArtistList(artist_list): u"""Last.fmから取得したアーティストのリストを取得 """ for artist_name in artist_list: print(artist_name) def main(args): global verbose verbose = args.verbose artist_list = getSimilarArtist(args.artist) artist_list = [args.artist,] + artist_list print("artist\ttitle\ttext") for artist in artist_list[:args.n_artists]: urls = getLyricUrlList(artist) if verbose: logger.info('{}: {} songs'.format(artist, len(urls))) for i, url in enumerate(urls, start=1): if verbose: if i%10 == 0: logger.info("Wrote " + str(i) + " songs") lyric = getLyricText(url[1]) print("{artist}\t{title}\t{text}".format( artist=artist, title=url[0].encode("utf-8"), text=lyric)) time.sleep(1.0) # Wait one second if __name__ == '__main__': init_logger() parser = argparse.ArgumentParser() parser.add_argument("-a", "--artist", default="湘南乃風", help="artist name") parser.add_argument("-n", "--n-artists", dest="n_artists", default=10, help="max number of artists") parser.add_argument("-v", "--verbose", action="store_true", default=False, help="verbose output") args = parser.parse_args() main(args)<|fim▁end|>
def getLyricUrlList(artist): u"""アーティストのすべての歌詞ページのUrlを取得
<|file_name|>assignment5.py<|end_file_name|><|fim▁begin|>import math import pandas as pd import numpy as np from scipy import misc from mpl_toolkits.mplot3d import Axes3D import matplotlib import matplotlib.pyplot as plt # Look pretty... # matplotlib.style.use('ggplot') plt.style.use('ggplot') def Plot2D(T, title, x, y):<|fim▁hole|> # This method picks a bunch of random samples (images in your case) # to plot onto the chart: fig = plt.figure() ax = fig.add_subplot(111) ax.set_title(title) ax.set_xlabel('Component: {0}'.format(x)) ax.set_ylabel('Component: {0}'.format(y)) ax.scatter(T[:,x],T[:,y], marker='.',alpha=0.7) from os import listdir file_path = "/Users/szabolcs/dev/git/DAT210x/Module4/Datasets/ALOI/32/" # # TODO: Start by creating a regular old, plain, "vanilla" # python list. You can call it 'samples'. # file_names = listdir(file_path) samples = [] # # TODO: Write a for-loop that iterates over the images in the # Module4/Datasets/ALOI/32/ folder, appending each of them to # your list. Each .PNG image should first be loaded into a # temporary NDArray, just as shown in the Feature # Representation reading. for file_name in file_names: pic = misc.imread(file_path + file_name) ser = [item for sublist in pic for item in sublist] pic = pd.Series(ser) #pic = pic[::2, ::2] pic = pic.values.reshape(-1, 3) samples.append(pic) # # Optional: Resample the image down by a factor of two if you # have a slower computer. You can also convert the image from # 0-255 to 0.0-1.0 if you'd like, but that will have no # effect on the algorithm's results. # df = pd.DataFrame.from_records(samples) print(df.shape) num_images, num_pixels = df.shape num_pixels = int(math.sqrt(num_pixels)) for i in range(num_images): df.loc[i,:] = df.loc[i,:].values.reshape(num_pixels, num_pixels).T.reshape(-1) print(df.shape) #df.iloc[0] = pd.to_numeric(df.iloc[0], errors="coerce") #print(df.dtypes) # # TODO: Once you're done answering the first three questions, # right before you converted your list to a dataframe, add in # additional code which also appends to your list the images # in the Module4/Datasets/ALOI/32_i directory. Re-run your # assignment and answer the final question below. # # .. your code here .. # # TODO: Convert the list to a dataframe # # .. your code here .. # # TODO: Implement Isomap here. Reduce the dataframe df down # to three components, using K=6 for your neighborhood size # from sklearn.manifold import Isomap imap = Isomap(n_components=2, n_neighbors=6) imap.fit(df) df_imap = imap.transform(df) Plot2D(df_imap, "Isomap", 0, 1) # # TODO: Create a 2D Scatter plot to graph your manifold. You # can use either 'o' or '.' as your marker. Graph the first two # isomap components # # .. your code here .. # # TODO: Create a 3D Scatter plot to graph your manifold. You # can use either 'o' or '.' as your marker: # # .. your code here .. plt.show()<|fim▁end|>
<|file_name|>callee.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use super::autoderef; use super::AutorefArgs; use super::check_argument_types; use super::check_expr; use super::check_method_argument_types; use super::demand; use super::DeferredCallResolution; use super::err_args; use super::Expectation; use super::expected_types_for_fn_args; use super::FnCtxt; use super::LvaluePreference; use super::method; use super::structurally_resolved_type; use super::TupleArgumentsFlag; use super::UnresolvedTypeAction; use super::write_call; use CrateCtxt; use middle::infer; use middle::ty::{self, Ty, ClosureTyper}; use syntax::ast; use syntax::codemap::Span; use syntax::parse::token; use syntax::ptr::P; use util::ppaux::Repr; /// Check that it is legal to call methods of the trait corresponding /// to `trait_id` (this only cares about the trait, not the specific /// method that is called) pub fn check_legal_trait_for_method_call(ccx: &CrateCtxt, span: Span, trait_id: ast::DefId) { let tcx = ccx.tcx; let did = Some(trait_id); let li = &tcx.lang_items; if did == li.drop_trait() { span_err!(tcx.sess, span, E0040, "explicit use of destructor method"); } else if !tcx.sess.features.borrow().unboxed_closures { // the #[feature(unboxed_closures)] feature isn't // activated so we need to enforce the closure // restrictions. let method = if did == li.fn_trait() { "call" } else if did == li.fn_mut_trait() { "call_mut" } else if did == li.fn_once_trait() { "call_once" } else { return // not a closure method, everything is OK. }; span_err!(tcx.sess, span, E0174, "explicit use of unboxed closure method `{}` is experimental", method); span_help!(tcx.sess, span, "add `#![feature(unboxed_closures)]` to the crate attributes to enable"); } } pub fn check_call<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, call_expr: &'tcx ast::Expr, callee_expr: &'tcx ast::Expr, arg_exprs: &'tcx [P<ast::Expr>], expected: Expectation<'tcx>) { check_expr(fcx, callee_expr); let original_callee_ty = fcx.expr_ty(callee_expr); let (callee_ty, _, result) = autoderef(fcx, callee_expr.span, original_callee_ty, Some(callee_expr), UnresolvedTypeAction::Error, LvaluePreference::NoPreference, |adj_ty, idx| { let autoderefref = ty::AutoDerefRef { autoderefs: idx, autoref: None }; try_overloaded_call_step(fcx, call_expr, callee_expr, adj_ty, autoderefref) }); match result { None => { // this will report an error since original_callee_ty is not a fn confirm_builtin_call(fcx, call_expr, original_callee_ty, arg_exprs, expected); } Some(CallStep::Builtin) => { confirm_builtin_call(fcx, call_expr, callee_ty, arg_exprs, expected); } Some(CallStep::DeferredClosure(fn_sig)) => { confirm_deferred_closure_call(fcx, call_expr, arg_exprs, expected, fn_sig); } Some(CallStep::Overloaded(method_callee)) => { confirm_overloaded_call(fcx, call_expr, callee_expr, arg_exprs, expected, method_callee); } } } enum CallStep<'tcx> { Builtin, DeferredClosure(ty::FnSig<'tcx>), Overloaded(ty::MethodCallee<'tcx>) } fn try_overloaded_call_step<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, call_expr: &'tcx ast::Expr, callee_expr: &'tcx ast::Expr, adjusted_ty: Ty<'tcx>, autoderefref: ty::AutoDerefRef<'tcx>) -> Option<CallStep<'tcx>> { debug!("try_overloaded_call_step(call_expr={}, adjusted_ty={}, autoderefref={})", call_expr.repr(fcx.tcx()), adjusted_ty.repr(fcx.tcx()), autoderefref.repr(fcx.tcx())); // If the callee is a bare function or a closure, then we're all set. match structurally_resolved_type(fcx, callee_expr.span, adjusted_ty).sty { ty::ty_bare_fn(..) => { fcx.write_adjustment(callee_expr.id, callee_expr.span, ty::AdjustDerefRef(autoderefref)); return Some(CallStep::Builtin); } ty::ty_closure(def_id, _, substs) => { assert_eq!(def_id.krate, ast::LOCAL_CRATE); // Check whether this is a call to a closure where we // haven't yet decided on whether the closure is fn vs // fnmut vs fnonce. If so, we have to defer further processing. if fcx.closure_kind(def_id).is_none() { let closure_ty = fcx.closure_type(def_id, substs); let fn_sig = fcx.infcx().replace_late_bound_regions_with_fresh_var(call_expr.span, infer::FnCall, &closure_ty.sig).0; fcx.record_deferred_call_resolution( def_id, box CallResolution {call_expr: call_expr, callee_expr: callee_expr, adjusted_ty: adjusted_ty, autoderefref: autoderefref, fn_sig: fn_sig.clone(), closure_def_id: def_id}); return Some(CallStep::DeferredClosure(fn_sig)); } } _ => {} } try_overloaded_call_traits(fcx, call_expr, callee_expr, adjusted_ty, autoderefref) .map(|method_callee| CallStep::Overloaded(method_callee)) } fn try_overloaded_call_traits<'a,'tcx>(fcx: &FnCtxt<'a, 'tcx>, call_expr: &ast::Expr, callee_expr: &ast::Expr, adjusted_ty: Ty<'tcx>, autoderefref: ty::AutoDerefRef<'tcx>) -> Option<ty::MethodCallee<'tcx>> { // Try the options that are least restrictive on the caller first. for &(opt_trait_def_id, method_name) in [ (fcx.tcx().lang_items.fn_trait(), token::intern("call")), (fcx.tcx().lang_items.fn_mut_trait(), token::intern("call_mut")), (fcx.tcx().lang_items.fn_once_trait(), token::intern("call_once")), ].iter() { let trait_def_id = match opt_trait_def_id { Some(def_id) => def_id, None => continue, }; match method::lookup_in_trait_adjusted(fcx, call_expr.span, Some(&*callee_expr), method_name, trait_def_id, autoderefref.clone(), adjusted_ty, None) { None => continue, Some(method_callee) => { return Some(method_callee); } } } None } fn confirm_builtin_call<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, call_expr: &ast::Expr, callee_ty: Ty<'tcx>, arg_exprs: &'tcx [P<ast::Expr>], expected: Expectation<'tcx>) { let error_fn_sig; let fn_sig = match callee_ty.sty { ty::ty_bare_fn(_, &ty::BareFnTy {ref sig, ..}) => { sig } _ => { fcx.type_error_message(call_expr.span, |actual| { format!("expected function, found `{}`", actual) }, callee_ty, None); // This is the "default" function signature, used in case of error. // In that case, we check each argument against "error" in order to // set up all the node type bindings. error_fn_sig = ty::Binder(ty::FnSig { inputs: err_args(fcx.tcx(), arg_exprs.len()), output: ty::FnConverging(fcx.tcx().types.err), variadic: false }); &error_fn_sig } }; // Replace any late-bound regions that appear in the function // signature with region variables. We also have to // renormalize the associated types at this point, since they // previously appeared within a `Binder<>` and hence would not // have been normalized before. let fn_sig = fcx.infcx().replace_late_bound_regions_with_fresh_var(call_expr.span, infer::FnCall, fn_sig).0; let fn_sig = fcx.normalize_associated_types_in(call_expr.span, &fn_sig); // Call the generic checker. let expected_arg_tys = expected_types_for_fn_args(fcx, call_expr.span, expected, fn_sig.output, &fn_sig.inputs); check_argument_types(fcx, call_expr.span, &fn_sig.inputs, &expected_arg_tys[..], arg_exprs, AutorefArgs::No, fn_sig.variadic, TupleArgumentsFlag::DontTupleArguments); write_call(fcx, call_expr, fn_sig.output); } fn confirm_deferred_closure_call<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, call_expr: &ast::Expr, arg_exprs: &'tcx [P<ast::Expr>], expected: Expectation<'tcx>, fn_sig: ty::FnSig<'tcx>) { // `fn_sig` is the *signature* of the cosure being called. We // don't know the full details yet (`Fn` vs `FnMut` etc), but we // do know the types expected for each argument and the return // type. let expected_arg_tys = expected_types_for_fn_args(fcx, call_expr.span, expected, fn_sig.output.clone(), &*fn_sig.inputs); check_argument_types(fcx, call_expr.span, &*fn_sig.inputs, &*expected_arg_tys, arg_exprs, AutorefArgs::No, fn_sig.variadic, TupleArgumentsFlag::TupleArguments); write_call(fcx, call_expr, fn_sig.output); } fn confirm_overloaded_call<'a,'tcx>(fcx: &FnCtxt<'a, 'tcx>, call_expr: &ast::Expr, callee_expr: &'tcx ast::Expr, arg_exprs: &'tcx [P<ast::Expr>], expected: Expectation<'tcx>, method_callee: ty::MethodCallee<'tcx>) { let output_type = check_method_argument_types(fcx, call_expr.span, method_callee.ty, callee_expr, arg_exprs, AutorefArgs::No, TupleArgumentsFlag::TupleArguments, expected); write_call(fcx, call_expr, output_type); write_overloaded_call_method_map(fcx, call_expr, method_callee); } fn write_overloaded_call_method_map<'a,'tcx>(fcx: &FnCtxt<'a, 'tcx>, call_expr: &ast::Expr, method_callee: ty::MethodCallee<'tcx>) { let method_call = ty::MethodCall::expr(call_expr.id); fcx.inh.method_map.borrow_mut().insert(method_call, method_callee); } struct CallResolution<'tcx> { call_expr: &'tcx ast::Expr, callee_expr: &'tcx ast::Expr, adjusted_ty: Ty<'tcx>, autoderefref: ty::AutoDerefRef<'tcx>, fn_sig: ty::FnSig<'tcx>, closure_def_id: ast::DefId, } impl<'tcx> Repr<'tcx> for CallResolution<'tcx> { fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String { format!("CallResolution(call_expr={}, callee_expr={}, adjusted_ty={}, \ autoderefref={}, fn_sig={}, closure_def_id={})", self.call_expr.repr(tcx), self.callee_expr.repr(tcx), self.adjusted_ty.repr(tcx), self.autoderefref.repr(tcx), self.fn_sig.repr(tcx), self.closure_def_id.repr(tcx)) } } impl<'tcx> DeferredCallResolution<'tcx> for CallResolution<'tcx> { fn resolve<'a>(&mut self, fcx: &FnCtxt<'a,'tcx>) { debug!("DeferredCallResolution::resolve() {}", self.repr(fcx.tcx())); // we should not be invoked until the closure kind has been // determined by upvar inference assert!(fcx.closure_kind(self.closure_def_id).is_some()); // We may now know enough to figure out fn vs fnmut etc. match try_overloaded_call_traits(fcx, self.call_expr, self.callee_expr, self.adjusted_ty, self.autoderefref.clone()) { Some(method_callee) => { // One problem is that when we get here, we are going // to have a newly instantiated function signature // from the call trait. This has to be reconciled with // the older function signature we had before. In // principle we *should* be able to fn_sigs(), but we // can't because of the annoying need for a TypeTrace. // (This always bites me, should find a way to // refactor it.) let method_sig = ty::no_late_bound_regions(fcx.tcx(), ty::ty_fn_sig(method_callee.ty)).unwrap(); debug!("attempt_resolution: method_callee={}", method_callee.repr(fcx.tcx())); for (&method_arg_ty, &self_arg_ty) in method_sig.inputs[1..].iter().zip(self.fn_sig.inputs.iter())<|fim▁hole|> demand::eqtype(fcx, self.call_expr.span, self_arg_ty, method_arg_ty); } demand::eqtype(fcx, self.call_expr.span, method_sig.output.unwrap(), self.fn_sig.output.unwrap()); write_overloaded_call_method_map(fcx, self.call_expr, method_callee); } None => { fcx.tcx().sess.span_bug( self.call_expr.span, "failed to find an overloaded call trait for closure call"); } } } }<|fim▁end|>
{
<|file_name|>cg.py<|end_file_name|><|fim▁begin|>import numpy as np def CG(A, X, B, maxiter=20, tolerance=1.0e-10, verbose=False): """Solve X*A=B using conjugate gradient method. ``X`` and ``B`` are ``ndarrays```of shape ``(m, nx, ny, nz)`` coresponding to matrices of size ``m*n`` (``n=nx*ny*nz``) and ``A`` is a callable representing an ``n*n`` matrix:: A(X, Y)<|fim▁hole|> will store ``X*A`` in the output array ``Y``. On return ``X`` will be the solution to ``X*A=B`` within ``tolerance``.""" m = len(X) shape = (m, 1, 1, 1) R = np.empty(X.shape, X.dtype.char) Q = np.empty(X.shape, X.dtype.char) A(X, R) R -= B P = R.copy() c1 = A.sum(np.reshape([abs(np.vdot(r, r)) for r in R], shape)) for i in range(maxiter): error = sum(c1.ravel()) if verbose: print 'CG-%d: %e' % (i, error) if error < tolerance: return i, error A(P, Q) #alpha = c1 / reshape([vdot(p, q) for p, q in zip(P, Q)], shape) alpha = c1 / A.sum(np.reshape([np.vdot(q,p) for p, q in zip(P, Q)], shape)) X -= alpha * P R -= alpha * Q c0 = c1 c1 = A.sum(np.reshape([abs(np.vdot(r, r)) for r in R], shape)) beta = c1 / c0 P *= beta P += R raise ArithmeticError('Did not converge!')<|fim▁end|>
<|file_name|>noop.ts<|end_file_name|><|fim▁begin|>/**<|fim▁hole|> * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { AbstractAlgorithm, AlgorithmInput, AlgorithmOptions, AlgorithmOutput, } from "./core"; import { Cluster } from "../cluster"; /** * Noop algorithm does not generate any clusters or filter markers by the an extended viewport. */ export class NoopAlgorithm extends AbstractAlgorithm { constructor({ ...options }: AlgorithmOptions) { super(options); } public calculate({ markers, map, mapCanvasProjection, }: AlgorithmInput): AlgorithmOutput { return { clusters: this.cluster({ markers, map, mapCanvasProjection }), changed: false, }; } protected cluster(input: AlgorithmInput): Cluster[] { return this.noop(input); } }<|fim▁end|>
* Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License");
<|file_name|>randfact.py<|end_file_name|><|fim▁begin|><|fim▁hole|>arguments = ["self", "info", "args"] helpstring = "randfact" minlevel = 1 def main(connection, info, args) : """Returns a random fact""" source = urllib2.urlopen("http://randomfunfacts.com/").read() fact = re.search(r"<strong><i>(.*)</i></strong>", source) connection.msg(info["channel"], "%s: %s" % (info["sender"], fact.group(1)))<|fim▁end|>
import re, urllib2
<|file_name|>ut_util.py<|end_file_name|><|fim▁begin|>__author__ = 'deevarvar' import string import random import os <|fim▁hole|>#generate a random string def string_generator(size=6, chars=string.ascii_letters+string.digits): return ''.join(random.choice(chars) for _ in range(size)) #emulate touch cmd def touchFile(fname, time=None): with open(fname, 'a'): os.utime(fname,time)<|fim▁end|>
<|file_name|>event_mail.py<|end_file_name|><|fim▁begin|># pylint: disable=api-one-deprecated from datetime import datetime from dateutil.relativedelta import relativedelta from odoo import api, fields, models, tools _INTERVALS = { "hours": lambda interval: relativedelta(hours=interval), "days": lambda interval: relativedelta(days=interval), "weeks": lambda interval: relativedelta(days=7 * interval), "months": lambda interval: relativedelta(months=interval), "now": lambda interval: relativedelta(hours=0), } class EventMailScheduler(models.Model): _inherit = "event.mail" interval_type = fields.Selection( selection_add=[ ("transferring_started", "Transferring started"), ("transferring_finished", "Transferring finished"), ] ) @api.depends( "event_id.state", "event_id.date_begin", "interval_type", "interval_unit", "interval_nbr", ) def _compute_scheduled_date(self): for rself in self: if rself.interval_type not in [ "transferring_started", "transferring_finished", ]:<|fim▁hole|> return super(EventMailScheduler, rself)._compute_scheduled_date() if rself.event_id.state not in ["confirm", "done"]: rself.scheduled_date = False else: date, sign = rself.event_id.create_date, 1 rself.scheduled_date = datetime.strptime( date, tools.DEFAULT_SERVER_DATETIME_FORMAT ) + _INTERVALS[rself.interval_unit](sign * rself.interval_nbr) def execute(self, registration=None): for rself in self: if rself.interval_type not in [ "transferring_started", "transferring_finished", ]: return super(EventMailScheduler, rself).execute() if registration: rself.write( { "mail_registration_ids": [ (0, 0, {"registration_id": registration.id}) ] } ) # execute scheduler on registrations rself.mail_registration_ids.filtered( lambda reg: reg.scheduled_date and reg.scheduled_date <= datetime.strftime( fields.datetime.now(), tools.DEFAULT_SERVER_DATETIME_FORMAT ) ).execute() return True class EventMailRegistration(models.Model): _inherit = "event.mail.registration" @api.one @api.depends( "registration_id", "scheduler_id.interval_unit", "scheduler_id.interval_type" ) def _compute_scheduled_date(self): # keep for-block event though it's api.one now (it was api.multi but it didn't work -- scheduled_date was empty) # When base module "event" will be updated we simply change api.one to api.multi without changing method body for rself in self: if rself.scheduler_id.interval_type not in [ "transferring_started", "transferring_finished", ]: return super(EventMailRegistration, rself)._compute_scheduled_date() if rself.registration_id: # date_open is not corresponded to its meaining, # but keep because it's copy-pasted code date_open_datetime = fields.datetime.now() rself.scheduled_date = date_open_datetime + _INTERVALS[ rself.scheduler_id.interval_unit ](rself.scheduler_id.interval_nbr)<|fim▁end|>
<|file_name|>io.py<|end_file_name|><|fim▁begin|>""" This module loads all the classes from the VTK IO library into its namespace. This is a required module.""" import os if os.name == 'posix': from libvtkIOPython import * else:<|fim▁hole|><|fim▁end|>
from vtkIOPython import *
<|file_name|>lc003-longest-substring-without-repeating-characters.py<|end_file_name|><|fim▁begin|># coding=utf-8 import unittest """3. Longest Substring Without Repeating Characters https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ Given a string, find the length of the **longest substring** without repeating characters. **Examples:** Given `"abcabcbb"`, the answer is `"abc"`, which the length is 3. Given `"bbbbb"`, the answer is `"b"`, with the length of 1. Given `"pwwkew"`, the answer is `"wke"`, with the length of 3. Note that the answer must be a **substring** , `"pwke"` is a _subsequence_ and not a<|fim▁hole|>Similar Questions: Longest Substring with At Most Two Distinct Characters (longest-substring-with-at-most-two-distinct-characters) """ class Solution(unittest.TestCase): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ cache = {} val, pos = 0, 0 while pos < len(s): if s[pos] in cache: pos = cache[s[pos]] + 1 val = max(val, len(cache)) cache.clear() else: cache[s[pos]] = pos pos += 1 val = max(val, len(cache)) return val def test(self): self.assertEqual(self.lengthOfLongestSubstring("abcabcbb"), 3) self.assertEqual(self.lengthOfLongestSubstring("bbbbb"), 1) self.assertEqual(self.lengthOfLongestSubstring("pwwkew"), 3) self.assertEqual(self.lengthOfLongestSubstring("c"), 1) if __name__ == "__main__": unittest.main()<|fim▁end|>
substring.
<|file_name|>gui_main.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'c:/steganography/main.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(1024, 576) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.group_image = QtGui.QGroupBox(self.centralwidget) self.group_image.setGeometry(QtCore.QRect(10, 10, 1001, 291)) self.group_image.setObjectName(_fromUtf8("group_image")) self.lbl_image = QtGui.QLabel(self.group_image) self.lbl_image.setGeometry(QtCore.QRect(180, 20, 451, 261)) self.lbl_image.setAutoFillBackground(False) self.lbl_image.setFrameShape(QtGui.QFrame.Panel) self.lbl_image.setFrameShadow(QtGui.QFrame.Raised) self.lbl_image.setText(_fromUtf8("")) self.lbl_image.setScaledContents(True) self.lbl_image.setObjectName(_fromUtf8("lbl_image")) self.lbl_filename = QtGui.QLabel(self.group_image) self.lbl_filename.setGeometry(QtCore.QRect(10, 20, 161, 21)) self.lbl_filename.setAlignment(QtCore.Qt.AlignCenter) self.lbl_filename.setObjectName(_fromUtf8("lbl_filename")) self.btn_load = QtGui.QPushButton(self.group_image) self.btn_load.setGeometry(QtCore.QRect(10, 50, 161, 31)) font = QtGui.QFont() font.setPointSize(10) self.btn_load.setFont(font) self.btn_load.setObjectName(_fromUtf8("btn_load")) self.lbl_spacing = QtGui.QLabel(self.group_image) self.lbl_spacing.setGeometry(QtCore.QRect(20, 150, 71, 21)) font = QtGui.QFont() font.setPointSize(9) font.setBold(True) font.setWeight(75) self.lbl_spacing.setFont(font) self.lbl_spacing.setObjectName(_fromUtf8("lbl_spacing")) self.box_spacing = QtGui.QSpinBox(self.group_image) self.box_spacing.setGeometry(QtCore.QRect(90, 150, 71, 22)) self.box_spacing.setMinimum(1) self.box_spacing.setMaximum(100) self.box_spacing.setProperty("value", 32) self.box_spacing.setObjectName(_fromUtf8("box_spacing")) self.radio_decode = QtGui.QRadioButton(self.group_image) self.radio_decode.setGeometry(QtCore.QRect(20, 120, 151, 17)) self.radio_decode.setChecked(False) self.radio_decode.setObjectName(_fromUtf8("radio_decode")) self.radio_encode = QtGui.QRadioButton(self.group_image) self.radio_encode.setGeometry(QtCore.QRect(20, 90, 141, 17)) self.radio_encode.setChecked(True) self.radio_encode.setObjectName(_fromUtf8("radio_encode")) self.verticalLayoutWidget = QtGui.QWidget(self.group_image) self.verticalLayoutWidget.setGeometry(QtCore.QRect(640, 20, 160, 131)) self.verticalLayoutWidget.setObjectName(_fromUtf8("verticalLayoutWidget")) self.layout_labels = QtGui.QVBoxLayout(self.verticalLayoutWidget) self.layout_labels.setSpacing(12) self.layout_labels.setObjectName(_fromUtf8("layout_labels")) self.lbl_height = QtGui.QLabel(self.verticalLayoutWidget) font = QtGui.QFont() font.setPointSize(9) font.setBold(True) font.setWeight(75) self.lbl_height.setFont(font) self.lbl_height.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lbl_height.setObjectName(_fromUtf8("lbl_height")) self.layout_labels.addWidget(self.lbl_height) self.lbl_width = QtGui.QLabel(self.verticalLayoutWidget) font = QtGui.QFont() font.setPointSize(9) font.setBold(True) font.setWeight(75) self.lbl_width.setFont(font) self.lbl_width.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lbl_width.setObjectName(_fromUtf8("lbl_width")) self.layout_labels.addWidget(self.lbl_width) self.lbl_format = QtGui.QLabel(self.verticalLayoutWidget) font = QtGui.QFont() font.setPointSize(9) font.setBold(True) font.setWeight(75) self.lbl_format.setFont(font) self.lbl_format.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lbl_format.setObjectName(_fromUtf8("lbl_format")) self.layout_labels.addWidget(self.lbl_format) self.lbl_size = QtGui.QLabel(self.verticalLayoutWidget) font = QtGui.QFont() font.setPointSize(9) font.setBold(True) font.setWeight(75) self.lbl_size.setFont(font) self.lbl_size.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lbl_size.setObjectName(_fromUtf8("lbl_size")) self.layout_labels.addWidget(self.lbl_size) self.lbl_max_length = QtGui.QLabel(self.verticalLayoutWidget) font = QtGui.QFont() font.setPointSize(9) font.setBold(True) font.setWeight(75) self.lbl_max_length.setFont(font) self.lbl_max_length.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lbl_max_length.setObjectName(_fromUtf8("lbl_max_length")) self.layout_labels.addWidget(self.lbl_max_length) self.verticalLayoutWidget_2 = QtGui.QWidget(self.group_image) self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(810, 20, 181, 130)) self.verticalLayoutWidget_2.setObjectName(_fromUtf8("verticalLayoutWidget_2")) self.layout_values = QtGui.QVBoxLayout(self.verticalLayoutWidget_2) self.layout_values.setSpacing(12) self.layout_values.setObjectName(_fromUtf8("layout_values")) self.lbl_height_value = QtGui.QLabel(self.verticalLayoutWidget_2) font = QtGui.QFont() font.setPointSize(9) self.lbl_height_value.setFont(font) self.lbl_height_value.setObjectName(_fromUtf8("lbl_height_value")) self.layout_values.addWidget(self.lbl_height_value) self.lbl_width_value = QtGui.QLabel(self.verticalLayoutWidget_2) font = QtGui.QFont() font.setPointSize(9) self.lbl_width_value.setFont(font) self.lbl_width_value.setObjectName(_fromUtf8("lbl_width_value")) self.layout_values.addWidget(self.lbl_width_value) self.lbl_format_value = QtGui.QLabel(self.verticalLayoutWidget_2) font = QtGui.QFont() font.setPointSize(9) self.lbl_format_value.setFont(font) self.lbl_format_value.setObjectName(_fromUtf8("lbl_format_value")) self.layout_values.addWidget(self.lbl_format_value) self.lbl_size_value = QtGui.QLabel(self.verticalLayoutWidget_2) font = QtGui.QFont() font.setPointSize(9) self.lbl_size_value.setFont(font) self.lbl_size_value.setObjectName(_fromUtf8("lbl_size_value")) self.layout_values.addWidget(self.lbl_size_value) self.lbl_max_length_value = QtGui.QLabel(self.verticalLayoutWidget_2) font = QtGui.QFont() font.setPointSize(9) self.lbl_max_length_value.setFont(font) self.lbl_max_length_value.setObjectName(_fromUtf8("lbl_max_length_value")) self.layout_values.addWidget(self.lbl_max_length_value) self.lbl_spacing_info = QtGui.QLabel(self.group_image) self.lbl_spacing_info.setGeometry(QtCore.QRect(20, 180, 141, 71)) self.lbl_spacing_info.setWordWrap(True) self.lbl_spacing_info.setObjectName(_fromUtf8("lbl_spacing_info")) self.lbl_status = QtGui.QLabel(self.group_image) self.lbl_status.setGeometry(QtCore.QRect(640, 160, 351, 121)) font = QtGui.QFont() font.setFamily(_fromUtf8("Consolas")) font.setPointSize(9) font.setBold(True) font.setWeight(75) self.lbl_status.setFont(font) self.lbl_status.setFrameShape(QtGui.QFrame.Panel) self.lbl_status.setFrameShadow(QtGui.QFrame.Sunken) self.lbl_status.setLineWidth(2) self.lbl_status.setScaledContents(False) self.lbl_status.setAlignment(QtCore.Qt.AlignCenter) self.lbl_status.setWordWrap(True) self.lbl_status.setIndent(-1) self.lbl_status.setObjectName(_fromUtf8("lbl_status")) self.group_message = QtGui.QGroupBox(self.centralwidget) self.group_message.setGeometry(QtCore.QRect(10, 310, 1001, 261)) self.group_message.setObjectName(_fromUtf8("group_message"))<|fim▁hole|> font = QtGui.QFont() font.setFamily(_fromUtf8("Consolas")) font.setPointSize(9) self.text_message.setFont(font) self.text_message.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.text_message.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.text_message.setObjectName(_fromUtf8("text_message")) self.btn_load_text_file = QtGui.QPushButton(self.group_message) self.btn_load_text_file.setGeometry(QtCore.QRect(10, 22, 161, 31)) font = QtGui.QFont() font.setPointSize(10) self.btn_load_text_file.setFont(font) self.btn_load_text_file.setObjectName(_fromUtf8("btn_load_text_file")) self.lbl_num_characters = QtGui.QLabel(self.group_message) self.lbl_num_characters.setGeometry(QtCore.QRect(180, 220, 811, 20)) font = QtGui.QFont() font.setFamily(_fromUtf8("Consolas")) font.setPointSize(10) self.lbl_num_characters.setFont(font) self.lbl_num_characters.setAlignment(QtCore.Qt.AlignCenter) self.lbl_num_characters.setObjectName(_fromUtf8("lbl_num_characters")) self.lbl_message_info = QtGui.QLabel(self.group_message) self.lbl_message_info.setGeometry(QtCore.QRect(10, 60, 151, 91)) self.lbl_message_info.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.lbl_message_info.setWordWrap(True) self.lbl_message_info.setObjectName(_fromUtf8("lbl_message_info")) self.lbl_allowed_symbols = QtGui.QLabel(self.group_message) self.lbl_allowed_symbols.setGeometry(QtCore.QRect(20, 140, 151, 101)) font = QtGui.QFont() font.setFamily(_fromUtf8("Consolas")) font.setPointSize(12) self.lbl_allowed_symbols.setFont(font) self.lbl_allowed_symbols.setAlignment(QtCore.Qt.AlignCenter) self.lbl_allowed_symbols.setWordWrap(True) self.lbl_allowed_symbols.setObjectName(_fromUtf8("lbl_allowed_symbols")) self.btn_process = QtGui.QPushButton(self.group_message) self.btn_process.setGeometry(QtCore.QRect(830, 220, 161, 31)) font = QtGui.QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.btn_process.setFont(font) self.btn_process.setAcceptDrops(False) self.btn_process.setAutoFillBackground(False) self.btn_process.setAutoDefault(True) self.btn_process.setDefault(True) self.btn_process.setObjectName(_fromUtf8("btn_process")) self.lbl_spacing_info_2 = QtGui.QLabel(self.centralwidget) self.lbl_spacing_info_2.setGeometry(QtCore.QRect(890, 0, 131, 20)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(109, 109, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(109, 109, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) self.lbl_spacing_info_2.setPalette(palette) font = QtGui.QFont() font.setPointSize(7) self.lbl_spacing_info_2.setFont(font) self.lbl_spacing_info_2.setWordWrap(True) self.lbl_spacing_info_2.setObjectName(_fromUtf8("lbl_spacing_info_2")) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "Nick\'s Image Steganography", None)) self.group_image.setTitle(_translate("MainWindow", "Image Settings", None)) self.lbl_filename.setText(_translate("MainWindow", "<no image selected>", None)) self.btn_load.setText(_translate("MainWindow", "Load Image", None)) self.lbl_spacing.setText(_translate("MainWindow", "Spacing:", None)) self.box_spacing.setToolTip(_translate("MainWindow", "Default: 32", None)) self.radio_decode.setText(_translate("MainWindow", "Decode Image", None)) self.radio_encode.setText(_translate("MainWindow", "Encode Message", None)) self.lbl_height.setText(_translate("MainWindow", "Height:", None)) self.lbl_width.setText(_translate("MainWindow", "Width:", None)) self.lbl_format.setText(_translate("MainWindow", "Format:", None)) self.lbl_size.setText(_translate("MainWindow", "Size:", None)) self.lbl_max_length.setText(_translate("MainWindow", "Max Message Length:", None)) self.lbl_height_value.setText(_translate("MainWindow", "0 px", None)) self.lbl_width_value.setText(_translate("MainWindow", "0 px", None)) self.lbl_format_value.setText(_translate("MainWindow", "NONE", None)) self.lbl_size_value.setText(_translate("MainWindow", "0 bytes", None)) self.lbl_max_length_value.setText(_translate("MainWindow", "0 characters", None)) self.lbl_spacing_info.setText(_translate("MainWindow", "This value selects how many pixels are skipped for every encoded pixel. Lower values will affect the image more.", None)) self.lbl_status.setText(_translate("MainWindow", "This mode allows you to select an image file and enter a message below. When you are finished, click Process.", None)) self.group_message.setTitle(_translate("MainWindow", "Message", None)) self.btn_load_text_file.setText(_translate("MainWindow", "Load Text File", None)) self.lbl_num_characters.setText(_translate("MainWindow", "0 / 0 characters", None)) self.lbl_message_info.setText(_translate("MainWindow", "Enter the message you would like to encode into the box. Whitespace characters will be converted into spaces. English letters, numbers, and spaces are supported, plus the following characters: ", None)) self.lbl_allowed_symbols.setText(_translate("MainWindow", "!\"#$%&\'()\\ *+-,/:;<=> ?@[]^_`{|}~", None)) self.btn_process.setText(_translate("MainWindow", "Process", None)) self.lbl_spacing_info_2.setText(_translate("MainWindow", "Copyright © 2015 Nick Klose", None)) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())<|fim▁end|>
self.text_message = QtGui.QTextEdit(self.group_message) self.text_message.setGeometry(QtCore.QRect(180, 20, 811, 191))
<|file_name|>floating_ip_pools.py<|end_file_name|><|fim▁begin|># Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import network ALIAS = 'os-floating-ip-pools' authorize = extensions.os_compute_authorizer(ALIAS) def _translate_floating_ip_view(pool_name): return { 'name': pool_name, } def _translate_floating_ip_pools_view(pools): return { 'floating_ip_pools': [_translate_floating_ip_view(pool_name) for pool_name in pools] } class FloatingIPPoolsController(wsgi.Controller): """The Floating IP Pool API controller for the OpenStack API.""" def __init__(self): self.network_api = network.API(skip_policy_check=True) super(FloatingIPPoolsController, self).__init__() @extensions.expected_errors(()) def index(self, req): """Return a list of pools.""" context = req.environ['nova.context'] authorize(context) pools = self.network_api.get_floating_ip_pools(context) return _translate_floating_ip_pools_view(pools) class FloatingIpPools(extensions.V21APIExtensionBase): """Floating IPs support."""<|fim▁hole|> name = "FloatingIpPools" alias = ALIAS version = 1 def get_resources(self): resource = [extensions.ResourceExtension(ALIAS, FloatingIPPoolsController())] return resource def get_controller_extensions(self): """It's an abstract function V21APIExtensionBase and the extension will not be loaded without it. """ return []<|fim▁end|>
<|file_name|>scripts.prod.js<|end_file_name|><|fim▁begin|>(function(jQuery) { "use strict"; var control = Echo.Control.manifest("Echo.Tests.Controls.TestControl"); if (Echo.Control.isDefined(control)) return; control.init = function() { if (!Echo.Variables) { Echo.Variables = {}; } Echo.Variables.TestControl = "production"; this.ready(); }; control.config = {}; control.templates.main = "";<|fim▁hole|> Echo.Control.create(control); })(Echo.jQuery);<|fim▁end|>
<|file_name|>fixnss.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python # # Copyright (C) 2012,2014 Stefano Sanfilippo. # See LICENSE.txt in the main source package for more information # from __future__ import with_statement import sys # Ugly ugly trick to give us compatibility both with Py2 and Py3k try: import cStringIO as StringIO except ImportError: try: import StringIO except ImportError: import io as StringIO FLAG = ['DropTail', 'RED', 'CBQ', 'FQ', 'SFQ', 'DRR'] def fix(filename, overwrite=False): """Will append a `Off` flag into each `(Duplex|Simplex)` Link declaration. Needed because the old file format was updated to include Queue Visualization. Converted file will be saved to ${somename}.new.nss Args: filename: the name of the file to be converted. overwrite: will overwrite input file if `True`. Returns: None """ with StringIO.StringIO() as buffer: with open(filename, 'rt') as sourcefile: ready = steady = False for line in sourcefile: buffer.write(line) if line[:-1] in FLAG: ready = True if ready and not steady: steady = True elif ready and steady: buffer.write('Off\n') ready = steady = False if not overwrite: filename = filename.replace('.nss', '.new.nss') with open(filename, 'wt') as sourcefile: sourcefile.write(buffer.getvalue()) def main(): filenames = sys.argv[1:] if filenames: for filename in filenames:<|fim▁hole|> print ('Converting %s' % filename) fix(filename) else: print('Usage: %s file1.nss [file2.nss [...]]' % sys.argv[0]) sys.exit(0) if __name__ == '__main__': main()<|fim▁end|>
<|file_name|>sha512.go<|end_file_name|><|fim▁begin|>package hash <|fim▁hole|>// Hashing with SHA512 func HashSHA512(input string) string { return HashWith(sha512.New(), input) }<|fim▁end|>
import "crypto/sha512"
<|file_name|>test_configuration.py<|end_file_name|><|fim▁begin|># tests/test_configuration.py # vim: ai et ts=4 sw=4 sts=4 ft=python fileencoding=utf-8 from io import StringIO from pcrunner.configuration import ( read_check_commands, read_check_commands_txt, read_check_commands_yaml, ) def test_read_check_commmands_txt_with_extra_lines(): fd = StringIO( u'''SERVICE|CHECK_01|check_dummy.py|0 OK -s 0 SERVICE|CHECK_02|check_dummy.py|1 WARNING -s 10 ''' ) assert read_check_commands_txt(fd) == [ { 'command': u'check_dummy.py 0 OK -s 0', 'name': u'CHECK_01', 'result_type': 'PROCESS_SERVICE_CHECK_RESULT', }, { 'command': u'check_dummy.py 1 WARNING -s 10', 'name': u'CHECK_02', 'result_type': 'PROCESS_SERVICE_CHECK_RESULT', }, ] def test_read_check_commmands_yaml(): fd = StringIO( u''' - name: 'CHECK_01' command: 'check_dummy.py 0 OK -s 0' result_type: 'PROCESS_SERVICE_CHECK_RESULT' - name: 'CHECK_02' command: 'check_dummy.py 1 WARNING -s 10' result_type: 'PROCESS_SERVICE_CHECK_RESULT' ''' ) assert read_check_commands_yaml(fd) == [<|fim▁hole|> 'result_type': 'PROCESS_SERVICE_CHECK_RESULT', }, { 'command': u'check_dummy.py 1 WARNING -s 10', 'name': u'CHECK_02', 'result_type': 'PROCESS_SERVICE_CHECK_RESULT', }, ] def test_read_check_commands_returns_empyt_list(): assert read_check_commands('/does/not/exists') == []<|fim▁end|>
{ 'command': u'check_dummy.py 0 OK -s 0', 'name': u'CHECK_01',
<|file_name|>tlsconfig_go1_8.go<|end_file_name|><|fim▁begin|>// +build go1.8 /* * * k6 - a next-generation load testing tool * Copyright (C) 2016 Load Impact * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package lib import "crypto/tls" var SupportedTLSVersions = map[string]int{ "ssl3.0": tls.VersionSSL30, "tls1.0": tls.VersionTLS10, "tls1.1": tls.VersionTLS11, "tls1.2": tls.VersionTLS12, } var SupportedTLSCipherSuites = map[string]uint16{ "TLS_RSA_WITH_RC4_128_SHA": tls.TLS_RSA_WITH_RC4_128_SHA, "TLS_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, "TLS_RSA_WITH_AES_128_CBC_SHA": tls.TLS_RSA_WITH_AES_128_CBC_SHA, "TLS_RSA_WITH_AES_256_CBC_SHA": tls.TLS_RSA_WITH_AES_256_CBC_SHA, "TLS_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_RSA_WITH_AES_128_GCM_SHA256, "TLS_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_RSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,<|fim▁hole|> "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, }<|fim▁end|>
"TLS_ECDHE_RSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>export default class UnitOfWork { sortAscending(set: Array<number>): Array<number> { if (!set || set.length === 0) { return []; } if (set.length === 1) { return [set[0]]; } for (let i=1; i<set.length; i++) { let v = set[i]; let z = i-1; while (z >= 0 && set[z] > v) { set[z+1] = set[z]; z = z - 1;<|fim▁hole|> return set; } }<|fim▁end|>
} set[z+1] = v; }
<|file_name|>fn.js<|end_file_name|><|fim▁begin|>'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = fn; var _includes = require('utilise/includes'); var _includes2 = _interopRequireDefault(_includes); var _client = require('utilise/client'); var _client2 = _interopRequireDefault(_client); var _all = require('utilise/all'); var _all2 = _interopRequireDefault(_all); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // register custom element prototype (render is automatic) function fn(ripple) { return function (res) { if (!customs || !customEl(res) || registered(res)) return (0, _all2.default)(res.name + ':not([inert])\n ,[is="' + res.name + '"]:not([inert])').map(ripple.draw);<|fim▁hole|> opts = { prototype: proto }; proto.attachedCallback = ripple.draw; document.registerElement(res.name, opts); }; } var registered = function registered(res) { return document.createElement(res.name).attachedCallback; }; var customs = _client2.default && !!document.registerElement, customEl = function customEl(d) { return (0, _includes2.default)('-')(d.name); };<|fim▁end|>
var proto = Object.create(HTMLElement.prototype),
<|file_name|>import_load_libs.py<|end_file_name|><|fim▁begin|>import unittest import re import os class ImportLoadLibs(unittest.TestCase): """ Test which libraries are loaded during importing ROOT """ # The whitelist is a list of regex expressions that mark wanted libraries # Note that the regex has to result in an exact match with the library name. known_libs = [ # libCore and dependencies 'libCore', 'libm',<|fim▁hole|> 'libzstd', 'libz', 'libpthread', 'libc', 'libdl', 'libpcre', # libCling and dependencies 'libCling.*', 'librt', 'libncurses.*', 'libtinfo', # by libncurses (on some older platforms) # libTree and dependencies 'libTree', 'libThread', 'libRIO', 'libNet', 'libImt', 'libMathCore', 'libMultiProc', 'libssl', 'libcrypt.*', # by libssl 'libtbb', 'liburing', # by libRIO if uring option is enabled # On centos7 libssl links against kerberos pulling in all dependencies below, removed with libssl1.1.0 'libgssapi_krb5', 'libkrb5', 'libk5crypto', 'libkrb5support', 'libselinux', 'libkeyutils', 'libcom_err', 'libresolv', # cppyy and Python libraries 'libcppyy.*', 'libROOTPythonizations.*', 'libpython.*', 'libutil.*', '.*cpython.*', '_.*', '.*module', 'operator', 'cStringIO', 'binascii', 'libbz2', 'libexpat', 'ISO8859-1', # System libraries and others 'libnss_.*', 'ld.*', 'libffi', ] # Verbose mode of the test verbose = False def test_import(self): """ Test libraries loaded after importing ROOT """ import ROOT libs = str(ROOT.gSystem.GetLibraries()) if self.verbose: print("Initial output from ROOT.gSystem.GetLibraries():\n" + libs) # Split paths libs = libs.split(' ') # Get library name without full path and .so* suffix libs = [os.path.basename(l).split('.so')[0] for l in libs \ if not l.startswith('-l') and not l.startswith('-L')] # Check that the loaded libraries are white listed bad_libs = [] good_libs = [] matched_re = [] for l in libs: matched = False for r in self.known_libs: m = re.match(r, l) if m: if m.group(0) == l: matched = True good_libs.append(l) matched_re.append(r) break if not matched: bad_libs.append(l) if self.verbose: print('Found whitelisted libraries after importing ROOT with the shown regex match:') for l, r in zip(good_libs, matched_re): print(' - {} ({})'.format(l, r)) import sys sys.stdout.flush() if bad_libs: raise Exception('Found not whitelisted libraries after importing ROOT:' \ + '\n - ' + '\n - '.join(bad_libs) \ + '\nIf the test fails with a library that is loaded on purpose, please add it to the whitelist.') if __name__ == '__main__': unittest.main()<|fim▁end|>
'liblz4', 'libxxhash', 'liblzma',
<|file_name|>urls.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # OpenCraft -- tools to aid developing and hosting free software projects # Copyright (C) 2015-2019 OpenCraft <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ URL Patterns for api app """ # Imports ##################################################################### from django.conf.urls import include, url from django.views.generic.base import RedirectView from drf_yasg.views import get_schema_view from rest_framework.permissions import AllowAny from api.auth import JWTAuthToken, JwtTokenRefresh, JwtTokenVerify from api.router import v1_router, v2_router from opencraft.swagger import api_info<|fim▁hole|># URL Patterns ################################################################ app_name = 'api' # pylint: disable=invalid-name schema_view = get_schema_view( info=api_info, public=True, permission_classes=(AllowAny,), ) urlpatterns = [ url(r'^$', RedirectView.as_view(url='v1/', permanent=False), name='index'), # v1 urls url(r'^v1/', include((v1_router.urls, 'api_v1'), namespace='v1')), url(r'^v1/auth/', include('rest_framework.urls', namespace='rest_framework')), # v2 urls url(r'^v2/', include((v2_router.urls, 'api_v2'), namespace='v2')), url(r'^v2/auth/token/', JWTAuthToken.as_view(), name='token_obtain_pair'), # They are required to check if the token is valid and to refresh the access # token and allow a session that lasts more than a few minutes url(r'^v2/auth/refresh/', JwtTokenRefresh.as_view(), name='token_refresh'), url(r'^v2/auth/verify/', JwtTokenVerify.as_view(), name='token_verify'), # Reset password url(r'^v2/password_reset/', include('django_rest_passwordreset.urls', namespace='password_reset')), # Documentation url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=10), name='schema-json'), url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=10), name='schema-swagger-ui'), url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=10), name='schema-redoc'), ]<|fim▁end|>
<|file_name|>graphics.js<|end_file_name|><|fim▁begin|>// Generated by CoffeeScript 1.10.0 var Graphics; Graphics = (function() { function Graphics(ctx, viewport1) { this.ctx = ctx; this.viewport = viewport1; this.transform = { x: 0, y: 0, rotation: 0, scale: 1 }; } Graphics.prototype.translate = function(dx, dy) { this.transform.x += dx; this.transform.y += dy; return this.ctx.translate(dx, dy); }; Graphics.prototype.setColor = function(color) { this.ctx.fillStyle = color;<|fim▁hole|> Graphics.prototype.setLineWidth = function(linewidth) { return this.ctx.lineWidth = linewidth; }; Graphics.prototype.setFont = function(fontdef) { return this.ctx.font = fontdef; }; Graphics.prototype.drawArc = function(x, y, r, sAngle, eAngle) { this.ctx.beginPath(); this.ctx.arc(x, y, r, sAngle, eAngle, true); return this.ctx.stroke(); }; Graphics.prototype.fillArc = function(x, y, r, sAngle, eAngle) { this.ctx.beginPath(); this.ctx.arc(x, y, r, sAngle, eAngle, true); return this.ctx.fill(); }; Graphics.prototype.drawCircle = function(x, y, r) { return this.drawArc(x, y, r, 0, 2 * Math.PI); }; Graphics.prototype.fillCircle = function(x, y, r) { return this.fillArc(x, y, r, 0, 2 * Math.PI); }; Graphics.prototype.drawRect = function(x, y, width, height) { return this.ctx.strokeRect(x, y, width, height); }; Graphics.prototype.fillRect = function(x, y, width, height) { return this.ctx.fillRect(x, y, width, height); }; Graphics.prototype.drawText = function(x, y, text) { return this.ctx.fillText(text, x, y); }; Graphics.prototype.drawLine = function(x1, y1, x2, y2) { this.ctx.beginPath(); this.ctx.moveTo(x1, y1); this.ctx.lineTo(x2, y2); return this.ctx.stroke(); }; Graphics.prototype.drawPoly = function(ptlist) { var i, len, pt; this.ctx.beginPath(); this.ctx.moveTo(ptlist[0].x, ptlist[0].y); for (i = 0, len = ptlist.length; i < len; i++) { pt = ptlist[i]; this.ctx.lineTo(pt.x, pt.y); } this.ctx.closePath(); return this.ctx.stroke(); }; Graphics.prototype.fillPoly = function(ptlist) { var i, len, pt; this.ctx.beginPath(); this.ctx.moveTo(ptlist[0].x, ptlist[0].y); for (i = 0, len = ptlist.length; i < len; i++) { pt = ptlist[i]; this.ctx.lineTo(pt.x, pt.y); } this.ctx.closePath(); return this.ctx.fill(); }; return Graphics; })(); exports.createFromCanvas = function(canvas, viewport) { return new Graphics(canvas.getContext('2d'), viewport); };<|fim▁end|>
return this.ctx.strokeStyle = color; };
<|file_name|>middleware.js<|end_file_name|><|fim▁begin|>var prettyURLs = require('../middleware/pretty-urls'), cors = require('../middleware/api/cors'), urlRedirects = require('../middleware/url-redirects'), auth = require('../../auth'); /** * Auth Middleware Packages * * IMPORTANT * - cors middleware MUST happen before pretty urls, because otherwise cors header can get lost on redirect * - cors middleware MUST happen after authenticateClient, because authenticateClient reads the trusted domains * - url redirects MUST happen after cors, otherwise cors header can get lost on redirect */ /** * Authentication for public endpoints */ module.exports.authenticatePublic = [ auth.authenticate.authenticateClient, auth.authenticate.authenticateUser, // This is a labs-enabled middleware auth.authorize.requiresAuthorizedUserPublicAPI, cors, urlRedirects, prettyURLs ]; /** * Authentication for private endpoints */ module.exports.authenticatePrivate = [ auth.authenticate.authenticateClient, auth.authenticate.authenticateUser, auth.authorize.requiresAuthorizedUser,<|fim▁hole|>]; /** * Authentication for client endpoints */ module.exports.authenticateClient = function authenticateClient(client) { return [ auth.authenticate.authenticateClient, auth.authenticate.authenticateUser, auth.authorize.requiresAuthorizedClient(client), cors, urlRedirects, prettyURLs ]; };<|fim▁end|>
cors, urlRedirects, prettyURLs
<|file_name|>LibertyOP_BasicTests_oauth_usingSocialConfig.java<|end_file_name|><|fim▁begin|>/******************************************************************************* * Copyright (c) 2017, 2021 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html<|fim▁hole|> package com.ibm.ws.security.social.fat.LibertyOP; import java.util.ArrayList; import java.util.List; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.runner.RunWith; import com.ibm.websphere.simplicity.log.Log; import com.ibm.ws.security.oauth_oidc.fat.commonTest.RSCommonTestTools; import com.ibm.ws.security.social.fat.LibertyOP.CommonTests.LibertyOPRepeatActions; import com.ibm.ws.security.social.fat.commonTests.Social_BasicTests; import com.ibm.ws.security.social.fat.utils.SocialConstants; import com.ibm.ws.security.social.fat.utils.SocialTestSettings; import componenttest.custom.junit.runner.FATRunner; import componenttest.custom.junit.runner.Mode; import componenttest.custom.junit.runner.Mode.TestMode; import componenttest.rules.repeater.RepeatTests; import componenttest.topology.impl.LibertyServerWrapper; @RunWith(FATRunner.class) @LibertyServerWrapper @Mode(TestMode.FULL) public class LibertyOP_BasicTests_oauth_usingSocialConfig extends Social_BasicTests { public static Class<?> thisClass = LibertyOP_BasicTests_oauth_usingSocialConfig.class; public static RSCommonTestTools rsTools = new RSCommonTestTools(); @ClassRule public static RepeatTests r = RepeatTests.with(LibertyOPRepeatActions.usingUserInfo()).andWith(LibertyOPRepeatActions.usingIntrospect()); @BeforeClass public static void setUp() throws Exception { classOverrideValidationEndpointValue = FATSuite.UserApiEndpoint; List<String> startMsgs = new ArrayList<String>(); startMsgs.add("CWWKT0016I.*" + SocialConstants.SOCIAL_DEFAULT_CONTEXT_ROOT); List<String> extraApps = new ArrayList<String>(); extraApps.add(SocialConstants.HELLOWORLD_SERVLET); // TODO fix List<String> opStartMsgs = new ArrayList<String>(); // opStartMsgs.add("CWWKS1600I.*" + SocialConstants.OIDCCONFIGMEDIATOR_APP); opStartMsgs.add("CWWKS1631I.*"); // TODO fix List<String> opExtraApps = new ArrayList<String>(); opExtraApps.add(SocialConstants.OP_SAMPLE_APP); String[] propagationTokenTypes = rsTools.chooseTokenSettings(SocialConstants.OIDC_OP); String tokenType = propagationTokenTypes[0]; String certType = propagationTokenTypes[1]; Log.info(thisClass, "setupBeforeTest", "inited tokenType to: " + tokenType); socialSettings = new SocialTestSettings(); testSettings = socialSettings; testOPServer = commonSetUp(SocialConstants.SERVER_NAME + ".LibertyOP.op", "op_server_orig.xml", SocialConstants.OIDC_OP, null, SocialConstants.DO_NOT_USE_DERBY, opStartMsgs, null, SocialConstants.OIDC_OP, true, true, tokenType, certType); genericTestServer = commonSetUp(SocialConstants.SERVER_NAME + ".LibertyOP.social", "server_LibertyOP_basicTests_oauth_usingSocialConfig.xml", SocialConstants.GENERIC_SERVER, extraApps, SocialConstants.DO_NOT_USE_DERBY, startMsgs); setActionsForProvider(SocialConstants.LIBERTYOP_PROVIDER, SocialConstants.OAUTH_OP); setGenericVSSpeicificProviderFlags(GenericConfig, "server_LibertyOP_basicTests_oauth_usingSocialConfig"); socialSettings = updateLibertyOPSettings(socialSettings); } }<|fim▁end|>
* * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/
<|file_name|>98a6883f88ed207a422bce14e041cea9032231df.js<|end_file_name|><|fim▁begin|>"use strict"; const http_1 = require("http"); const WebSocketServer = require("ws"); const express = require("express"); const dgram = require("dgram"); const readUInt64BE = require("readuint64be"); const buffer_1 = require("buffer"); const _ = require("lodash"); // Health Insurrance: process.on("uncaughtException", function (err) { console.log(err); }); const debug = require("debug")("PeerTracker:Server"), redis = require("redis"), GeoIpNativeLite = require("geoip-native-lite"), bencode = require("bencode"); // Load in GeoData GeoIpNativeLite.loadDataSync(); // Keep statistics going, update every 30 min let stats = { seedCount: 0, leechCount: 0, torrentCount: 0, activeTcount: 0, scrapeCount: 0, successfulDown: 0, countries: {} }; const ACTION_CONNECT = 0, ACTION_ANNOUNCE = 1, ACTION_SCRAPE = 2, ACTION_ERROR = 3, INTERVAL = 1801, startConnectionIdHigh = 0x417, startConnectionIdLow = 0x27101980; // Without using streams, this can handle ~320 IPv4 addresses. More doesn't necessarily mean better. const MAX_PEER_SIZE = 1500; const FOUR_AND_FIFTEEN_DAYS = 415 * 24 * 60 * 60; // assuming start time is seconds for redis; // Redis let client; class Server { constructor(opts) { this._debug = (...args) => { args[0] = "[" + this._debugId + "] " + args[0]; debug.apply(null, args); }; const self = this; if (!opts) opts = { port: 80, udpPort: 1337, docker: false }; self._debugId = ~~((Math.random() * 100000) + 1); self._debug("peer-tracker Server instance created"); self.PORT = opts.port; self.udpPORT = opts.udpPort; self.server = http_1.createServer(); self.wss = new WebSocketServer.Server({ server: self.server }); self.udp4 = dgram.createSocket({ type: "udp4", reuseAddr: true }); self.app = express(); // PREP VISUAL AID: console.log(` . | | | ||| /___\\ |_ _| | | | | | | | | |__| |__| | | | | | | | | | | | | Peer Tracker 1.1.0 | | | | | | | | Running in standalone mode | | | | UDP PORT: ${self.udpPORT} | | | | HTTP & WS PORT: ${self.PORT} | | | | | |_| | |__| |__| | | | | LET'S BUILD AN EMPIRE! | | | | https://github.com/CraigglesO/peer-tracker | | | | | | | | |____|_|____| `); // Redis if (opts.docker) client = redis.createClient("6379", "redis"); else client = redis.createClient(); // If an error occurs, print it to the console client.on("error", function (err) { console.log("Redis error: " + err); }); client.on("ready", function () { console.log(new Date() + ": Redis is up and running."); }); self.app.set("trust proxy", function (ip) { return true; }); // Express self.app.get("/", function (req, res) { let ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; if (ip.indexOf("::ffff:") !== -1) ip = ip.slice(7); res.status(202).send("Welcome to the Empire. Your address: " + ip); }); self.app.get("/stat.json", function (req, res) { res.status(202).send(stats); }); self.app.get("/stat", function (req, res) { // { seedCount, leechCount, torrentCount, activeTcount, scrapeCount, successfulDown, countries }; let parsedResponce = `<h1><span style="color:blue;">V1.0.3</span> - ${stats.torrentCount} Torrents {${stats.activeTcount} active}</h1>\n <h2>Successful Downloads: ${stats.successfulDown}</h2>\n <h2>Number of Scrapes to this tracker: ${stats.scrapeCount}</h2>\n <h3>Connected Peers: ${stats.seedCount + stats.leechCount}</h3>\n <h3><ul>Seeders: ${stats.seedCount}</ul></h3>\n <h3><ul>Leechers: ${stats.leechCount}</ul></h3>\n <h3>Countries that have connected: <h3>\n <ul>`; let countries; for (countries in stats.countries) parsedResponce += `<li>${stats.countries[countries]}</li>\n`; parsedResponce += "</ul>"; res.status(202).send(parsedResponce); }); self.app.get("*", function (req, res) { res.status(404).send("<h1>404 Not Found</h1>"); }); self.server.on("request", self.app.bind(self)); self.server.listen(self.PORT, function () { console.log(new Date() + ": HTTP Server Ready" + "\n" + new Date() + ": Websockets Ready."); }); // WebSocket: self.wss.on("connection", function connection(ws) { // let location = url.parse(ws.upgradeReq.url, true); let ip; let peerAddress; let port; if (opts.docker) { ip = ws.upgradeReq.headers["x-forwarded-for"]; peerAddress = ip.split(":")[0]; port = ip.split(":")[1]; } else { peerAddress = ws._socket.remoteAddress; port = ws._socket.remotePort; } if (peerAddress.indexOf("::ffff:") !== -1) peerAddress = peerAddress.slice(7); console.log("peerAddress", peerAddress); ws.on("message", function incoming(msg) { handleMessage(msg, peerAddress, port, "ws", (reply) => { ws.send(reply); }); }); }); // UDP: self.udp4.bind(self.udpPORT); self.udp4.on("message", function (msg, rinfo) { handleMessage(msg, rinfo.address, rinfo.port, "udp", (reply) => { self.udp4.send(reply, 0, reply.length, rinfo.port, rinfo.address, (err) => { if (err) { console.log("udp4 error: ", err); } ; }); }); }); self.udp4.on("error", function (err) { console.log("error", err); }); self.udp4.on("listening", () => { console.log(new Date() + ": UDP-4 Bound and ready."); }); self.updateStatus((info) => { stats = info; }); setInterval(() => { console.log("STAT UPDATE, " + Date.now()); self.updateStatus((info) => { stats = info; }); }, 30 * 60 * 1000); } updateStatus(cb) { const self = this; // Get hashes -> iterate through hashes and get all peers and leechers // Also get number of scrapes 'scrape' // Number of active hashes hash+':time' let NOW = Date.now(), seedCount = 0, // check leechCount = 0, // check torrentCount = 0, // check activeTcount = 0, // check scrapeCount = 0, // check successfulDown = 0, // check countries = {}; client.get("hashes", (err, reply) => { if (!reply) return; let hashList = reply.split(","); torrentCount = hashList.length; client.get("scrape", (err, rply) => { if (err) { return; } if (!rply) return; scrapeCount = rply; }); hashList.forEach((hash, i) => { client.mget([hash + ":seeders", hash + ":leechers", hash + ":time", hash + ":completed"], (err, rply) => { if (err) { return; } // iterate through: // seeders if (rply[0]) { rply[0] = rply[0].split(","); seedCount += rply[0].length; rply[0].forEach((addr) => { let ip = addr.split(":")[0]; let country = GeoIpNativeLite.lookup(ip); if (country) countries[country] = country.toUpperCase(); }); } if (rply[1]) { rply[1] = rply[1].split(","); seedCount += rply[1].length; rply[1].forEach((addr) => { let ip = addr.split(":")[0]; let country = GeoIpNativeLite.lookup(ip); if (country) countries[country] = country.toUpperCase(); }); } if (rply[2]) { if (((NOW - rply[2]) / 1000) < 432000) activeTcount++; } if (rply[3]) { successfulDown += Number(rply[3]); } if (i === (torrentCount - 1)) { cb({ seedCount, leechCount, torrentCount, activeTcount, scrapeCount, successfulDown, countries }); } }); }); }); } } // MESSAGE FUNCTIONS: function handleMessage(msg, peerAddress, port, type, cb) { // PACKET SIZES: // CONNECT: 16 - ANNOUNCE: 98 - SCRAPE: 16 OR (16 + 20 * n) let buf = new buffer_1.Buffer(msg), bufLength = buf.length, transaction_id = 0, action = null, connectionIdHigh = null, connectionIdLow = null, hash = null, responce = null, PEER_ID = null, PEER_ADDRESS = null, PEER_KEY = null, NUM_WANT = null, peerPort = port, peers = null; // Ensure packet fullfills the minimal 16 byte requirement. if (bufLength < 16) { ERROR(); } else { // Get generic data: connectionIdHigh = buf.readUInt32BE(0), connectionIdLow = buf.readUInt32BE(4), action = buf.readUInt32BE(8), transaction_id = buf.readUInt32BE(12); // 12 32-bit integer transaction_id } switch (action) { case ACTION_CONNECT: // Check whether the transaction ID is equal to the one you chose. if (startConnectionIdLow !== connectionIdLow || startConnectionIdHigh !== connectionIdHigh) { ERROR(); break; } // Create a new Connection ID and Transaction ID for this user... kill after 30 seconds: let newConnectionIDHigh = ~~((Math.random() * 100000) + 1); let newConnectionIDLow = ~~((Math.random() * 100000) + 1); client.setex(peerAddress + ":" + newConnectionIDHigh, 60, 1); client.setex(peerAddress + ":" + newConnectionIDLow, 60, 1); client.setex(peerAddress + ":" + startConnectionIdLow, 60, 1); client.setex(peerAddress + ":" + startConnectionIdHigh, 60, 1); // client.setex(peerAddress + ':' + transaction_id , 30 * 1000, 1); // THIS MIGHT BE WRONG // Create a responce buffer: responce = new buffer_1.Buffer(16); responce.fill(0); responce.writeUInt32BE(ACTION_CONNECT, 0); // 0 32-bit integer action 0 // connect responce.writeUInt32BE(transaction_id, 4); // 4 32-bit integer transaction_id responce.writeUInt32BE(newConnectionIDHigh, 8); // 8 64-bit integer connection_id responce.writeUInt32BE(newConnectionIDLow, 12); // 8 64-bit integer connection_id cb(responce); break; case ACTION_ANNOUNCE: // Checks to make sure the packet is worth analyzing: // 1. packet is atleast 84 bytes if (bufLength < 84) { ERROR(); break; } // Minimal requirements: hash = buf.slice(16, 36); hash = hash.toString("hex"); PEER_ID = buf.slice(36, 56); // -WD0017-I0mH4sMSAPOJ && -LT1000-9BjtQhMtTtTc PEER_ID = PEER_ID.toString(); let DOWNLOADED = readUInt64BE(buf, 56), LEFT = readUInt64BE(buf, 64), UPLOADED = readUInt64BE(buf, 72), EVENT = buf.readUInt32BE(80); if (bufLength > 96) { PEER_ADDRESS = buf.readUInt16BE(84); PEER_KEY = buf.readUInt16BE(88); NUM_WANT = buf.readUInt16BE(92); peerPort = buf.readUInt16BE(96); } // 2. check that Transaction ID and Connection ID match client.mget([peerAddress + ":" + connectionIdHigh, peerAddress + ":" + connectionIdLow], (err, reply) => { if (!reply[0] || !reply[1] || err) { ERROR(); return; } addHash(hash); // Check EVENT // 0: none; 1: completed; 2: started; 3: stopped // If 1, 2, or 3 do sets first. if (EVENT === 1) { // Change the array this peer is housed in. removePeer(peerAddress + ":" + peerPort, hash + type + ":leechers");<|fim▁hole|> addPeer(peerAddress + ":" + peerPort, hash + type + ":seeders"); // Increment total users who completed file client.incr(hash + ":completed"); } else if (EVENT === 2) { // Add to array (leecher array if LEFT is > 0) if (LEFT > 0) addPeer(peerAddress + ":" + peerPort, hash + type + ":leechers"); else addPeer(peerAddress + ":" + peerPort, hash + type + ":seeders"); } else if (EVENT === 3) { // Remove peer from array (leecher array if LEFT is > 0) removePeer(peerAddress + ":" + peerPort, hash + type + ":leechers"); removePeer(peerAddress + ":" + peerPort, hash + type + ":seeders"); return; } client.mget([hash + type + ":seeders", hash + type + ":leechers"], (err, rply) => { if (err) { ERROR(); return; } // Convert all addresses to a proper hex buffer: // Addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize let addresses = addrToBuffer(rply[0], rply[1], LEFT); // Create a responce buffer: responce = new buffer_1.Buffer(20); responce.fill(0); responce.writeUInt32BE(ACTION_ANNOUNCE, 0); // 0 32-bit integer action 1 -> announce responce.writeUInt32BE(transaction_id, 4); // 4 32-bit integer transaction_id responce.writeUInt32BE(INTERVAL, 8); // 8 32-bit integer interval responce.writeUInt32BE(addresses[0], 12); // 12 32-bit integer leechers responce.writeUInt32BE(addresses[1], 16); // 16 32-bit integer seeders responce = buffer_1.Buffer.concat([responce, addresses[2]]); // 20 + 6 * n 32-bit integer IP address // 24 + 6 * n 16-bit integer TCP port cb(responce); }); }); break; case ACTION_SCRAPE: // Check whether the transaction ID is equal to the one you chose. // 2. check that Transaction ID and Connection ID match // addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize // Create a responce buffer: client.incr("scrape"); let responces = new buffer_1.Buffer(8); responces.fill(0); responces.writeUInt32BE(ACTION_SCRAPE, 0); // 0 32-bit integer action 2 -> scrape responces.writeUInt32BE(transaction_id, 4); // 4 32-bit integer transaction_id let bufferSum = []; // LOOP THROUGH REQUESTS for (let i = 16; i < (buf.length - 16); i += 20) { hash = buf.slice(i, i + 20); hash = hash.toString("hex"); client.mget([hash + type + ":seeders", hash + type + ":leechers", hash + type + ":completed"], (err, rply) => { if (err) { ERROR(); return; } // convert all addresses to a proper hex buffer: let addresses = addrToBuffer(rply[0], rply[1], 1); let responce = new buffer_1.Buffer(20); responce.fill(0); responce.writeUInt32BE(addresses[1], 8); // 8 + 12 * n 32-bit integer seeders responce.writeUInt32BE(rply[2], 12); // 12 + 12 * n 32-bit integer completed responce.writeUInt32BE(addresses[0], 16); // 16 + 12 * n 32-bit integer leechers bufferSum.push(responce); if ((i + 16) >= (buf.length - 16)) { let scrapes = buffer_1.Buffer.concat(bufferSum); responces = buffer_1.Buffer.concat([responces, scrapes]); cb(responces); } }); } break; default: ERROR(); } function ERROR() { responce = new buffer_1.Buffer(11); responce.fill(0); responce.writeUInt32BE(ACTION_ERROR, 0); responce.writeUInt32BE(transaction_id, 4); responce.write("900", 8); cb(responce); } function addPeer(peer, where) { client.get(where, (err, reply) => { if (err) { ERROR(); return; } else { if (!reply) reply = peer; else reply = peer + "," + reply; reply = reply.split(","); reply = _.uniq(reply); // Keep the list under MAX_PEER_SIZE; if (reply.length > MAX_PEER_SIZE) { reply = reply.slice(0, MAX_PEER_SIZE); } reply = reply.join(","); client.set(where, reply); } }); } function removePeer(peer, where) { client.get(where, (err, reply) => { if (err) { ERROR(); return; } else { if (!reply) return; else { reply = reply.split(","); let index = reply.indexOf(peer); if (index > -1) { reply.splice(index, 1); } reply = reply.join(","); client.set(where, reply); } } }); } function addrToBuffer(seeders, leechers, LEFT) { // Addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize // Also we don't need to send the users own address // If peer is a leecher, send more seeders; if peer is a seeder, send only leechers let leecherCount = 0, seederCount = 0, peerBuffer = null, peerBufferSize = 0; if (LEFT === 0 || !seeders || seeders === "") seeders = new buffer_1.Buffer(0); else { seeders = seeders.split(","); seederCount = seeders.length; seeders = seeders.map((addressPort) => { let addr = addressPort.split(":")[0]; let port = addressPort.split(":")[1]; addr = addr.split("."); let b = new buffer_1.Buffer(6); b.fill(0); b.writeUInt8(addr[0], 0); b.writeUInt8(addr[1], 1); b.writeUInt8(addr[2], 2); b.writeUInt8(addr[3], 3); b.writeUInt16BE(port, 4); return b; }); seeders = buffer_1.Buffer.concat(seeders); } if (LEFT > 0 && seederCount > 50 && leechers > 15) leechers = leechers.slice(0, 15); if (!leechers || leechers === "") leechers = new buffer_1.Buffer(0); else { leechers = leechers.split(","); leecherCount = leechers.length; leechers = leechers.map((addressPort) => { let addr = addressPort.split(":")[0]; let port = addressPort.split(":")[1]; addr = addr.split("."); let b = new buffer_1.Buffer(6); b.fill(0); b.writeUInt8(addr[0], 0); b.writeUInt8(addr[1], 1); b.writeUInt8(addr[2], 2); b.writeUInt8(addr[3], 3); b.writeUInt16BE(port, 4); return b; }); leechers = buffer_1.Buffer.concat(leechers); } peerBuffer = buffer_1.Buffer.concat([seeders, leechers]); // Addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize return [leecherCount, seederCount, peerBuffer]; } // Add a new hash to the swarm, ensure uniqeness function addHash(hash) { client.get("hashes", (err, reply) => { if (err) { ERROR(); return; } if (!reply) reply = hash; else reply = hash + "," + reply; reply = reply.split(","); reply = _.uniq(reply); reply = reply.join(","); client.set("hashes", reply); client.set(hash + ":time", Date.now()); }); } function getHashes() { let r = client.get("hashes", (err, reply) => { if (err) { ERROR(); return null; } reply = reply.split(","); return reply; }); return r; } } function binaryToHex(str) { if (typeof str !== "string") { str = String(str); } return buffer_1.Buffer.from(str, "binary").toString("hex"); } function hexToBinary(str) { if (typeof str !== "string") { str = String(str); } return buffer_1.Buffer.from(str, "hex").toString("binary"); } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Server; //# sourceMappingURL=/Users/connor/Desktop/Programming/myModules/peer-tracker/ts-node/b80e7f10257a0a2b7f29aee28a53e164f19fc5f2/98a6883f88ed207a422bce14e041cea9032231df.js.map<|fim▁end|>
<|file_name|>key.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- ''' The Salt Key backend API and interface used by the CLI. The Key class can be used to manage salt keys directly without interfacing with the CLI. ''' # Import python libs from __future__ import absolute_import, print_function import os import copy import json import stat import shutil import fnmatch import hashlib import logging # Import salt libs import salt.crypt import salt.utils import salt.exceptions import salt.utils.event import salt.daemons.masterapi from salt.utils import kinds from salt.utils.event import tagify # Import third party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin import salt.ext.six as six from salt.ext.six.moves import input # pylint: enable=import-error,no-name-in-module,redefined-builtin try: import msgpack except ImportError: pass log = logging.getLogger(__name__) def get_key(opts): if opts['transport'] in ('zeromq', 'tcp'): return Key(opts) else: return RaetKey(opts) class KeyCLI(object): ''' Manage key CLI operations ''' def __init__(self, opts): self.opts = opts if self.opts['transport'] in ('zeromq', 'tcp'): self.key = Key(opts) else: self.key = RaetKey(opts) def list_status(self, status): ''' Print out the keys under a named status :param str status: A string indicating which set of keys to return ''' keys = self.key.list_keys() if status.startswith('acc'): salt.output.display_output( {self.key.ACC: keys[self.key.ACC]}, 'key', self.opts ) elif status.startswith(('pre', 'un')): salt.output.display_output( {self.key.PEND: keys[self.key.PEND]}, 'key', self.opts ) elif status.startswith('rej'): salt.output.display_output( {self.key.REJ: keys[self.key.REJ]}, 'key', self.opts ) elif status.startswith('den'): if self.key.DEN: salt.output.display_output( {self.key.DEN: keys[self.key.DEN]}, 'key', self.opts ) elif status.startswith('all'): self.list_all() def list_all(self): ''' Print out all keys ''' salt.output.display_output( self.key.list_keys(), 'key', self.opts) def accept(self, match, include_rejected=False): ''' Accept the keys matched :param str match: A string to match against. i.e. 'web*' :param bool include_rejected: Whether or not to accept a matched key that was formerly rejected ''' def _print_accepted(matches, after_match): if self.key.ACC in after_match: accepted = sorted( set(after_match[self.key.ACC]).difference( set(matches.get(self.key.ACC, [])) ) ) for key in accepted: print('Key for minion {0} accepted.'.format(key)) matches = self.key.name_match(match) keys = {} if self.key.PEND in matches: keys[self.key.PEND] = matches[self.key.PEND] if include_rejected and bool(matches.get(self.key.REJ)): keys[self.key.REJ] = matches[self.key.REJ] if not keys: msg = ( 'The key glob {0!r} does not match any unaccepted {1}keys.' .format(match, 'or rejected ' if include_rejected else '') ) print(msg) raise salt.exceptions.SaltSystemExit(code=1) if not self.opts.get('yes', False): print('The following keys are going to be accepted:') salt.output.display_output( keys, 'key', self.opts) try: veri = input('Proceed? [n/Y] ') except KeyboardInterrupt: raise SystemExit("\nExiting on CTRL-c") if not veri or veri.lower().startswith('y'): _print_accepted( matches, self.key.accept( match_dict=keys, include_rejected=include_rejected ) ) else: print('The following keys are going to be accepted:') salt.output.display_output( keys, 'key', self.opts) _print_accepted( matches, self.key.accept( match_dict=keys, include_rejected=include_rejected ) ) def accept_all(self, include_rejected=False): ''' Accept all keys :param bool include_rejected: Whether or not to accept a matched key that was formerly rejected ''' self.accept('*', include_rejected=include_rejected) def delete(self, match): ''' Delete the matched keys :param str match: A string to match against. i.e. 'web*' ''' def _print_deleted(matches, after_match): deleted = [] for keydir in (self.key.ACC, self.key.PEND, self.key.REJ): deleted.extend(list( set(matches.get(keydir, [])).difference( set(after_match.get(keydir, [])) ) )) for key in sorted(deleted): print('Key for minion {0} deleted.'.format(key)) matches = self.key.name_match(match) if not matches: print( 'The key glob {0!r} does not match any accepted, unaccepted ' 'or rejected keys.'.format(match) ) raise salt.exceptions.SaltSystemExit(code=1) if not self.opts.get('yes', False): print('The following keys are going to be deleted:') salt.output.display_output( matches, 'key', self.opts) try: veri = input('Proceed? [N/y] ') except KeyboardInterrupt: raise SystemExit("\nExiting on CTRL-c") if veri.lower().startswith('y'): _print_deleted( matches, self.key.delete_key(match_dict=matches) ) else: print('Deleting the following keys:') salt.output.display_output( matches, 'key', self.opts) _print_deleted( matches, self.key.delete_key(match_dict=matches) ) def delete_all(self): ''' Delete all keys ''' self.delete('*') def reject(self, match, include_accepted=False): ''' Reject the matched keys :param str match: A string to match against. i.e. 'web*' :param bool include_accepted: Whether or not to accept a matched key that was formerly accepted ''' def _print_rejected(matches, after_match): if self.key.REJ in after_match: rejected = sorted( set(after_match[self.key.REJ]).difference( set(matches.get(self.key.REJ, [])) ) ) for key in rejected: print('Key for minion {0} rejected.'.format(key)) matches = self.key.name_match(match) keys = {} if self.key.PEND in matches: keys[self.key.PEND] = matches[self.key.PEND] if include_accepted and bool(matches.get(self.key.ACC)): keys[self.key.ACC] = matches[self.key.ACC] if not keys: msg = 'The key glob {0!r} does not match any {1} keys.'.format( match, 'accepted or unaccepted' if include_accepted else 'unaccepted' ) print(msg) return if not self.opts.get('yes', False): print('The following keys are going to be rejected:') salt.output.display_output( keys, 'key', self.opts) veri = input('Proceed? [n/Y] ') if veri.lower().startswith('n'): return _print_rejected( matches, self.key.reject( match_dict=matches, include_accepted=include_accepted ) ) def reject_all(self, include_accepted=False): ''' Reject all keys :param bool include_accepted: Whether or not to accept a matched key that was formerly accepted ''' self.reject('*', include_accepted=include_accepted) def print_key(self, match): ''' Print out a single key :param str match: A string to match against. i.e. 'web*' ''' matches = self.key.key_str(match) salt.output.display_output( matches, 'key', self.opts) def print_all(self): ''' Print out all managed keys ''' self.print_key('*') def finger(self, match): ''' Print out the fingerprints for the matched keys :param str match: A string to match against. i.e. 'web*' ''' matches = self.key.finger(match) salt.output.display_output( matches, 'key', self.opts) def finger_all(self): ''' Print out all fingerprints ''' matches = self.key.finger('*') salt.output.display_output( matches, 'key', self.opts) def prep_signature(self): ''' Searches for usable keys to create the master public-key signature ''' self.privkey = None self.pubkey = None # check given pub-key if self.opts['pub']: if not os.path.isfile(self.opts['pub']): print('Public-key {0} does not exist'.format(self.opts['pub'])) return self.pubkey = self.opts['pub'] # default to master.pub else: mpub = self.opts['pki_dir'] + '/' + 'master.pub' if os.path.isfile(mpub): self.pubkey = mpub # check given priv-key if self.opts['priv']: if not os.path.isfile(self.opts['priv']): print('Private-key {0} does not exist'.format(self.opts['priv'])) return self.privkey = self.opts['priv'] # default to master_sign.pem else: mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem' if os.path.isfile(mpriv): self.privkey = mpriv if not self.privkey: if self.opts['auto_create']: print('Generating new signing key-pair {0}.* in {1}' ''.format(self.opts['master_sign_key_name'], self.opts['pki_dir'])) salt.crypt.gen_keys(self.opts['pki_dir'], self.opts['master_sign_key_name'], self.opts['keysize'], self.opts.get('user')) self.privkey = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem' else: print('No usable private-key found') return if not self.pubkey: print('No usable public-key found') return print('Using public-key {0}'.format(self.pubkey)) print('Using private-key {0}'.format(self.privkey)) if self.opts['signature_path']: if not os.path.isdir(self.opts['signature_path']): print('target directory {0} does not exist' ''.format(self.opts['signature_path'])) else: self.opts['signature_path'] = self.opts['pki_dir'] sign_path = self.opts['signature_path'] + '/' + self.opts['master_pubkey_signature'] self.key.gen_signature(self.privkey, self.pubkey, sign_path) def run(self): ''' Run the logic for saltkey ''' if self.opts['gen_keys']: self.key.gen_keys() return elif self.opts['gen_signature']: self.prep_signature() return if self.opts['list']: self.list_status(self.opts['list']) elif self.opts['list_all']: self.list_all() elif self.opts['print']: self.print_key(self.opts['print']) elif self.opts['print_all']: self.print_all() elif self.opts['accept']: self.accept( self.opts['accept'], include_rejected=self.opts['include_all'] ) elif self.opts['accept_all']: self.accept_all(include_rejected=self.opts['include_all']) elif self.opts['reject']: self.reject( self.opts['reject'], include_accepted=self.opts['include_all'] ) elif self.opts['reject_all']: self.reject_all(include_accepted=self.opts['include_all']) elif self.opts['delete']: self.delete(self.opts['delete']) elif self.opts['delete_all']: self.delete_all() elif self.opts['finger']: self.finger(self.opts['finger']) elif self.opts['finger_all']: self.finger_all() else: self.list_all() class MultiKeyCLI(KeyCLI): ''' Manage multiple key backends from the CLI ''' def __init__(self, opts): opts['__multi_key'] = True super(MultiKeyCLI, self).__init__(opts) # Remove the key attribute set in KeyCLI.__init__ delattr(self, 'key') zopts = copy.copy(opts) ropts = copy.copy(opts) self.keys = {} zopts['transport'] = 'zeromq' self.keys['ZMQ Keys'] = KeyCLI(zopts) ropts['transport'] = 'raet' self.keys['RAET Keys'] = KeyCLI(ropts) def _call_all(self, fun, *args): ''' Call the given function on all backend keys ''' for kback in self.keys: print(kback) getattr(self.keys[kback], fun)(*args) def list_status(self, status): self._call_all('list_status', status) def list_all(self): self._call_all('list_all') def accept(self, match, include_rejected=False): self._call_all('accept', match, include_rejected) def accept_all(self, include_rejected=False): self._call_all('accept_all', include_rejected) def delete(self, match): self._call_all('delete', match) def delete_all(self): self._call_all('delete_all') def reject(self, match, include_accepted=False): self._call_all('reject', match, include_accepted) def reject_all(self, include_accepted=False): self._call_all('reject_all', include_accepted) def print_key(self, match): self._call_all('print_key', match) def print_all(self): self._call_all('print_all') def finger(self, match): self._call_all('finger', match) def finger_all(self): self._call_all('finger_all') def prep_signature(self): self._call_all('prep_signature') class Key(object): ''' The object that encapsulates saltkey actions ''' ACC = 'minions' PEND = 'minions_pre' REJ = 'minions_rejected' DEN = 'minions_denied' def __init__(self, opts): self.opts = opts kind = self.opts.get('__role', '') # application kind if kind not in kinds.APPL_KINDS: emsg = ("Invalid application kind = '{0}'.".format(kind)) log.error(emsg + '\n') raise ValueError(emsg) self.event = salt.utils.event.get_event( kind, opts['sock_dir'], opts['transport'], opts=opts, listen=False) def _check_minions_directories(self): ''' Return the minion keys directory paths ''' minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC) minions_pre = os.path.join(self.opts['pki_dir'], self.PEND) minions_rejected = os.path.join(self.opts['pki_dir'], self.REJ) minions_denied = os.path.join(self.opts['pki_dir'], self.DEN) return minions_accepted, minions_pre, minions_rejected, minions_denied def gen_keys(self): ''' Generate minion RSA public keypair ''' salt.crypt.gen_keys( self.opts['gen_keys_dir'], self.opts['gen_keys'], self.opts['keysize']) return def gen_signature(self, privkey, pubkey, sig_path): ''' Generate master public-key-signature ''' return salt.crypt.gen_signature(privkey, pubkey, sig_path) def check_minion_cache(self, preserve_minions=None): ''' Check the minion cache to make sure that old minion data is cleared Optionally, pass in a list of minions which should have their caches preserved. To preserve all caches, set __opts__['preserve_minion_cache'] ''' if preserve_minions is None: preserve_minions = [] m_cache = os.path.join(self.opts['cachedir'], self.ACC) if not os.path.isdir(m_cache): return keys = self.list_keys() minions = [] for key, val in six.iteritems(keys): minions.extend(val) if not self.opts.get('preserve_minion_cache', False) or not preserve_minions: for minion in os.listdir(m_cache): if minion not in minions and minion not in preserve_minions: shutil.rmtree(os.path.join(m_cache, minion)) def check_master(self): ''' Log if the master is not running :rtype: bool :return: Whether or not the master is running ''' if not os.path.exists( os.path.join( self.opts['sock_dir'], 'publish_pull.ipc' ) ): return False return True def name_match(self, match, full=False): ''' Accept a glob which to match the of a key and return the key's location ''' if full: matches = self.all_keys() else: matches = self.list_keys() ret = {} if ',' in match and isinstance(match, str): match = match.split(',') for status, keys in six.iteritems(matches): for key in salt.utils.isorted(keys): if isinstance(match, list): for match_item in match: if fnmatch.fnmatch(key, match_item): if status not in ret: ret[status] = [] ret[status].append(key) else: if fnmatch.fnmatch(key, match): if status not in ret: ret[status] = [] ret[status].append(key) return ret def dict_match(self, match_dict): ''' Accept a dictionary of keys and return the current state of the specified keys ''' ret = {} cur_keys = self.list_keys() for status, keys in six.iteritems(match_dict): for key in salt.utils.isorted(keys): for keydir in (self.ACC, self.PEND, self.REJ, self.DEN): if keydir and fnmatch.filter(cur_keys.get(keydir, []), key): ret.setdefault(keydir, []).append(key) return ret def local_keys(self): ''' Return a dict of local keys ''' ret = {'local': []} for fn_ in salt.utils.isorted(os.listdir(self.opts['pki_dir'])): if fn_.endswith('.pub') or fn_.endswith('.pem'): path = os.path.join(self.opts['pki_dir'], fn_) if os.path.isfile(path): ret['local'].append(fn_) return ret def list_keys(self): ''' Return a dict of managed keys and what the key status are ''' key_dirs = [] # We have to differentiate between RaetKey._check_minions_directories # and Zeromq-Keys. Raet-Keys only have three states while ZeroMQ-keys # havd an additional 'denied' state. if self.opts['transport'] in ('zeromq', 'tcp'): key_dirs = self._check_minions_directories() else: key_dirs = self._check_minions_directories() ret = {} for dir_ in key_dirs: ret[os.path.basename(dir_)] = [] try: for fn_ in salt.utils.isorted(os.listdir(dir_)): if not fn_.startswith('.'): if os.path.isfile(os.path.join(dir_, fn_)): ret[os.path.basename(dir_)].append(fn_) except (OSError, IOError): # key dir kind is not created yet, just skip continue return ret def all_keys(self): ''' Merge managed keys with local keys ''' keys = self.list_keys() keys.update(self.local_keys()) return keys def list_status(self, match): ''' Return a dict of managed keys under a named status ''' acc, pre, rej, den = self._check_minions_directories() ret = {} if match.startswith('acc'): ret[os.path.basename(acc)] = [] for fn_ in salt.utils.isorted(os.listdir(acc)): if not fn_.startswith('.'): if os.path.isfile(os.path.join(acc, fn_)): ret[os.path.basename(acc)].append(fn_) elif match.startswith('pre') or match.startswith('un'): ret[os.path.basename(pre)] = [] for fn_ in salt.utils.isorted(os.listdir(pre)): if not fn_.startswith('.'): if os.path.isfile(os.path.join(pre, fn_)): ret[os.path.basename(pre)].append(fn_) elif match.startswith('rej'): ret[os.path.basename(rej)] = [] for fn_ in salt.utils.isorted(os.listdir(rej)): if not fn_.startswith('.'): if os.path.isfile(os.path.join(rej, fn_)): ret[os.path.basename(rej)].append(fn_) elif match.startswith('den'): ret[os.path.basename(den)] = [] for fn_ in salt.utils.isorted(os.listdir(den)): if not fn_.startswith('.'): if os.path.isfile(os.path.join(den, fn_)): ret[os.path.basename(den)].append(fn_) elif match.startswith('all'): return self.all_keys() return ret def key_str(self, match): ''' Return the specified public key or keys based on a glob ''' ret = {} for status, keys in six.iteritems(self.name_match(match)): ret[status] = {} for key in salt.utils.isorted(keys): path = os.path.join(self.opts['pki_dir'], status, key) with salt.utils.fopen(path, 'r') as fp_: ret[status][key] = fp_.read() return ret def key_str_all(self): ''' Return all managed key strings ''' ret = {} for status, keys in six.iteritems(self.list_keys()): ret[status] = {} for key in salt.utils.isorted(keys): path = os.path.join(self.opts['pki_dir'], status, key) with salt.utils.fopen(path, 'r') as fp_: ret[status][key] = fp_.read() return ret def accept(self, match=None, match_dict=None, include_rejected=False): ''' Accept public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict". ''' if match is not None: matches = self.name_match(match) elif match_dict is not None and isinstance(match_dict, dict): matches = match_dict else: matches = {} keydirs = [self.PEND] if include_rejected: keydirs.append(self.REJ) for keydir in keydirs: for key in matches.get(keydir, []): try: shutil.move( os.path.join( self.opts['pki_dir'], keydir, key), os.path.join( self.opts['pki_dir'], self.ACC, key) ) eload = {'result': True, 'act': 'accept', 'id': key} self.event.fire_event(eload, tagify(prefix='key')) except (IOError, OSError): pass return ( self.name_match(match) if match is not None else self.dict_match(matches) ) def accept_all(self): ''' Accept all keys in pre ''' keys = self.list_keys() for key in keys[self.PEND]: try: shutil.move( os.path.join( self.opts['pki_dir'], self.PEND, key), os.path.join( self.opts['pki_dir'], self.ACC, key) ) eload = {'result': True, 'act': 'accept', 'id': key} self.event.fire_event(eload, tagify(prefix='key')) except (IOError, OSError): pass return self.list_keys() def delete_key(self, match=None, match_dict=None, preserve_minions=False): ''' Delete public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict". To preserve the master caches of minions who are matched, set preserve_minions ''' if match is not None: matches = self.name_match(match) elif match_dict is not None and isinstance(match_dict, dict): matches = match_dict else: matches = {} for status, keys in six.iteritems(matches): for key in keys: try: os.remove(os.path.join(self.opts['pki_dir'], status, key)) eload = {'result': True, 'act': 'delete', 'id': key} self.event.fire_event(eload, tagify(prefix='key')) except (OSError, IOError): pass self.check_minion_cache(preserve_minions=matches.get('minions', [])) if self.opts.get('rotate_aes_key'): salt.crypt.dropfile(self.opts['cachedir'], self.opts['user']) return ( self.name_match(match) if match is not None else self.dict_match(matches) ) def delete_all(self): ''' Delete all keys ''' for status, keys in six.iteritems(self.list_keys()): for key in keys: try: os.remove(os.path.join(self.opts['pki_dir'], status, key)) eload = {'result': True, 'act': 'delete', 'id': key} self.event.fire_event(eload, tagify(prefix='key')) except (OSError, IOError): pass self.check_minion_cache() if self.opts.get('rotate_aes_key'): salt.crypt.dropfile(self.opts['cachedir'], self.opts['user']) return self.list_keys() def reject(self, match=None, match_dict=None, include_accepted=False): ''' Reject public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict". ''' if match is not None: matches = self.name_match(match) elif match_dict is not None and isinstance(match_dict, dict): matches = match_dict else: matches = {} keydirs = [self.PEND] if include_accepted: keydirs.append(self.ACC) for keydir in keydirs: for key in matches.get(keydir, []): try:<|fim▁hole|> self.opts['pki_dir'], keydir, key), os.path.join( self.opts['pki_dir'], self.REJ, key) ) eload = {'result': True, 'act': 'reject', 'id': key} self.event.fire_event(eload, tagify(prefix='key')) except (IOError, OSError): pass self.check_minion_cache() if self.opts.get('rotate_aes_key'): salt.crypt.dropfile(self.opts['cachedir'], self.opts['user']) return ( self.name_match(match) if match is not None else self.dict_match(matches) ) def reject_all(self): ''' Reject all keys in pre ''' keys = self.list_keys() for key in keys[self.PEND]: try: shutil.move( os.path.join( self.opts['pki_dir'], self.PEND, key), os.path.join( self.opts['pki_dir'], self.REJ, key) ) eload = {'result': True, 'act': 'reject', 'id': key} self.event.fire_event(eload, tagify(prefix='key')) except (IOError, OSError): pass self.check_minion_cache() if self.opts.get('rotate_aes_key'): salt.crypt.dropfile(self.opts['cachedir'], self.opts['user']) return self.list_keys() def finger(self, match): ''' Return the fingerprint for a specified key ''' matches = self.name_match(match, True) ret = {} for status, keys in six.iteritems(matches): ret[status] = {} for key in keys: if status == 'local': path = os.path.join(self.opts['pki_dir'], key) else: path = os.path.join(self.opts['pki_dir'], status, key) ret[status][key] = salt.utils.pem_finger(path, sum_type=self.opts['hash_type']) return ret def finger_all(self): ''' Return fingerprins for all keys ''' ret = {} for status, keys in six.iteritems(self.list_keys()): ret[status] = {} for key in keys: if status == 'local': path = os.path.join(self.opts['pki_dir'], key) else: path = os.path.join(self.opts['pki_dir'], status, key) ret[status][key] = salt.utils.pem_finger(path, sum_type=self.opts['hash_type']) return ret class RaetKey(Key): ''' Manage keys from the raet backend ''' ACC = 'accepted' PEND = 'pending' REJ = 'rejected' DEN = None def __init__(self, opts): Key.__init__(self, opts) self.auto_key = salt.daemons.masterapi.AutoKey(self.opts) self.serial = salt.payload.Serial(self.opts) def _check_minions_directories(self): ''' Return the minion keys directory paths ''' accepted = os.path.join(self.opts['pki_dir'], self.ACC) pre = os.path.join(self.opts['pki_dir'], self.PEND) rejected = os.path.join(self.opts['pki_dir'], self.REJ) return accepted, pre, rejected def check_minion_cache(self, preserve_minions=False): ''' Check the minion cache to make sure that old minion data is cleared ''' keys = self.list_keys() minions = [] for key, val in six.iteritems(keys): minions.extend(val) m_cache = os.path.join(self.opts['cachedir'], 'minions') if os.path.isdir(m_cache): for minion in os.listdir(m_cache): if minion not in minions: shutil.rmtree(os.path.join(m_cache, minion)) kind = self.opts.get('__role', '') # application kind if kind not in kinds.APPL_KINDS: emsg = ("Invalid application kind = '{0}'.".format(kind)) log.error(emsg + '\n') raise ValueError(emsg) role = self.opts.get('id', '') if not role: emsg = ("Invalid id.") log.error(emsg + "\n") raise ValueError(emsg) name = "{0}_{1}".format(role, kind) road_cache = os.path.join(self.opts['cachedir'], 'raet', name, 'remote') if os.path.isdir(road_cache): for road in os.listdir(road_cache): root, ext = os.path.splitext(road) if ext not in ['.json', '.msgpack']: continue prefix, sep, name = root.partition('.') if not name or prefix != 'estate': continue path = os.path.join(road_cache, road) with salt.utils.fopen(path, 'rb') as fp_: if ext == '.json': data = json.load(fp_) elif ext == '.msgpack': data = msgpack.load(fp_) if data['role'] not in minions: os.remove(path) def gen_keys(self): ''' Use libnacl to generate and safely save a private key ''' import libnacl.public d_key = libnacl.dual.DualSecret() path = '{0}.key'.format(os.path.join( self.opts['gen_keys_dir'], self.opts['gen_keys'])) d_key.save(path, 'msgpack') def check_master(self): ''' Log if the master is not running NOT YET IMPLEMENTED ''' return True def local_keys(self): ''' Return a dict of local keys ''' ret = {'local': []} fn_ = os.path.join(self.opts['pki_dir'], 'local.key') if os.path.isfile(fn_): ret['local'].append(fn_) return ret def status(self, minion_id, pub, verify): ''' Accepts the minion id, device id, curve public and verify keys. If the key is not present, put it in pending and return "pending", If the key has been accepted return "accepted" if the key should be rejected, return "rejected" ''' acc, pre, rej = self._check_minions_directories() # pylint: disable=W0632 acc_path = os.path.join(acc, minion_id) pre_path = os.path.join(pre, minion_id) rej_path = os.path.join(rej, minion_id) # open mode is turned on, force accept the key keydata = { 'minion_id': minion_id, 'pub': pub, 'verify': verify} if self.opts['open_mode']: # always accept and overwrite with salt.utils.fopen(acc_path, 'w+b') as fp_: fp_.write(self.serial.dumps(keydata)) return self.ACC if os.path.isfile(rej_path): log.debug("Rejection Reason: Keys already rejected.\n") return self.REJ elif os.path.isfile(acc_path): # The minion id has been accepted, verify the key strings with salt.utils.fopen(acc_path, 'rb') as fp_: keydata = self.serial.loads(fp_.read()) if keydata['pub'] == pub and keydata['verify'] == verify: return self.ACC else: log.debug("Rejection Reason: Keys not match prior accepted.\n") return self.REJ elif os.path.isfile(pre_path): auto_reject = self.auto_key.check_autoreject(minion_id) auto_sign = self.auto_key.check_autosign(minion_id) with salt.utils.fopen(pre_path, 'rb') as fp_: keydata = self.serial.loads(fp_.read()) if keydata['pub'] == pub and keydata['verify'] == verify: if auto_reject: self.reject(minion_id) log.debug("Rejection Reason: Auto reject pended.\n") return self.REJ elif auto_sign: self.accept(minion_id) return self.ACC return self.PEND else: log.debug("Rejection Reason: Keys not match prior pended.\n") return self.REJ # This is a new key, evaluate auto accept/reject files and place # accordingly auto_reject = self.auto_key.check_autoreject(minion_id) auto_sign = self.auto_key.check_autosign(minion_id) if self.opts['auto_accept']: w_path = acc_path ret = self.ACC elif auto_sign: w_path = acc_path ret = self.ACC elif auto_reject: w_path = rej_path log.debug("Rejection Reason: Auto reject new.\n") ret = self.REJ else: w_path = pre_path ret = self.PEND with salt.utils.fopen(w_path, 'w+b') as fp_: fp_.write(self.serial.dumps(keydata)) return ret def _get_key_str(self, minion_id, status): ''' Return the key string in the form of: pub: <pub> verify: <verify> ''' path = os.path.join(self.opts['pki_dir'], status, minion_id) with salt.utils.fopen(path, 'r') as fp_: keydata = self.serial.loads(fp_.read()) return 'pub: {0}\nverify: {1}'.format( keydata['pub'], keydata['verify']) def _get_key_finger(self, path): ''' Return a sha256 kingerprint for the key ''' with salt.utils.fopen(path, 'r') as fp_: keydata = self.serial.loads(fp_.read()) key = 'pub: {0}\nverify: {1}'.format( keydata['pub'], keydata['verify']) return hashlib.sha256(key).hexdigest() def key_str(self, match): ''' Return the specified public key or keys based on a glob ''' ret = {} for status, keys in six.iteritems(self.name_match(match)): ret[status] = {} for key in salt.utils.isorted(keys): ret[status][key] = self._get_key_str(key, status) return ret def key_str_all(self): ''' Return all managed key strings ''' ret = {} for status, keys in six.iteritems(self.list_keys()): ret[status] = {} for key in salt.utils.isorted(keys): ret[status][key] = self._get_key_str(key, status) return ret def accept(self, match=None, match_dict=None, include_rejected=False): ''' Accept public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict". ''' if match is not None: matches = self.name_match(match) elif match_dict is not None and isinstance(match_dict, dict): matches = match_dict else: matches = {} keydirs = [self.PEND] if include_rejected: keydirs.append(self.REJ) for keydir in keydirs: for key in matches.get(keydir, []): try: shutil.move( os.path.join( self.opts['pki_dir'], keydir, key), os.path.join( self.opts['pki_dir'], self.ACC, key) ) except (IOError, OSError): pass return ( self.name_match(match) if match is not None else self.dict_match(matches) ) def accept_all(self): ''' Accept all keys in pre ''' keys = self.list_keys() for key in keys[self.PEND]: try: shutil.move( os.path.join( self.opts['pki_dir'], self.PEND, key), os.path.join( self.opts['pki_dir'], self.ACC, key) ) except (IOError, OSError): pass return self.list_keys() def delete_key(self, match=None, match_dict=None, preserve_minions=False): ''' Delete public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict". ''' if match is not None: matches = self.name_match(match) elif match_dict is not None and isinstance(match_dict, dict): matches = match_dict else: matches = {} for status, keys in six.iteritems(matches): for key in keys: try: os.remove(os.path.join(self.opts['pki_dir'], status, key)) except (OSError, IOError): pass self.check_minion_cache(preserve_minions=matches.get('minions', [])) return ( self.name_match(match) if match is not None else self.dict_match(matches) ) def delete_all(self): ''' Delete all keys ''' for status, keys in six.iteritems(self.list_keys()): for key in keys: try: os.remove(os.path.join(self.opts['pki_dir'], status, key)) except (OSError, IOError): pass self.check_minion_cache() return self.list_keys() def reject(self, match=None, match_dict=None, include_accepted=False): ''' Reject public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict". ''' if match is not None: matches = self.name_match(match) elif match_dict is not None and isinstance(match_dict, dict): matches = match_dict else: matches = {} keydirs = [self.PEND] if include_accepted: keydirs.append(self.ACC) for keydir in keydirs: for key in matches.get(keydir, []): try: shutil.move( os.path.join( self.opts['pki_dir'], keydir, key), os.path.join( self.opts['pki_dir'], self.REJ, key) ) except (IOError, OSError): pass self.check_minion_cache() return ( self.name_match(match) if match is not None else self.dict_match(matches) ) def reject_all(self): ''' Reject all keys in pre ''' keys = self.list_keys() for key in keys[self.PEND]: try: shutil.move( os.path.join( self.opts['pki_dir'], self.PEND, key), os.path.join( self.opts['pki_dir'], self.REJ, key) ) except (IOError, OSError): pass self.check_minion_cache() return self.list_keys() def finger(self, match): ''' Return the fingerprint for a specified key ''' matches = self.name_match(match, True) ret = {} for status, keys in six.iteritems(matches): ret[status] = {} for key in keys: if status == 'local': path = os.path.join(self.opts['pki_dir'], key) else: path = os.path.join(self.opts['pki_dir'], status, key) ret[status][key] = self._get_key_finger(path) return ret def finger_all(self): ''' Return fingerprints for all keys ''' ret = {} for status, keys in six.iteritems(self.list_keys()): ret[status] = {} for key in keys: if status == 'local': path = os.path.join(self.opts['pki_dir'], key) else: path = os.path.join(self.opts['pki_dir'], status, key) ret[status][key] = self._get_key_finger(path) return ret def read_all_remote(self): ''' Return a dict of all remote key data ''' data = {} for status, mids in six.iteritems(self.list_keys()): for mid in mids: keydata = self.read_remote(mid, status) if keydata: keydata['acceptance'] = status data[mid] = keydata return data def read_remote(self, minion_id, status=ACC): ''' Read in a remote key of status ''' path = os.path.join(self.opts['pki_dir'], status, minion_id) if not os.path.isfile(path): return {} with salt.utils.fopen(path, 'rb') as fp_: return self.serial.loads(fp_.read()) def read_local(self): ''' Read in the local private keys, return an empy dict if the keys do not exist ''' path = os.path.join(self.opts['pki_dir'], 'local.key') if not os.path.isfile(path): return {} with salt.utils.fopen(path, 'rb') as fp_: return self.serial.loads(fp_.read()) def write_local(self, priv, sign): ''' Write the private key and the signing key to a file on disk ''' keydata = {'priv': priv, 'sign': sign} path = os.path.join(self.opts['pki_dir'], 'local.key') c_umask = os.umask(191) if os.path.exists(path): #mode = os.stat(path).st_mode os.chmod(path, stat.S_IWUSR | stat.S_IRUSR) with salt.utils.fopen(path, 'w+') as fp_: fp_.write(self.serial.dumps(keydata)) os.chmod(path, stat.S_IRUSR) os.umask(c_umask) def delete_local(self): ''' Delete the local private key file ''' path = os.path.join(self.opts['pki_dir'], 'local.key') if os.path.isfile(path): os.remove(path) def delete_pki_dir(self): ''' Delete the private key directory ''' path = self.opts['pki_dir'] if os.path.exists(path): shutil.rmtree(path)<|fim▁end|>
shutil.move( os.path.join(
<|file_name|>spectrum_analyzer.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import time import numpy as np import matplotlib matplotlib.use('GTKAgg') from matplotlib import pyplot as plt from koheron import connect from drivers import Spectrum from drivers import Laser host = os.getenv('HOST','192.168.1.100') client = connect(host, name='spectrum') driver = Spectrum(client) laser = Laser(client) laser.start() current = 30 # mA laser.set_current(current) # driver.reset_acquisition() wfm_size = 4096 decimation_factor = 1 index_low = 0 index_high = wfm_size / 2 signal = driver.get_decimated_data(decimation_factor, index_low, index_high) print('Signal') print(signal) mhz = 1e6<|fim▁hole|> # Plot parameters fig = plt.figure() ax = fig.add_subplot(111) x = np.linspace(freq_min, freq_max, (wfm_size / 2)) print('X') print(len(x)) y = 10*np.log10(signal) print('Y') print(len(y)) li, = ax.plot(x, y) fig.canvas.draw() ax.set_xlim((x[0],x[-1])) ax.set_ylim((0,200)) ax.set_xlabel('Frequency (MHz)') ax.set_ylabel('Power spectral density (dB)') while True: try: signal = driver.get_decimated_data(decimation_factor, index_low, index_high) li.set_ydata(10*np.log10(signal)) fig.canvas.draw() plt.pause(0.001) except KeyboardInterrupt: # Save last spectrum in a csv file np.savetxt("psd.csv", signal, delimiter=",") laser.stop() driver.close() break<|fim▁end|>
sampling_rate = 125e6 freq_min = 0 freq_max = sampling_rate / mhz / 2
<|file_name|>ClassNames.ts<|end_file_name|><|fim▁begin|>/** * Class names to use for display elements. */ export interface ClassNames { /** * Class name for the contents container. */ contentArea: string; /** * Class name for each menu's div. */ menu: string; /** * Class name for each menu's children container. */ menuChildren: string; /** * Class name for the inner area div. */ menusInnerArea: string; /** * Class name for a faked inner area div. */ menusInnerAreaFake: string; /** * Class name for the surrounding area div. */ menusOuterArea: string; /** * Class name for each menu title div. */ menuTitle: string; /** * Class name for an option's container. */ option: string;<|fim▁hole|> optionLeft: string; /** * Class name for the right half of a two-part option. */ optionRight: string; /** * Class name for each options container div. */ options: string; /** * Class name for each options list within its container. */ optionsList: string; } /** * Default class names to use for display elements. */ export const defaultClassNames: ClassNames = { contentArea: "content-area", menu: "menu", menuChildren: "menu-children", menuTitle: "menu-title", menusInnerArea: "menus-inner-area", menusInnerAreaFake: "menus-inner-area-fake", menusOuterArea: "menus-outer-area", option: "option", optionLeft: "option-left", optionRight: "option-right", options: "options", optionsList: "options-list", };<|fim▁end|>
/** * Class name for the left half of a two-part option. */
<|file_name|>script.js<|end_file_name|><|fim▁begin|>$(document).ready(function(){ //The user will be prompted to continue and go down the page by clicking on an HTML element //The result will be a smooth transition of the word ">>>Continue" and then a smooth scroll down the page //to the next stage of the user's process in the application: making an account(probably done through Google and Facebook) $(document).ready(function(){ $('#userPrompt>span:nth-child(1)').delay(350).fadeTo(450,1.0); $('#userPrompt>span:nth-child(2)').delay(450).fadeTo(450,1.0); $('#userPrompt>span:nth-child(3)').delay(550).fadeTo(450,1.0); //this div represents the bottom option, or the 'quick presentation div' $('#Continue').delay(700).fadeTo(850,1.0); //Continue button }); /*$('#userPrompt').click(function(){ $('#promptOverlay').fadeTo(850,0.0); $(this).delay(850).animate({marginLeft: '900px'}, 850) $(this).delay(100).fadeOut(850); }); The "#promptOverlay" div is not longer in use, and as a result, we do not need to use this line of code... Let's keep things....simpler... */ $('#userPrompt').one("click",function(){ $(this).fadeTo(850,0); //Scroll Down var height = $("#navBar").css('height'); $('html , body').animate({ scrollTop: 725 }, 1250); //Create Options on Options Bar div, first by making a dividing line $('#imagine').delay(1250).animate({ height: '330px' }); //Create Third option by making it now visible... $('#quick').delay(1850).fadeTo(300, 1); //Time to make options visible... $('.heading').delay(2000).fadeTo(300, 1); }); //With options now created, we can create some functionality to those options, making the user's experience both meaningful and aesthetically pleasing. /*$('#returner, #imagine').click(function(){ //alert("Log into account"); Test $('.heading').fadeTo(850, 0); $('#quick').fadeOut(); $('#imagine').delay(250).animate({ height: '0px' }); $('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)"); $('#optionsBar'); });*/ /*$('#newUser').one("click", function(){ //alert("Make account"); Test $('#optionsBar>div').fadeOut(850); $('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)"); var welcomeHeader = '<h3 margin-top="20px" class="heading">Welcome to ShowCase. Please Log In Below...</h3>'; var inputTypeOne = '<input type="text/plain">keep' //$('h3').delay(1900).html("Welcome to ShowCase. Please Log In Below...").appendTo("#optionsBar"); <|fim▁hole|> var styles = { fontFamily: 'Lato', color: 'rgba(16,16,14,0.65)', paddingTop: '10px', }; // $(welcomeHeader).css(headerStyle); $('#optionsBar').css(styles); });//End of Account Creation Process...* $('#quick').click(function(){ //alert("I just don't care."); Test $('.heading').fadeTo(850, 0); $('#quick').fadeOut(); $('#imagine').delay(250).animate({ height: '0px' }); $('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)"); });*/ });<|fim▁end|>
$(welcomeHeader).hide().delay(2000).appendTo('#optionsBar').fadeIn(100);
<|file_name|>setupenv_windows.py<|end_file_name|><|fim▁begin|>#----------------------------------------------------------------------------- # Copyright (c) 2013, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- # Install necessary 3rd party Python modules to run all tests. # This script is supposed to be used in a continuous integration system: # https://jenkins.shiningpanda.com/pyinstaller/ # Python there is mostly 64bit. Only Python 2.4 is 32bit on Windows 7. import glob import optparse import os import platform import sys # easy_install command used in a Python script. from setuptools.command import easy_install # Expand PYTHONPATH with PyInstaller package to support running without # installation -- only if not running in a virtualenv. if not hasattr(sys, 'real_prefix'): pyi_home = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..') sys.path.insert(0, pyi_home) from PyInstaller.compat import is_py25, is_py26 PYVER = '.'.join([str(x) for x in sys.version_info[0:2]]) def py_arch(): """ .exe installers of Python modules contain architecture name in filename. """ mapping = {'32bit': 'win32', '64bit': 'win-amd64'} arch = platform.architecture()[0] return mapping[arch] _PACKAGES = { 'docutils': ['docutils'], 'jinja2': ['jinja2'], 'sphinx': ['sphinx'], 'pytz': ['pytz'], 'IPython': ['IPython'], # 'modulename': 'pypi_name_or_url_or_path' 'MySQLdb': ['MySQL-python-*%s-py%s.exe' % (py_arch(), PYVER)], 'numpy': ['numpy-unoptimized-*%s-py%s.exe' % (py_arch(), PYVER)], 'PIL': ['PIL-*%s-py%s.exe' % (py_arch(), PYVER)], 'psycopg2': ['psycopg2-*%s-py%s.exe' % (py_arch(), PYVER)], #'pycrypto': ['pycrypto'], 'pyodbc': ['pyodbc'], #'simplejson': ['simplejson'], 'sqlalchemy': ['SQLAlchemy-*%s-py%s.exe' % (py_arch(), PYVER)], 'wx': ['wxPython-common-*%s-py%s.exe' % (py_arch(), PYVER), 'wxPython-2*%s-py%s.exe' % (py_arch(), PYVER)], # PyWin32 is installed on ShiningPanda hosting. 'win32api': ['http://downloads.sourceforge.net/project/pywin32/pywin32/Build%%20217/pywin32-217.%s-py%s.exe' % (py_arch(), PYVER)], } _PY_VERSION = { 'MySQLdb': is_py26, 'numpy': is_py26, 'PIL': is_py26, 'psycopg2': is_py26, 'simplejson': is_py25,<|fim▁hole|> 'wx': is_py26, } def main(): parser = optparse.OptionParser() parser.add_option('-d', '--download-dir', help='Directory with maually downloaded python modules.' ) opts, _ = parser.parse_args() # Install packages. for k, v in _PACKAGES.items(): # Test python version for module. if k in _PY_VERSION: # Python version too old, skip module. if PYVER < _PY_VERSION[k]: continue try: __import__(k) print 'Already installed... %s' % k # Module is not available - install it. except ImportError: # If not url or module name then look for installers in download area. if not v[0].startswith('http') and v[0].endswith('exe'): files = [] # Try all file patterns. for pattern in v: pattern = os.path.join(opts.download_dir, pattern) files += glob.glob(pattern) # No file with that pattern was not found - skip it. if not files: print 'Skipping module... %s' % k continue # Full path to installers in download directory. v = files print 'Installing module... %s' % k # Some modules might require several .exe files to install. for f in v: print ' %s' % f # Use --no-deps ... installing module dependencies might fail # because easy_install tries to install the same module from # PYPI from source code and if fails because of C code that # that needs to be compiled. try: easy_install.main(['--no-deps', '--always-unzip', f]) except Exception: print ' %s installation failed' % k if __name__ == '__main__': main()<|fim▁end|>
# Installers are available only for Python 2.6/2.7.
<|file_name|>repositoryCache.ts<|end_file_name|><|fim▁begin|>// // Copyright (c) Microsoft. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // import { EntityField} from '../../lib/entityMetadataProvider/entityMetadataProvider'; import { EntityMetadataType, IEntityMetadata } from '../../lib/entityMetadataProvider/entityMetadata'; import { IEntityMetadataFixedQuery, FixedQueryType } from '../../lib/entityMetadataProvider/query'; import { EntityMetadataMappings, MetadataMappingDefinition } from '../../lib/entityMetadataProvider/declarations'; import { PostgresGetAllEntities, PostgresJsonEntityQuery, PostgresSettings, PostgresConfiguration } from '../../lib/entityMetadataProvider/postgres'; import { stringOrNumberAsString } from '../../utils'; import { MemorySettings } from '../../lib/entityMetadataProvider/memory'; import { Operations } from '../../business/operations'; const type = new EntityMetadataType('RepositoryCache'); interface IRepositoryCacheProperties { organizationId: any; repositoryName: any; repositoryDetails: any; cacheUpdated: any; } const repositoryId = 'repositoryId'; const Field: IRepositoryCacheProperties = { organizationId: 'organizationId', repositoryName: 'repositoryName', repositoryDetails: 'repositoryDetails', cacheUpdated: 'cacheUpdated', } const fieldNames = Object.getOwnPropertyNames(Field); export class RepositoryCacheEntity implements IRepositoryCacheProperties { repositoryId: string; repositoryName: string; organizationId: string; repositoryDetails: any; cacheUpdated: Date; constructor() { this.cacheUpdated = new Date(); } hydrateToInstance(operations: Operations) { try { const organization = operations.getOrganizationById(Number(this.organizationId)); const clone = {...this.repositoryDetails}; clone.id = Number(this.repositoryId); // GitHub entities are numbers return organization.repository(this.repositoryName, clone); } catch (noConfiguredOrganization) { throw noConfiguredOrganization; } } } export class RepositoryCacheFixedQueryAll implements IEntityMetadataFixedQuery { public readonly fixedQueryType: FixedQueryType = FixedQueryType.RepositoryCacheGetAll;<|fim▁hole|>export class RepositoryCacheGetOrganizationIdsQuery implements IEntityMetadataFixedQuery { public readonly fixedQueryType: FixedQueryType = FixedQueryType.RepositoryCacheGetOrganizationIds; } export class RepositoryCacheDeleteByOrganizationId implements IEntityMetadataFixedQuery { public readonly fixedQueryType: FixedQueryType = FixedQueryType.RepositoryCacheDeleteByOrganizationId; constructor(public organizationId: string) { if (typeof(this.organizationId) !== 'string') { throw new Error(`${organizationId} must be a string`); } } } export class RepositoryCacheFixedQueryByOrganizationId implements IEntityMetadataFixedQuery { public readonly fixedQueryType: FixedQueryType = FixedQueryType.RepositoryCacheGetByOrganizationId; constructor(public organizationId: string) { if (typeof(this.organizationId) !== 'string') { throw new Error(`${organizationId} must be a string`); } } } EntityMetadataMappings.Register(type, MetadataMappingDefinition.EntityInstantiate, () => { return new RepositoryCacheEntity(); }); EntityMetadataMappings.Register(type, MetadataMappingDefinition.EntityIdColumnName, repositoryId); EntityMetadataMappings.Register(type, MemorySettings.MemoryMapping, new Map<string, string>([ [Field.organizationId, 'orgid'], [Field.repositoryName, 'repoName'], [Field.repositoryDetails, 'repoDetails'], [Field.cacheUpdated, 'cached'], ])); EntityMetadataMappings.RuntimeValidateMappings(type, MemorySettings.MemoryMapping, fieldNames, [repositoryId]); PostgresConfiguration.SetDefaultTableName(type, 'repositorycache'); EntityMetadataMappings.Register(type, PostgresSettings.PostgresDefaultTypeColumnName, 'repositorycache'); PostgresConfiguration.MapFieldsToColumnNames(type, new Map<string, string>([ [Field.organizationId, (Field.organizationId as string).toLowerCase()], // net new [Field.repositoryName, (Field.repositoryName as string).toLowerCase()], [Field.repositoryDetails, (Field.repositoryDetails as string).toLowerCase()], [Field.cacheUpdated, (Field.cacheUpdated as string).toLowerCase()], ])); PostgresConfiguration.ValidateMappings(type, fieldNames, [repositoryId]); EntityMetadataMappings.Register(type, PostgresSettings.PostgresQueries, (query: IEntityMetadataFixedQuery, mapMetadataPropertiesToFields: string[], metadataColumnName: string, tableName: string, getEntityTypeColumnValue) => { const entityTypeColumn = mapMetadataPropertiesToFields[EntityField.Type]; const entityTypeValue = getEntityTypeColumnValue(type); switch (query.fixedQueryType) { case FixedQueryType.RepositoryCacheGetAll: return PostgresGetAllEntities(tableName, entityTypeColumn, entityTypeValue); case FixedQueryType.RepositoryCacheGetByOrganizationId: { const { organizationId } = query as RepositoryCacheFixedQueryByOrganizationId; if (!organizationId) { throw new Error('organizationId required'); } return PostgresJsonEntityQuery(tableName, entityTypeColumn, entityTypeValue, metadataColumnName, { organizationid: stringOrNumberAsString(organizationId), }); } case FixedQueryType.RepositoryCacheDeleteByOrganizationId: { const { organizationId } = query as RepositoryCacheDeleteByOrganizationId; return { sql: (`DELETE FROM ${tableName} WHERE ${metadataColumnName}->>'organizationid' = $1`), values: [ organizationId ], skipEntityMapping: true, }; } case FixedQueryType.RepositoryCacheGetOrganizationIds: { return { sql: (` SELECT DISTINCT(${metadataColumnName}->>'organizationid') as organizationid FROM ${tableName}`), values: [], skipEntityMapping: true, }; } default: throw new Error(`The fixed query type "${query.fixedQueryType}" is not implemented by this provider for the type ${type}, or is of an unknown type`); } }); EntityMetadataMappings.Register(type, MemorySettings.MemoryQueries, (query: IEntityMetadataFixedQuery, allInTypeBin: IEntityMetadata[]) => { switch (query.fixedQueryType) { case FixedQueryType.RepositoryCacheGetAll: return allInTypeBin; case FixedQueryType.RepositoryCacheGetByOrganizationId: { const { organizationId } = query as RepositoryCacheFixedQueryByOrganizationId; if (!organizationId) { throw new Error('organizationId required'); } throw new Error('Not implemented yet'); } default: throw new Error(`The fixed query type "${query.fixedQueryType}" is not implemented by this provider for the type ${type}, or is of an unknown type`); } }); // Runtime validation of FieldNames for (let i = 0; i < fieldNames.length; i++) { const fn = fieldNames[i]; if (Field[fn] !== fn) { throw new Error(`Field name ${fn} and value do not match in ${__filename}`); } } export const EntityImplementation = { EnsureDefinitions: () => {}, Type: type, };<|fim▁end|>
}
<|file_name|>GetFileAndSys.C<|end_file_name|><|fim▁begin|>#include "TString.h" #include "TGraph.h" #include "TGraphErrors.h" #include "TGraphAsymmErrors.h" #include <fstream> #include <Riostream.h> #include <sstream> #include <fstream> using namespace std; TGraphErrors* GetGraphWithSymmYErrorsFromFile(TString txtFileName, Color_t markerColor=1, Style_t markerStyle=20, Size_t markerSize=1, Style_t lineStyle=1,Width_t lineWidth=2, bool IsNoErr=0) { Float_t x_array[400],ex_array[400],y_array[400],ey_array[400]; Char_t buffer[2048]; Float_t x,y,ex,ey; Int_t nlines = 0; ifstream infile(txtFileName.Data()); if (!infile.is_open()) { cout << "Error opening file. Exiting." << endl; } else { while (!infile.eof()) { infile.getline(buffer,2048); sscanf(buffer,"%f %f %f\n",&x,&y,&ey); x_array[nlines] = x; ex_array[nlines] = 0; y_array[nlines] = y; ey_array[nlines] = ey; if(IsNoErr) ey_array[nlines]=0; nlines++; } } TGraphErrors *graph = new TGraphErrors(nlines-1,x_array,y_array,ex_array,ey_array); txtFileName.Remove(txtFileName.Index(".txt"),4); graph->SetName(txtFileName.Data()); graph->SetMarkerStyle(markerStyle); graph->SetMarkerColor(markerColor); graph->SetLineStyle(lineStyle); graph->SetLineColor(markerColor); graph->SetMarkerSize(markerSize); graph->SetLineWidth(3); return graph; } void drawSysBoxValue(TGraph* gr, int fillcolor=TColor::GetColor("#ffff00"), double xwidth=0.3, double *percent, double xshift=0) { TBox* box; for(int n=0;n<gr->GetN();n++) { double x,y; gr->GetPoint(n,x,y); double yerr = percent[n];<|fim▁hole|> box->SetFillColor(kGray); box->Draw("Fsame"); } }<|fim▁end|>
box = new TBox(x+xshift-xwidth,y-fabs(yerr),x+xwidth,y+fabs(yerr)); box->SetLineWidth(0);
<|file_name|>params.js<|end_file_name|><|fim▁begin|>export default { modules: require('glob!./glob.txt'), options: { name: 'Comment',<|fim▁hole|><|fim▁end|>
}, info: true, utils: {}, };
<|file_name|>ios-minus-outline.d.ts<|end_file_name|><|fim▁begin|>import * as React from 'react'; import { IconBaseProps } from 'react-icon-base';<|fim▁hole|><|fim▁end|>
export default class IoIosMinusOutline extends React.Component<IconBaseProps, any> { }
<|file_name|>jquery-ui-accessible-tabs.js<|end_file_name|><|fim▁begin|>/* Copyright 2008-2009 University of Cambridge Copyright 2008-2009 University of Toronto Licensed under the Educational Community License (ECL), Version 2.0 or the New BSD license. You may not use this file except in compliance with one these Licenses. You may obtain a copy of the ECL 2.0 License and BSD License at https://source.fluidproject.org/svn/LICENSE.txt */ /*global jQuery*/ var fluid = fluid || {}; (function ($) { var selectOnFocus = false; // Private functions. var makeTabsSelectable = function (tablist) { var tabs = tablist.children("li"); <|fim▁hole|> // When we're using the Windows style interaction, select the tab as soon as it's focused. var selectTab = function (tabToSelect) { if (selectOnFocus) { tablist.tabs('select', tabs.index(tabToSelect)); } }; // Make the tab list selectable with the arrow keys: // * Pass in the items you want to make selectable. // * Register your onSelect callback to make the tab actually selected. // * Specify the orientation of the tabs (the default is vertical) fluid.selectable(tablist, { selectableElements: tabs, onSelect: selectTab, direction: fluid.a11y.orientation.HORIZONTAL }); // Use an activation handler if we are using the "Mac OS" style tab interaction. // In this case, we shouldn't actually select the tab until the Enter or Space key is pressed. fluid.activatable(tablist, function (tabToSelect) { if (!selectOnFocus) { tablist.tabs('select', tabs.index(tabToSelect)); } }); }; var addARIA = function (tablist, panelsId) { var tabs = tablist.children("li"); var panels = $("#" + "panels" + " > div"); // Give the container a role of tablist tablist.attr("role", "tablist"); // Each tab should have a role of Tab, // and a "position in set" property describing its order within the tab list. tabs.each (function(i, tab) { $(tab).attr("role", "tab"); }); // Give each panel a role of tabpanel panels.attr("role", "tabpanel"); // And associate each panel with its tab using the labelledby relation. panels.each (function (i, panel) { $(panel).attr("aria-labelledby", panel.id.split("Panel")[0] + "Tab"); }); }; // Public API. fluid.accessibletabs = function (tabsId, panelsId) { var tablist = $("#" + tabsId); // Remove the anchors in the list from the tab order. fluid.tabindex(tablist.find("a"), -1); // Turn the list into a jQuery UI tabs widget. tablist.tabs(); // Make them accessible. makeTabsSelectable(tablist); addARIA(tablist, panelsId); }; // When the document is loaded, initialize our tabs. $(function () { selectOnFocus = false; // Instantiate the tabs widget. fluid.accessibletabs("tabs", "panels"); // Bind the select on focus link. $("#selectOnFocusLink").click(function (evt) { selectOnFocus = !selectOnFocus; if (selectOnFocus) { $(evt.target).text("Enabled"); } else { $(evt.target).text("Disabled"); } return false; }); }); }) (jQuery);<|fim▁end|>
// Put the tablist in the tab focus order. Take each tab *out* of the tab order // so that they can be navigated with the arrow keys instead of the tab key. fluid.tabbable(tablist);
<|file_name|>core.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- "Main module defining filesystem and file classes" from __future__ import absolute_import import ctypes import logging import os import posixpath import re import warnings import operator import functools from collections import deque from .compatibility import FileNotFoundError, ConnectionError, PY3 from .conf import conf from .utils import (read_block, seek_delimiter, ensure_bytes, ensure_string, ensure_trailing_slash, MyNone) logger = logging.getLogger(__name__) _lib = None DEFAULT_READ_BUFFER_SIZE = 2 ** 16 DEFAULT_WRITE_BUFFER_SIZE = 2 ** 26 def _nbytes(buf): buf = memoryview(buf) if PY3: return buf.nbytes return buf.itemsize * functools.reduce(operator.mul, buf.shape) class HDFileSystem(object): """ Connection to an HDFS namenode >>> hdfs = HDFileSystem(host='127.0.0.1', port=8020) # doctest: +SKIP """ _first_pid = None def __init__(self, host=MyNone, port=MyNone, connect=True, autoconf=True, pars=None, **kwargs): """ Parameters ---------- host: str; port: int Overrides which take precedence over information in conf files and other passed parameters connect: bool (True) Whether to automatically attempt to establish a connection to the name-node. autoconf: bool (True) Whether to use the configuration found in the conf module as the set of defaults pars : {str: str} any parameters for hadoop, that you can find in hdfs-site.xml, https://hadoop.apache.org/docs/r2.6.0/hadoop-project-dist/hadoop-hdfs/hdfs-default.xml This dict looks exactly like the one produced by conf - you can, for example, remove any problematic entries. kwargs: key/value Further override parameters. These are applied after the default conf and pars; the most typical things to set are: host : str (localhost) namenode hostname or IP address, in case of HA mode it is name of the cluster that can be found in "fs.defaultFS" option. port : int (8020) namenode RPC port usually 8020, in HA mode port mast be None user, ticket_cache, token, effective_user : str kerberos things """ self.conf = conf.copy() if autoconf else {} if pars: self.conf.update(pars) self.conf.update(kwargs) if host is not MyNone: self.conf['host'] = host if port is not MyNone: self.conf['port'] = port self._handle = None if self.conf.get('ticket_cache') and self.conf.get('token'): m = "It is not possible to use ticket_cache and token at same time" raise RuntimeError(m) if connect: self.connect() def __getstate__(self): d = self.__dict__.copy() del d['_handle'] logger.debug("Serialize with state: %s", d) return d def __setstate__(self, state): self.__dict__.update(state) self._handle = None self.connect() def connect(self): """ Connect to the name node This happens automatically at startup """ get_lib() conf = self.conf.copy() if self._handle: return if HDFileSystem._first_pid is None: HDFileSystem._first_pid = os.getpid() elif HDFileSystem._first_pid != os.getpid(): warnings.warn("Attempting to re-use hdfs3 in child process %d, " "but it was initialized in parent process %d. " "Beware that hdfs3 is not fork-safe and this may " "lead to bugs or crashes." % (os.getpid(), HDFileSystem._first_pid), RuntimeWarning, stacklevel=2) o = _lib.hdfsNewBuilder() _lib.hdfsBuilderSetNameNode(o, ensure_bytes(conf.pop('host'))) port = conf.pop('port', None) if port is not None: _lib.hdfsBuilderSetNameNodePort(o, port) user = conf.pop('user', None) if user is not None: _lib.hdfsBuilderSetUserName(o, ensure_bytes(user)) effective_user = ensure_bytes(conf.pop('effective_user', None)) ticket_cache = conf.pop('ticket_cache', None) if ticket_cache is not None: _lib.hdfsBuilderSetKerbTicketCachePath(o, ensure_bytes(ticket_cache)) token = conf.pop('token', None) if token is not None: _lib.hdfsBuilderSetToken(o, ensure_bytes(token)) for par, val in conf.items(): if not _lib.hdfsBuilderConfSetStr(o, ensure_bytes(par), ensure_bytes(val)) == 0: warnings.warn('Setting conf parameter %s failed' % par) fs = _lib.hdfsBuilderConnect(o, effective_user) _lib.hdfsFreeBuilder(o) if fs: logger.debug("Connect to handle %d", fs.contents.filesystem) self._handle = fs else: msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise ConnectionError('Connection Failed: {}'.format(msg)) def delegate_token(self, user=None): """Generate delegate auth token. Parameters ---------- user: bytes/str User to pass to delegation (defaults to user supplied to instance); this user is the only one that can renew the token. """ if user is None and self.user is None: raise ValueError('Delegation requires a user') user = user or self.user out = _lib.hdfsGetDelegationToken(self._handle, ensure_bytes(user)) if out: self.token = out return out else: raise RuntimeError('Token delegation failed') def renew_token(self, token=None): """ Renew delegation token Parameters ---------- token: str or None If None, uses the instance's token. It is an error to do that if there is no token. Returns ------- New expiration time for the token """ token = token or self.token if token is None: raise ValueError('There is no token to renew') return _lib.hdfsRenewDelegationToken(self._handle, ensure_bytes(token)) def cancel_token(self, token=None): """ Revoke delegation token Parameters ---------- token: str or None If None, uses the instance's token. It is an error to do that if there is no token. """ token = token or self.token if token is None: raise ValueError('There is no token to cancel') out = _lib.hdfsCancelDelegationToken(self._handle, ensure_bytes(token)) if out: raise RuntimeError('Token cancel failed') if token == self.token: # now our token is invalid - this FS may not work self.token = None def disconnect(self): """ Disconnect from name node """ if self._handle: logger.debug("Disconnect from handle %d", self._handle.contents.filesystem) _lib.hdfsDisconnect(self._handle) self._handle = None def open(self, path, mode='rb', replication=0, buff=0, block_size=0): """ Open a file for reading or writing Parameters ---------- path: string Path of file on HDFS mode: string One of 'rb', 'wb', or 'ab' replication: int Replication factor; if zero, use system default (only on write) buf: int (=0) Client buffer size (bytes); if 0, use default. block_size: int Size of data-node blocks if writing """ if not self._handle: raise IOError("Filesystem not connected") if block_size and mode != 'wb': raise ValueError('Block size only valid when writing new file') if ('a' in mode and self.exists(path) and replication != 0 and replication > 1): raise IOError("Appending to an existing file with replication > 1" " is unsupported") if 'b' not in mode: raise NotImplementedError("Text mode not supported, use mode='%s'" " and manage bytes" % (mode + 'b')) return HDFile(self, path, mode, replication=replication, buff=buff, block_size=block_size) def du(self, path, total=False, deep=False): """Returns file sizes on a path. Parameters ---------- path : string where to look total : bool (False) to add up the sizes to a grand total deep : bool (False) whether to recurse into subdirectories """ fi = self.ls(path, True) if deep: for apath in fi: if apath['kind'] == 'directory': fi.extend(self.ls(apath['name'], True)) if total: return {path: sum(f['size'] for f in fi)} return {p['name']: p['size'] for p in fi} def df(self): """ Used/free disc space on the HDFS system """ cap = _lib.hdfsGetCapacity(self._handle) used = _lib.hdfsGetUsed(self._handle) return {'capacity': cap, 'used': used, 'percent-free': 100 * (cap - used) / cap} def get_block_locations(self, path, start=0, length=0): """ Fetch physical locations of blocks """ if not self._handle: raise IOError("Filesystem not connected") start = int(start) or 0 length = int(length) or self.info(path)['size'] nblocks = ctypes.c_int(0) out = _lib.hdfsGetFileBlockLocations(self._handle, ensure_bytes(path), ctypes.c_int64(start), ctypes.c_int64(length), ctypes.byref(nblocks)) locs = [] for i in range(nblocks.value): block = out[i] hosts = [block.hosts[i] for i in range(block.numOfNodes)] locs.append({'hosts': hosts, 'length': block.length, 'offset': block.offset}) _lib.hdfsFreeFileBlockLocations(out, nblocks) return locs def info(self, path): """ File information (as a dict) """ if not self.exists(path): raise FileNotFoundError(path) fi = _lib.hdfsGetPathInfo(self._handle, ensure_bytes(path)).contents out = fi.to_dict() _lib.hdfsFreeFileInfo(ctypes.byref(fi), 1) return out def isdir(self, path): """Return True if path refers to an existing directory.""" try: info = self.info(path) return info['kind'] == 'directory' except EnvironmentError: return False def isfile(self, path): """Return True if path refers to an existing file.""" try: info = self.info(path) return info['kind'] == 'file' except EnvironmentError: return False def walk(self, path): """Directory tree generator, see ``os.walk``""" full_dirs = [] dirs = [] files = [] for info in self.ls(path, True): name = info['name'] tail = posixpath.split(name)[1] if info['kind'] == 'directory': full_dirs.append(name) dirs.append(tail) else: files.append(tail) yield path, dirs, files for d in full_dirs: for res in self.walk(d): yield res def glob(self, path): """ Get list of paths mathing glob-like pattern (i.e., with "*"s). If passed a directory, gets all contained files; if passed path to a file, without any "*", returns one-element list containing that filename. Does not support python3.5's "**" notation. """ path = ensure_string(path) try: f = self.info(path) if f['kind'] == 'directory' and '*' not in path: path = ensure_trailing_slash(path) + '*' else: return [f['name']] except IOError: pass if '/' in path[:path.index('*')]: ind = path[:path.index('*')].rindex('/') root = path[:ind + 1] else: root = '/' allpaths = [] for dirname, dirs, fils in self.walk(root): allpaths.extend(posixpath.join(dirname, d) for d in dirs) allpaths.extend(posixpath.join(dirname, f) for f in fils) pattern = re.compile("^" + path.replace('//', '/') .rstrip('/') .replace('*', '[^/]*') .replace('?', '.') + "$") return [p for p in allpaths if pattern.match(p.replace('//', '/').rstrip('/'))] def ls(self, path, detail=False): """ List files at path Parameters ---------- path : string/bytes location at which to list files detail : bool (=True) if True, each list item is a dict of file properties; otherwise, returns list of filenames """ if not self.exists(path): raise FileNotFoundError(path) num = ctypes.c_int(0) fi = _lib.hdfsListDirectory(self._handle, ensure_bytes(path), ctypes.byref(num)) out = [fi[i].to_dict() for i in range(num.value)] _lib.hdfsFreeFileInfo(fi, num.value) if detail: return out else: return [o['name'] for o in out] @property def host(self): return self.conf.get('host', '') @property def port(self): return self.conf.get('port', '') def __repr__(self): if self._handle is None: state = 'Disconnected' else: state = 'Connected' return 'hdfs://%s:%s, %s' % (self.host, self.port, state) def __del__(self): if self._handle: self.disconnect() def mkdir(self, path): """ Make directory at path """ out = _lib.hdfsCreateDirectory(self._handle, ensure_bytes(path)) if out != 0: msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise IOError('Create directory failed: {}'.format(msg)) def makedirs(self, path, mode=0o711): """ Create directory together with any necessary intermediates """ out = _lib.hdfsCreateDirectoryEx(self._handle, ensure_bytes(path), ctypes.c_short(mode), 1) if out != 0: msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise IOError('Create directory failed: {}'.format(msg)) def set_replication(self, path, replication): """ Instruct HDFS to set the replication for the given file. If successful, the head-node's table is updated immediately, but actual copying will be queued for later. It is acceptable to set a replication that cannot be supported (e.g., higher than the number of data-nodes). """ if replication < 0: raise ValueError('Replication must be positive,' ' or 0 for system default') out = _lib.hdfsSetReplication(self._handle, ensure_bytes(path), ctypes.c_int16(int(replication))) if out != 0: msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise IOError('Set replication failed: {}'.format(msg)) def mv(self, path1, path2): """ Move file at path1 to path2 """ if not self.exists(path1): raise FileNotFoundError(path1) out = _lib.hdfsRename(self._handle, ensure_bytes(path1), ensure_bytes(path2)) return out == 0 def concat(self, destination, paths): """Concatenate inputs to destination Source files *should* all have the same block size and replication. The destination file must be in the same directory as the source files. If the target exists, it will be appended to. Some HDFSs impose that the target file must exist and be an exact number of blocks long, and that each concated file except the last is also a whole number of blocks. The source files are deleted on successful completion. """ if not self.exists(destination): self.touch(destination) arr = (ctypes.c_char_p * (len(paths) + 1))() arr[:-1] = [ensure_bytes(s) for s in paths] arr[-1] = ctypes.c_char_p() # NULL pointer out = _lib.hdfsConcat(self._handle, ensure_bytes(destination), arr) if out != 0: msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise IOError('Concat failed on %s %s' % (destination, msg)) def rm(self, path, recursive=True): "Use recursive for `rm -r`, i.e., delete directory and contents" if not self.exists(path): raise FileNotFoundError(path) out = _lib.hdfsDelete(self._handle, ensure_bytes(path), bool(recursive)) if out != 0: msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise IOError('Remove failed on %s %s' % (path, msg)) def exists(self, path): """ Is there an entry at path? """ out = _lib.hdfsExists(self._handle, ensure_bytes(path)) return out == 0 def chmod(self, path, mode): """Change access control of given path Exactly what permissions the file will get depends on HDFS configurations. Parameters ---------- path : string file/directory to change mode : integer As with the POSIX standard, each octal digit refers to user-group-all, in that order, with read-write-execute as the bits of each group. Examples -------- Make read/writeable to all >>> hdfs.chmod('/path/to/file', 0o777) # doctest: +SKIP Make read/writeable only to user >>> hdfs.chmod('/path/to/file', 0o700) # doctest: +SKIP Make read-only to user >>> hdfs.chmod('/path/to/file', 0o100) # doctest: +SKIP """ if not self.exists(path): raise FileNotFoundError(path) out = _lib.hdfsChmod(self._handle, ensure_bytes(path), ctypes.c_short(mode)) if out != 0: msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise IOError("chmod failed on %s %s" % (path, msg)) def chown(self, path, owner, group): """ Change owner/group """ if not self.exists(path): raise FileNotFoundError(path) out = _lib.hdfsChown(self._handle, ensure_bytes(path), ensure_bytes(owner), ensure_bytes(group)) if out != 0: msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise IOError("chown failed on %s %s" % (path, msg)) def cat(self, path): """ Return contents of file """ if not self.exists(path): raise FileNotFoundError(path) with self.open(path, 'rb') as f: result = f.read() return result def get(self, hdfs_path, local_path, blocksize=DEFAULT_READ_BUFFER_SIZE): """ Copy HDFS file to local """ # TODO: _lib.hdfsCopy() may do this more efficiently if not self.exists(hdfs_path): raise FileNotFoundError(hdfs_path) with self.open(hdfs_path, 'rb') as f: with open(local_path, 'wb') as f2: out = 1 while out: out = f.read(blocksize) f2.write(out) def getmerge(self, path, filename, blocksize=DEFAULT_READ_BUFFER_SIZE): """ Concat all files in path (a directory) to local output file """ files = self.ls(path) with open(filename, 'wb') as f2: for apath in files: with self.open(apath, 'rb') as f: out = 1 while out: out = f.read(blocksize) f2.write(out) def put(self, filename, path, chunk=DEFAULT_WRITE_BUFFER_SIZE, replication=0, block_size=0): """ Copy local file to path in HDFS """ with self.open(path, 'wb', replication=replication, block_size=block_size) as target: with open(filename, 'rb') as source: while True: out = source.read(chunk) if len(out) == 0: break target.write(out) def tail(self, path, size=1024): """ Return last bytes of file """ length = self.du(path)[ensure_trailing_slash(path)] if size > length: return self.cat(path) with self.open(path, 'rb') as f: f.seek(length - size) return f.read(size) def head(self, path, size=1024): """ Return first bytes of file """ with self.open(path, 'rb') as f: return f.read(size) def touch(self, path): """ Create zero-length file """ self.open(path, 'wb').close() def read_block(self, fn, offset, length, delimiter=None): """ Read a block of bytes from an HDFS file Starting at ``offset`` of the file, read ``length`` bytes. If ``delimiter`` is set then we ensure that the read starts and stops at delimiter boundaries that follow the locations ``offset`` and ``offset + length``. If ``offset`` is zero then we start at zero. The bytestring returned will not include the surrounding delimiter strings. If offset+length is beyond the eof, reads to eof. Parameters ---------- fn: string Path to filename on HDFS offset: int Byte offset to start read length: int Number of bytes to read delimiter: bytes (optional) Ensure reading starts and stops at delimiter bytestring Examples -------- >>> hdfs.read_block('/data/file.csv', 0, 13) # doctest: +SKIP b'Alice, 100\\nBo' >>> hdfs.read_block('/data/file.csv', 0, 13, delimiter=b'\\n') # doctest: +SKIP b'Alice, 100\\nBob, 200' See Also -------- hdfs3.utils.read_block """ with self.open(fn, 'rb') as f: size = f.info()['size'] if offset + length > size: length = size - offset bytes = read_block(f, offset, length, delimiter) return bytes def list_encryption_zones(self): """Get list of all the encryption zones""" x = ctypes.c_int(8) out = _lib.hdfsListEncryptionZones(self._handle, x) if not out: msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise IOError("EZ listing failed: %s" % msg) <|fim▁hole|> def create_encryption_zone(self, path, key_name): out = _lib.hdfsCreateEncryptionZone(self._handle, ensure_bytes(path), ensure_bytes(key_name)) if out != 0: msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise IOError("EZ create failed: %s %s" % (path, msg)) def get_lib(): """ Import C-lib only on demand """ global _lib if _lib is None: from .lib import _lib as l _lib = l mode_numbers = {'w': 1, 'r': 0, 'a': 1025, 'wb': 1, 'rb': 0, 'ab': 1025} class HDFile(object): """ File on HDFS Matches the standard Python file interface. Examples -------- >>> with hdfs.open('/path/to/hdfs/file.txt') as f: # doctest: +SKIP ... bytes = f.read(1000) # doctest: +SKIP >>> with hdfs.open('/path/to/hdfs/file.csv') as f: # doctest: +SKIP ... df = pd.read_csv(f, nrows=1000) # doctest: +SKIP """ def __init__(self, fs, path, mode, replication=0, buff=0, block_size=0): """ Called by open on a HDFileSystem """ if 't' in mode: raise NotImplementedError("Opening a file in text mode is not" " supported, use ``io.TextIOWrapper``.") self.fs = fs self.path = path self.replication = replication self.buff = buff self._fs = fs._handle self.buffers = [] self._handle = None self.mode = mode self.block_size = block_size self.lines = deque([]) self._set_handle() self.size = self.info()['size'] def _set_handle(self): out = _lib.hdfsOpenFile(self._fs, ensure_bytes(self.path), mode_numbers[self.mode], self.buff, ctypes.c_short(self.replication), ctypes.c_int64(self.block_size)) if not out: msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise IOError("Could not open file: %s, mode: %s %s" % (self.path, self.mode, msg)) self._handle = out def readinto(self, length, out): """ Read up to ``length`` bytes from the file into the ``out`` buffer, which can be of any type that implements the buffer protocol (example: ``bytearray``, ``memoryview`` (py3 only), numpy array, ...). Parameters ---------- length : int maximum number of bytes to read out : buffer where to write the output data Returns ------- int number of bytes read """ if not _lib.hdfsFileIsOpenForRead(self._handle): raise IOError('File not in read mode') bufsize = length bufpos = 0 # convert from buffer protocol to ctypes-compatible type buflen = _nbytes(out) buf_for_ctypes = (ctypes.c_byte * buflen).from_buffer(out) while length: bufp = ctypes.byref(buf_for_ctypes, bufpos) ret = _lib.hdfsRead( self._fs, self._handle, bufp, ctypes.c_int32(bufsize - bufpos)) if ret == 0: # EOF break if ret > 0: length -= ret bufpos += ret else: raise IOError('Read file %s Failed:' % self.path, -ret) return bufpos def read(self, length=None, out_buffer=None): """ Read up to ``length`` bytes from the file. Reads shorter than ``length`` only occur at the end of the file, if less data is available. If ``out_buffer`` is given, read directly into ``out_buffer``. It can be anything that implements the buffer protocol, for example ``bytearray``, ``memoryview`` (py3 only), numpy arrays, ... Parameters ---------- length : int number of bytes to read. if it is None, read all remaining bytes from the current position. out_buffer : buffer, None or True the buffer to use as output, None to return bytes, True to create and return new buffer Returns ------- bytes the data read (only if out_buffer is None) memoryview the data read as a memoryview into the buffer """ return_buffer = out_buffer is not None max_read = self.size - self.tell() read_length = max_read if length in [None, -1] else length read_length = min(max_read, read_length) if out_buffer is None or out_buffer is True: out_buffer = bytearray(read_length) else: if _nbytes(out_buffer) < read_length: raise IOError('buffer too small (%d < %d)' % (_nbytes(out_buffer), read_length)) bytes_read = self.readinto(length=read_length, out=out_buffer) if bytes_read < _nbytes(out_buffer): out_buffer = memoryview(out_buffer)[:bytes_read] if return_buffer: return memoryview(out_buffer) return memoryview(out_buffer).tobytes() def readline(self, chunksize=0, lineterminator='\n'): """ Return a line using buffered reading. A line is a sequence of bytes between ``'\n'`` markers (or given line-terminator). Line iteration uses this method internally. Note: this function requires many calls to HDFS and is slow; it is in general better to wrap an HDFile with an ``io.TextIOWrapper`` for buffering, text decoding and newline support. """ if chunksize == 0: chunksize = self.buff if self.buff != 0 else DEFAULT_READ_BUFFER_SIZE lineterminator = ensure_bytes(lineterminator) start = self.tell() seek_delimiter(self, lineterminator, chunksize, allow_zero=False) end = self.tell() self.seek(start) return self.read(end - start) def _genline(self): while True: out = self.readline() if out: yield out else: raise StopIteration def __iter__(self): """ Enables `for line in file:` usage """ return self._genline() def __next__(self): """ Enables reading a file as a buffer in pandas """ out = self.readline() if out: return out else: raise StopIteration # PY2 compatibility next = __next__ def readlines(self): """ Return all lines in a file as a list """ return list(self) def tell(self): """ Get current byte location in a file """ out = _lib.hdfsTell(self._fs, self._handle) if out == -1: msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise IOError('Tell Failed on file %s %s' % (self.path, msg)) return out def seek(self, offset, from_what=0): """ Set file read position. Read mode only. Attempt to move out of file bounds raises an exception. Note that, by the convention in python file seek, offset should be <=0 if from_what is 2. Parameters ---------- offset : int byte location in the file. from_what : int 0, 1, 2 if 0 (befault), relative to file start; if 1, relative to current location; if 2, relative to file end. Returns ------- new position """ if from_what not in {0, 1, 2}: raise ValueError('seek mode must be 0, 1 or 2') info = self.info() if from_what == 1: offset = offset + self.tell() elif from_what == 2: offset = info['size'] + offset if offset < 0 or offset > info['size']: raise ValueError('Attempt to seek outside file') out = _lib.hdfsSeek(self._fs, self._handle, ctypes.c_int64(offset)) if out == -1: # pragma: no cover msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise IOError('Seek Failed on file %s' % (self.path, msg)) return self.tell() def info(self): """ Filesystem metadata about this file """ return self.fs.info(self.path) def write(self, data): """ Write bytes to open file (which must be in w or a mode) """ data = ensure_bytes(data) if not data: return if not _lib.hdfsFileIsOpenForWrite(self._handle): msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise IOError('File not write mode: {}'.format(msg)) write_block = self.buff if self.buff != 0 else DEFAULT_WRITE_BUFFER_SIZE for offset in range(0, len(data), write_block): d = ensure_bytes(data[offset:offset + write_block]) if not _lib.hdfsWrite(self._fs, self._handle, d, len(d)) == len(d): msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0] raise IOError('Write failed on file %s, %s' % (self.path, msg)) return len(data) def flush(self): """ Send buffer to the data-node; actual write may happen later """ _lib.hdfsFlush(self._fs, self._handle) def close(self): """ Flush and close file, ensuring the data is readable """ self.flush() _lib.hdfsCloseFile(self._fs, self._handle) self._handle = None # _libhdfs releases memory self.mode = 'closed' @property def read1(self): return self.read @property def closed(self): return self.mode == 'closed' def writable(self): return self.mode.startswith('w') or self.mode.startswith('a') def seekable(self): return self.readable() def readable(self): return self.mode.startswith('r') def __del__(self): self.close() def __repr__(self): return 'hdfs://%s:%s%s, %s' % (self.fs.host, self.fs.port, self.path, self.mode) def __enter__(self): return self def __exit__(self, *args): self.close()<|fim▁end|>
res = [out[i].to_dict() for i in range(x.value)] if res: _lib.hdfsFreeEncryptionZoneInfo(out, x) return res
<|file_name|>dates_finished.py<|end_file_name|><|fim▁begin|># # Example file for working with date information # (For Python 3.x, be sure to use the ExampleSnippets3.txt file) from datetime import date from datetime import time from datetime import datetime def main(): ## DATE OBJECTS # Get today's date from the simple today() method from the date class today = date.today() print "Today's date is ", today # print out the date's individual components<|fim▁hole|> # retrieve today's weekday (0=Monday, 6=Sunday) print "Today's Weekday #: ", today.weekday() ## DATETIME OBJECTS # Get today's date from the datetime class today = datetime.now() print "The current date and time is ", today # Get the current time t = datetime.time(datetime.now()) print "The current time is ", t # weekday returns 0 (monday) through 6 (sunday) wd = date.weekday(today) # Days start at 0 for Monday days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"] print "Today is day number %d" % wd print "Which is a " + days[wd] if __name__ == "__main__": main();<|fim▁end|>
print "Date Components: ", today.day, today.month, today.year
<|file_name|>logger.py<|end_file_name|><|fim▁begin|># Higgins - A multi-media server # Copyright (c) 2007-2009 Michael Frank <[email protected]> # # This program is free software; for license information see # the COPYING file.<|fim▁hole|>from higgins.logger import Loggable class UPnPLogger(Loggable): log_domain = "upnp" logger = UPnPLogger()<|fim▁end|>
<|file_name|>data.py<|end_file_name|><|fim▁begin|>## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <[email protected]> ## This program is published under a GPLv2 license import re from dadict import DADict from error import log_loading ############ ## Consts ## ############ ETHER_ANY = "\x00"*6 ETHER_BROADCAST = "\xff"*6 ETH_P_ALL = 3 ETH_P_IP = 0x800 ETH_P_ARP = 0x806 ETH_P_IPV6 = 0x86dd # From net/if_arp.h ARPHDR_ETHER = 1 ARPHDR_METRICOM = 23 ARPHDR_PPP = 512 ARPHDR_LOOPBACK = 772 ARPHDR_TUN = 65534 # From net/ipv6.h on Linux (+ Additions) IPV6_ADDR_UNICAST = 0x01 IPV6_ADDR_MULTICAST = 0x02 IPV6_ADDR_CAST_MASK = 0x0F IPV6_ADDR_LOOPBACK = 0x10 IPV6_ADDR_GLOBAL = 0x00 IPV6_ADDR_LINKLOCAL = 0x20 IPV6_ADDR_SITELOCAL = 0x40 # deprecated since Sept. 2004 by RFC 3879 IPV6_ADDR_SCOPE_MASK = 0xF0 #IPV6_ADDR_COMPATv4 = 0x80 # deprecated; i.e. ::/96 #IPV6_ADDR_MAPPED = 0x1000 # i.e.; ::ffff:0.0.0.0/96 IPV6_ADDR_6TO4 = 0x0100 # Added to have more specific info (should be 0x0101 ?) IPV6_ADDR_UNSPECIFIED = 0x10000 MTU = 1600 # file parsing to get some values : def load_protocols(filename): spaces = re.compile("[ \t]+|\n") dct = DADict(_name=filename) try: for l in open(filename): try: shrp = l.find("#") if shrp >= 0: l = l[:shrp] l = l.strip() if not l: continue lt = tuple(re.split(spaces, l)) if len(lt) < 2 or not lt[0]: continue dct[lt[0]] = int(lt[1]) except Exception,e: log_loading.info("Couldn't parse file [%s]: line [%r] (%s)" % (filename,l,e)) except IOError: log_loading.info("Can't open /etc/protocols file") return dct IP_PROTOS=load_protocols("/etc/protocols") def load_ethertypes(filename): spaces = re.compile("[ \t]+|\n") dct = DADict(_name=filename) try: f=open(filename) for l in f: try: shrp = l.find("#") if shrp >= 0: l = l[:shrp] l = l.strip() if not l: continue lt = tuple(re.split(spaces, l)) if len(lt) < 2 or not lt[0]: continue dct[lt[0]] = int(lt[1], 16) except Exception,e: log_loading.info("Couldn't parse file [%s]: line [%r] (%s)" % (filename,l,e)) f.close() except IOError,msg: pass return dct ETHER_TYPES=load_ethertypes("/etc/ethertypes") def load_services(filename): spaces = re.compile("[ \t]+|\n") tdct=DADict(_name="%s-tcp"%filename) udct=DADict(_name="%s-udp"%filename) try: f=open(filename) for l in f: try: shrp = l.find("#") if shrp >= 0: l = l[:shrp] l = l.strip() if not l: continue lt = tuple(re.split(spaces, l)) if len(lt) < 2 or not lt[0]: continue if lt[1].endswith("/tcp"): tdct[lt[0]] = int(lt[1].split('/')[0]) elif lt[1].endswith("/udp"): udct[lt[0]] = int(lt[1].split('/')[0]) except Exception,e: log_loading.warning("Couldn't file [%s]: line [%r] (%s)" % (filename,l,e)) f.close() except IOError: log_loading.info("Can't open /etc/services file") return tdct,udct TCP_SERVICES,UDP_SERVICES=load_services("/etc/services") class ManufDA(DADict): def fixname(self, val): return val def _get_manuf_couple(self, mac): oui = ":".join(mac.split(":")[:3]).upper() return self.__dict__.get(oui,(mac,mac)) def _get_manuf(self, mac): return self._get_manuf_couple(mac)[1] def _get_short_manuf(self, mac): return self._get_manuf_couple(mac)[0] def _resolve_MAC(self, mac): oui = ":".join(mac.split(":")[:3]).upper() if oui in self: return ":".join([self[oui][0]]+ mac.split(":")[3:]) return mac<|fim▁hole|> def load_manuf(filename): try: manufdb=ManufDA(_name=filename) for l in open(filename): try: l = l.strip() if not l or l.startswith("#"): continue oui,shrt=l.split()[:2] i = l.find("#") if i < 0: lng=shrt else: lng = l[i+2:] manufdb[oui] = shrt,lng except Exception,e: log_loading.warning("Couldn't parse one line from [%s] [%r] (%s)" % (filename, l, e)) except IOError: #log_loading.warning("Couldn't open [%s] file" % filename) pass return manufdb ##################### ## knowledge bases ## ##################### class KnowledgeBase: def __init__(self, filename): self.filename = filename self.base = None def lazy_init(self): self.base = "" def reload(self, filename = None): if filename is not None: self.filename = filename oldbase = self.base self.base = None self.lazy_init() if self.base is None: self.base = oldbase def get_base(self): if self.base is None: self.lazy_init() return self.base<|fim▁end|>
<|file_name|>request_redraw_threaded.rs<|end_file_name|><|fim▁begin|>use std::{thread, time}; use simple_logger::SimpleLogger; use winit::{ event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, };<|fim▁hole|>fn main() { SimpleLogger::new().init().unwrap(); let event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_title("A fantastic window!") .build(&event_loop) .unwrap(); thread::spawn(move || loop { thread::sleep(time::Duration::from_secs(1)); window.request_redraw(); }); event_loop.run(move |event, _, control_flow| { println!("{:?}", event); *control_flow = ControlFlow::Wait; match event { Event::WindowEvent { event, .. } => match event { WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, _ => (), }, Event::RedrawRequested(_) => { println!("\nredrawing!\n"); } _ => (), } }); }<|fim▁end|>