text
stringlengths
2
1.04M
meta
dict
<div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">Willkommen bei DimeERP</h3> </div> <div class="box-body"> <a routerLink="/timetrack/track" class="btn btn-primary">Zeiterfassung</a> </div> </div>
{ "content_hash": "a3c87a4d18d0aae541a73b6f628e1007", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 78, "avg_line_length": 31.375, "alnum_prop": 0.6613545816733067, "repo_name": "stiftungswo/Dime", "id": "212a3d8a0dc50129167cf6fb6dec062682b8d069", "size": "251", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Dime/FrontendBundle/Resources/public/lib/src/component/main/welcome_component.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5126" }, { "name": "CSS", "bytes": "4914" }, { "name": "Dart", "bytes": "334314" }, { "name": "Dockerfile", "bytes": "1590" }, { "name": "HTML", "bytes": "152174" }, { "name": "Makefile", "bytes": "5624" }, { "name": "PHP", "bytes": "977400" }, { "name": "Python", "bytes": "7839" }, { "name": "Shell", "bytes": "10120" } ], "symlink_target": "" }
using System; using System.Linq; using Entities; using ItsaRepository.Interfaces; using ServiceInterfaces; namespace Services { public class AdminService : IAdminService { private readonly IPostRepository _repository; public AdminService(IPostRepository repository) { _repository = repository; } public Post AddBlogPost(Post entry) { return _repository.Create(entry); } public void DeleteBlogPost(Guid id) { var post = (from e in _repository.Entities where e.Id == id select e).FirstOrDefault(); _repository.Delete(post); } } }
{ "content_hash": "98327cfdfc85ccf68f58f8b74629b0d2", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 55, "avg_line_length": 23.193548387096776, "alnum_prop": 0.5785813630041725, "repo_name": "kevinrjones/Itsa", "id": "d013699d99d80639a7983d44f62f7deee84d047b", "size": "719", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Services/AdminService.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "98" }, { "name": "C#", "bytes": "290375" }, { "name": "JavaScript", "bytes": "3892814" }, { "name": "PowerShell", "bytes": "100" } ], "symlink_target": "" }
from ubuntu:trusty MAINTAINER Charlie Lewis <charliel@lab41.org> ENV REFRESHED_AT 2014-07-07 RUN sed 's/main$/main universe/' -i /etc/apt/sources.list RUN sed 's/us-east-1.ec2.archive.ubuntu.com/nova.clouds.archive.ubuntu.com/' -i /etc/apt/sources.list RUN apt-get update RUN apt-get install -y software-properties-common python-software-properties RUN add-apt-repository ppa:ubuntu-toolchain-r/test RUN apt-get update RUN apt-get install -y build-essential \ c++-4.7 \ git \ g++-4.7 \ npm \ python-matplotlib \ python-mysqldb \ python-numpy \ python-scipy \ python-setuptools RUN easy_install pip RUN npm config set registry http://registry.npmjs.org/ RUN npm install tty.js # sets root password to password, but isn't accessible from the outside RUN echo 'mysql-server-5.5 mysql-server/root_password password password' | debconf-set-selections RUN echo 'mysql-server-5.5 mysql-server/root_password_again password password' | debconf-set-selections RUN apt-get update && apt-get install -y mysql-server && apt-get clean && rm -rf /var/lib/apt/lists/* ENV REDWOOD_PULLED_AT 2014-06-24 RUN git clone https://github.com/Lab41/Redwood.git ADD visual.py /Redwood/redwood/helpers/visual.py ADD redwood /Redwood/bin/redwood RUN rm -rf /Redwood/Filters/file_types.py RUN mkdir /Redwood/mysql RUN mkdir -p /Redwood/reports/output/reports RUN mv /Redwood/reports/resources /Redwood/reports/output/reports/resources RUN cd /Redwood; python setup.py install ADD . /src ADD favicon.ico /node_modules/tty.js/static/favicon.ico ADD index.html /node_modules/tty.js/static/index.html ADD tty.js /node_modules/tty.js/bin/tty.js # add rsyslog RUN sed 's/#\$ModLoad imudp/\$ModLoad imudp/' -i /etc/rsyslog.conf RUN sed 's/#\$UDPServerRun 514/\$UDPServerRun 514/' -i /etc/rsyslog.conf # use non root user RUN touch /etc/rsyslog.d/50-default.conf RUN echo "mysql ALL=NOPASSWD: /etc/init.d/rsyslog start" >> /etc/sudoers RUN chown -R mysql /Redwood /src /node_modules/tty.js /etc/rsyslog.d/50-default.conf USER mysql EXPOSE 8000 CMD printf "*.*\t@$REMOTE_HOST" >> /etc/rsyslog.d/50-default.conf; \ sudo /etc/init.d/rsyslog start; \ logger started redwood container $PARENT_HOST; \ /src/startup.sh
{ "content_hash": "701ba88024a5583b11806c84a0ef9140", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 103, "avg_line_length": 38.17460317460318, "alnum_prop": 0.6902286902286903, "repo_name": "kfoss/try41", "id": "11590f7526dce7088f36346b5b679942213a239f", "size": "2405", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dockerfiles/redwood/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.apache.calcite.plan; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.convert.ConverterRule; import org.apache.calcite.rel.metadata.RelMetadataQuery; import org.apache.calcite.util.Pair; import org.apache.calcite.util.graph.DefaultDirectedGraph; import org.apache.calcite.util.graph.DefaultEdge; import org.apache.calcite.util.graph.DirectedGraph; import org.apache.calcite.util.graph.Graphs; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import java.util.List; /** * Definition of the convention trait. * A new set of conversion information is created for * each planner that registers at least one {@link ConverterRule} instance. * * <p>Conversion data is held in a {@link LoadingCache} * with weak keys so that the JVM's garbage * collector may reclaim the conversion data after the planner itself has been * garbage collected. The conversion information consists of a graph of * conversions (from one calling convention to another) and a map of graph arcs * to {@link ConverterRule}s. */ public class ConventionTraitDef extends RelTraitDef<Convention> { //~ Static fields/initializers --------------------------------------------- public static final ConventionTraitDef INSTANCE = new ConventionTraitDef(); //~ Instance fields -------------------------------------------------------- /** * Weak-key cache of RelOptPlanner to ConversionData. The idea is that when * the planner goes away, so does the cache entry. */ private final LoadingCache<RelOptPlanner, ConversionData> conversionCache = CacheBuilder.newBuilder().weakKeys() .build(CacheLoader.from(ConversionData::new)); //~ Constructors ----------------------------------------------------------- private ConventionTraitDef() { super(); } //~ Methods ---------------------------------------------------------------- // implement RelTraitDef public Class<Convention> getTraitClass() { return Convention.class; } public String getSimpleName() { return "convention"; } public Convention getDefault() { return Convention.NONE; } public void registerConverterRule( RelOptPlanner planner, ConverterRule converterRule) { if (converterRule.isGuaranteed()) { ConversionData conversionData = getConversionData(planner); final Convention inConvention = (Convention) converterRule.getInTrait(); final Convention outConvention = (Convention) converterRule.getOutTrait(); conversionData.conversionGraph.addVertex(inConvention); conversionData.conversionGraph.addVertex(outConvention); conversionData.conversionGraph.addEdge(inConvention, outConvention); conversionData.mapArcToConverterRule.put( Pair.of(inConvention, outConvention), converterRule); } } public void deregisterConverterRule( RelOptPlanner planner, ConverterRule converterRule) { if (converterRule.isGuaranteed()) { ConversionData conversionData = getConversionData(planner); final Convention inConvention = (Convention) converterRule.getInTrait(); final Convention outConvention = (Convention) converterRule.getOutTrait(); final boolean removed = conversionData.conversionGraph.removeEdge( inConvention, outConvention); assert removed; conversionData.mapArcToConverterRule.remove( Pair.of(inConvention, outConvention), converterRule); } } // implement RelTraitDef public RelNode convert( RelOptPlanner planner, RelNode rel, Convention toConvention, boolean allowInfiniteCostConverters) { final RelMetadataQuery mq = rel.getCluster().getMetadataQuery(); final ConversionData conversionData = getConversionData(planner); final Convention fromConvention = rel.getConvention(); List<List<Convention>> conversionPaths = conversionData.getPaths(fromConvention, toConvention); loop: for (List<Convention> conversionPath : conversionPaths) { assert conversionPath.get(0) == fromConvention; assert conversionPath.get(conversionPath.size() - 1) == toConvention; RelNode converted = rel; Convention previous = null; for (Convention arc : conversionPath) { if (planner.getCost(converted, mq).isInfinite() && !allowInfiniteCostConverters) { continue loop; } if (previous != null) { converted = changeConvention( converted, previous, arc, conversionData.mapArcToConverterRule); if (converted == null) { throw new AssertionError("Converter from " + previous + " to " + arc + " guaranteed that it could convert any relexp"); } } previous = arc; } return converted; } return null; } /** * Tries to convert a relational expression to the target convention of an * arc. */ private RelNode changeConvention( RelNode rel, Convention source, Convention target, final Multimap<Pair<Convention, Convention>, ConverterRule> mapArcToConverterRule) { assert source == rel.getConvention(); // Try to apply each converter rule for this arc's source/target calling // conventions. final Pair<Convention, Convention> key = Pair.of(source, target); for (ConverterRule rule : mapArcToConverterRule.get(key)) { assert rule.getInTrait() == source; assert rule.getOutTrait() == target; RelNode converted = rule.convert(rel); if (converted != null) { return converted; } } return null; } public boolean canConvert( RelOptPlanner planner, Convention fromConvention, Convention toConvention) { ConversionData conversionData = getConversionData(planner); return fromConvention.canConvertConvention(toConvention) || conversionData.getShortestPath(fromConvention, toConvention) != null; } private ConversionData getConversionData(RelOptPlanner planner) { return conversionCache.getUnchecked(planner); } //~ Inner Classes ---------------------------------------------------------- /** Workspace for converting from one convention to another. */ private static final class ConversionData { final DirectedGraph<Convention, DefaultEdge> conversionGraph = DefaultDirectedGraph.create(); /** * For a given source/target convention, there may be several possible * conversion rules. Maps {@link DefaultEdge} to a * collection of {@link ConverterRule} objects. */ final Multimap<Pair<Convention, Convention>, ConverterRule> mapArcToConverterRule = HashMultimap.create(); private Graphs.FrozenGraph<Convention, DefaultEdge> pathMap; public List<List<Convention>> getPaths( Convention fromConvention, Convention toConvention) { return getPathMap().getPaths(fromConvention, toConvention); } private Graphs.FrozenGraph<Convention, DefaultEdge> getPathMap() { if (pathMap == null) { pathMap = Graphs.makeImmutable(conversionGraph); } return pathMap; } public List<Convention> getShortestPath( Convention fromConvention, Convention toConvention) { return getPathMap().getShortestPath(fromConvention, toConvention); } } }
{ "content_hash": "c4cc9e013d6743ca3527b61df8d7f0a3", "timestamp": "", "source": "github", "line_count": 228, "max_line_length": 87, "avg_line_length": 33.45614035087719, "alnum_prop": 0.6739643418982695, "repo_name": "googleinterns/calcite", "id": "13a4ad97f8d79b0c29a8fff6eda4792ff206c894", "size": "8425", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/org/apache/calcite/plan/ConventionTraitDef.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3674" }, { "name": "CSS", "bytes": "36583" }, { "name": "FreeMarker", "bytes": "359111" }, { "name": "HTML", "bytes": "28321" }, { "name": "Java", "bytes": "19344166" }, { "name": "Kotlin", "bytes": "150911" }, { "name": "PigLatin", "bytes": "1419" }, { "name": "Python", "bytes": "1610" }, { "name": "Ruby", "bytes": "1807" }, { "name": "Shell", "bytes": "7078" }, { "name": "TSQL", "bytes": "1761" } ], "symlink_target": "" }
using TpDotNetCore.Controllers; namespace TpDotNetCore.Domain.Punches.Repositories { public interface IWeekPunchRepository : IBasePunchRepository<WeekPunch, WeekResponse, string> { WeekResponse GetWeek(string userId, double? week, double? year); } }
{ "content_hash": "7098fba5a1a86ba377d967579c4ef696", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 97, "avg_line_length": 30, "alnum_prop": 0.7666666666666667, "repo_name": "htschan/Tp", "id": "0f1ab169ccd401720f8153ce3278feeec873637d", "size": "270", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TpDotNetCore/Domain/Punches/Repositories/IWeekPunchRepository.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "399" }, { "name": "C#", "bytes": "236122" }, { "name": "CSS", "bytes": "60969" }, { "name": "HTML", "bytes": "60660" }, { "name": "JavaScript", "bytes": "13940" }, { "name": "PowerShell", "bytes": "397" }, { "name": "SCSS", "bytes": "10299" }, { "name": "TypeScript", "bytes": "691692" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "ba12bd3a9aecdeafa873316379b1d4e2", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "f928f5814ff8eda41ea0ba4e11407e45c7a55c0e", "size": "195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Iridaceae/Romulea/Romulea columnae/Romulea columnae grandiscapa/Romulea hartungii montana/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright 2005-2014 Red Hat, Inc. Red Hat 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.jboss.jube.images</groupId> <artifactId>parent-project</artifactId> <version>2.0.0-SNAPSHOT</version> </parent> <groupId>org.jboss.jube.images.examples</groupId> <artifactId>parent-project</artifactId> <packaging>pom</packaging> <name>Jube :: Images :: Examples</name> <properties> </properties> <modules> <module>cxf-cdi</module> </modules> </project>
{ "content_hash": "e376292773641c8b5d39a1756b4d680b", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 108, "avg_line_length": 32.97560975609756, "alnum_prop": 0.6974852071005917, "repo_name": "rajdavies/jube", "id": "cbbe55777551544570570570d3b8ebf189e42759", "size": "1352", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "images/examples/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// +k8s:deepcopy-gen=package,register // +groupName=kubeadm.k8s.io package kubeadm
{ "content_hash": "5a376e3a4775890ce806b6380711c873", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 37, "avg_line_length": 17, "alnum_prop": 0.7529411764705882, "repo_name": "mtcode/autoscaler", "id": "3c49375b7673a31bef32eff6b32a6d7ae1cc769f", "size": "654", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cluster-autoscaler/vendor/k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/doc.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "737060" }, { "name": "Makefile", "bytes": "5445" }, { "name": "Python", "bytes": "18053" }, { "name": "Shell", "bytes": "13264" } ], "symlink_target": "" }
layout: post title: "Pour avoir préféré le crime de l’illégalité au crime de l’inhumanité" category: vrac --- > Nous nous souvenions de quinze années de sacrifices inutiles, de quinze années d’abus de confiance et de reniement. Nous nous souvenions de l’évacuation de la Haute-Région, des villageois accrochés à nos camions, qui, à bout de forces, tombaient en pleurant dans la poussière de la route. Nous nous souvenions de Diên Biên Phû, de l’entrée du Vietminh à Hanoï. Nous nous souvenions de la stupeur et du mépris de nos camarades de combat vietnamiens en apprenant notre départ du Tonkin. Nous nous souvenions des villages abandonnés par nous et dont les habitants avaient été massacrés. Nous nous souvenions des milliers de Tonkinois se jetant à la mer pour rejoindre les bateaux français. Nous pensions à toutes ces promesses solennelles faites sur cette terre d’Afrique. Nous pensions à tous ces hommes, à toutes ces femmes, à tous ces jeunes qui avaient choisi la France à cause de nous et qui, à cause de nous, risquaient chaque jour, à chaque instant, une mort affreuse. Nous pensions à ces inscriptions qui recouvrent les murs de tous ces villages et mechtas d’Algérie : "L’Armée nous protégera, l’armée restera". > > Nous pensions à notre honneur perdu Extrait de la plaidorie du commandant Hélie Denoix de Saint Marc devant le haut tribunal militaire, 5 juin 1961.
{ "content_hash": "63736b0a70827105024771ae9b4a3dee", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 119, "avg_line_length": 64.77272727272727, "alnum_prop": 0.775438596491228, "repo_name": "jbfavre/jbfavre.org", "id": "2ac09d40c015fe96aee18e2fe1ed4a8d4dca4a58", "size": "1489", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/fr/2013-08-26-Pour-avoir-prefere-le-crime-de-illegalite-au-crime-de-inhumanite.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "25328" }, { "name": "HTML", "bytes": "30805" }, { "name": "JavaScript", "bytes": "2987" }, { "name": "Ruby", "bytes": "37955" } ], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package de.dplatz.padersprinter.control; import de.dplatz.padersprinter.control.LocationService.HttpClient; import de.dplatz.padersprinter.entity.Location; import java.io.IOException; import java.io.InputStream; import java.util.List; import static java.util.stream.Stream.empty; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.ws.rs.core.Response; import org.hamcrest.CoreMatchers; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Rule; import org.mockito.Matchers; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; /** * * @author daniel.platz */ @Ignore public class LocationServiceTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); final private LocationService cut = new LocationService(); @Test public void searchLocations() throws IOException { Response response = multiResponse(); HttpClient httpClientMock = mock(HttpClient.class); when(httpClientMock.get(Matchers.anyObject())).thenReturn(response); cut.httpClient = httpClientMock; List<Location> locations = cut.searchOriginLocations("Paderborn") .toList() .toBlocking() .single(); assertThat(locations, is(not(empty()))); assertThat(locations, CoreMatchers.hasItem(hasProperty("name", is("Paderborn, Almeweg")))); } @Test public void searchLocationsWithUnqiueResult() throws IOException { Response response = singleResponse(); HttpClient httpClientMock = mock(HttpClient.class); when(httpClientMock.get(Matchers.anyObject())).thenReturn(response); cut.httpClient = httpClientMock; Location single = cut.searchOriginLocations("Paderborn Hbf") .toBlocking() .single(); assertThat(single.getName(), is("Paderborn, Paderborn Hbf")); } private Response multiResponse() throws IOException { try (InputStream is = LocationServiceTest.class.getResourceAsStream("/ajax-multi-response.json")) { JsonArray jsonArray = Json.createReader(is).readArray(); Response response = mock(Response.class); when(response.getStatus()).thenReturn(200); when(response.readEntity(JsonArray.class)).thenReturn(jsonArray); return response; } } private Response singleResponse() throws IOException { try (InputStream is = LocationServiceTest.class.getResourceAsStream("/ajax-single-response.json")) { JsonObject jsonObject = Json.createReader(is).readObject(); Response response = mock(Response.class); when(response.getStatus()).thenReturn(200); when(response.readEntity(JsonArray.class)).thenThrow(new ClassCastException()); when(response.readEntity(JsonObject.class)).thenReturn(jsonObject); return response; } } }
{ "content_hash": "ec5fe7fa00b15fe6c5aacf50c18fbba7", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 108, "avg_line_length": 37.33684210526316, "alnum_prop": 0.6791654919650408, "repo_name": "38leinaD/padersprinter-query", "id": "bda0fbeb6f1bd82b24027f0d0d1634e92e442d27", "size": "3547", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/de/dplatz/padersprinter/control/LocationServiceTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "106079" }, { "name": "Java", "bytes": "48021" } ], "symlink_target": "" }
// Copyright 2018 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // An open-addressing // hashtable with quadratic probing. // // This is a low level hashtable on top of which different interfaces can be // implemented, like flat_hash_set, node_hash_set, string_hash_set, etc. // // The table interface is similar to that of std::unordered_set. Notable // differences are that most member functions support heterogeneous keys when // BOTH the hash and eq functions are marked as transparent. They do so by // providing a typedef called `is_transparent`. // // When heterogeneous lookup is enabled, functions that take key_type act as if // they have an overload set like: // // iterator find(const key_type& key); // template <class K> // iterator find(const K& key); // // size_type erase(const key_type& key); // template <class K> // size_type erase(const K& key); // // std::pair<iterator, iterator> equal_range(const key_type& key); // template <class K> // std::pair<iterator, iterator> equal_range(const K& key); // // When heterogeneous lookup is disabled, only the explicit `key_type` overloads // exist. // // find() also supports passing the hash explicitly: // // iterator find(const key_type& key, size_t hash); // template <class U> // iterator find(const U& key, size_t hash); // // In addition the pointer to element and iterator stability guarantees are // weaker: all iterators and pointers are invalidated after a new element is // inserted. // // IMPLEMENTATION DETAILS // // The table stores elements inline in a slot array. In addition to the slot // array the table maintains some control state per slot. The extra state is one // byte per slot and stores empty or deleted marks, or alternatively 7 bits from // the hash of an occupied slot. The table is split into logical groups of // slots, like so: // // Group 1 Group 2 Group 3 // +---------------+---------------+---------------+ // | | | | | | | | | | | | | | | | | | | | | | | | | // +---------------+---------------+---------------+ // // On lookup the hash is split into two parts: // - H2: 7 bits (those stored in the control bytes) // - H1: the rest of the bits // The groups are probed using H1. For each group the slots are matched to H2 in // parallel. Because H2 is 7 bits (128 states) and the number of slots per group // is low (8 or 16) in almost all cases a match in H2 is also a lookup hit. // // On insert, once the right group is found (as in lookup), its slots are // filled in order. // // On erase a slot is cleared. In case the group did not have any empty slots // before the erase, the erased slot is marked as deleted. // // Groups without empty slots (but maybe with deleted slots) extend the probe // sequence. The probing algorithm is quadratic. Given N the number of groups, // the probing function for the i'th probe is: // // P(0) = H1 % N // // P(i) = (P(i - 1) + i) % N // // This probing function guarantees that after N probes, all the groups of the // table will be probed exactly once. #ifndef ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_ #define ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_ #include <algorithm> #include <cmath> #include <cstdint> #include <cstring> #include <iterator> #include <limits> #include <memory> #include <tuple> #include <type_traits> #include <utility> #include "absl/base/internal/bits.h" #include "absl/base/internal/endian.h" #include "absl/base/optimization.h" #include "absl/base/port.h" #include "absl/container/internal/common.h" #include "absl/container/internal/compressed_tuple.h" #include "absl/container/internal/container_memory.h" #include "absl/container/internal/hash_policy_traits.h" #include "absl/container/internal/hashtable_debug_hooks.h" #include "absl/container/internal/hashtablez_sampler.h" #include "absl/container/internal/have_sse.h" #include "absl/container/internal/layout.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" #include "absl/utility/utility.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { template <size_t Width> class probe_seq { public: probe_seq(size_t hash, size_t mask) { assert(((mask + 1) & mask) == 0 && "not a mask"); mask_ = mask; offset_ = hash & mask_; } size_t offset() const { return offset_; } size_t offset(size_t i) const { return (offset_ + i) & mask_; } void next() { index_ += Width; offset_ += index_; offset_ &= mask_; } // 0-based probe index. The i-th probe in the probe sequence. size_t index() const { return index_; } private: size_t mask_; size_t offset_; size_t index_ = 0; }; template <class ContainerKey, class Hash, class Eq> struct RequireUsableKey { template <class PassedKey, class... Args> std::pair< decltype(std::declval<const Hash&>()(std::declval<const PassedKey&>())), decltype(std::declval<const Eq&>()(std::declval<const ContainerKey&>(), std::declval<const PassedKey&>()))>* operator()(const PassedKey&, const Args&...) const; }; template <class E, class Policy, class Hash, class Eq, class... Ts> struct IsDecomposable : std::false_type {}; template <class Policy, class Hash, class Eq, class... Ts> struct IsDecomposable< absl::void_t<decltype( Policy::apply(RequireUsableKey<typename Policy::key_type, Hash, Eq>(), std::declval<Ts>()...))>, Policy, Hash, Eq, Ts...> : std::true_type {}; // TODO(alkis): Switch to std::is_nothrow_swappable when gcc/clang supports it. template <class T> constexpr bool IsNoThrowSwappable() { using std::swap; return noexcept(swap(std::declval<T&>(), std::declval<T&>())); } template <typename T> int TrailingZeros(T x) { return sizeof(T) == 8 ? base_internal::CountTrailingZerosNonZero64( static_cast<uint64_t>(x)) : base_internal::CountTrailingZerosNonZero32( static_cast<uint32_t>(x)); } template <typename T> int LeadingZeros(T x) { return sizeof(T) == 8 ? base_internal::CountLeadingZeros64(static_cast<uint64_t>(x)) : base_internal::CountLeadingZeros32(static_cast<uint32_t>(x)); } // An abstraction over a bitmask. It provides an easy way to iterate through the // indexes of the set bits of a bitmask. When Shift=0 (platforms with SSE), // this is a true bitmask. On non-SSE, platforms the arithematic used to // emulate the SSE behavior works in bytes (Shift=3) and leaves each bytes as // either 0x00 or 0x80. // // For example: // for (int i : BitMask<uint32_t, 16>(0x5)) -> yields 0, 2 // for (int i : BitMask<uint64_t, 8, 3>(0x0000000080800000)) -> yields 2, 3 template <class T, int SignificantBits, int Shift = 0> class BitMask { static_assert(std::is_unsigned<T>::value, ""); static_assert(Shift == 0 || Shift == 3, ""); public: // These are useful for unit tests (gunit). using value_type = int; using iterator = BitMask; using const_iterator = BitMask; explicit BitMask(T mask) : mask_(mask) {} BitMask& operator++() { mask_ &= (mask_ - 1); return *this; } explicit operator bool() const { return mask_ != 0; } int operator*() const { return LowestBitSet(); } int LowestBitSet() const { return container_internal::TrailingZeros(mask_) >> Shift; } int HighestBitSet() const { return (sizeof(T) * CHAR_BIT - container_internal::LeadingZeros(mask_) - 1) >> Shift; } BitMask begin() const { return *this; } BitMask end() const { return BitMask(0); } int TrailingZeros() const { return container_internal::TrailingZeros(mask_) >> Shift; } int LeadingZeros() const { constexpr int total_significant_bits = SignificantBits << Shift; constexpr int extra_bits = sizeof(T) * 8 - total_significant_bits; return container_internal::LeadingZeros(mask_ << extra_bits) >> Shift; } private: friend bool operator==(const BitMask& a, const BitMask& b) { return a.mask_ == b.mask_; } friend bool operator!=(const BitMask& a, const BitMask& b) { return a.mask_ != b.mask_; } T mask_; }; using ctrl_t = signed char; using h2_t = uint8_t; // The values here are selected for maximum performance. See the static asserts // below for details. enum Ctrl : ctrl_t { kEmpty = -128, // 0b10000000 kDeleted = -2, // 0b11111110 kSentinel = -1, // 0b11111111 }; static_assert( kEmpty & kDeleted & kSentinel & 0x80, "Special markers need to have the MSB to make checking for them efficient"); static_assert(kEmpty < kSentinel && kDeleted < kSentinel, "kEmpty and kDeleted must be smaller than kSentinel to make the " "SIMD test of IsEmptyOrDeleted() efficient"); static_assert(kSentinel == -1, "kSentinel must be -1 to elide loading it from memory into SIMD " "registers (pcmpeqd xmm, xmm)"); static_assert(kEmpty == -128, "kEmpty must be -128 to make the SIMD check for its " "existence efficient (psignb xmm, xmm)"); static_assert(~kEmpty & ~kDeleted & kSentinel & 0x7F, "kEmpty and kDeleted must share an unset bit that is not shared " "by kSentinel to make the scalar test for MatchEmptyOrDeleted() " "efficient"); static_assert(kDeleted == -2, "kDeleted must be -2 to make the implementation of " "ConvertSpecialToEmptyAndFullToDeleted efficient"); // A single block of empty control bytes for tables without any slots allocated. // This enables removing a branch in the hot path of find(). inline ctrl_t* EmptyGroup() { alignas(16) static constexpr ctrl_t empty_group[] = { kSentinel, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty}; return const_cast<ctrl_t*>(empty_group); } // Mixes a randomly generated per-process seed with `hash` and `ctrl` to // randomize insertion order within groups. bool ShouldInsertBackwards(size_t hash, ctrl_t* ctrl); // Returns a hash seed. // // The seed consists of the ctrl_ pointer, which adds enough entropy to ensure // non-determinism of iteration order in most cases. inline size_t HashSeed(const ctrl_t* ctrl) { // The low bits of the pointer have little or no entropy because of // alignment. We shift the pointer to try to use higher entropy bits. A // good number seems to be 12 bits, because that aligns with page size. return reinterpret_cast<uintptr_t>(ctrl) >> 12; } inline size_t H1(size_t hash, const ctrl_t* ctrl) { return (hash >> 7) ^ HashSeed(ctrl); } inline ctrl_t H2(size_t hash) { return hash & 0x7F; } inline bool IsEmpty(ctrl_t c) { return c == kEmpty; } inline bool IsFull(ctrl_t c) { return c >= 0; } inline bool IsDeleted(ctrl_t c) { return c == kDeleted; } inline bool IsEmptyOrDeleted(ctrl_t c) { return c < kSentinel; } #if ABSL_INTERNAL_RAW_HASH_SET_HAVE_SSE2 // https://github.com/abseil/abseil-cpp/issues/209 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87853 // _mm_cmpgt_epi8 is broken under GCC with -funsigned-char // Work around this by using the portable implementation of Group // when using -funsigned-char under GCC. inline __m128i _mm_cmpgt_epi8_fixed(__m128i a, __m128i b) { #if defined(__GNUC__) && !defined(__clang__) if (std::is_unsigned<char>::value) { const __m128i mask = _mm_set1_epi8(0x80); const __m128i diff = _mm_subs_epi8(b, a); return _mm_cmpeq_epi8(_mm_and_si128(diff, mask), mask); } #endif return _mm_cmpgt_epi8(a, b); } struct GroupSse2Impl { static constexpr size_t kWidth = 16; // the number of slots per group explicit GroupSse2Impl(const ctrl_t* pos) { ctrl = _mm_loadu_si128(reinterpret_cast<const __m128i*>(pos)); } // Returns a bitmask representing the positions of slots that match hash. BitMask<uint32_t, kWidth> Match(h2_t hash) const { auto match = _mm_set1_epi8(hash); return BitMask<uint32_t, kWidth>( _mm_movemask_epi8(_mm_cmpeq_epi8(match, ctrl))); } // Returns a bitmask representing the positions of empty slots. BitMask<uint32_t, kWidth> MatchEmpty() const { #if ABSL_INTERNAL_RAW_HASH_SET_HAVE_SSSE3 // This only works because kEmpty is -128. return BitMask<uint32_t, kWidth>( _mm_movemask_epi8(_mm_sign_epi8(ctrl, ctrl))); #else return Match(static_cast<h2_t>(kEmpty)); #endif } // Returns a bitmask representing the positions of empty or deleted slots. BitMask<uint32_t, kWidth> MatchEmptyOrDeleted() const { auto special = _mm_set1_epi8(kSentinel); return BitMask<uint32_t, kWidth>( _mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl))); } // Returns the number of trailing empty or deleted elements in the group. uint32_t CountLeadingEmptyOrDeleted() const { auto special = _mm_set1_epi8(kSentinel); return TrailingZeros( _mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl)) + 1); } void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const { auto msbs = _mm_set1_epi8(static_cast<char>(-128)); auto x126 = _mm_set1_epi8(126); #if ABSL_INTERNAL_RAW_HASH_SET_HAVE_SSSE3 auto res = _mm_or_si128(_mm_shuffle_epi8(x126, ctrl), msbs); #else auto zero = _mm_setzero_si128(); auto special_mask = _mm_cmpgt_epi8_fixed(zero, ctrl); auto res = _mm_or_si128(msbs, _mm_andnot_si128(special_mask, x126)); #endif _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), res); } __m128i ctrl; }; #endif // ABSL_INTERNAL_RAW_HASH_SET_HAVE_SSE2 struct GroupPortableImpl { static constexpr size_t kWidth = 8; explicit GroupPortableImpl(const ctrl_t* pos) : ctrl(little_endian::Load64(pos)) {} BitMask<uint64_t, kWidth, 3> Match(h2_t hash) const { // For the technique, see: // http://graphics.stanford.edu/~seander/bithacks.html##ValueInWord // (Determine if a word has a byte equal to n). // // Caveat: there are false positives but: // - they only occur if there is a real match // - they never occur on kEmpty, kDeleted, kSentinel // - they will be handled gracefully by subsequent checks in code // // Example: // v = 0x1716151413121110 // hash = 0x12 // retval = (v - lsbs) & ~v & msbs = 0x0000000080800000 constexpr uint64_t msbs = 0x8080808080808080ULL; constexpr uint64_t lsbs = 0x0101010101010101ULL; auto x = ctrl ^ (lsbs * hash); return BitMask<uint64_t, kWidth, 3>((x - lsbs) & ~x & msbs); } BitMask<uint64_t, kWidth, 3> MatchEmpty() const { constexpr uint64_t msbs = 0x8080808080808080ULL; return BitMask<uint64_t, kWidth, 3>((ctrl & (~ctrl << 6)) & msbs); } BitMask<uint64_t, kWidth, 3> MatchEmptyOrDeleted() const { constexpr uint64_t msbs = 0x8080808080808080ULL; return BitMask<uint64_t, kWidth, 3>((ctrl & (~ctrl << 7)) & msbs); } uint32_t CountLeadingEmptyOrDeleted() const { constexpr uint64_t gaps = 0x00FEFEFEFEFEFEFEULL; return (TrailingZeros(((~ctrl & (ctrl >> 7)) | gaps) + 1) + 7) >> 3; } void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const { constexpr uint64_t msbs = 0x8080808080808080ULL; constexpr uint64_t lsbs = 0x0101010101010101ULL; auto x = ctrl & msbs; auto res = (~x + (x >> 7)) & ~lsbs; little_endian::Store64(dst, res); } uint64_t ctrl; }; #if ABSL_INTERNAL_RAW_HASH_SET_HAVE_SSE2 using Group = GroupSse2Impl; #else using Group = GroupPortableImpl; #endif template <class Policy, class Hash, class Eq, class Alloc> class raw_hash_set; inline bool IsValidCapacity(size_t n) { return ((n + 1) & n) == 0 && n > 0; } // PRECONDITION: // IsValidCapacity(capacity) // ctrl[capacity] == kSentinel // ctrl[i] != kSentinel for all i < capacity // Applies mapping for every byte in ctrl: // DELETED -> EMPTY // EMPTY -> EMPTY // FULL -> DELETED inline void ConvertDeletedToEmptyAndFullToDeleted( ctrl_t* ctrl, size_t capacity) { assert(ctrl[capacity] == kSentinel); assert(IsValidCapacity(capacity)); for (ctrl_t* pos = ctrl; pos != ctrl + capacity + 1; pos += Group::kWidth) { Group{pos}.ConvertSpecialToEmptyAndFullToDeleted(pos); } // Copy the cloned ctrl bytes. std::memcpy(ctrl + capacity + 1, ctrl, Group::kWidth); ctrl[capacity] = kSentinel; } // Rounds up the capacity to the next power of 2 minus 1, with a minimum of 1. inline size_t NormalizeCapacity(size_t n) { return n ? ~size_t{} >> LeadingZeros(n) : 1; } // We use 7/8th as maximum load factor. // For 16-wide groups, that gives an average of two empty slots per group. inline size_t CapacityToGrowth(size_t capacity) { assert(IsValidCapacity(capacity)); // `capacity*7/8` if (Group::kWidth == 8 && capacity == 7) { // x-x/8 does not work when x==7. return 6; } return capacity - capacity / 8; } // From desired "growth" to a lowerbound of the necessary capacity. // Might not be a valid one and required NormalizeCapacity(). inline size_t GrowthToLowerboundCapacity(size_t growth) { // `growth*8/7` if (Group::kWidth == 8 && growth == 7) { // x+(x-1)/7 does not work when x==7. return 8; } return growth + static_cast<size_t>((static_cast<int64_t>(growth) - 1) / 7); } // Policy: a policy defines how to perform different operations on // the slots of the hashtable (see hash_policy_traits.h for the full interface // of policy). // // Hash: a (possibly polymorphic) functor that hashes keys of the hashtable. The // functor should accept a key and return size_t as hash. For best performance // it is important that the hash function provides high entropy across all bits // of the hash. // // Eq: a (possibly polymorphic) functor that compares two keys for equality. It // should accept two (of possibly different type) keys and return a bool: true // if they are equal, false if they are not. If two keys compare equal, then // their hash values as defined by Hash MUST be equal. // // Allocator: an Allocator [https://devdocs.io/cpp/concept/allocator] with which // the storage of the hashtable will be allocated and the elements will be // constructed and destroyed. template <class Policy, class Hash, class Eq, class Alloc> class raw_hash_set { using PolicyTraits = hash_policy_traits<Policy>; using KeyArgImpl = KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>; public: using init_type = typename PolicyTraits::init_type; using key_type = typename PolicyTraits::key_type; // TODO(sbenza): Hide slot_type as it is an implementation detail. Needs user // code fixes! using slot_type = typename PolicyTraits::slot_type; using allocator_type = Alloc; using size_type = size_t; using difference_type = ptrdiff_t; using hasher = Hash; using key_equal = Eq; using policy_type = Policy; using value_type = typename PolicyTraits::value_type; using reference = value_type&; using const_reference = const value_type&; using pointer = typename absl::allocator_traits< allocator_type>::template rebind_traits<value_type>::pointer; using const_pointer = typename absl::allocator_traits< allocator_type>::template rebind_traits<value_type>::const_pointer; // Alias used for heterogeneous lookup functions. // `key_arg<K>` evaluates to `K` when the functors are transparent and to // `key_type` otherwise. It permits template argument deduction on `K` for the // transparent case. template <class K> using key_arg = typename KeyArgImpl::template type<K, key_type>; private: // Give an early error when key_type is not hashable/eq. auto KeyTypeCanBeHashed(const Hash& h, const key_type& k) -> decltype(h(k)); auto KeyTypeCanBeEq(const Eq& eq, const key_type& k) -> decltype(eq(k, k)); using Layout = absl::container_internal::Layout<ctrl_t, slot_type>; static Layout MakeLayout(size_t capacity) { assert(IsValidCapacity(capacity)); return Layout(capacity + Group::kWidth + 1, capacity); } using AllocTraits = absl::allocator_traits<allocator_type>; using SlotAlloc = typename absl::allocator_traits< allocator_type>::template rebind_alloc<slot_type>; using SlotAllocTraits = typename absl::allocator_traits< allocator_type>::template rebind_traits<slot_type>; static_assert(std::is_lvalue_reference<reference>::value, "Policy::element() must return a reference"); template <typename T> struct SameAsElementReference : std::is_same<typename std::remove_cv< typename std::remove_reference<reference>::type>::type, typename std::remove_cv< typename std::remove_reference<T>::type>::type> {}; // An enabler for insert(T&&): T must be convertible to init_type or be the // same as [cv] value_type [ref]. // Note: we separate SameAsElementReference into its own type to avoid using // reference unless we need to. MSVC doesn't seem to like it in some // cases. template <class T> using RequiresInsertable = typename std::enable_if< absl::disjunction<std::is_convertible<T, init_type>, SameAsElementReference<T>>::value, int>::type; // RequiresNotInit is a workaround for gcc prior to 7.1. // See https://godbolt.org/g/Y4xsUh. template <class T> using RequiresNotInit = typename std::enable_if<!std::is_same<T, init_type>::value, int>::type; template <class... Ts> using IsDecomposable = IsDecomposable<void, PolicyTraits, Hash, Eq, Ts...>; public: static_assert(std::is_same<pointer, value_type*>::value, "Allocators with custom pointer types are not supported"); static_assert(std::is_same<const_pointer, const value_type*>::value, "Allocators with custom pointer types are not supported"); class iterator { friend class raw_hash_set; public: using iterator_category = std::forward_iterator_tag; using value_type = typename raw_hash_set::value_type; using reference = absl::conditional_t<PolicyTraits::constant_iterators::value, const value_type&, value_type&>; using pointer = absl::remove_reference_t<reference>*; using difference_type = typename raw_hash_set::difference_type; iterator() {} // PRECONDITION: not an end() iterator. reference operator*() const { assert_is_full(); return PolicyTraits::element(slot_); } // PRECONDITION: not an end() iterator. pointer operator->() const { return &operator*(); } // PRECONDITION: not an end() iterator. iterator& operator++() { assert_is_full(); ++ctrl_; ++slot_; skip_empty_or_deleted(); return *this; } // PRECONDITION: not an end() iterator. iterator operator++(int) { auto tmp = *this; ++*this; return tmp; } friend bool operator==(const iterator& a, const iterator& b) { a.assert_is_valid(); b.assert_is_valid(); return a.ctrl_ == b.ctrl_; } friend bool operator!=(const iterator& a, const iterator& b) { return !(a == b); } private: iterator(ctrl_t* ctrl, slot_type* slot) : ctrl_(ctrl), slot_(slot) { // This assumption helps the compiler know that any non-end iterator is // not equal to any end iterator. ABSL_INTERNAL_ASSUME(ctrl != nullptr); } void assert_is_full() const { ABSL_HARDENING_ASSERT(ctrl_ != nullptr && IsFull(*ctrl_)); } void assert_is_valid() const { ABSL_HARDENING_ASSERT(ctrl_ == nullptr || IsFull(*ctrl_)); } void skip_empty_or_deleted() { while (IsEmptyOrDeleted(*ctrl_)) { uint32_t shift = Group{ctrl_}.CountLeadingEmptyOrDeleted(); ctrl_ += shift; slot_ += shift; } if (ABSL_PREDICT_FALSE(*ctrl_ == kSentinel)) ctrl_ = nullptr; } ctrl_t* ctrl_ = nullptr; // To avoid uninitialized member warnings, put slot_ in an anonymous union. // The member is not initialized on singleton and end iterators. union { slot_type* slot_; }; }; class const_iterator { friend class raw_hash_set; public: using iterator_category = typename iterator::iterator_category; using value_type = typename raw_hash_set::value_type; using reference = typename raw_hash_set::const_reference; using pointer = typename raw_hash_set::const_pointer; using difference_type = typename raw_hash_set::difference_type; const_iterator() {} // Implicit construction from iterator. const_iterator(iterator i) : inner_(std::move(i)) {} reference operator*() const { return *inner_; } pointer operator->() const { return inner_.operator->(); } const_iterator& operator++() { ++inner_; return *this; } const_iterator operator++(int) { return inner_++; } friend bool operator==(const const_iterator& a, const const_iterator& b) { return a.inner_ == b.inner_; } friend bool operator!=(const const_iterator& a, const const_iterator& b) { return !(a == b); } private: const_iterator(const ctrl_t* ctrl, const slot_type* slot) : inner_(const_cast<ctrl_t*>(ctrl), const_cast<slot_type*>(slot)) {} iterator inner_; }; using node_type = node_handle<Policy, hash_policy_traits<Policy>, Alloc>; using insert_return_type = InsertReturnType<iterator, node_type>; raw_hash_set() noexcept( std::is_nothrow_default_constructible<hasher>::value&& std::is_nothrow_default_constructible<key_equal>::value&& std::is_nothrow_default_constructible<allocator_type>::value) {} explicit raw_hash_set(size_t bucket_count, const hasher& hash = hasher(), const key_equal& eq = key_equal(), const allocator_type& alloc = allocator_type()) : ctrl_(EmptyGroup()), settings_(0, hash, eq, alloc) { if (bucket_count) { capacity_ = NormalizeCapacity(bucket_count); reset_growth_left(); initialize_slots(); } } raw_hash_set(size_t bucket_count, const hasher& hash, const allocator_type& alloc) : raw_hash_set(bucket_count, hash, key_equal(), alloc) {} raw_hash_set(size_t bucket_count, const allocator_type& alloc) : raw_hash_set(bucket_count, hasher(), key_equal(), alloc) {} explicit raw_hash_set(const allocator_type& alloc) : raw_hash_set(0, hasher(), key_equal(), alloc) {} template <class InputIter> raw_hash_set(InputIter first, InputIter last, size_t bucket_count = 0, const hasher& hash = hasher(), const key_equal& eq = key_equal(), const allocator_type& alloc = allocator_type()) : raw_hash_set(bucket_count, hash, eq, alloc) { insert(first, last); } template <class InputIter> raw_hash_set(InputIter first, InputIter last, size_t bucket_count, const hasher& hash, const allocator_type& alloc) : raw_hash_set(first, last, bucket_count, hash, key_equal(), alloc) {} template <class InputIter> raw_hash_set(InputIter first, InputIter last, size_t bucket_count, const allocator_type& alloc) : raw_hash_set(first, last, bucket_count, hasher(), key_equal(), alloc) {} template <class InputIter> raw_hash_set(InputIter first, InputIter last, const allocator_type& alloc) : raw_hash_set(first, last, 0, hasher(), key_equal(), alloc) {} // Instead of accepting std::initializer_list<value_type> as the first // argument like std::unordered_set<value_type> does, we have two overloads // that accept std::initializer_list<T> and std::initializer_list<init_type>. // This is advantageous for performance. // // // Turns {"abc", "def"} into std::initializer_list<std::string>, then // // copies the strings into the set. // std::unordered_set<std::string> s = {"abc", "def"}; // // // Turns {"abc", "def"} into std::initializer_list<const char*>, then // // copies the strings into the set. // absl::flat_hash_set<std::string> s = {"abc", "def"}; // // The same trick is used in insert(). // // The enabler is necessary to prevent this constructor from triggering where // the copy constructor is meant to be called. // // absl::flat_hash_set<int> a, b{a}; // // RequiresNotInit<T> is a workaround for gcc prior to 7.1. template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0> raw_hash_set(std::initializer_list<T> init, size_t bucket_count = 0, const hasher& hash = hasher(), const key_equal& eq = key_equal(), const allocator_type& alloc = allocator_type()) : raw_hash_set(init.begin(), init.end(), bucket_count, hash, eq, alloc) {} raw_hash_set(std::initializer_list<init_type> init, size_t bucket_count = 0, const hasher& hash = hasher(), const key_equal& eq = key_equal(), const allocator_type& alloc = allocator_type()) : raw_hash_set(init.begin(), init.end(), bucket_count, hash, eq, alloc) {} template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0> raw_hash_set(std::initializer_list<T> init, size_t bucket_count, const hasher& hash, const allocator_type& alloc) : raw_hash_set(init, bucket_count, hash, key_equal(), alloc) {} raw_hash_set(std::initializer_list<init_type> init, size_t bucket_count, const hasher& hash, const allocator_type& alloc) : raw_hash_set(init, bucket_count, hash, key_equal(), alloc) {} template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0> raw_hash_set(std::initializer_list<T> init, size_t bucket_count, const allocator_type& alloc) : raw_hash_set(init, bucket_count, hasher(), key_equal(), alloc) {} raw_hash_set(std::initializer_list<init_type> init, size_t bucket_count, const allocator_type& alloc) : raw_hash_set(init, bucket_count, hasher(), key_equal(), alloc) {} template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0> raw_hash_set(std::initializer_list<T> init, const allocator_type& alloc) : raw_hash_set(init, 0, hasher(), key_equal(), alloc) {} raw_hash_set(std::initializer_list<init_type> init, const allocator_type& alloc) : raw_hash_set(init, 0, hasher(), key_equal(), alloc) {} raw_hash_set(const raw_hash_set& that) : raw_hash_set(that, AllocTraits::select_on_container_copy_construction( that.alloc_ref())) {} raw_hash_set(const raw_hash_set& that, const allocator_type& a) : raw_hash_set(0, that.hash_ref(), that.eq_ref(), a) { reserve(that.size()); // Because the table is guaranteed to be empty, we can do something faster // than a full `insert`. for (const auto& v : that) { const size_t hash = PolicyTraits::apply(HashElement{hash_ref()}, v); auto target = find_first_non_full(hash); set_ctrl(target.offset, H2(hash)); emplace_at(target.offset, v); infoz_.RecordInsert(hash, target.probe_length); } size_ = that.size(); growth_left() -= that.size(); } raw_hash_set(raw_hash_set&& that) noexcept( std::is_nothrow_copy_constructible<hasher>::value&& std::is_nothrow_copy_constructible<key_equal>::value&& std::is_nothrow_copy_constructible<allocator_type>::value) : ctrl_(absl::exchange(that.ctrl_, EmptyGroup())), slots_(absl::exchange(that.slots_, nullptr)), size_(absl::exchange(that.size_, 0)), capacity_(absl::exchange(that.capacity_, 0)), infoz_(absl::exchange(that.infoz_, HashtablezInfoHandle())), // Hash, equality and allocator are copied instead of moved because // `that` must be left valid. If Hash is std::function<Key>, moving it // would create a nullptr functor that cannot be called. settings_(that.settings_) { // growth_left was copied above, reset the one from `that`. that.growth_left() = 0; } raw_hash_set(raw_hash_set&& that, const allocator_type& a) : ctrl_(EmptyGroup()), slots_(nullptr), size_(0), capacity_(0), settings_(0, that.hash_ref(), that.eq_ref(), a) { if (a == that.alloc_ref()) { std::swap(ctrl_, that.ctrl_); std::swap(slots_, that.slots_); std::swap(size_, that.size_); std::swap(capacity_, that.capacity_); std::swap(growth_left(), that.growth_left()); std::swap(infoz_, that.infoz_); } else { reserve(that.size()); // Note: this will copy elements of dense_set and unordered_set instead of // moving them. This can be fixed if it ever becomes an issue. for (auto& elem : that) insert(std::move(elem)); } } raw_hash_set& operator=(const raw_hash_set& that) { raw_hash_set tmp(that, AllocTraits::propagate_on_container_copy_assignment::value ? that.alloc_ref() : alloc_ref()); swap(tmp); return *this; } raw_hash_set& operator=(raw_hash_set&& that) noexcept( absl::allocator_traits<allocator_type>::is_always_equal::value&& std::is_nothrow_move_assignable<hasher>::value&& std::is_nothrow_move_assignable<key_equal>::value) { // TODO(sbenza): We should only use the operations from the noexcept clause // to make sure we actually adhere to that contract. return move_assign( std::move(that), typename AllocTraits::propagate_on_container_move_assignment()); } ~raw_hash_set() { destroy_slots(); } iterator begin() { auto it = iterator_at(0); it.skip_empty_or_deleted(); return it; } iterator end() { return {}; } const_iterator begin() const { return const_cast<raw_hash_set*>(this)->begin(); } const_iterator end() const { return {}; } const_iterator cbegin() const { return begin(); } const_iterator cend() const { return end(); } bool empty() const { return !size(); } size_t size() const { return size_; } size_t capacity() const { return capacity_; } size_t max_size() const { return (std::numeric_limits<size_t>::max)(); } ABSL_ATTRIBUTE_REINITIALIZES void clear() { // Iterating over this container is O(bucket_count()). When bucket_count() // is much greater than size(), iteration becomes prohibitively expensive. // For clear() it is more important to reuse the allocated array when the // container is small because allocation takes comparatively long time // compared to destruction of the elements of the container. So we pick the // largest bucket_count() threshold for which iteration is still fast and // past that we simply deallocate the array. if (capacity_ > 127) { destroy_slots(); } else if (capacity_) { for (size_t i = 0; i != capacity_; ++i) { if (IsFull(ctrl_[i])) { PolicyTraits::destroy(&alloc_ref(), slots_ + i); } } size_ = 0; reset_ctrl(); reset_growth_left(); } assert(empty()); infoz_.RecordStorageChanged(0, capacity_); } // This overload kicks in when the argument is an rvalue of insertable and // decomposable type other than init_type. // // flat_hash_map<std::string, int> m; // m.insert(std::make_pair("abc", 42)); // TODO(cheshire): A type alias T2 is introduced as a workaround for the nvcc // bug. template <class T, RequiresInsertable<T> = 0, class T2 = T, typename std::enable_if<IsDecomposable<T2>::value, int>::type = 0, T* = nullptr> std::pair<iterator, bool> insert(T&& value) { return emplace(std::forward<T>(value)); } // This overload kicks in when the argument is a bitfield or an lvalue of // insertable and decomposable type. // // union { int n : 1; }; // flat_hash_set<int> s; // s.insert(n); // // flat_hash_set<std::string> s; // const char* p = "hello"; // s.insert(p); // // TODO(romanp): Once we stop supporting gcc 5.1 and below, replace // RequiresInsertable<T> with RequiresInsertable<const T&>. // We are hitting this bug: https://godbolt.org/g/1Vht4f. template < class T, RequiresInsertable<T> = 0, typename std::enable_if<IsDecomposable<const T&>::value, int>::type = 0> std::pair<iterator, bool> insert(const T& value) { return emplace(value); } // This overload kicks in when the argument is an rvalue of init_type. Its // purpose is to handle brace-init-list arguments. // // flat_hash_map<std::string, int> s; // s.insert({"abc", 42}); std::pair<iterator, bool> insert(init_type&& value) { return emplace(std::move(value)); } // TODO(cheshire): A type alias T2 is introduced as a workaround for the nvcc // bug. template <class T, RequiresInsertable<T> = 0, class T2 = T, typename std::enable_if<IsDecomposable<T2>::value, int>::type = 0, T* = nullptr> iterator insert(const_iterator, T&& value) { return insert(std::forward<T>(value)).first; } // TODO(romanp): Once we stop supporting gcc 5.1 and below, replace // RequiresInsertable<T> with RequiresInsertable<const T&>. // We are hitting this bug: https://godbolt.org/g/1Vht4f. template < class T, RequiresInsertable<T> = 0, typename std::enable_if<IsDecomposable<const T&>::value, int>::type = 0> iterator insert(const_iterator, const T& value) { return insert(value).first; } iterator insert(const_iterator, init_type&& value) { return insert(std::move(value)).first; } template <class InputIt> void insert(InputIt first, InputIt last) { for (; first != last; ++first) insert(*first); } template <class T, RequiresNotInit<T> = 0, RequiresInsertable<const T&> = 0> void insert(std::initializer_list<T> ilist) { insert(ilist.begin(), ilist.end()); } void insert(std::initializer_list<init_type> ilist) { insert(ilist.begin(), ilist.end()); } insert_return_type insert(node_type&& node) { if (!node) return {end(), false, node_type()}; const auto& elem = PolicyTraits::element(CommonAccess::GetSlot(node)); auto res = PolicyTraits::apply( InsertSlot<false>{*this, std::move(*CommonAccess::GetSlot(node))}, elem); if (res.second) { CommonAccess::Reset(&node); return {res.first, true, node_type()}; } else { return {res.first, false, std::move(node)}; } } iterator insert(const_iterator, node_type&& node) { return insert(std::move(node)).first; } // This overload kicks in if we can deduce the key from args. This enables us // to avoid constructing value_type if an entry with the same key already // exists. // // For example: // // flat_hash_map<std::string, std::string> m = {{"abc", "def"}}; // // Creates no std::string copies and makes no heap allocations. // m.emplace("abc", "xyz"); template <class... Args, typename std::enable_if< IsDecomposable<Args...>::value, int>::type = 0> std::pair<iterator, bool> emplace(Args&&... args) { return PolicyTraits::apply(EmplaceDecomposable{*this}, std::forward<Args>(args)...); } // This overload kicks in if we cannot deduce the key from args. It constructs // value_type unconditionally and then either moves it into the table or // destroys. template <class... Args, typename std::enable_if< !IsDecomposable<Args...>::value, int>::type = 0> std::pair<iterator, bool> emplace(Args&&... args) { alignas(slot_type) unsigned char raw[sizeof(slot_type)]; slot_type* slot = reinterpret_cast<slot_type*>(&raw); PolicyTraits::construct(&alloc_ref(), slot, std::forward<Args>(args)...); const auto& elem = PolicyTraits::element(slot); return PolicyTraits::apply(InsertSlot<true>{*this, std::move(*slot)}, elem); } template <class... Args> iterator emplace_hint(const_iterator, Args&&... args) { return emplace(std::forward<Args>(args)...).first; } // Extension API: support for lazy emplace. // // Looks up key in the table. If found, returns the iterator to the element. // Otherwise calls `f` with one argument of type `raw_hash_set::constructor`. // // `f` must abide by several restrictions: // - it MUST call `raw_hash_set::constructor` with arguments as if a // `raw_hash_set::value_type` is constructed, // - it MUST NOT access the container before the call to // `raw_hash_set::constructor`, and // - it MUST NOT erase the lazily emplaced element. // Doing any of these is undefined behavior. // // For example: // // std::unordered_set<ArenaString> s; // // Makes ArenaStr even if "abc" is in the map. // s.insert(ArenaString(&arena, "abc")); // // flat_hash_set<ArenaStr> s; // // Makes ArenaStr only if "abc" is not in the map. // s.lazy_emplace("abc", [&](const constructor& ctor) { // ctor(&arena, "abc"); // }); // // WARNING: This API is currently experimental. If there is a way to implement // the same thing with the rest of the API, prefer that. class constructor { friend class raw_hash_set; public: template <class... Args> void operator()(Args&&... args) const { assert(*slot_); PolicyTraits::construct(alloc_, *slot_, std::forward<Args>(args)...); *slot_ = nullptr; } private: constructor(allocator_type* a, slot_type** slot) : alloc_(a), slot_(slot) {} allocator_type* alloc_; slot_type** slot_; }; template <class K = key_type, class F> iterator lazy_emplace(const key_arg<K>& key, F&& f) { auto res = find_or_prepare_insert(key); if (res.second) { slot_type* slot = slots_ + res.first; std::forward<F>(f)(constructor(&alloc_ref(), &slot)); assert(!slot); } return iterator_at(res.first); } // Extension API: support for heterogeneous keys. // // std::unordered_set<std::string> s; // // Turns "abc" into std::string. // s.erase("abc"); // // flat_hash_set<std::string> s; // // Uses "abc" directly without copying it into std::string. // s.erase("abc"); template <class K = key_type> size_type erase(const key_arg<K>& key) { auto it = find(key); if (it == end()) return 0; erase(it); return 1; } // Erases the element pointed to by `it`. Unlike `std::unordered_set::erase`, // this method returns void to reduce algorithmic complexity to O(1). The // iterator is invalidated, so any increment should be done before calling // erase. In order to erase while iterating across a map, use the following // idiom (which also works for standard containers): // // for (auto it = m.begin(), end = m.end(); it != end;) { // // `erase()` will invalidate `it`, so advance `it` first. // auto copy_it = it++; // if (<pred>) { // m.erase(copy_it); // } // } void erase(const_iterator cit) { erase(cit.inner_); } // This overload is necessary because otherwise erase<K>(const K&) would be // a better match if non-const iterator is passed as an argument. void erase(iterator it) { it.assert_is_full(); PolicyTraits::destroy(&alloc_ref(), it.slot_); erase_meta_only(it); } iterator erase(const_iterator first, const_iterator last) { while (first != last) { erase(first++); } return last.inner_; } // Moves elements from `src` into `this`. // If the element already exists in `this`, it is left unmodified in `src`. template <typename H, typename E> void merge(raw_hash_set<Policy, H, E, Alloc>& src) { // NOLINT assert(this != &src); for (auto it = src.begin(), e = src.end(); it != e;) { auto next = std::next(it); if (PolicyTraits::apply(InsertSlot<false>{*this, std::move(*it.slot_)}, PolicyTraits::element(it.slot_)) .second) { src.erase_meta_only(it); } it = next; } } template <typename H, typename E> void merge(raw_hash_set<Policy, H, E, Alloc>&& src) { merge(src); } node_type extract(const_iterator position) { position.inner_.assert_is_full(); auto node = CommonAccess::Transfer<node_type>(alloc_ref(), position.inner_.slot_); erase_meta_only(position); return node; } template < class K = key_type, typename std::enable_if<!std::is_same<K, iterator>::value, int>::type = 0> node_type extract(const key_arg<K>& key) { auto it = find(key); return it == end() ? node_type() : extract(const_iterator{it}); } void swap(raw_hash_set& that) noexcept( IsNoThrowSwappable<hasher>() && IsNoThrowSwappable<key_equal>() && (!AllocTraits::propagate_on_container_swap::value || IsNoThrowSwappable<allocator_type>())) { using std::swap; swap(ctrl_, that.ctrl_); swap(slots_, that.slots_); swap(size_, that.size_); swap(capacity_, that.capacity_); swap(growth_left(), that.growth_left()); swap(hash_ref(), that.hash_ref()); swap(eq_ref(), that.eq_ref()); swap(infoz_, that.infoz_); if (AllocTraits::propagate_on_container_swap::value) { swap(alloc_ref(), that.alloc_ref()); } else { // If the allocators do not compare equal it is officially undefined // behavior. We choose to do nothing. } } void rehash(size_t n) { if (n == 0 && capacity_ == 0) return; if (n == 0 && size_ == 0) { destroy_slots(); infoz_.RecordStorageChanged(0, 0); return; } // bitor is a faster way of doing `max` here. We will round up to the next // power-of-2-minus-1, so bitor is good enough. auto m = NormalizeCapacity(n | GrowthToLowerboundCapacity(size())); // n == 0 unconditionally rehashes as per the standard. if (n == 0 || m > capacity_) { resize(m); } } void reserve(size_t n) { rehash(GrowthToLowerboundCapacity(n)); } // Extension API: support for heterogeneous keys. // // std::unordered_set<std::string> s; // // Turns "abc" into std::string. // s.count("abc"); // // ch_set<std::string> s; // // Uses "abc" directly without copying it into std::string. // s.count("abc"); template <class K = key_type> size_t count(const key_arg<K>& key) const { return find(key) == end() ? 0 : 1; } // Issues CPU prefetch instructions for the memory needed to find or insert // a key. Like all lookup functions, this support heterogeneous keys. // // NOTE: This is a very low level operation and should not be used without // specific benchmarks indicating its importance. template <class K = key_type> void prefetch(const key_arg<K>& key) const { (void)key; #if defined(__GNUC__) auto seq = probe(hash_ref()(key)); __builtin_prefetch(static_cast<const void*>(ctrl_ + seq.offset())); __builtin_prefetch(static_cast<const void*>(slots_ + seq.offset())); #endif // __GNUC__ } // The API of find() has two extensions. // // 1. The hash can be passed by the user. It must be equal to the hash of the // key. // // 2. The type of the key argument doesn't have to be key_type. This is so // called heterogeneous key support. template <class K = key_type> iterator find(const key_arg<K>& key, size_t hash) { auto seq = probe(hash); while (true) { Group g{ctrl_ + seq.offset()}; for (int i : g.Match(H2(hash))) { if (ABSL_PREDICT_TRUE(PolicyTraits::apply( EqualElement<K>{key, eq_ref()}, PolicyTraits::element(slots_ + seq.offset(i))))) return iterator_at(seq.offset(i)); } if (ABSL_PREDICT_TRUE(g.MatchEmpty())) return end(); seq.next(); } } template <class K = key_type> iterator find(const key_arg<K>& key) { return find(key, hash_ref()(key)); } template <class K = key_type> const_iterator find(const key_arg<K>& key, size_t hash) const { return const_cast<raw_hash_set*>(this)->find(key, hash); } template <class K = key_type> const_iterator find(const key_arg<K>& key) const { return find(key, hash_ref()(key)); } template <class K = key_type> bool contains(const key_arg<K>& key) const { return find(key) != end(); } template <class K = key_type> std::pair<iterator, iterator> equal_range(const key_arg<K>& key) { auto it = find(key); if (it != end()) return {it, std::next(it)}; return {it, it}; } template <class K = key_type> std::pair<const_iterator, const_iterator> equal_range( const key_arg<K>& key) const { auto it = find(key); if (it != end()) return {it, std::next(it)}; return {it, it}; } size_t bucket_count() const { return capacity_; } float load_factor() const { return capacity_ ? static_cast<double>(size()) / capacity_ : 0.0; } float max_load_factor() const { return 1.0f; } void max_load_factor(float) { // Does nothing. } hasher hash_function() const { return hash_ref(); } key_equal key_eq() const { return eq_ref(); } allocator_type get_allocator() const { return alloc_ref(); } friend bool operator==(const raw_hash_set& a, const raw_hash_set& b) { if (a.size() != b.size()) return false; const raw_hash_set* outer = &a; const raw_hash_set* inner = &b; if (outer->capacity() > inner->capacity()) std::swap(outer, inner); for (const value_type& elem : *outer) if (!inner->has_element(elem)) return false; return true; } friend bool operator!=(const raw_hash_set& a, const raw_hash_set& b) { return !(a == b); } friend void swap(raw_hash_set& a, raw_hash_set& b) noexcept(noexcept(a.swap(b))) { a.swap(b); } private: template <class Container, typename Enabler> friend struct absl::container_internal::hashtable_debug_internal:: HashtableDebugAccess; struct FindElement { template <class K, class... Args> const_iterator operator()(const K& key, Args&&...) const { return s.find(key); } const raw_hash_set& s; }; struct HashElement { template <class K, class... Args> size_t operator()(const K& key, Args&&...) const { return h(key); } const hasher& h; }; template <class K1> struct EqualElement { template <class K2, class... Args> bool operator()(const K2& lhs, Args&&...) const { return eq(lhs, rhs); } const K1& rhs; const key_equal& eq; }; struct EmplaceDecomposable { template <class K, class... Args> std::pair<iterator, bool> operator()(const K& key, Args&&... args) const { auto res = s.find_or_prepare_insert(key); if (res.second) { s.emplace_at(res.first, std::forward<Args>(args)...); } return {s.iterator_at(res.first), res.second}; } raw_hash_set& s; }; template <bool do_destroy> struct InsertSlot { template <class K, class... Args> std::pair<iterator, bool> operator()(const K& key, Args&&...) && { auto res = s.find_or_prepare_insert(key); if (res.second) { PolicyTraits::transfer(&s.alloc_ref(), s.slots_ + res.first, &slot); } else if (do_destroy) { PolicyTraits::destroy(&s.alloc_ref(), &slot); } return {s.iterator_at(res.first), res.second}; } raw_hash_set& s; // Constructed slot. Either moved into place or destroyed. slot_type&& slot; }; // "erases" the object from the container, except that it doesn't actually // destroy the object. It only updates all the metadata of the class. // This can be used in conjunction with Policy::transfer to move the object to // another place. void erase_meta_only(const_iterator it) { assert(IsFull(*it.inner_.ctrl_) && "erasing a dangling iterator"); --size_; const size_t index = it.inner_.ctrl_ - ctrl_; const size_t index_before = (index - Group::kWidth) & capacity_; const auto empty_after = Group(it.inner_.ctrl_).MatchEmpty(); const auto empty_before = Group(ctrl_ + index_before).MatchEmpty(); // We count how many consecutive non empties we have to the right and to the // left of `it`. If the sum is >= kWidth then there is at least one probe // window that might have seen a full group. bool was_never_full = empty_before && empty_after && static_cast<size_t>(empty_after.TrailingZeros() + empty_before.LeadingZeros()) < Group::kWidth; set_ctrl(index, was_never_full ? kEmpty : kDeleted); growth_left() += was_never_full; infoz_.RecordErase(); } void initialize_slots() { assert(capacity_); // Folks with custom allocators often make unwarranted assumptions about the // behavior of their classes vis-a-vis trivial destructability and what // calls they will or wont make. Avoid sampling for people with custom // allocators to get us out of this mess. This is not a hard guarantee but // a workaround while we plan the exact guarantee we want to provide. // // People are often sloppy with the exact type of their allocator (sometimes // it has an extra const or is missing the pair, but rebinds made it work // anyway). To avoid the ambiguity, we work off SlotAlloc which we have // bound more carefully. if (std::is_same<SlotAlloc, std::allocator<slot_type>>::value && slots_ == nullptr) { infoz_ = Sample(); } auto layout = MakeLayout(capacity_); char* mem = static_cast<char*>( Allocate<Layout::Alignment()>(&alloc_ref(), layout.AllocSize())); ctrl_ = reinterpret_cast<ctrl_t*>(layout.template Pointer<0>(mem)); slots_ = layout.template Pointer<1>(mem); reset_ctrl(); reset_growth_left(); infoz_.RecordStorageChanged(size_, capacity_); } void destroy_slots() { if (!capacity_) return; for (size_t i = 0; i != capacity_; ++i) { if (IsFull(ctrl_[i])) { PolicyTraits::destroy(&alloc_ref(), slots_ + i); } } auto layout = MakeLayout(capacity_); // Unpoison before returning the memory to the allocator. SanitizerUnpoisonMemoryRegion(slots_, sizeof(slot_type) * capacity_); Deallocate<Layout::Alignment()>(&alloc_ref(), ctrl_, layout.AllocSize()); ctrl_ = EmptyGroup(); slots_ = nullptr; size_ = 0; capacity_ = 0; growth_left() = 0; } void resize(size_t new_capacity) { assert(IsValidCapacity(new_capacity)); auto* old_ctrl = ctrl_; auto* old_slots = slots_; const size_t old_capacity = capacity_; capacity_ = new_capacity; initialize_slots(); size_t total_probe_length = 0; for (size_t i = 0; i != old_capacity; ++i) { if (IsFull(old_ctrl[i])) { size_t hash = PolicyTraits::apply(HashElement{hash_ref()}, PolicyTraits::element(old_slots + i)); auto target = find_first_non_full(hash); size_t new_i = target.offset; total_probe_length += target.probe_length; set_ctrl(new_i, H2(hash)); PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, old_slots + i); } } if (old_capacity) { SanitizerUnpoisonMemoryRegion(old_slots, sizeof(slot_type) * old_capacity); auto layout = MakeLayout(old_capacity); Deallocate<Layout::Alignment()>(&alloc_ref(), old_ctrl, layout.AllocSize()); } infoz_.RecordRehash(total_probe_length); } void drop_deletes_without_resize() ABSL_ATTRIBUTE_NOINLINE { assert(IsValidCapacity(capacity_)); assert(!is_small()); // Algorithm: // - mark all DELETED slots as EMPTY // - mark all FULL slots as DELETED // - for each slot marked as DELETED // hash = Hash(element) // target = find_first_non_full(hash) // if target is in the same group // mark slot as FULL // else if target is EMPTY // transfer element to target // mark slot as EMPTY // mark target as FULL // else if target is DELETED // swap current element with target element // mark target as FULL // repeat procedure for current slot with moved from element (target) ConvertDeletedToEmptyAndFullToDeleted(ctrl_, capacity_); alignas(slot_type) unsigned char raw[sizeof(slot_type)]; size_t total_probe_length = 0; slot_type* slot = reinterpret_cast<slot_type*>(&raw); for (size_t i = 0; i != capacity_; ++i) { if (!IsDeleted(ctrl_[i])) continue; size_t hash = PolicyTraits::apply(HashElement{hash_ref()}, PolicyTraits::element(slots_ + i)); auto target = find_first_non_full(hash); size_t new_i = target.offset; total_probe_length += target.probe_length; // Verify if the old and new i fall within the same group wrt the hash. // If they do, we don't need to move the object as it falls already in the // best probe we can. const auto probe_index = [&](size_t pos) { return ((pos - probe(hash).offset()) & capacity_) / Group::kWidth; }; // Element doesn't move. if (ABSL_PREDICT_TRUE(probe_index(new_i) == probe_index(i))) { set_ctrl(i, H2(hash)); continue; } if (IsEmpty(ctrl_[new_i])) { // Transfer element to the empty spot. // set_ctrl poisons/unpoisons the slots so we have to call it at the // right time. set_ctrl(new_i, H2(hash)); PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, slots_ + i); set_ctrl(i, kEmpty); } else { assert(IsDeleted(ctrl_[new_i])); set_ctrl(new_i, H2(hash)); // Until we are done rehashing, DELETED marks previously FULL slots. // Swap i and new_i elements. PolicyTraits::transfer(&alloc_ref(), slot, slots_ + i); PolicyTraits::transfer(&alloc_ref(), slots_ + i, slots_ + new_i); PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, slot); --i; // repeat } } reset_growth_left(); infoz_.RecordRehash(total_probe_length); } void rehash_and_grow_if_necessary() { if (capacity_ == 0) { resize(1); } else if (size() <= CapacityToGrowth(capacity()) / 2) { // Squash DELETED without growing if there is enough capacity. drop_deletes_without_resize(); } else { // Otherwise grow the container. resize(capacity_ * 2 + 1); } } bool has_element(const value_type& elem) const { size_t hash = PolicyTraits::apply(HashElement{hash_ref()}, elem); auto seq = probe(hash); while (true) { Group g{ctrl_ + seq.offset()}; for (int i : g.Match(H2(hash))) { if (ABSL_PREDICT_TRUE(PolicyTraits::element(slots_ + seq.offset(i)) == elem)) return true; } if (ABSL_PREDICT_TRUE(g.MatchEmpty())) return false; seq.next(); assert(seq.index() < capacity_ && "full table!"); } return false; } // Probes the raw_hash_set with the probe sequence for hash and returns the // pointer to the first empty or deleted slot. // NOTE: this function must work with tables having both kEmpty and kDelete // in one group. Such tables appears during drop_deletes_without_resize. // // This function is very useful when insertions happen and: // - the input is already a set // - there are enough slots // - the element with the hash is not in the table struct FindInfo { size_t offset; size_t probe_length; }; FindInfo find_first_non_full(size_t hash) { auto seq = probe(hash); while (true) { Group g{ctrl_ + seq.offset()}; auto mask = g.MatchEmptyOrDeleted(); if (mask) { #if !defined(NDEBUG) // We want to add entropy even when ASLR is not enabled. // In debug build we will randomly insert in either the front or back of // the group. // TODO(kfm,sbenza): revisit after we do unconditional mixing if (!is_small() && ShouldInsertBackwards(hash, ctrl_)) { return {seq.offset(mask.HighestBitSet()), seq.index()}; } #endif return {seq.offset(mask.LowestBitSet()), seq.index()}; } assert(seq.index() < capacity_ && "full table!"); seq.next(); } } // TODO(alkis): Optimize this assuming *this and that don't overlap. raw_hash_set& move_assign(raw_hash_set&& that, std::true_type) { raw_hash_set tmp(std::move(that)); swap(tmp); return *this; } raw_hash_set& move_assign(raw_hash_set&& that, std::false_type) { raw_hash_set tmp(std::move(that), alloc_ref()); swap(tmp); return *this; } protected: template <class K> std::pair<size_t, bool> find_or_prepare_insert(const K& key) { auto hash = hash_ref()(key); auto seq = probe(hash); while (true) { Group g{ctrl_ + seq.offset()}; for (int i : g.Match(H2(hash))) { if (ABSL_PREDICT_TRUE(PolicyTraits::apply( EqualElement<K>{key, eq_ref()}, PolicyTraits::element(slots_ + seq.offset(i))))) return {seq.offset(i), false}; } if (ABSL_PREDICT_TRUE(g.MatchEmpty())) break; seq.next(); } return {prepare_insert(hash), true}; } size_t prepare_insert(size_t hash) ABSL_ATTRIBUTE_NOINLINE { auto target = find_first_non_full(hash); if (ABSL_PREDICT_FALSE(growth_left() == 0 && !IsDeleted(ctrl_[target.offset]))) { rehash_and_grow_if_necessary(); target = find_first_non_full(hash); } ++size_; growth_left() -= IsEmpty(ctrl_[target.offset]); set_ctrl(target.offset, H2(hash)); infoz_.RecordInsert(hash, target.probe_length); return target.offset; } // Constructs the value in the space pointed by the iterator. This only works // after an unsuccessful find_or_prepare_insert() and before any other // modifications happen in the raw_hash_set. // // PRECONDITION: i is an index returned from find_or_prepare_insert(k), where // k is the key decomposed from `forward<Args>(args)...`, and the bool // returned by find_or_prepare_insert(k) was true. // POSTCONDITION: *m.iterator_at(i) == value_type(forward<Args>(args)...). template <class... Args> void emplace_at(size_t i, Args&&... args) { PolicyTraits::construct(&alloc_ref(), slots_ + i, std::forward<Args>(args)...); assert(PolicyTraits::apply(FindElement{*this}, *iterator_at(i)) == iterator_at(i) && "constructed value does not match the lookup key"); } iterator iterator_at(size_t i) { return {ctrl_ + i, slots_ + i}; } const_iterator iterator_at(size_t i) const { return {ctrl_ + i, slots_ + i}; } private: friend struct RawHashSetTestOnlyAccess; probe_seq<Group::kWidth> probe(size_t hash) const { return probe_seq<Group::kWidth>(H1(hash, ctrl_), capacity_); } // Reset all ctrl bytes back to kEmpty, except the sentinel. void reset_ctrl() { std::memset(ctrl_, kEmpty, capacity_ + Group::kWidth); ctrl_[capacity_] = kSentinel; SanitizerPoisonMemoryRegion(slots_, sizeof(slot_type) * capacity_); } void reset_growth_left() { growth_left() = CapacityToGrowth(capacity()) - size_; } // Sets the control byte, and if `i < Group::kWidth`, set the cloned byte at // the end too. void set_ctrl(size_t i, ctrl_t h) { assert(i < capacity_); if (IsFull(h)) { SanitizerUnpoisonObject(slots_ + i); } else { SanitizerPoisonObject(slots_ + i); } ctrl_[i] = h; ctrl_[((i - Group::kWidth) & capacity_) + 1 + ((Group::kWidth - 1) & capacity_)] = h; } size_t& growth_left() { return settings_.template get<0>(); } // The representation of the object has two modes: // - small: For capacities < kWidth-1 // - large: For the rest. // // Differences: // - In small mode we are able to use the whole capacity. The extra control // bytes give us at least one "empty" control byte to stop the iteration. // This is important to make 1 a valid capacity. // // - In small mode only the first `capacity()` control bytes after the // sentinel are valid. The rest contain dummy kEmpty values that do not // represent a real slot. This is important to take into account on // find_first_non_full(), where we never try ShouldInsertBackwards() for // small tables. bool is_small() const { return capacity_ < Group::kWidth - 1; } hasher& hash_ref() { return settings_.template get<1>(); } const hasher& hash_ref() const { return settings_.template get<1>(); } key_equal& eq_ref() { return settings_.template get<2>(); } const key_equal& eq_ref() const { return settings_.template get<2>(); } allocator_type& alloc_ref() { return settings_.template get<3>(); } const allocator_type& alloc_ref() const { return settings_.template get<3>(); } // TODO(alkis): Investigate removing some of these fields: // - ctrl/slots can be derived from each other // - size can be moved into the slot array ctrl_t* ctrl_ = EmptyGroup(); // [(capacity + 1) * ctrl_t] slot_type* slots_ = nullptr; // [capacity * slot_type] size_t size_ = 0; // number of full slots size_t capacity_ = 0; // total number of slots HashtablezInfoHandle infoz_; absl::container_internal::CompressedTuple<size_t /* growth_left */, hasher, key_equal, allocator_type> settings_{0, hasher{}, key_equal{}, allocator_type{}}; }; // Erases all elements that satisfy the predicate `pred` from the container `c`. template <typename P, typename H, typename E, typename A, typename Predicate> void EraseIf(Predicate pred, raw_hash_set<P, H, E, A>* c) { for (auto it = c->begin(), last = c->end(); it != last;) { auto copy_it = it++; if (pred(*copy_it)) { c->erase(copy_it); } } } namespace hashtable_debug_internal { template <typename Set> struct HashtableDebugAccess<Set, absl::void_t<typename Set::raw_hash_set>> { using Traits = typename Set::PolicyTraits; using Slot = typename Traits::slot_type; static size_t GetNumProbes(const Set& set, const typename Set::key_type& key) { size_t num_probes = 0; size_t hash = set.hash_ref()(key); auto seq = set.probe(hash); while (true) { container_internal::Group g{set.ctrl_ + seq.offset()}; for (int i : g.Match(container_internal::H2(hash))) { if (Traits::apply( typename Set::template EqualElement<typename Set::key_type>{ key, set.eq_ref()}, Traits::element(set.slots_ + seq.offset(i)))) return num_probes; ++num_probes; } if (g.MatchEmpty()) return num_probes; seq.next(); ++num_probes; } } static size_t AllocatedByteSize(const Set& c) { size_t capacity = c.capacity_; if (capacity == 0) return 0; auto layout = Set::MakeLayout(capacity); size_t m = layout.AllocSize(); size_t per_slot = Traits::space_used(static_cast<const Slot*>(nullptr)); if (per_slot != ~size_t{}) { m += per_slot * c.size(); } else { for (size_t i = 0; i != capacity; ++i) { if (container_internal::IsFull(c.ctrl_[i])) { m += Traits::space_used(c.slots_ + i); } } } return m; } static size_t LowerBoundAllocatedByteSize(size_t size) { size_t capacity = GrowthToLowerboundCapacity(size); if (capacity == 0) return 0; auto layout = Set::MakeLayout(NormalizeCapacity(capacity)); size_t m = layout.AllocSize(); size_t per_slot = Traits::space_used(static_cast<const Slot*>(nullptr)); if (per_slot != ~size_t{}) { m += per_slot * size; } return m; } }; } // namespace hashtable_debug_internal } // namespace container_internal ABSL_NAMESPACE_END } // namespace absl #endif // ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_
{ "content_hash": "b624919c995a86e4a2d67716c9753950", "timestamp": "", "source": "github", "line_count": 1885, "max_line_length": 80, "avg_line_length": 36.36498673740053, "alnum_prop": 0.6334247534574313, "repo_name": "endlessm/chromium-browser", "id": "df0f2b2b54bee0b87ce004c659e3eafe4a976f35", "size": "68548", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/abseil-cpp/absl/container/internal/raw_hash_set.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from rest_framework.reverse import reverse from test_project.test_app.models import Post from test_project.test_app.tests.factories import UserFactory, PostFactory, CommentFactory from yak.rest_core.test import SchemaTestCase from yak.rest_social_network.models import Follow, Comment, Tag, Like User = get_user_model() class BaseAPITests(SchemaTestCase): def setUp(self): super(BaseAPITests, self).setUp() self.dev_user = UserFactory() class FlagTestCase(BaseAPITests): def test_users_can_flag_content(self): test_user = UserFactory() content_type = ContentType.objects.get_for_model(Post) flag_url = reverse('flag') data = { 'content_type': content_type.pk, 'object_id': PostFactory().pk } self.assertSchemaPost(flag_url, "$flagRequest", "$flagResponse", data, test_user) class ShareTestCase(BaseAPITests): def test_users_can_share_content(self): test_user = UserFactory() content_type = ContentType.objects.get_for_model(Post) shares_url = reverse('shares-list') data = { 'content_type': content_type.pk, 'object_id': PostFactory().pk, 'shared_with': [test_user.pk] } self.assertSchemaPost(shares_url, "$shareRequest", "$shareResponse", data, self.dev_user) def test_users_can_share_content_multiple_times(self): sharing_user = UserFactory() test_user = UserFactory() content_type = ContentType.objects.get_for_model(Post) shares_url = reverse('shares-list') data = { 'content_type': content_type.pk, 'object_id': PostFactory().pk, 'shared_with': [test_user.pk] } self.assertSchemaPost(shares_url, "$shareRequest", "$shareResponse", data, sharing_user) data['shared_with'] = [self.dev_user.pk] self.assertSchemaPost(shares_url, "$shareRequest", "$shareResponse", data, sharing_user) class LikeTestCase(BaseAPITests): def test_users_can_like_content(self): content_type = ContentType.objects.get_for_model(Post) likes_url = reverse('likes-list') data = { 'content_type': content_type.pk, 'object_id': PostFactory().pk, } self.assertSchemaPost(likes_url, "$likeRequest", "$likeResponse", data, self.dev_user) def test_liked_mixin(self): post = PostFactory() url = reverse("posts-detail", args=[post.pk]) like = Like.objects.create(content_type=ContentType.objects.get_for_model(Post), object_id=post.pk, user=self.dev_user) response = self.assertSchemaGet(url, None, "$postResponse", self.dev_user) self.assertEqual(response.data["liked_id"], like.pk) other_post = PostFactory() url = reverse("posts-detail", args=[other_post.pk]) response = self.assertSchemaGet(url, None, "$postResponse", self.dev_user) self.assertIsNone(response.data["liked_id"]) class CommentTestCase(BaseAPITests): def test_users_can_comment_on_content(self): content_type = ContentType.objects.get_for_model(Post) comments_url = reverse('comments-list') data = { 'content_type': content_type.pk, 'object_id': PostFactory().pk, 'description': 'This is a user comment.' } self.assertSchemaPost(comments_url, "$commentRequest", "$commentResponse", data, self.dev_user) def test_comment_related_tags(self): content_type = ContentType.objects.get_for_model(Post) Comment.objects.create(content_type=content_type, object_id=1, description='Testing of a hashtag. #django', user=self.dev_user) tags_url = reverse('tags-list') response = self.assertSchemaGet(tags_url, None, "$tagResponse", self.dev_user) self.assertEqual(response.data['results'][0]['name'], 'django') self.assertIsNotNone(Tag.objects.get(name='django')) def test_comments_for_specific_object(self): test_user = UserFactory() post_content_type = ContentType.objects.get_for_model(Post) post = PostFactory(user=test_user) comment = CommentFactory(content_type=post_content_type, object_id=post.pk) post2 = PostFactory(user=test_user) CommentFactory(content_type=post_content_type, object_id=post2.pk) url = reverse('comments-list') parameters = { 'content_type': post_content_type.pk, 'object_id': post.pk, } response = self.assertSchemaGet(url, parameters, "$commentResponse", self.dev_user) self.assertEqual(len(response.data["results"]), 1) self.assertEqual(response.data["results"][0]["id"], comment.pk) class UserFollowingTestCase(BaseAPITests): def test_user_can_follow_each_other(self): test_user1 = UserFactory() user_content_type = ContentType.objects.get_for_model(User) follow_url = reverse('follows-list') # Dev User to follow Test User 1 data = { 'content_type': user_content_type.pk, 'object_id': test_user1.pk } response = self.assertSchemaPost(follow_url, "$followRequest", "$followResponse", data, self.dev_user) self.assertEqual(response.data['following']['username'], test_user1.username) def test_following_endpoint(self): test_user1 = UserFactory() test_user2 = UserFactory() user_content_type = ContentType.objects.get_for_model(User) # Dev User to follow User 1, User 2 to follow Dev User Follow.objects.create(content_type=user_content_type, object_id=test_user1.pk, user=self.dev_user) Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=test_user2) following_url = reverse('users-following', args=[self.dev_user.pk]) response = self.assertSchemaGet(following_url, None, "$followResponse", self.dev_user) self.assertEqual(len(response.data), 1) self.assertEqual(response.data[0]['following']['username'], test_user1.username) def test_follower_endpoint(self): test_user1 = UserFactory() test_user2 = UserFactory() user_content_type = ContentType.objects.get_for_model(User) # Dev User to follow User 1, User 2 to follow Dev User Follow.objects.create(content_type=user_content_type, object_id=test_user1.pk, user=self.dev_user) Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=test_user2) followers_url = reverse('users-followers', args=[self.dev_user.pk]) response = self.assertSchemaGet(followers_url, None, "$followResponse", self.dev_user) self.assertEqual(len(response.data), 1) self.assertEqual(response.data[0]['follower']['username'], test_user2.username) def test_follow_pagination(self): user_content_type = ContentType.objects.get_for_model(User) for _ in range(0, 30): user = UserFactory() Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=user) followers_url = reverse('users-followers', args=[self.dev_user.pk]) response = self.assertSchemaGet(followers_url, None, "$followResponse", self.dev_user) self.assertEqual(len(response.data), settings.REST_FRAMEWORK['PAGE_SIZE']) response = self.assertSchemaGet(followers_url, {"page": 2}, "$followResponse", self.dev_user) self.assertEqual(len(response.data), 30 - settings.REST_FRAMEWORK['PAGE_SIZE']) def test_user_can_unfollow_user(self): follower = UserFactory() user_content_type = ContentType.objects.get_for_model(User) follow_object = Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=follower) follows_url = reverse('follows-detail', kwargs={'pk': follow_object.pk}) # If you are not the follower of the user, you cannot unfollow the user self.assertSchemaDelete(follows_url, self.dev_user, unauthorized=True) # If you are the follower of that user, you can unfollow the user self.assertSchemaDelete(follows_url, follower) # Check that original follow object no longer exists self.assertEqual(Follow.objects.filter(pk=follow_object.pk).exists(), False) def test_user_following_and_follower_count(self): follower1 = UserFactory() follower2 = UserFactory() following = UserFactory() user_content_type = ContentType.objects.get_for_model(User) # Follower setup Follow.objects.create(content_type=user_content_type, object_id=following.pk, user=self.dev_user) Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=follower1) Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=follower2) users_url = reverse('users-detail', kwargs={'pk': self.dev_user.pk}) response = self.assertSchemaGet(users_url, None, "$userResponse", self.dev_user) self.assertEqual(response.data['user_following_count'], 1) self.assertEqual(response.data['user_followers_count'], 2) def test_bulk_follow(self): user1 = UserFactory() user2 = UserFactory() url = reverse('follows-bulk-create') user_content_type = ContentType.objects.get_for_model(User) data = [ {'content_type': user_content_type.pk, 'object_id': user1.pk}, {'content_type': user_content_type.pk, 'object_id': user2.pk} ] self.assertSchemaPost(url, "$followRequest", "$followResponse", data, self.dev_user) self.assertEqual(user1.user_followers_count(), 1) self.assertEqual(user2.user_followers_count(), 1) def test_follow_id(self): follower = UserFactory() user_content_type = ContentType.objects.get_for_model(User) follow_object = Follow.objects.create(content_type=user_content_type, object_id=self.dev_user.pk, user=follower) url = reverse("users-detail", args=[self.dev_user.pk]) response = self.assertSchemaGet(url, None, "$userResponse", follower) self.assertEqual(response.data['follow_id'], follow_object.pk) not_follower = UserFactory() url = reverse("users-detail", args=[self.dev_user.pk]) response = self.assertSchemaGet(url, None, "$userResponse", not_follower) self.assertIsNone(response.data['follow_id'])
{ "content_hash": "53a1132c02a254b25ca3b8255e79117e", "timestamp": "", "source": "github", "line_count": 230, "max_line_length": 120, "avg_line_length": 47.004347826086956, "alnum_prop": 0.6543335491628897, "repo_name": "yeti/YAK-server", "id": "d56037e772b67730a46f45c1e69a0d221bf5329c", "size": "10811", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test_project/test_app/tests/test_social.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2288" }, { "name": "Python", "bytes": "177485" } ], "symlink_target": "" }
package br.senac.tads3.pi03b.gruposete.servlets; import br.senac.tads3.pi03b.gruposete.dao.ClienteDAO; import br.senac.tads3.pi03b.gruposete.dao.RelatorioDAO; import br.senac.tads3.pi03b.gruposete.models.Cliente; import br.senac.tads3.pi03b.gruposete.models.RelatorioMudancas; import br.senac.tads3.pi03b.gruposete.services.ClienteService; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpSession; @WebServlet(name = "CadastroClienteServlet", urlPatterns = {"/CadastroCliente"}) public class CadastroClienteServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/jsp/CadastroCliente.jsp"); dispatcher.forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ClienteService service = new ClienteService(); ClienteDAO dao = new ClienteDAO(); RelatorioDAO relatorioDAO = new RelatorioDAO(); RelatorioMudancas relatorio = new RelatorioMudancas(); String nome = request.getParameter("nome"); String cpf = request.getParameter("cpf"); String sexo = request.getParameter("sexo"); String data_nasc = request.getParameter("nascimento"); String telefone = request.getParameter("telefone"); String celular = request.getParameter("celular"); String email = request.getParameter("email"); int numero = Integer.parseInt(request.getParameter("numero")); String cep = request.getParameter("cep"); String rua = request.getParameter("rua"); String estado = request.getParameter("estado"); String cidade = request.getParameter("cidade"); String complemento = request.getParameter("complemento"); request.setAttribute("erroNome", service.validaNome(nome)); try { request.setAttribute("erroCpf", service.validaCpf(cpf)); } catch (SQLException | ClassNotFoundException ex) { Logger.getLogger(CadastroClienteServlet.class.getName()).log(Level.SEVERE, null, ex); } request.setAttribute("erroNascimento", service.validaNascimento(data_nasc)); request.setAttribute("erroRua", service.validaRua(rua)); request.setAttribute("erroNumero", service.validaNumero(numero)); request.setAttribute("erroCep", service.validaCep(cep)); request.setAttribute("erroCidade", service.validaCidade(cidade)); request.setAttribute("erroEmail", service.validaEmail(email)); Cliente cliente = new Cliente(nome.trim(), cpf.trim(), sexo.trim(), data_nasc.trim(), numero, cep.trim(), rua.trim(), estado.trim(), cidade.trim(), complemento.trim(), celular.trim(), telefone.trim(), email.trim(), true); try { if (service.validaCliente(nome, cpf, data_nasc, rua, numero, cep, cidade, email)) { RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/jsp/CadastroCliente.jsp"); dispatcher.forward(request, response); } else { try { HttpSession sessao = request.getSession(); int identificacaoF = (int) sessao.getAttribute("id_func"); dao.inserir(cliente); relatorio.setId_func(identificacaoF); relatorio.setMudanca("Cadastro de cliente efetuado!"); relatorioDAO.inserir(relatorio); response.sendRedirect(request.getContextPath() + "/inicio"); } catch (Exception ex) { Logger.getLogger(CadastroClienteServlet.class.getName()).log(Level.SEVERE, null, ex); } } } catch (SQLException | ClassNotFoundException ex) { Logger.getLogger(CadastroClienteServlet.class.getName()).log(Level.SEVERE, null, ex); } } }
{ "content_hash": "cba600a25746a4de2718fdd04fc486f7", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 111, "avg_line_length": 43.410714285714285, "alnum_prop": 0.6211435623200329, "repo_name": "ArtCouSan/Loja_Agencia_De_Viagens", "id": "f5049821c6ec49ace93ce64e2349712d48b852e0", "size": "4862", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "agenciaturismo/src/main/java/br/senac/tads3/pi03b/gruposete/servlets/CadastroClienteServlet.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "334128" } ], "symlink_target": "" }
package com.wxs.amqp.conf; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; /** * Created with IntelliJ IDEA. * User: FujiRen * Date: 2018/4/6 * Time: 22:19 */ @Component @ConfigurationProperties(prefix = "spring.rabbitmq") public class MQConfig { private String username; private String password; private String virtualHost1; private String virtualHost2; private String host; private int port; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getVirtualHost1() { return virtualHost1; } public void setVirtualHost1(String virtualHost1) { this.virtualHost1 = virtualHost1; } public String getVirtualHost2() { return virtualHost2; } public void setVirtualHost2(String virtualHost2) { this.virtualHost2 = virtualHost2; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } }
{ "content_hash": "f32f03640e2f4ffb6513e3ea3cdee7c3", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 78, "avg_line_length": 22, "alnum_prop": 0.6715749039692702, "repo_name": "wuxinshui/spring-boot-samples", "id": "819f4568fd35bc592f07d0751b54ac2101f7f9a0", "size": "1562", "binary": false, "copies": "1", "ref": "refs/heads/springboot2.1.x", "path": "spring-boot-sample-amqp/src/main/java/com/wxs/amqp/conf/MQConfig.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "30426" }, { "name": "HTML", "bytes": "589606" }, { "name": "Java", "bytes": "550985" }, { "name": "JavaScript", "bytes": "1114438" }, { "name": "PHP", "bytes": "2157" }, { "name": "TSQL", "bytes": "24470" } ], "symlink_target": "" }
template <typename T> class node { public: node(std::shared_ptr<node> next, T value) : value(value), next(next) {} T value; std::shared_ptr<node> next; }; template <typename T> class list { public: class const_iterator { public: const_iterator(std::shared_ptr<node<T>> n) : n(n) {} const_iterator(const const_iterator& rhs) : n(rhs.n) {} bool operator!= (const const_iterator& other) const { return n != other.n; } T operator* () const { return n->value; } const const_iterator& operator++ () { n = n->next; return *this; } private: std::shared_ptr<node<T>> n; }; const_iterator begin() const { return const_iterator(first); } const_iterator end() const { return const_iterator(nullptr); } list() {} const T& head() const { return first->value; } const list tail() const { return list(first->next); } const list operator<<(const T &t) const { if(!first) return list(nullptr, t); return list(first->next, t); } private: list(std::shared_ptr<node<T>> first) : first(first) {} list(std::shared_ptr<node<T>> first, T t) : first( std::make_shared<node<T>>(first, t) ) {} std::shared_ptr<node<T>> first; }; class xml_exception : public std::exception { public: xml_exception(const std::string &m = "XML Exception") : msg(m) {} virtual const char *what() const throw() { return msg.c_str(); } private: std::string msg; }; class xmlnode { public: xmlnode(tinyxml2::XMLNode *node) : node(node) {} xmlnode() = default; xmlnode operator[](const std::string &tag) const { if(!node) throw xml_exception("Invalid node"); return xmlnode(node->FirstChildElement(tag.c_str())); } bool valid() { return node != nullptr; } class const_iterator { public: const_iterator(tinyxml2::XMLNode *node, const char *name = nullptr) : node(node), name(name) {} const_iterator(const const_iterator& rhs) : node(rhs.node), name(rhs.name) {} bool operator!= (const const_iterator& other) const { return node != other.node; } xmlnode operator* () const { return xmlnode(node); } const const_iterator& operator++ () { node = node->NextSiblingElement(name); return *this; } private: tinyxml2::XMLNode *node; const char *name; }; class xmlnodelist { public: xmlnodelist(tinyxml2::XMLNode *node, const std::string &name = "") : node(node), name(name) {} const_iterator begin() const { return const_iterator(node, name == "" ? nullptr : name.c_str()); } const_iterator end() const { return const_iterator(nullptr); } private: tinyxml2::XMLNode *node; std::string name; }; xmlnodelist all(const std::string &name = "") const { if(!node) throw xml_exception("Invalid node"); return xmlnodelist(node->FirstChildElement(name.c_str()), name); } std::string attr(const std::string &name) const { if(!node) throw xml_exception("Invalid node"); return ((tinyxml2::XMLElement*)node)->Attribute(name.c_str()); } std::string text() const { if(!node) throw xml_exception("Invalid node"); return ((tinyxml2::XMLElement*)node)->GetText(); } protected: tinyxml2::XMLNode *node; }; class xmldoc : public xmlnode { public: static xmldoc fromText(const std::string &text) { return xmldoc(text); } static xmldoc fromFile(utils::File file) { auto text = file.read(); return xmldoc(text); } static xmldoc fromFile(std::string const& fileName) { auto text = utils::File{fileName}.read(); return xmldoc(text); } xmldoc(const xmldoc &other) = default; xmldoc() = default; private: xmldoc(const std::string &text) : xmlnode(nullptr) { doc = std::make_shared<tinyxml2::XMLDocument>(); if(doc->Parse(text.c_str()) != tinyxml2::XML_NO_ERROR) { const char *s0 = doc->GetErrorStr1(); const char *s1 = doc->GetErrorStr2(); std::string text; if(s0) text += std::string(s0); if(s1) text += std::string(s1); throw xml_exception(text); } node = doc.get(); } std::shared_ptr<tinyxml2::XMLDocument> doc; }; #endif // APONE_XML_H
{ "content_hash": "b6d0827c1fd5f1b8852be1c2b134c9ff", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 106, "avg_line_length": 26.29310344827586, "alnum_prop": 0.5693989071038251, "repo_name": "sasq64/apone", "id": "7f30265619541934446fa63dd2f07dfe22665cd9", "size": "4703", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mods/xml/xml.h", "mode": "33188", "license": "mit", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "Assembly", "bytes": "141281" }, { "name": "Awk", "bytes": "3962" }, { "name": "Batchfile", "bytes": "621" }, { "name": "C", "bytes": "30905460" }, { "name": "C#", "bytes": "55626" }, { "name": "C++", "bytes": "10272716" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "81371" }, { "name": "CSS", "bytes": "34404" }, { "name": "DIGITAL Command Language", "bytes": "63119" }, { "name": "Fortran", "bytes": "57604" }, { "name": "GLSL", "bytes": "8370" }, { "name": "HTML", "bytes": "10825184" }, { "name": "JavaScript", "bytes": "90812" }, { "name": "M4", "bytes": "99898" }, { "name": "Makefile", "bytes": "2094831" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "OCaml", "bytes": "254027" }, { "name": "Objective-C", "bytes": "51127" }, { "name": "Pascal", "bytes": "70297" }, { "name": "Perl", "bytes": "74190" }, { "name": "Python", "bytes": "234082" }, { "name": "Roff", "bytes": "305267" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "1465048" }, { "name": "Standard ML", "bytes": "1219" }, { "name": "TeX", "bytes": "323102" }, { "name": "sed", "bytes": "236" } ], "symlink_target": "" }
package bazaar4idea.command; import com.intellij.openapi.project.Project; import bazaar4idea.BzrFile; import org.jetbrains.annotations.NotNull; import java.util.Arrays; public class BzrAddCommand { private final Project project; public BzrAddCommand(Project project) { this.project = project; } public void execute(@NotNull BzrFile bzrFile) { ShellCommandService.getInstance(project) .execute(bzrFile.getRepo(), "add", Arrays.asList(bzrFile.getRelativePath())); } }
{ "content_hash": "ad150684411f5749bab1ec6d39934762", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 85, "avg_line_length": 22.681818181818183, "alnum_prop": 0.7555110220440882, "repo_name": "bwrsandman/bzr4j", "id": "049a9d6a6d276749409d009c405228f7e7e28471", "size": "1083", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/intellij/src/main/java/bazaar4idea/command/BzrAddCommand.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1044148" }, { "name": "Shell", "bytes": "31" } ], "symlink_target": "" }
<?php return [ 'fields_not_accepted'=> 'Kolommen :field worden niet geaccepteerd in de zoekopdracht', ];
{ "content_hash": "7a053c3a39e3bf2c883f60058d36ea08", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 90, "avg_line_length": 22, "alnum_prop": 0.7, "repo_name": "markeilander/repository", "id": "86f763902acffc54adafd7a8abd4e19d90178c7c", "size": "110", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Lang/en/criteria.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "56087" } ], "symlink_target": "" }
IElement* CLuaStorage_ThisElement::pElement = NULL; IDataFactory* CLuaStorage_ThisElement::pInputData = NULL; IDataFactory* CLuaStorage_ThisElement::pOutputData = NULL; CList<IDataFactory*, IDataFactory*> CLuaStorage_FactoriesContainer::mFactoriesList;
{ "content_hash": "e5b9c09a8cea3962c4377d53bb2e2437", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 83, "avg_line_length": 44.666666666666664, "alnum_prop": 0.7873134328358209, "repo_name": "egorpushkin/neurolab", "id": "cb6fb20c5c45db37b55caf2afead64e0857a8907", "size": "317", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/NetworkElements/ScriptsNet/Elements/Source/LuaExtension/GlobalStorage.cpp", "mode": "33261", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "112" }, { "name": "C", "bytes": "1787692" }, { "name": "C++", "bytes": "9312245" }, { "name": "CSS", "bytes": "44465" }, { "name": "Clarion", "bytes": "5268" }, { "name": "HTML", "bytes": "408820" }, { "name": "JavaScript", "bytes": "5476" }, { "name": "Makefile", "bytes": "39256" }, { "name": "Objective-C", "bytes": "97952" }, { "name": "TeX", "bytes": "3128" } ], "symlink_target": "" }
import Ember from 'ember'; import Resolver from 'ember/resolver'; import loadInitializers from 'ember/load-initializers'; import config from './config/environment'; import CarouselItem from 'ember-widgets/views/carousel-item'; var App; Ember.MODEL_FACTORY_INJECTIONS = true; App = Ember.Application.extend({ modulePrefix: config.modulePrefix, podModulePrefix: config.podModulePrefix, Resolver: Resolver }); // Legacy view-as-component weirdness. Don't ever ever ever do this. Ember.Handlebars.helper('carousel-item', CarouselItem); loadInitializers(App, config.modulePrefix); export default App;
{ "content_hash": "baa2ecedc9dc84da2bc7162e41d5c1b8", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 68, "avg_line_length": 27.636363636363637, "alnum_prop": 0.7828947368421053, "repo_name": "Addepar/ember-widgets-addon", "id": "325fc59f308096ec91e6a6997318ad395b672c7a", "size": "608", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/dummy/app/app.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "52588" }, { "name": "HTML", "bytes": "43956" }, { "name": "JavaScript", "bytes": "123559" } ], "symlink_target": "" }
using System; using System.Collections.Generic; namespace EZOper.NetSiteUtilities.AopApi { /// <summary> /// AOP API: alipay.point.balance.get /// </summary> public class AlipayPointBalanceGetRequest : IAopRequest<AlipayPointBalanceGetResponse> { #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.point.balance.get"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
{ "content_hash": "47fce954fd191d585e49d8a3d9e063c5", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 90, "avg_line_length": 23.068627450980394, "alnum_prop": 0.6064598385040374, "repo_name": "erikzhouxin/CSharpSolution", "id": "84dff1bc2a90fc32397ad5152250096e0261e7e5", "size": "2353", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "NetSiteUtilities/AopApi/Request/AlipayPointBalanceGetRequest.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "153832" }, { "name": "Batchfile", "bytes": "104" }, { "name": "C#", "bytes": "16507100" }, { "name": "CSS", "bytes": "1339701" }, { "name": "HTML", "bytes": "25059213" }, { "name": "Java", "bytes": "10698" }, { "name": "JavaScript", "bytes": "53532704" }, { "name": "PHP", "bytes": "48348" }, { "name": "PLSQL", "bytes": "8976" }, { "name": "PowerShell", "bytes": "471" }, { "name": "Ruby", "bytes": "1030" } ], "symlink_target": "" }
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.content.model; /** * Model definition for AccountStatusDataQualityIssue. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Content API for Shopping. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class AccountStatusDataQualityIssue extends com.google.api.client.json.GenericJson { /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String country; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String destination; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String detail; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String displayedValue; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<AccountStatusExampleItem> exampleItems; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String id; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String lastChecked; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String location; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Long numItems; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String severity; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String submittedValue; /** * @return value or {@code null} for none */ public java.lang.String getCountry() { return country; } /** * @param country country or {@code null} for none */ public AccountStatusDataQualityIssue setCountry(java.lang.String country) { this.country = country; return this; } /** * @return value or {@code null} for none */ public java.lang.String getDestination() { return destination; } /** * @param destination destination or {@code null} for none */ public AccountStatusDataQualityIssue setDestination(java.lang.String destination) { this.destination = destination; return this; } /** * @return value or {@code null} for none */ public java.lang.String getDetail() { return detail; } /** * @param detail detail or {@code null} for none */ public AccountStatusDataQualityIssue setDetail(java.lang.String detail) { this.detail = detail; return this; } /** * @return value or {@code null} for none */ public java.lang.String getDisplayedValue() { return displayedValue; } /** * @param displayedValue displayedValue or {@code null} for none */ public AccountStatusDataQualityIssue setDisplayedValue(java.lang.String displayedValue) { this.displayedValue = displayedValue; return this; } /** * @return value or {@code null} for none */ public java.util.List<AccountStatusExampleItem> getExampleItems() { return exampleItems; } /** * @param exampleItems exampleItems or {@code null} for none */ public AccountStatusDataQualityIssue setExampleItems(java.util.List<AccountStatusExampleItem> exampleItems) { this.exampleItems = exampleItems; return this; } /** * @return value or {@code null} for none */ public java.lang.String getId() { return id; } /** * @param id id or {@code null} for none */ public AccountStatusDataQualityIssue setId(java.lang.String id) { this.id = id; return this; } /** * @return value or {@code null} for none */ public java.lang.String getLastChecked() { return lastChecked; } /** * @param lastChecked lastChecked or {@code null} for none */ public AccountStatusDataQualityIssue setLastChecked(java.lang.String lastChecked) { this.lastChecked = lastChecked; return this; } /** * @return value or {@code null} for none */ public java.lang.String getLocation() { return location; } /** * @param location location or {@code null} for none */ public AccountStatusDataQualityIssue setLocation(java.lang.String location) { this.location = location; return this; } /** * @return value or {@code null} for none */ public java.lang.Long getNumItems() { return numItems; } /** * @param numItems numItems or {@code null} for none */ public AccountStatusDataQualityIssue setNumItems(java.lang.Long numItems) { this.numItems = numItems; return this; } /** * @return value or {@code null} for none */ public java.lang.String getSeverity() { return severity; } /** * @param severity severity or {@code null} for none */ public AccountStatusDataQualityIssue setSeverity(java.lang.String severity) { this.severity = severity; return this; } /** * @return value or {@code null} for none */ public java.lang.String getSubmittedValue() { return submittedValue; } /** * @param submittedValue submittedValue or {@code null} for none */ public AccountStatusDataQualityIssue setSubmittedValue(java.lang.String submittedValue) { this.submittedValue = submittedValue; return this; } @Override public AccountStatusDataQualityIssue set(String fieldName, Object value) { return (AccountStatusDataQualityIssue) super.set(fieldName, value); } @Override public AccountStatusDataQualityIssue clone() { return (AccountStatusDataQualityIssue) super.clone(); } }
{ "content_hash": "ab4850d81651485b5569a46a54cb30fe", "timestamp": "", "source": "github", "line_count": 274, "max_line_length": 182, "avg_line_length": 24.445255474452555, "alnum_prop": 0.6784114661092864, "repo_name": "googleapis/google-api-java-client-services", "id": "f162d69096571a69c9c6dc134a92743416fead87", "size": "6698", "binary": false, "copies": "4", "ref": "refs/heads/main", "path": "clients/google-api-services-content/v2/1.29.2/com/google/api/services/content/model/AccountStatusDataQualityIssue.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html><head><title>BiwaScheme : Scheme interpreter for browsers</title ><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link href="css/screen.css" rel="stylesheet" type="text/css" /></head ><body><div id="menu"><a href="index.html"><img src="images/biwascheme_logo.png" /></a ><ul><li><a href="download.html">Download</a ></li ><li><a href="status.html">Status</a ></li ><li><a href="development.html">Development</a ></li ></ul ></div ><div id="content"><h2>Download</h2 ><h3>On-line REPL</h3 ><p>If you just want to try it:<a href="repos/repl.html">BiwaScheme REPL</a ></p ><h3>Release version</h3 ><a href="http://github.com/yhara/biwascheme/downloads">zip and tgz</a ><h3>Latest version</h3 ><p>You can also download the latest verison from the git repository:<br /><a href="http://github.com/yhara/biwascheme">http://github.com/yhara/biwascheme</a ></p ><div id="footer">&copy; 2007-2009 Yutaka HARA and the BiwaScheme team</div ></div ></body ></html >
{ "content_hash": "a85c079c9e60d74c1b2d50fafc355aaa", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 157, "avg_line_length": 39.925925925925924, "alnum_prop": 0.6836734693877551, "repo_name": "masatake/biwascheme", "id": "ffb6496814edac0fd6fd185aa91bfabca64f77e3", "size": "1078", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "website/download.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "338774" }, { "name": "Scheme", "bytes": "41131" }, { "name": "Shell", "bytes": "148" } ], "symlink_target": "" }
struct VeritasEngine::Process::Impl : public VeritasEngine::SmallObject<> { Process::Status m_status { Process::Status::Uninitalized }; }; VeritasEngine::Process::Process() : m_impl{ std::make_unique<Impl>() } { } VeritasEngine::Process::~Process() = default; VeritasEngine::Process::Status VeritasEngine::Process::GetStatus() const { return m_impl->m_status; } void VeritasEngine::Process::Succeed() { m_impl->m_status = Process::Status::Succeeded; } void VeritasEngine::Process::Fail() { m_impl->m_status = Process::Status::Failed; } void VeritasEngine::Process::Pause() { m_impl->m_status = Process::Status::Paused; } void VeritasEngine::Process::UnPause() { m_impl->m_status = Process::Status::Running; } void VeritasEngine::Process::OnInitialized() { m_impl->m_status = Process::Status::Running; } void VeritasEngine::Process::OnSuccess() { } void VeritasEngine::Process::OnFail() { } void VeritasEngine::Process::OnAbort() { }
{ "content_hash": "897120d51646fb78ffdc327ddf597967", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 73, "avg_line_length": 17.46551724137931, "alnum_prop": 0.667324777887463, "repo_name": "webfinesse/veritas-engine", "id": "eab007f6aeab286685c9498117d8155c68e4b301", "size": "1035", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "VeritasEngine/Process.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "478237" }, { "name": "C++", "bytes": "3855486" }, { "name": "HLSL", "bytes": "11780" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BENRGOIN_KEYSTORE_H #define BENRGOIN_KEYSTORE_H #include "crypter.h" #include "sync.h" #include <boost/signals2/signal.hpp> class CScript; /** A virtual base class for key stores */ class CKeyStore { protected: mutable CCriticalSection cs_KeyStore; public: virtual ~CKeyStore() {} // Add a key to the store. virtual bool AddKey(const CKey& key) =0; // Check whether a key corresponding to a given address is present in the store. virtual bool HaveKey(const CKeyID &address) const =0; virtual bool GetKey(const CKeyID &address, CKey& keyOut) const =0; virtual void GetKeys(std::set<CKeyID> &setAddress) const =0; virtual bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const; // Support for BIP 0013 : see https://en.bitcoin.it/wiki/BIP_0013 virtual bool AddCScript(const CScript& redeemScript) =0; virtual bool HaveCScript(const CScriptID &hash) const =0; virtual bool GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const =0; virtual bool GetSecret(const CKeyID &address, CSecret& vchSecret, bool &fCompressed) const { CKey key; if (!GetKey(address, key)) return false; vchSecret = key.GetSecret(fCompressed); return true; } }; typedef std::map<CKeyID, std::pair<CSecret, bool> > KeyMap; typedef std::map<CScriptID, CScript > ScriptMap; /** Basic key store, that keeps keys in an address->secret map */ class CBasicKeyStore : public CKeyStore { protected: KeyMap mapKeys; ScriptMap mapScripts; public: bool AddKey(const CKey& key); bool HaveKey(const CKeyID &address) const { bool result; { LOCK(cs_KeyStore); result = (mapKeys.count(address) > 0); } return result; } void GetKeys(std::set<CKeyID> &setAddress) const { setAddress.clear(); { LOCK(cs_KeyStore); KeyMap::const_iterator mi = mapKeys.begin(); while (mi != mapKeys.end()) { setAddress.insert((*mi).first); mi++; } } } bool GetKey(const CKeyID &address, CKey &keyOut) const { { LOCK(cs_KeyStore); KeyMap::const_iterator mi = mapKeys.find(address); if (mi != mapKeys.end()) { keyOut.Reset(); keyOut.SetSecret((*mi).second.first, (*mi).second.second); return true; } } return false; } virtual bool AddCScript(const CScript& redeemScript); virtual bool HaveCScript(const CScriptID &hash) const; virtual bool GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const; }; typedef std::map<CKeyID, std::pair<CPubKey, std::vector<unsigned char> > > CryptedKeyMap; /** Keystore which keeps the private keys encrypted. * It derives from the basic key store, which is used if no encryption is active. */ class CCryptoKeyStore : public CBasicKeyStore { private: CryptedKeyMap mapCryptedKeys; CKeyingMaterial vMasterKey; // if fUseCrypto is true, mapKeys must be empty // if fUseCrypto is false, vMasterKey must be empty bool fUseCrypto; protected: bool SetCrypted(); // will encrypt previously unencrypted keys bool EncryptKeys(CKeyingMaterial& vMasterKeyIn); bool Unlock(const CKeyingMaterial& vMasterKeyIn); public: CCryptoKeyStore() : fUseCrypto(false) { } bool IsCrypted() const { return fUseCrypto; } bool IsLocked() const { if (!IsCrypted()) return false; bool result; { LOCK(cs_KeyStore); result = vMasterKey.empty(); } return result; } bool Lock(); virtual bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret); bool AddKey(const CKey& key); bool HaveKey(const CKeyID &address) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::HaveKey(address); return mapCryptedKeys.count(address) > 0; } return false; } bool GetKey(const CKeyID &address, CKey& keyOut) const; bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const; void GetKeys(std::set<CKeyID> &setAddress) const { if (!IsCrypted()) { CBasicKeyStore::GetKeys(setAddress); return; } setAddress.clear(); CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin(); while (mi != mapCryptedKeys.end()) { setAddress.insert((*mi).first); mi++; } } /* Wallet status (encrypted, locked) changed. * Note: Called without locks held. */ boost::signals2::signal<void (CCryptoKeyStore* wallet)> NotifyStatusChanged; }; #endif
{ "content_hash": "5bd6c53d9ff6917a4e226e0c32019c26", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 109, "avg_line_length": 28.157608695652176, "alnum_prop": 0.6226597182011194, "repo_name": "EnergyCoin/energycoin", "id": "9f4d08b10d46d28a4925576dc0a0be7cdfdad4f1", "size": "5181", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/keystore.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "73073" }, { "name": "C", "bytes": "65428" }, { "name": "C++", "bytes": "1623263" }, { "name": "Objective-C++", "bytes": "2476" }, { "name": "Python", "bytes": "11647" }, { "name": "Shell", "bytes": "1299" }, { "name": "TypeScript", "bytes": "126822" } ], "symlink_target": "" }
[Link](https://www.codewars.com/kata/even-or-odd) ## Instructions Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers.
{ "content_hash": "738b09b4e1dbd41dfc3f190183c04598", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 116, "avg_line_length": 37, "alnum_prop": 0.7513513513513513, "repo_name": "Madh93/codewars_rb", "id": "f7ba94ce22455ea09ff3e51ec29d0ee66c2162e6", "size": "200", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/kata/kyu8/even_or_odd/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "29109" } ], "symlink_target": "" }
title: afo7 type: products image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png heading: o7 description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj main: heading: Foo Bar BAz description: |- ***This is i a thing***kjh hjk kj # Blah Blah ## Blah![undefined](undefined) ### Baah image1: alt: kkkk ---
{ "content_hash": "5a9fa33bd5f2864772b1126426f8ac0b", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 61, "avg_line_length": 22.2, "alnum_prop": 0.6636636636636637, "repo_name": "pblack/kaldi-hugo-cms-template", "id": "c1810869b64849e90af603a26ae2d55d25d867b5", "size": "337", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "site/content/pages2/afo7.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "94394" }, { "name": "HTML", "bytes": "18889" }, { "name": "JavaScript", "bytes": "10014" } ], "symlink_target": "" }
// Inferno utils/5l/obj.c // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/5l/obj.c // // Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved. // Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net) // Portions Copyright © 1997-1999 Vita Nuova Limited // Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com) // Portions Copyright © 2004,2006 Bruce Ellis // Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net) // Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others // Portions Copyright © 2009 The Go Authors. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package mips64 import ( "cmd/internal/objabi" "cmd/internal/sys" "cmd/link/internal/ld" ) func Init() (*sys.Arch, ld.Arch) { arch := sys.ArchMIPS64 if objabi.GOARCH == "mips64le" { arch = sys.ArchMIPS64LE } theArch := ld.Arch{ Funcalign: funcAlign, Maxalign: maxAlign, Minalign: minAlign, Dwarfregsp: dwarfRegSP, Dwarfreglr: dwarfRegLR, Adddynrel: adddynrel, Archinit: archinit, Archreloc: archreloc, Archrelocvariant: archrelocvariant, Asmb: asmb, Asmb2: asmb2, Elfreloc1: elfreloc1, Elfsetupplt: elfsetupplt, Gentext2: gentext2, Machoreloc1: machoreloc1, Linuxdynld: "/lib64/ld64.so.1", Freebsddynld: "XXX", Openbsddynld: "XXX", Netbsddynld: "XXX", Dragonflydynld: "XXX", Solarisdynld: "XXX", } return arch, theArch } func archinit(ctxt *ld.Link) { switch ctxt.HeadType { default: ld.Exitf("unknown -H option: %v", ctxt.HeadType) case objabi.Hplan9: /* plan 9 */ ld.HEADR = 32 if *ld.FlagTextAddr == -1 { *ld.FlagTextAddr = 16*1024 + int64(ld.HEADR) } if *ld.FlagRound == -1 { *ld.FlagRound = 16 * 1024 } case objabi.Hlinux: /* mips64 elf */ ld.Elfinit(ctxt) ld.HEADR = ld.ELFRESERVE if *ld.FlagTextAddr == -1 { *ld.FlagTextAddr = 0x10000 + int64(ld.HEADR) } if *ld.FlagRound == -1 { *ld.FlagRound = 0x10000 } } }
{ "content_hash": "3429be2d1cf4e8e03793c3e072de7093", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 81, "avg_line_length": 32.10204081632653, "alnum_prop": 0.6929434202161475, "repo_name": "akutz/go", "id": "5efa3564124d920918084e7d3df64f7909db7726", "size": "3154", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/cmd/link/internal/mips64/obj.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "1019992" }, { "name": "Awk", "bytes": "450" }, { "name": "Batchfile", "bytes": "7207" }, { "name": "C", "bytes": "213674" }, { "name": "C++", "bytes": "1373" }, { "name": "CSS", "bytes": "8" }, { "name": "Go", "bytes": "25639298" }, { "name": "HTML", "bytes": "841569" }, { "name": "JavaScript", "bytes": "2550" }, { "name": "Logos", "bytes": "1248" }, { "name": "Makefile", "bytes": "2252" }, { "name": "Perl", "bytes": "34180" }, { "name": "Protocol Buffer", "bytes": "1509" }, { "name": "Python", "bytes": "12446" }, { "name": "Shell", "bytes": "61974" }, { "name": "Yacc", "bytes": "42403" } ], "symlink_target": "" }
// Copyright (C) 2015 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.metrics.proc; import com.google.gerrit.extensions.events.LifecycleListener; import com.google.gerrit.lifecycle.LifecycleModule; import com.google.gerrit.metrics.MetricMaker; import com.google.inject.Inject; /** Guice module to configure metrics on server startup. */ public abstract class MetricModule extends LifecycleModule { /** Configure metrics during server startup. */ protected abstract void configure(MetricMaker metrics); @Override protected void configure() { listener().toInstance(new LifecycleListener() { @Inject MetricMaker metrics; @Override public void start() { configure(metrics); } @Override public void stop() { } }); } }
{ "content_hash": "f3fce0a62b65dcb00c9b109921c2faaf", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 75, "avg_line_length": 31.558139534883722, "alnum_prop": 0.7280766396462786, "repo_name": "MerritCR/merrit", "id": "c556ee4e082bfcbb8fe4aa1783cb6028c83a216b", "size": "1357", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "gerrit-server/src/main/java/com/google/gerrit/metrics/proc/MetricModule.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "52838" }, { "name": "GAP", "bytes": "4119" }, { "name": "Go", "bytes": "6200" }, { "name": "Groff", "bytes": "28221" }, { "name": "HTML", "bytes": "380099" }, { "name": "Java", "bytes": "10070223" }, { "name": "JavaScript", "bytes": "197056" }, { "name": "Makefile", "bytes": "1313" }, { "name": "PLpgSQL", "bytes": "4202" }, { "name": "Perl", "bytes": "9943" }, { "name": "Prolog", "bytes": "17904" }, { "name": "Python", "bytes": "18218" }, { "name": "Shell", "bytes": "48919" }, { "name": "TypeScript", "bytes": "1882" } ], "symlink_target": "" }
"""Get useful information from live Python objects. This module encapsulates the interface provided by the internal special attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion. It also provides some help for examining source code and class layout. Here are some of the useful functions provided by this module: ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(), isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(), isroutine() - check object types getmembers() - get members of an object that satisfy a given condition getfile(), getsourcefile(), getsource() - find an object's source code getdoc(), getcomments() - get documentation on an object getmodule() - determine the module that an object came from getclasstree() - arrange classes so as to represent their hierarchy getargvalues(), getcallargs() - get info about function arguments getfullargspec() - same, with support for Python 3 features formatargspec(), formatargvalues() - format an argument spec getouterframes(), getinnerframes() - get info about frames currentframe() - get the current stack frame stack(), trace() - get info about frames on the stack or in a traceback signature() - get a Signature object for the callable """ # This module is in the public domain. No warranties. __author__ = ('Ka-Ping Yee <ping@lfw.org>', 'Yury Selivanov <yselivanov@sprymix.com>') import ast import dis import collections.abc import enum import importlib.machinery import itertools import linecache import os import re import sys import tokenize import token import types import warnings import functools import builtins from operator import attrgetter from collections import namedtuple, OrderedDict # Create constants for the compiler flags in Include/code.h # We try to get them from dis to avoid duplication mod_dict = globals() for k, v in dis.COMPILER_FLAG_NAMES.items(): mod_dict["CO_" + v] = k # See Include/object.h TPFLAGS_IS_ABSTRACT = 1 << 20 # ----------------------------------------------------------- type-checking def ismodule(object): """Return true if the object is a module. Module objects provide these attributes: __cached__ pathname to byte compiled file __doc__ documentation string __file__ filename (missing for built-in modules)""" return isinstance(object, types.ModuleType) def isclass(object): """Return true if the object is a class. Class objects provide these attributes: __doc__ documentation string __module__ name of module in which this class was defined""" return isinstance(object, type) def ismethod(object): """Return true if the object is an instance method. Instance method objects provide these attributes: __doc__ documentation string __name__ name with which this method was defined __func__ function object containing implementation of method __self__ instance to which this method is bound""" return isinstance(object, types.MethodType) def ismethoddescriptor(object): """Return true if the object is a method descriptor. But not if ismethod() or isclass() or isfunction() are true. This is new in Python 2.2, and, for example, is true of int.__add__. An object passing this test has a __get__ attribute but not a __set__ attribute, but beyond that the set of attributes varies. __name__ is usually sensible, and __doc__ often is. Methods implemented via descriptors that also pass one of the other tests return false from the ismethoddescriptor() test, simply because the other tests promise more -- you can, e.g., count on having the __func__ attribute (etc) when an object passes ismethod().""" if isclass(object) or ismethod(object) or isfunction(object): # mutual exclusion return False tp = type(object) return hasattr(tp, "__get__") and not hasattr(tp, "__set__") def isdatadescriptor(object): """Return true if the object is a data descriptor. Data descriptors have both a __get__ and a __set__ attribute. Examples are properties (defined in Python) and getsets and members (defined in C). Typically, data descriptors will also have __name__ and __doc__ attributes (properties, getsets, and members have both of these attributes), but this is not guaranteed.""" if isclass(object) or ismethod(object) or isfunction(object): # mutual exclusion return False tp = type(object) return hasattr(tp, "__set__") and hasattr(tp, "__get__") if hasattr(types, 'MemberDescriptorType'): # CPython and equivalent def ismemberdescriptor(object): """Return true if the object is a member descriptor. Member descriptors are specialized descriptors defined in extension modules.""" return isinstance(object, types.MemberDescriptorType) else: # Other implementations def ismemberdescriptor(object): """Return true if the object is a member descriptor. Member descriptors are specialized descriptors defined in extension modules.""" return False if hasattr(types, 'GetSetDescriptorType'): # CPython and equivalent def isgetsetdescriptor(object): """Return true if the object is a getset descriptor. getset descriptors are specialized descriptors defined in extension modules.""" return isinstance(object, types.GetSetDescriptorType) else: # Other implementations def isgetsetdescriptor(object): """Return true if the object is a getset descriptor. getset descriptors are specialized descriptors defined in extension modules.""" return False def isfunction(object): """Return true if the object is a user-defined function. Function objects provide these attributes: __doc__ documentation string __name__ name with which this function was defined __code__ code object containing compiled function bytecode __defaults__ tuple of any default values for arguments __globals__ global namespace in which this function was defined __annotations__ dict of parameter annotations __kwdefaults__ dict of keyword only parameters with defaults""" return isinstance(object, types.FunctionType) def isgeneratorfunction(object): """Return true if the object is a user-defined generator function. Generator function objects provide the same attributes as functions. See help(isfunction) for a list of attributes.""" return bool((isfunction(object) or ismethod(object)) and object.__code__.co_flags & CO_GENERATOR) def iscoroutinefunction(object): """Return true if the object is a coroutine function. Coroutine functions are defined with "async def" syntax. """ return bool((isfunction(object) or ismethod(object)) and object.__code__.co_flags & CO_COROUTINE) def isasyncgenfunction(object): """Return true if the object is an asynchronous generator function. Asynchronous generator functions are defined with "async def" syntax and have "yield" expressions in their body. """ return bool((isfunction(object) or ismethod(object)) and object.__code__.co_flags & CO_ASYNC_GENERATOR) def isasyncgen(object): """Return true if the object is an asynchronous generator.""" return isinstance(object, types.AsyncGeneratorType) def isgenerator(object): """Return true if the object is a generator. Generator objects provide these attributes: __iter__ defined to support iteration over container close raises a new GeneratorExit exception inside the generator to terminate the iteration gi_code code object gi_frame frame object or possibly None once the generator has been exhausted gi_running set to 1 when generator is executing, 0 otherwise next return the next item from the container send resumes the generator and "sends" a value that becomes the result of the current yield-expression throw used to raise an exception inside the generator""" return isinstance(object, types.GeneratorType) def iscoroutine(object): """Return true if the object is a coroutine.""" return isinstance(object, types.CoroutineType) def isawaitable(object): """Return true if object can be passed to an ``await`` expression.""" return (isinstance(object, types.CoroutineType) or isinstance(object, types.GeneratorType) and bool(object.gi_code.co_flags & CO_ITERABLE_COROUTINE) or isinstance(object, collections.abc.Awaitable)) def istraceback(object): """Return true if the object is a traceback. Traceback objects provide these attributes: tb_frame frame object at this level tb_lasti index of last attempted instruction in bytecode tb_lineno current line number in Python source code tb_next next inner traceback object (called by this level)""" return isinstance(object, types.TracebackType) def isframe(object): """Return true if the object is a frame object. Frame objects provide these attributes: f_back next outer frame object (this frame's caller) f_builtins built-in namespace seen by this frame f_code code object being executed in this frame f_globals global namespace seen by this frame f_lasti index of last attempted instruction in bytecode f_lineno current line number in Python source code f_locals local namespace seen by this frame f_trace tracing function for this frame, or None""" return isinstance(object, types.FrameType) def iscode(object): """Return true if the object is a code object. Code objects provide these attributes: co_argcount number of arguments (not including * or ** args) co_code string of raw compiled bytecode co_consts tuple of constants used in the bytecode co_filename name of file in which this code object was created co_firstlineno number of first line in Python source code co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg co_lnotab encoded mapping of line numbers to bytecode indices co_name name with which this code object was defined co_names tuple of names of local variables co_nlocals number of local variables co_stacksize virtual machine stack space required co_varnames tuple of names of arguments and local variables""" return isinstance(object, types.CodeType) def isbuiltin(object): """Return true if the object is a built-in function or method. Built-in functions and methods provide these attributes: __doc__ documentation string __name__ original name of this function or method __self__ instance to which a method is bound, or None""" return isinstance(object, types.BuiltinFunctionType) def isroutine(object): """Return true if the object is any kind of function or method.""" return (isbuiltin(object) or isfunction(object) or ismethod(object) or ismethoddescriptor(object)) def isabstract(object): """Return true if the object is an abstract base class (ABC).""" return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT) def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" if isclass(object): mro = (object,) + getmro(object) else: mro = () results = [] processed = set() names = dir(object) # :dd any DynamicClassAttributes to the list of names if object is a class; # this may result in duplicate entries if, for example, a virtual # attribute with the same name as a DynamicClassAttribute exists try: for base in object.__bases__: for k, v in base.__dict__.items(): if isinstance(v, types.DynamicClassAttribute): names.append(k) except AttributeError: pass for key in names: # First try to get the value via getattr. Some descriptors don't # like calling their __get__ (see bug #1785), so fall back to # looking in the __dict__. try: value = getattr(object, key) # handle the duplicate key if key in processed: raise AttributeError except AttributeError: for base in mro: if key in base.__dict__: value = base.__dict__[key] break else: # could be a (currently) missing slot member, or a buggy # __dir__; discard and move on continue if not predicate or predicate(value): results.append((key, value)) processed.add(key) results.sort(key=lambda pair: pair[0]) return results Attribute = namedtuple('Attribute', 'name kind defining_class object') def classify_class_attrs(cls): """Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: 0. The name (a string). 1. The kind of attribute this is, one of these strings: 'class method' created via classmethod() 'static method' created via staticmethod() 'property' created via property() 'method' any other flavor of method or descriptor 'data' not a method 2. The class which defined this attribute (a class). 3. The object as obtained by calling getattr; if this fails, or if the resulting object does not live anywhere in the class' mro (including metaclasses) then the object is looked up in the defining class's dict (found by walking the mro). If one of the items in dir(cls) is stored in the metaclass it will now be discovered and not have None be listed as the class in which it was defined. Any items whose home class cannot be discovered are skipped. """ mro = getmro(cls) metamro = getmro(type(cls)) # for attributes stored in the metaclass metamro = tuple([cls for cls in metamro if cls not in (type, object)]) class_bases = (cls,) + mro all_bases = class_bases + metamro names = dir(cls) # :dd any DynamicClassAttributes to the list of names; # this may result in duplicate entries if, for example, a virtual # attribute with the same name as a DynamicClassAttribute exists. for base in mro: for k, v in base.__dict__.items(): if isinstance(v, types.DynamicClassAttribute): names.append(k) result = [] processed = set() for name in names: # Get the object associated with the name, and where it was defined. # Normal objects will be looked up with both getattr and directly in # its class' dict (in case getattr fails [bug #1785], and also to look # for a docstring). # For DynamicClassAttributes on the second pass we only look in the # class's dict. # # Getting an obj from the __dict__ sometimes reveals more than # using getattr. Static and class methods are dramatic examples. homecls = None get_obj = None dict_obj = None if name not in processed: try: if name == '__dict__': raise Exception("__dict__ is special, don't want the proxy") get_obj = getattr(cls, name) except Exception as exc: pass else: homecls = getattr(get_obj, "__objclass__", homecls) if homecls not in class_bases: # if the resulting object does not live somewhere in the # mro, drop it and search the mro manually homecls = None last_cls = None # first look in the classes for srch_cls in class_bases: srch_obj = getattr(srch_cls, name, None) if srch_obj is get_obj: last_cls = srch_cls # then check the metaclasses for srch_cls in metamro: try: srch_obj = srch_cls.__getattr__(cls, name) except AttributeError: continue if srch_obj is get_obj: last_cls = srch_cls if last_cls is not None: homecls = last_cls for base in all_bases: if name in base.__dict__: dict_obj = base.__dict__[name] if homecls not in metamro: homecls = base break if homecls is None: # unable to locate the attribute anywhere, most likely due to # buggy custom __dir__; discard and move on continue obj = get_obj if get_obj is not None else dict_obj # Classify the object or its descriptor. if isinstance(dict_obj, staticmethod): kind = "static method" obj = dict_obj elif isinstance(dict_obj, classmethod): kind = "class method" obj = dict_obj elif isinstance(dict_obj, property): kind = "property" obj = dict_obj elif isroutine(obj): kind = "method" else: kind = "data" result.append(Attribute(name, kind, homecls, obj)) processed.add(name) return result # ----------------------------------------------------------- class helpers def getmro(cls): "Return tuple of base classes (including cls) in method resolution order." return cls.__mro__ # -------------------------------------------------------- function helpers def unwrap(func, *, stop=None): """Get the object wrapped by *func*. Follows the chain of :attr:`__wrapped__` attributes returning the last object in the chain. *stop* is an optional callback accepting an object in the wrapper chain as its sole argument that allows the unwrapping to be terminated early if the callback returns a true value. If the callback never returns a true value, the last object in the chain is returned as usual. For example, :func:`signature` uses this to stop unwrapping if any object in the chain has a ``__signature__`` attribute defined. :exc:`ValueError` is raised if a cycle is encountered. """ if stop is None: def _is_wrapper(f): return hasattr(f, '__wrapped__') else: def _is_wrapper(f): return hasattr(f, '__wrapped__') and not stop(f) f = func # remember the original func for error reporting memo = {id(f)} # Memoise by id to tolerate non-hashable objects while _is_wrapper(func): func = func.__wrapped__ id_func = id(func) if id_func in memo: raise ValueError('wrapper loop when unwrapping {!r}'.format(f)) memo.add(id_func) return func # -------------------------------------------------- source code extraction def indentsize(line): """Return the indent size, in spaces, at the start of a line of text.""" expline = line.expandtabs() return len(expline) - len(expline.lstrip()) def _findclass(func): cls = sys.modules.get(func.__module__) if cls is None: return None for name in func.__qualname__.split('.')[:-1]: cls = getattr(cls, name) if not isclass(cls): return None return cls def _finddoc(obj): if isclass(obj): for base in obj.__mro__: if base is not object: try: doc = base.__doc__ except AttributeError: continue if doc is not None: return doc return None if ismethod(obj): name = obj.__func__.__name__ self = obj.__self__ if (isclass(self) and getattr(getattr(self, name, None), '__func__') is obj.__func__): # classmethod cls = self else: cls = self.__class__ elif isfunction(obj): name = obj.__name__ cls = _findclass(obj) if cls is None or getattr(cls, name) is not obj: return None elif isbuiltin(obj): name = obj.__name__ self = obj.__self__ if (isclass(self) and self.__qualname__ + '.' + name == obj.__qualname__): # classmethod cls = self else: cls = self.__class__ # Should be tested before isdatadescriptor(). elif isinstance(obj, property): func = obj.fget name = func.__name__ cls = _findclass(func) if cls is None or getattr(cls, name) is not obj: return None elif ismethoddescriptor(obj) or isdatadescriptor(obj): name = obj.__name__ cls = obj.__objclass__ if getattr(cls, name) is not obj: return None else: return None for base in cls.__mro__: try: doc = getattr(base, name).__doc__ except AttributeError: continue if doc is not None: return doc return None def getdoc(object): """Get the documentation string for an object. All tabs are expanded to spaces. To clean up docstrings that are indented to line up with blocks of code, any whitespace than can be uniformly removed from the second line onwards is removed.""" try: doc = object.__doc__ except AttributeError: return None if doc is None: try: doc = _finddoc(object) except (AttributeError, TypeError): return None if not isinstance(doc, str): return None return cleandoc(doc) def cleandoc(doc): """Clean up indentation from docstrings. Any whitespace that can be uniformly removed from the second line onwards is removed.""" try: lines = doc.expandtabs().split('\n') except UnicodeError: return None else: # Find minimum indentation of any non-blank lines after first line. margin = sys.maxsize for line in lines[1:]: content = len(line.lstrip()) if content: indent = len(line) - content margin = min(margin, indent) # Remove indentation. if lines: lines[0] = lines[0].lstrip() if margin < sys.maxsize: for i in range(1, len(lines)): lines[i] = lines[i][margin:] # Remove any trailing or leading blank lines. while lines and not lines[-1]: lines.pop() while lines and not lines[0]: lines.pop(0) return '\n'.join(lines) def getfile(object): """Work out which source or compiled file an object was defined in.""" if ismodule(object): if hasattr(object, '__file__'): return object.__file__ raise TypeError('{!r} is a built-in module'.format(object)) if isclass(object): if hasattr(object, '__module__'): object = sys.modules.get(object.__module__) if hasattr(object, '__file__'): return object.__file__ raise TypeError('{!r} is a built-in class'.format(object)) if ismethod(object): object = object.__func__ if isfunction(object): object = object.__code__ if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): return object.co_filename raise TypeError('{!r} is not a module, class, method, ' 'function, traceback, frame, or code object'.format(object)) def getmodulename(path): """Return the module name for a given file, or None.""" fname = os.path.basename(path) # Check for paths that look like an actual module file suffixes = [(-len(suffix), suffix) for suffix in importlib.machinery.all_suffixes()] suffixes.sort() # try longest suffixes first, in case they overlap for neglen, suffix in suffixes: if fname.endswith(suffix): return fname[:neglen] return None def getsourcefile(object): """Return the filename that can be used to locate an object's source. Return None if no way can be identified to get the source. """ filename = getfile(object) all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:] all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:] if any(filename.endswith(s) for s in all_bytecode_suffixes): filename = (os.path.splitext(filename)[0] + importlib.machinery.SOURCE_SUFFIXES[0]) elif any(filename.endswith(s) for s in importlib.machinery.EXTENSION_SUFFIXES): return None if os.path.exists(filename): return filename # only return a non-existent filename if the module has a PEP 302 loader if getattr(getmodule(object, filename), '__loader__', None) is not None: return filename # or it is in the linecache if filename in linecache.cache: return filename def getabsfile(object, _filename=None): """Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible.""" if _filename is None: _filename = getsourcefile(object) or getfile(object) return os.path.normcase(os.path.abspath(_filename)) modulesbyfile = {} _filesbymodname = {} def getmodule(object, _filename=None): """Return the module an object was defined in, or None if not found.""" if ismodule(object): return object if hasattr(object, '__module__'): return sys.modules.get(object.__module__) # Try the filename to modulename cache if _filename is not None and _filename in modulesbyfile: return sys.modules.get(modulesbyfile[_filename]) # Try the cache again with the absolute file name try: file = getabsfile(object, _filename) except TypeError: return None if file in modulesbyfile: return sys.modules.get(modulesbyfile[file]) # Update the filename to module name cache and check yet again # Copy sys.modules in order to cope with changes while iterating for modname, module in list(sys.modules.items()): if ismodule(module) and hasattr(module, '__file__'): f = module.__file__ if f == _filesbymodname.get(modname, None): # Have already mapped this module, so skip it continue _filesbymodname[modname] = f f = getabsfile(module) # Always map to the name the module knows itself by modulesbyfile[f] = modulesbyfile[ os.path.realpath(f)] = module.__name__ if file in modulesbyfile: return sys.modules.get(modulesbyfile[file]) # Check the main module main = sys.modules['__main__'] if not hasattr(object, '__name__'): return None if hasattr(main, object.__name__): mainobject = getattr(main, object.__name__) if mainobject is object: return main # Check builtins builtin = sys.modules['builtins'] if hasattr(builtin, object.__name__): builtinobject = getattr(builtin, object.__name__) if builtinobject is object: return builtin def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An OSError is raised if the source code cannot be retrieved.""" file = getsourcefile(object) if file: # Invalidate cache if needed. linecache.checkcache(file) else: file = getfile(object) # Allow filenames in form of "<something>" to pass through. # `doctest` monkeypatches `linecache` module to enable # inspection, so let `linecache.getlines` to be called. if not (file.startswith('<') and file.endswith('>')): raise OSError('source code not available') module = getmodule(object, file) if module: lines = linecache.getlines(file, module.__dict__) else: lines = linecache.getlines(file) if not lines: raise OSError('could not get source code') if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^(\s*)class\s*' + name + r'\b') # make some effort to find the best matching class definition: # use the one with the least indentation, which is the one # that's most probably not inside a function definition. candidates = [] for i in range(len(lines)): match = pat.match(lines[i]) if match: # if it's at toplevel, it's already the best one if lines[i][0] == 'c': return lines, i # else add whitespace to candidate list candidates.append((match.group(1), i)) if candidates: # this will sort by whitespace, and by line number, # less whitespace first candidates.sort() return lines, candidates[0][1] else: raise OSError('could not find class definition') if ismethod(object): object = object.__func__ if isfunction(object): object = object.__code__ if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise OSError('could not find function definition') lnum = object.co_firstlineno - 1 pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise OSError('could not find code object') def getcomments(object): """Get lines of comments immediately preceding an object's source code. Returns None when source can't be found. """ try: lines, lnum = findsource(object) except (OSError, TypeError): return None if ismodule(object): # Look for a comment block at the top of the file. start = 0 if lines and lines[0][:2] == '#!': start = 1 while start < len(lines) and lines[start].strip() in ('', '#'): start = start + 1 if start < len(lines) and lines[start][:1] == '#': comments = [] end = start while end < len(lines) and lines[end][:1] == '#': comments.append(lines[end].expandtabs()) end = end + 1 return ''.join(comments) # Look for a preceding block of comments at the same indentation. elif lnum > 0: indent = indentsize(lines[lnum]) end = lnum - 1 if end >= 0 and lines[end].lstrip()[:1] == '#' and \ indentsize(lines[end]) == indent: comments = [lines[end].expandtabs().lstrip()] if end > 0: end = end - 1 comment = lines[end].expandtabs().lstrip() while comment[:1] == '#' and indentsize(lines[end]) == indent: comments[:0] = [comment] end = end - 1 if end < 0: break comment = lines[end].expandtabs().lstrip() while comments and comments[0].strip() == '#': comments[:1] = [] while comments and comments[-1].strip() == '#': comments[-1:] = [] return ''.join(comments) class EndOfBlock(Exception): pass class BlockFinder: """Provide a tokeneater() method to detect the end of a code block.""" def __init__(self): self.indent = 0 self.islambda = False self.started = False self.passline = False self.indecorator = False self.decoratorhasargs = False self.last = 1 def tokeneater(self, type, token, srowcol, erowcol, line): if not self.started and not self.indecorator: # skip any decorators if token == "@": self.indecorator = True # look for the first "def", "class" or "lambda" elif token in ("def", "class", "lambda"): if token == "lambda": self.islambda = True self.started = True self.passline = True # skip to the end of the line elif token == "(": if self.indecorator: self.decoratorhasargs = True elif token == ")": if self.indecorator: self.indecorator = False self.decoratorhasargs = False elif type == tokenize.NEWLINE: self.passline = False # stop skipping when a NEWLINE is seen self.last = srowcol[0] if self.islambda: # lambdas always end at the first NEWLINE raise EndOfBlock # hitting a NEWLINE when in a decorator without args # ends the decorator if self.indecorator and not self.decoratorhasargs: self.indecorator = False elif self.passline: pass elif type == tokenize.INDENT: self.indent = self.indent + 1 self.passline = True elif type == tokenize.DEDENT: self.indent = self.indent - 1 # the end of matching indent/dedent pairs end a block # (note that this only works for "def"/"class" blocks, # not e.g. for "if: else:" or "try: finally:" blocks) if self.indent <= 0: raise EndOfBlock elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL): # any other token on the same indentation level end the previous # block as well, except the pseudo-tokens COMMENT and NL. raise EndOfBlock def getblock(lines): """Extract the block of code at the top of the given list of lines.""" blockfinder = BlockFinder() try: tokens = tokenize.generate_tokens(iter(lines).__next__) for _token in tokens: blockfinder.tokeneater(*_token) except (EndOfBlock, IndentationError): pass return lines[:blockfinder.last] def getsourcelines(object): """Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An OSError is raised if the source code cannot be retrieved.""" object = unwrap(object) lines, lnum = findsource(object) if ismodule(object): return lines, 0 else: return getblock(lines[lnum:]), lnum + 1 def getsource(object): """Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An OSError is raised if the source code cannot be retrieved.""" lines, lnum = getsourcelines(object) return ''.join(lines) # --------------------------------------------------- class tree extraction def walktree(classes, children, parent): """Recursive helper function for getclasstree().""" results = [] classes.sort(key=attrgetter('__module__', '__name__')) for c in classes: results.append((c, c.__bases__)) if c in children: results.append(walktree(children[c], children, c)) return results def getclasstree(classes, unique=False): """Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple containing a class and a tuple of its base classes. If the 'unique' argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times.""" children = {} roots = [] for c in classes: if c.__bases__: for parent in c.__bases__: if not parent in children: children[parent] = [] if c not in children[parent]: children[parent].append(c) if unique and parent in classes: break elif c not in roots: roots.append(c) for parent in children: if parent not in classes: roots.append(parent) return walktree(roots, children, None) # ------------------------------------------------ argument list extraction Arguments = namedtuple('Arguments', 'args, varargs, varkw') def getargs(co): """Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' is the list of argument names. Keyword-only arguments are appended. 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" args, varargs, kwonlyargs, varkw = _getfullargs(co) return Arguments(args + kwonlyargs, varargs, varkw) def _getfullargs(co): """Get information about the arguments accepted by a code object. Four things are returned: (args, varargs, kwonlyargs, varkw), where 'args' and 'kwonlyargs' are lists of argument names, and 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" if not iscode(co): raise TypeError('{!r} is not a code object'.format(co)) nargs = co.co_argcount names = co.co_varnames nkwargs = co.co_kwonlyargcount args = list(names[:nargs]) kwonlyargs = list(names[nargs:nargs+nkwargs]) step = 0 nargs += nkwargs varargs = None if co.co_flags & CO_VARARGS: varargs = co.co_varnames[nargs] nargs = nargs + 1 varkw = None if co.co_flags & CO_VARKEYWORDS: varkw = co.co_varnames[nargs] return args, varargs, kwonlyargs, varkw ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults') def getargspec(func): """Get the names and default values of a function's parameters. A tuple of four things is returned: (args, varargs, keywords, defaults). 'args' is a list of the argument names, including keyword-only argument names. 'varargs' and 'keywords' are the names of the * and ** parameters or None. 'defaults' is an n-tuple of the default values of the last n parameters. This function is deprecated, as it does not support annotations or keyword-only parameters and will raise ValueError if either is present on the supplied callable. For a more structured introspection API, use inspect.signature() instead. Alternatively, use getfullargspec() for an API with a similar namedtuple based interface, but full support for annotations and keyword-only parameters. """ warnings.warn("inspect.getargspec() is deprecated, " "use inspect.signature() or inspect.getfullargspec()", DeprecationWarning, stacklevel=2) args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \ getfullargspec(func) if kwonlyargs or ann: raise ValueError("Function has keyword-only parameters or annotations" ", use getfullargspec() API which can support them") return ArgSpec(args, varargs, varkw, defaults) FullArgSpec = namedtuple('FullArgSpec', 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations') def getfullargspec(func): """Get the names and default values of a callable object's parameters. A tuple of seven things is returned: (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations). 'args' is a list of the parameter names. 'varargs' and 'varkw' are the names of the * and ** parameters or None. 'defaults' is an n-tuple of the default values of the last n parameters. 'kwonlyargs' is a list of keyword-only parameter names. 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults. 'annotations' is a dictionary mapping parameter names to annotations. Notable differences from inspect.signature(): - the "self" parameter is always reported, even for bound methods - wrapper chains defined by __wrapped__ *not* unwrapped automatically """ try: # Re: `skip_bound_arg=False` # # There is a notable difference in behaviour between getfullargspec # and Signature: the former always returns 'self' parameter for bound # methods, whereas the Signature always shows the actual calling # signature of the passed object. # # To simulate this behaviour, we "unbind" bound methods, to trick # inspect.signature to always return their first parameter ("self", # usually) # Re: `follow_wrapper_chains=False` # # getfullargspec() historically ignored __wrapped__ attributes, # so we ensure that remains the case in 3.3+ sig = _signature_from_callable(func, follow_wrapper_chains=False, skip_bound_arg=False, sigcls=Signature) except Exception as ex: # Most of the times 'signature' will raise ValueError. # But, it can also raise AttributeError, and, maybe something # else. So to be fully backwards compatible, we catch all # possible exceptions here, and reraise a TypeError. raise TypeError('unsupported callable') from ex args = [] varargs = None varkw = None kwonlyargs = [] defaults = () annotations = {} defaults = () kwdefaults = {} if sig.return_annotation is not sig.empty: annotations['return'] = sig.return_annotation for param in sig.parameters.values(): kind = param.kind name = param.name if kind is _POSITIONAL_ONLY: args.append(name) elif kind is _POSITIONAL_OR_KEYWORD: args.append(name) if param.default is not param.empty: defaults += (param.default,) elif kind is _VAR_POSITIONAL: varargs = name elif kind is _KEYWORD_ONLY: kwonlyargs.append(name) if param.default is not param.empty: kwdefaults[name] = param.default elif kind is _VAR_KEYWORD: varkw = name if param.annotation is not param.empty: annotations[name] = param.annotation if not kwdefaults: # compatibility with 'func.__kwdefaults__' kwdefaults = None if not defaults: # compatibility with 'func.__defaults__' defaults = None return FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwdefaults, annotations) ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals') def getargvalues(frame): """Get information about arguments passed into a particular frame. A tuple of four things is returned: (args, varargs, varkw, locals). 'args' is a list of the argument names. 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'locals' is the locals dictionary of the given frame.""" args, varargs, varkw = getargs(frame.f_code) return ArgInfo(args, varargs, varkw, frame.f_locals) def formatannotation(annotation, base_module=None): if getattr(annotation, '__module__', None) == 'typing': return repr(annotation).replace('typing.', '') if isinstance(annotation, type): if annotation.__module__ in ('builtins', base_module): return annotation.__qualname__ return annotation.__module__+'.'+annotation.__qualname__ return repr(annotation) def formatannotationrelativeto(object): module = getattr(object, '__module__', None) def _formatannotation(annotation): return formatannotation(annotation, module) return _formatannotation def formatargspec(args, varargs=None, varkw=None, defaults=None, kwonlyargs=(), kwonlydefaults={}, annotations={}, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), formatreturns=lambda text: ' -> ' + text, formatannotation=formatannotation): """Format an argument spec from the values returned by getfullargspec. The first seven arguments are (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations). The other five arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The last argument is an optional function to format the sequence of arguments.""" def formatargandannotation(arg): result = formatarg(arg) if arg in annotations: result += ': ' + formatannotation(annotations[arg]) return result specs = [] if defaults: firstdefault = len(args) - len(defaults) for i, arg in enumerate(args): spec = formatargandannotation(arg) if defaults and i >= firstdefault: spec = spec + formatvalue(defaults[i - firstdefault]) specs.append(spec) if varargs is not None: specs.append(formatvarargs(formatargandannotation(varargs))) else: if kwonlyargs: specs.append('*') if kwonlyargs: for kwonlyarg in kwonlyargs: spec = formatargandannotation(kwonlyarg) if kwonlydefaults and kwonlyarg in kwonlydefaults: spec += formatvalue(kwonlydefaults[kwonlyarg]) specs.append(spec) if varkw is not None: specs.append(formatvarkw(formatargandannotation(varkw))) result = '(' + ', '.join(specs) + ')' if 'return' in annotations: result += formatreturns(formatannotation(annotations['return'])) return result def formatargvalues(args, varargs, varkw, locals, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value)): """Format an argument spec from the 4 values returned by getargvalues. The first four arguments are (args, varargs, varkw, locals). The next four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional function to format the sequence of arguments.""" def convert(name, locals=locals, formatarg=formatarg, formatvalue=formatvalue): return formatarg(name) + formatvalue(locals[name]) specs = [] for i in range(len(args)): specs.append(convert(args[i])) if varargs: specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) if varkw: specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) return '(' + ', '.join(specs) + ')' def _missing_arguments(f_name, argnames, pos, values): names = [repr(name) for name in argnames if name not in values] missing = len(names) if missing == 1: s = names[0] elif missing == 2: s = "{} and {}".format(*names) else: tail = ", {} and {}".format(*names[-2:]) del names[-2:] s = ", ".join(names) + tail raise TypeError("%s() missing %i required %s argument%s: %s" % (f_name, missing, "positional" if pos else "keyword-only", "" if missing == 1 else "s", s)) def _too_many(f_name, args, kwonly, varargs, defcount, given, values): atleast = len(args) - defcount kwonly_given = len([arg for arg in kwonly if arg in values]) if varargs: plural = atleast != 1 sig = "at least %d" % (atleast,) elif defcount: plural = True sig = "from %d to %d" % (atleast, len(args)) else: plural = len(args) != 1 sig = str(len(args)) kwonly_sig = "" if kwonly_given: msg = " positional argument%s (and %d keyword-only argument%s)" kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given, "s" if kwonly_given != 1 else "")) raise TypeError("%s() takes %s positional argument%s but %d%s %s given" % (f_name, sig, "s" if plural else "", given, kwonly_sig, "was" if given == 1 and not kwonly_given else "were")) def getcallargs(*func_and_positional, **named): """Get the mapping of arguments to values. A dict is returned, with keys the function argument names (including the names of the * and ** arguments, if any), and values the respective bound values from 'positional' and 'named'.""" func = func_and_positional[0] positional = func_and_positional[1:] spec = getfullargspec(func) args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec f_name = func.__name__ arg2value = {} if ismethod(func) and func.__self__ is not None: # implicit 'self' (or 'cls' for classmethods) argument positional = (func.__self__,) + positional num_pos = len(positional) num_args = len(args) num_defaults = len(defaults) if defaults else 0 n = min(num_pos, num_args) for i in range(n): arg2value[args[i]] = positional[i] if varargs: arg2value[varargs] = tuple(positional[n:]) possible_kwargs = set(args + kwonlyargs) if varkw: arg2value[varkw] = {} for kw, value in named.items(): if kw not in possible_kwargs: if not varkw: raise TypeError("%s() got an unexpected keyword argument %r" % (f_name, kw)) arg2value[varkw][kw] = value continue if kw in arg2value: raise TypeError("%s() got multiple values for argument %r" % (f_name, kw)) arg2value[kw] = value if num_pos > num_args and not varargs: _too_many(f_name, args, kwonlyargs, varargs, num_defaults, num_pos, arg2value) if num_pos < num_args: req = args[:num_args - num_defaults] for arg in req: if arg not in arg2value: _missing_arguments(f_name, req, True, arg2value) for i, arg in enumerate(args[num_args - num_defaults:]): if arg not in arg2value: arg2value[arg] = defaults[i] missing = 0 for kwarg in kwonlyargs: if kwarg not in arg2value: if kwonlydefaults and kwarg in kwonlydefaults: arg2value[kwarg] = kwonlydefaults[kwarg] else: missing += 1 if missing: _missing_arguments(f_name, kwonlyargs, False, arg2value) return arg2value ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound') def getclosurevars(func): """ Get the mapping of free variables to their current values. Returns a named tuple of dicts mapping the current nonlocal, global and builtin references as seen by the body of the function. A final set of unbound names that could not be resolved is also provided. """ if ismethod(func): func = func.__func__ if not isfunction(func): raise TypeError("'{!r}' is not a Python function".format(func)) code = func.__code__ # Nonlocal references are named in co_freevars and resolved # by looking them up in __closure__ by positional index if func.__closure__ is None: nonlocal_vars = {} else: nonlocal_vars = { var : cell.cell_contents for var, cell in zip(code.co_freevars, func.__closure__) } # Global and builtin references are named in co_names and resolved # by looking them up in __globals__ or __builtins__ global_ns = func.__globals__ builtin_ns = global_ns.get("__builtins__", builtins.__dict__) if ismodule(builtin_ns): builtin_ns = builtin_ns.__dict__ global_vars = {} builtin_vars = {} unbound_names = set() for name in code.co_names: if name in ("None", "True", "False"): # Because these used to be builtins instead of keywords, they # may still show up as name references. We ignore them. continue try: global_vars[name] = global_ns[name] except KeyError: try: builtin_vars[name] = builtin_ns[name] except KeyError: unbound_names.add(name) return ClosureVars(nonlocal_vars, global_vars, builtin_vars, unbound_names) # -------------------------------------------------- stack frame extraction Traceback = namedtuple('Traceback', 'filename lineno function code_context index') def getframeinfo(frame, context=1): """Get information about a frame or traceback object. A tuple of five things is returned: the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line within that list. The optional second argument specifies the number of lines of context to return, which are centered around the current line.""" if istraceback(frame): lineno = frame.tb_lineno frame = frame.tb_frame else: lineno = frame.f_lineno if not isframe(frame): raise TypeError('{!r} is not a frame or traceback object'.format(frame)) filename = getsourcefile(frame) or getfile(frame) if context > 0: start = lineno - 1 - context//2 try: lines, lnum = findsource(frame) except OSError: lines = index = None else: start = max(start, 1) start = max(0, min(start, len(lines) - context)) lines = lines[start:start+context] index = lineno - 1 - start else: lines = index = None return Traceback(filename, lineno, frame.f_code.co_name, lines, index) def getlineno(frame): """Get the line number from a frame object, allowing for optimization.""" # FrameType.f_lineno is now a descriptor that grovels co_lnotab return frame.f_lineno FrameInfo = namedtuple('FrameInfo', ('frame',) + Traceback._fields) def getouterframes(frame, context=1): """Get a list of records for a frame and all higher (calling) frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.""" framelist = [] while frame: frameinfo = (frame,) + getframeinfo(frame, context) framelist.append(FrameInfo(*frameinfo)) frame = frame.f_back return framelist def getinnerframes(tb, context=1): """Get a list of records for a traceback's frame and all lower frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.""" framelist = [] while tb: frameinfo = (tb.tb_frame,) + getframeinfo(tb, context) framelist.append(FrameInfo(*frameinfo)) tb = tb.tb_next return framelist def currentframe(): """Return the frame of the caller or None if this is not possible.""" return sys._getframe(1) if hasattr(sys, "_getframe") else None def stack(context=1): """Return a list of records for the stack above the caller's frame.""" return getouterframes(sys._getframe(1), context) def trace(context=1): """Return a list of records for the stack below the current exception.""" return getinnerframes(sys.exc_info()[2], context) # ------------------------------------------------ static version of getattr _sentinel = object() def _static_getmro(klass): return type.__dict__['__mro__'].__get__(klass) def _check_instance(obj, attr): instance_dict = {} try: instance_dict = object.__getattribute__(obj, "__dict__") except AttributeError: pass return dict.get(instance_dict, attr, _sentinel) def _check_class(klass, attr): for entry in _static_getmro(klass): if _shadowed_dict(type(entry)) is _sentinel: try: return entry.__dict__[attr] except KeyError: pass return _sentinel def _is_type(obj): try: _static_getmro(obj) except TypeError: return False return True def _shadowed_dict(klass): dict_attr = type.__dict__["__dict__"] for entry in _static_getmro(klass): try: class_dict = dict_attr.__get__(entry)["__dict__"] except KeyError: pass else: if not (type(class_dict) is types.GetSetDescriptorType and class_dict.__name__ == "__dict__" and class_dict.__objclass__ is entry): return class_dict return _sentinel def getattr_static(obj, attr, default=_sentinel): """Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__ or __getattribute__. Note: this function may not be able to retrieve all attributes that getattr can fetch (like dynamically created attributes) and may find attributes that getattr can't (like descriptors that raise AttributeError). It can also return descriptor objects instead of instance members in some cases. See the documentation for details. """ instance_result = _sentinel if not _is_type(obj): klass = type(obj) dict_attr = _shadowed_dict(klass) if (dict_attr is _sentinel or type(dict_attr) is types.MemberDescriptorType): instance_result = _check_instance(obj, attr) else: klass = obj klass_result = _check_class(klass, attr) if instance_result is not _sentinel and klass_result is not _sentinel: if (_check_class(type(klass_result), '__get__') is not _sentinel and _check_class(type(klass_result), '__set__') is not _sentinel): return klass_result if instance_result is not _sentinel: return instance_result if klass_result is not _sentinel: return klass_result if obj is klass: # for types we check the metaclass too for entry in _static_getmro(type(klass)): if _shadowed_dict(type(entry)) is _sentinel: try: return entry.__dict__[attr] except KeyError: pass if default is not _sentinel: return default raise AttributeError(attr) # ------------------------------------------------ generator introspection GEN_CREATED = 'GEN_CREATED' GEN_RUNNING = 'GEN_RUNNING' GEN_SUSPENDED = 'GEN_SUSPENDED' GEN_CLOSED = 'GEN_CLOSED' def getgeneratorstate(generator): """Get current state of a generator-iterator. Possible states are: GEN_CREATED: Waiting to start execution. GEN_RUNNING: Currently being executed by the interpreter. GEN_SUSPENDED: Currently suspended at a yield expression. GEN_CLOSED: Execution has completed. """ if generator.gi_running: return GEN_RUNNING if generator.gi_frame is None: return GEN_CLOSED if generator.gi_frame.f_lasti == -1: return GEN_CREATED return GEN_SUSPENDED def getgeneratorlocals(generator): """ Get the mapping of generator local variables to their current values. A dict is returned, with the keys the local variable names and values the bound values.""" if not isgenerator(generator): raise TypeError("'{!r}' is not a Python generator".format(generator)) frame = getattr(generator, "gi_frame", None) if frame is not None: return generator.gi_frame.f_locals else: return {} # ------------------------------------------------ coroutine introspection CORO_CREATED = 'CORO_CREATED' CORO_RUNNING = 'CORO_RUNNING' CORO_SUSPENDED = 'CORO_SUSPENDED' CORO_CLOSED = 'CORO_CLOSED' def getcoroutinestate(coroutine): """Get current state of a coroutine object. Possible states are: CORO_CREATED: Waiting to start execution. CORO_RUNNING: Currently being executed by the interpreter. CORO_SUSPENDED: Currently suspended at an await expression. CORO_CLOSED: Execution has completed. """ if coroutine.cr_running: return CORO_RUNNING if coroutine.cr_frame is None: return CORO_CLOSED if coroutine.cr_frame.f_lasti == -1: return CORO_CREATED return CORO_SUSPENDED def getcoroutinelocals(coroutine): """ Get the mapping of coroutine local variables to their current values. A dict is returned, with the keys the local variable names and values the bound values.""" frame = getattr(coroutine, "cr_frame", None) if frame is not None: return frame.f_locals else: return {} ############################################################################### ### Function Signature Object (PEP 362) ############################################################################### _WrapperDescriptor = type(type.__call__) _MethodWrapper = type(all.__call__) _ClassMethodWrapper = type(int.__dict__['from_bytes']) _NonUserDefinedCallables = (_WrapperDescriptor, _MethodWrapper, _ClassMethodWrapper, types.BuiltinFunctionType) def _signature_get_user_defined_method(cls, method_name): """Private helper. Checks if ``cls`` has an attribute named ``method_name`` and returns it only if it is a pure python function. """ try: meth = getattr(cls, method_name) except AttributeError: return else: if not isinstance(meth, _NonUserDefinedCallables): # Once '__signature__' will be added to 'C'-level # callables, this check won't be necessary return meth def _signature_get_partial(wrapped_sig, partial, extra_args=()): """Private helper to calculate how 'wrapped_sig' signature will look like after applying a 'functools.partial' object (or alike) on it. """ old_params = wrapped_sig.parameters new_params = OrderedDict(old_params.items()) partial_args = partial.args or () partial_keywords = partial.keywords or {} if extra_args: partial_args = extra_args + partial_args try: ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords) except TypeError as ex: msg = 'partial object {!r} has incorrect arguments'.format(partial) raise ValueError(msg) from ex transform_to_kwonly = False for param_name, param in old_params.items(): try: arg_value = ba.arguments[param_name] except KeyError: pass else: if param.kind is _POSITIONAL_ONLY: # If positional-only parameter is bound by partial, # it effectively disappears from the signature new_params.pop(param_name) continue if param.kind is _POSITIONAL_OR_KEYWORD: if param_name in partial_keywords: # This means that this parameter, and all parameters # after it should be keyword-only (and var-positional # should be removed). Here's why. Consider the following # function: # foo(a, b, *args, c): # pass # # "partial(foo, a='spam')" will have the following # signature: "(*, a='spam', b, c)". Because attempting # to call that partial with "(10, 20)" arguments will # raise a TypeError, saying that "a" argument received # multiple values. transform_to_kwonly = True # Set the new default value new_params[param_name] = param.replace(default=arg_value) else: # was passed as a positional argument new_params.pop(param.name) continue if param.kind is _KEYWORD_ONLY: # Set the new default value new_params[param_name] = param.replace(default=arg_value) if transform_to_kwonly: assert param.kind is not _POSITIONAL_ONLY if param.kind is _POSITIONAL_OR_KEYWORD: new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY) new_params[param_name] = new_param new_params.move_to_end(param_name) elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD): new_params.move_to_end(param_name) elif param.kind is _VAR_POSITIONAL: new_params.pop(param.name) return wrapped_sig.replace(parameters=new_params.values()) def _signature_bound_method(sig): """Private helper to transform signatures for unbound functions to bound methods. """ params = tuple(sig.parameters.values()) if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY): raise ValueError('invalid method signature') kind = params[0].kind if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY): # Drop first parameter: # '(p1, p2[, ...])' -> '(p2[, ...])' params = params[1:] else: if kind is not _VAR_POSITIONAL: # Unless we add a new parameter type we never # get here raise ValueError('invalid argument type') # It's a var-positional parameter. # Do nothing. '(*args[, ...])' -> '(*args[, ...])' return sig.replace(parameters=params) def _signature_is_builtin(obj): """Private helper to test if `obj` is a callable that might support Argument Clinic's __text_signature__ protocol. """ return (isbuiltin(obj) or ismethoddescriptor(obj) or isinstance(obj, _NonUserDefinedCallables) or # Can't test 'isinstance(type)' here, as it would # also be True for regular python classes obj in (type, object)) def _signature_is_functionlike(obj): """Private helper to test if `obj` is a duck type of FunctionType. A good example of such objects are functions compiled with Cython, which have all attributes that a pure Python function would have, but have their code statically compiled. """ if not callable(obj) or isclass(obj): # All function-like objects are obviously callables, # and not classes. return False name = getattr(obj, '__name__', None) code = getattr(obj, '__code__', None) defaults = getattr(obj, '__defaults__', _void) # Important to use _void ... kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here annotations = getattr(obj, '__annotations__', None) return (isinstance(code, types.CodeType) and isinstance(name, str) and (defaults is None or isinstance(defaults, tuple)) and (kwdefaults is None or isinstance(kwdefaults, dict)) and isinstance(annotations, dict)) def _signature_get_bound_param(spec): """ Private helper to get first parameter name from a __text_signature__ of a builtin method, which should be in the following format: '($param1, ...)'. Assumptions are that the first argument won't have a default value or an annotation. """ assert spec.startswith('($') pos = spec.find(',') if pos == -1: pos = spec.find(')') cpos = spec.find(':') assert cpos == -1 or cpos > pos cpos = spec.find('=') assert cpos == -1 or cpos > pos return spec[2:pos] def _signature_strip_non_python_syntax(signature): """ Private helper function. Takes a signature in Argument Clinic's extended signature format. Returns a tuple of three things: * that signature re-rendered in standard Python syntax, * the index of the "self" parameter (generally 0), or None if the function does not have a "self" parameter, and * the index of the last "positional only" parameter, or None if the signature has no positional-only parameters. """ if not signature: return signature, None, None self_parameter = None last_positional_only = None lines = [l.encode('ascii') for l in signature.split('\n')] generator = iter(lines).__next__ token_stream = tokenize.tokenize(generator) delayed_comma = False skip_next_comma = False text = [] add = text.append current_parameter = 0 OP = token.OP ERRORTOKEN = token.ERRORTOKEN # token stream always starts with ENCODING token, skip it t = next(token_stream) assert t.type == tokenize.ENCODING for t in token_stream: type, string = t.type, t.string if type == OP: if string == ',': if skip_next_comma: skip_next_comma = False else: assert not delayed_comma delayed_comma = True current_parameter += 1 continue if string == '/': assert not skip_next_comma assert last_positional_only is None skip_next_comma = True last_positional_only = current_parameter - 1 continue if (type == ERRORTOKEN) and (string == '$'): assert self_parameter is None self_parameter = current_parameter continue if delayed_comma: delayed_comma = False if not ((type == OP) and (string == ')')): add(', ') add(string) if (string == ','): add(' ') clean_signature = ''.join(text) return clean_signature, self_parameter, last_positional_only def _signature_fromstr(cls, obj, s, skip_bound_arg=True): """Private helper to parse content of '__text_signature__' and return a Signature based on it. """ Parameter = cls._parameter_cls clean_signature, self_parameter, last_positional_only = \ _signature_strip_non_python_syntax(s) program = "def foo" + clean_signature + ": pass" try: module = ast.parse(program) except SyntaxError: module = None if not isinstance(module, ast.Module): raise ValueError("{!r} builtin has invalid signature".format(obj)) f = module.body[0] parameters = [] empty = Parameter.empty invalid = object() module = None module_dict = {} module_name = getattr(obj, '__module__', None) if module_name: module = sys.modules.get(module_name, None) if module: module_dict = module.__dict__ sys_module_dict = sys.modules def parse_name(node): assert isinstance(node, ast.arg) if node.annotation != None: raise ValueError("Annotations are not currently supported") return node.arg def wrap_value(s): try: value = eval(s, module_dict) except NameError: try: value = eval(s, sys_module_dict) except NameError: raise RuntimeError() if isinstance(value, str): return ast.Str(value) if isinstance(value, (int, float)): return ast.Num(value) if isinstance(value, bytes): return ast.Bytes(value) if value in (True, False, None): return ast.NameConstant(value) raise RuntimeError() class RewriteSymbolics(ast.NodeTransformer): def visit_Attribute(self, node): a = [] n = node while isinstance(n, ast.Attribute): a.append(n.attr) n = n.value if not isinstance(n, ast.Name): raise RuntimeError() a.append(n.id) value = ".".join(reversed(a)) return wrap_value(value) def visit_Name(self, node): if not isinstance(node.ctx, ast.Load): raise ValueError() return wrap_value(node.id) def p(name_node, default_node, default=empty): name = parse_name(name_node) if name is invalid: return None if default_node and default_node is not _empty: try: default_node = RewriteSymbolics().visit(default_node) o = ast.literal_eval(default_node) except ValueError: o = invalid if o is invalid: return None default = o if o is not invalid else default parameters.append(Parameter(name, kind, default=default, annotation=empty)) # non-keyword-only parameters args = reversed(f.args.args) defaults = reversed(f.args.defaults) iter = itertools.zip_longest(args, defaults, fillvalue=None) if last_positional_only is not None: kind = Parameter.POSITIONAL_ONLY else: kind = Parameter.POSITIONAL_OR_KEYWORD for i, (name, default) in enumerate(reversed(list(iter))): p(name, default) if i == last_positional_only: kind = Parameter.POSITIONAL_OR_KEYWORD # *args if f.args.vararg: kind = Parameter.VAR_POSITIONAL p(f.args.vararg, empty) # keyword-only arguments kind = Parameter.KEYWORD_ONLY for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults): p(name, default) # **kwargs if f.args.kwarg: kind = Parameter.VAR_KEYWORD p(f.args.kwarg, empty) if self_parameter is not None: # Possibly strip the bound argument: # - We *always* strip first bound argument if # it is a module. # - We don't strip first bound argument if # skip_bound_arg is False. assert parameters _self = getattr(obj, '__self__', None) self_isbound = _self is not None self_ismodule = ismodule(_self) if self_isbound and (self_ismodule or skip_bound_arg): parameters.pop(0) else: # for builtins, self parameter is always positional-only! p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY) parameters[0] = p return cls(parameters, return_annotation=cls.empty) def _signature_from_builtin(cls, func, skip_bound_arg=True): """Private helper function to get signature for builtin callables. """ if not _signature_is_builtin(func): raise TypeError("{!r} is not a Python builtin " "function".format(func)) s = getattr(func, "__text_signature__", None) if not s: raise ValueError("no signature found for builtin {!r}".format(func)) return _signature_fromstr(cls, func, s, skip_bound_arg) def _signature_from_function(cls, func): """Private helper: constructs Signature for the given python function.""" is_duck_function = False if not isfunction(func): if _signature_is_functionlike(func): is_duck_function = True else: # If it's not a pure Python function, and not a duck type # of pure function: raise TypeError('{!r} is not a Python function'.format(func)) Parameter = cls._parameter_cls # Parameter information. func_code = func.__code__ pos_count = func_code.co_argcount arg_names = func_code.co_varnames positional = tuple(arg_names[:pos_count]) keyword_only_count = func_code.co_kwonlyargcount keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)] annotations = func.__annotations__ defaults = func.__defaults__ kwdefaults = func.__kwdefaults__ if defaults: pos_default_count = len(defaults) else: pos_default_count = 0 parameters = [] # Non-keyword-only parameters w/o defaults. non_default_count = pos_count - pos_default_count for name in positional[:non_default_count]: annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_POSITIONAL_OR_KEYWORD)) # ... w/ defaults. for offset, name in enumerate(positional[non_default_count:]): annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_POSITIONAL_OR_KEYWORD, default=defaults[offset])) # *args if func_code.co_flags & CO_VARARGS: name = arg_names[pos_count + keyword_only_count] annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_VAR_POSITIONAL)) # Keyword-only parameters. for name in keyword_only: default = _empty if kwdefaults is not None: default = kwdefaults.get(name, _empty) annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_KEYWORD_ONLY, default=default)) # **kwargs if func_code.co_flags & CO_VARKEYWORDS: index = pos_count + keyword_only_count if func_code.co_flags & CO_VARARGS: index += 1 name = arg_names[index] annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_VAR_KEYWORD)) # Is 'func' is a pure Python function - don't validate the # parameters list (for correct order and defaults), it should be OK. return cls(parameters, return_annotation=annotations.get('return', _empty), __validate_parameters__=is_duck_function) def _signature_from_callable(obj, *, follow_wrapper_chains=True, skip_bound_arg=True, sigcls): """Private helper function to get signature for arbitrary callable objects. """ if not callable(obj): raise TypeError('{!r} is not a callable object'.format(obj)) if isinstance(obj, types.MethodType): # In this case we skip the first parameter of the underlying # function (usually `self` or `cls`). sig = _signature_from_callable( obj.__func__, follow_wrapper_chains=follow_wrapper_chains, skip_bound_arg=skip_bound_arg, sigcls=sigcls) if skip_bound_arg: return _signature_bound_method(sig) else: return sig # Was this function wrapped by a decorator? if follow_wrapper_chains: obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__"))) if isinstance(obj, types.MethodType): # If the unwrapped object is a *method*, we might want to # skip its first parameter (self). # See test_signature_wrapped_bound_method for details. return _signature_from_callable( obj, follow_wrapper_chains=follow_wrapper_chains, skip_bound_arg=skip_bound_arg, sigcls=sigcls) try: sig = obj.__signature__ except AttributeError: pass else: if sig is not None: if not isinstance(sig, Signature): raise TypeError( 'unexpected object {!r} in __signature__ ' 'attribute'.format(sig)) return sig try: partialmethod = obj._partialmethod except AttributeError: pass else: if isinstance(partialmethod, functools.partialmethod): # Unbound partialmethod (see functools.partialmethod) # This means, that we need to calculate the signature # as if it's a regular partial object, but taking into # account that the first positional argument # (usually `self`, or `cls`) will not be passed # automatically (as for boundmethods) wrapped_sig = _signature_from_callable( partialmethod.func, follow_wrapper_chains=follow_wrapper_chains, skip_bound_arg=skip_bound_arg, sigcls=sigcls) sig = _signature_get_partial(wrapped_sig, partialmethod, (None,)) first_wrapped_param = tuple(wrapped_sig.parameters.values())[0] new_params = (first_wrapped_param,) + tuple(sig.parameters.values()) return sig.replace(parameters=new_params) if isfunction(obj) or _signature_is_functionlike(obj): # If it's a pure Python function, or an object that is duck type # of a Python function (Cython functions, for instance), then: return _signature_from_function(sigcls, obj) if _signature_is_builtin(obj): return _signature_from_builtin(sigcls, obj, skip_bound_arg=skip_bound_arg) if isinstance(obj, functools.partial): wrapped_sig = _signature_from_callable( obj.func, follow_wrapper_chains=follow_wrapper_chains, skip_bound_arg=skip_bound_arg, sigcls=sigcls) return _signature_get_partial(wrapped_sig, obj) sig = None if isinstance(obj, type): # obj is a class or a metaclass # First, let's see if it has an overloaded __call__ defined # in its metaclass call = _signature_get_user_defined_method(type(obj), '__call__') if call is not None: sig = _signature_from_callable( call, follow_wrapper_chains=follow_wrapper_chains, skip_bound_arg=skip_bound_arg, sigcls=sigcls) else: # Now we check if the 'obj' class has a '__new__' method new = _signature_get_user_defined_method(obj, '__new__') if new is not None: sig = _signature_from_callable( new, follow_wrapper_chains=follow_wrapper_chains, skip_bound_arg=skip_bound_arg, sigcls=sigcls) else: # Finally, we should have at least __init__ implemented init = _signature_get_user_defined_method(obj, '__init__') if init is not None: sig = _signature_from_callable( init, follow_wrapper_chains=follow_wrapper_chains, skip_bound_arg=skip_bound_arg, sigcls=sigcls) if sig is None: # At this point we know, that `obj` is a class, with no user- # defined '__init__', '__new__', or class-level '__call__' for base in obj.__mro__[:-1]: # Since '__text_signature__' is implemented as a # descriptor that extracts text signature from the # class docstring, if 'obj' is derived from a builtin # class, its own '__text_signature__' may be 'None'. # Therefore, we go through the MRO (except the last # class in there, which is 'object') to find the first # class with non-empty text signature. try: text_sig = base.__text_signature__ except AttributeError: pass else: if text_sig: # If 'obj' class has a __text_signature__ attribute: # return a signature based on it return _signature_fromstr(sigcls, obj, text_sig) # No '__text_signature__' was found for the 'obj' class. # Last option is to check if its '__init__' is # object.__init__ or type.__init__. if type not in obj.__mro__: # We have a class (not metaclass), but no user-defined # __init__ or __new__ for it if (obj.__init__ is object.__init__ and obj.__new__ is object.__new__): # Return a signature of 'object' builtin. return signature(object) else: raise ValueError( 'no signature found for builtin type {!r}'.format(obj)) elif not isinstance(obj, _NonUserDefinedCallables): # An object with __call__ # We also check that the 'obj' is not an instance of # _WrapperDescriptor or _MethodWrapper to avoid # infinite recursion (and even potential segfault) call = _signature_get_user_defined_method(type(obj), '__call__') if call is not None: try: sig = _signature_from_callable( call, follow_wrapper_chains=follow_wrapper_chains, skip_bound_arg=skip_bound_arg, sigcls=sigcls) except ValueError as ex: msg = 'no signature found for {!r}'.format(obj) raise ValueError(msg) from ex if sig is not None: # For classes and objects we skip the first parameter of their # __call__, __new__, or __init__ methods if skip_bound_arg: return _signature_bound_method(sig) else: return sig if isinstance(obj, types.BuiltinFunctionType): # Raise a nicer error message for builtins msg = 'no signature found for builtin function {!r}'.format(obj) raise ValueError(msg) raise ValueError('callable {!r} is not supported by signature'.format(obj)) class _void: """A private marker - used in Parameter & Signature.""" class _empty: """Marker object for Signature.empty and Parameter.empty.""" class _ParameterKind(enum.IntEnum): POSITIONAL_ONLY = 0 POSITIONAL_OR_KEYWORD = 1 VAR_POSITIONAL = 2 KEYWORD_ONLY = 3 VAR_KEYWORD = 4 def __str__(self): return self._name_ _POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY _POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD _VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL _KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY _VAR_KEYWORD = _ParameterKind.VAR_KEYWORD class Parameter: """Represents a parameter in a function signature. Has the following public attributes: * name : str The name of the parameter as a string. * default : object The default value for the parameter if specified. If the parameter has no default value, this attribute is set to `Parameter.empty`. * annotation The annotation for the parameter if specified. If the parameter has no annotation, this attribute is set to `Parameter.empty`. * kind : str Describes how argument values are bound to the parameter. Possible values: `Parameter.POSITIONAL_ONLY`, `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`, `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`. """ __slots__ = ('_name', '_kind', '_default', '_annotation') POSITIONAL_ONLY = _POSITIONAL_ONLY POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD VAR_POSITIONAL = _VAR_POSITIONAL KEYWORD_ONLY = _KEYWORD_ONLY VAR_KEYWORD = _VAR_KEYWORD empty = _empty def __init__(self, name, kind, *, default=_empty, annotation=_empty): if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD, _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD): raise ValueError("invalid value for 'Parameter.kind' attribute") self._kind = kind if default is not _empty: if kind in (_VAR_POSITIONAL, _VAR_KEYWORD): msg = '{} parameters cannot have default values'.format(kind) raise ValueError(msg) self._default = default self._annotation = annotation if name is _empty: raise ValueError('name is a required attribute for Parameter') if not isinstance(name, str): raise TypeError("name must be a str, not a {!r}".format(name)) if name[0] == '.' and name[1:].isdigit(): # These are implicit arguments generated by comprehensions. In # order to provide a friendlier interface to users, we recast # their name as "implicitN" and treat them as positional-only. # See issue 19611. if kind != _POSITIONAL_OR_KEYWORD: raise ValueError( 'implicit arguments must be passed in as {}'.format( _POSITIONAL_OR_KEYWORD ) ) self._kind = _POSITIONAL_ONLY name = 'implicit{}'.format(name[1:]) if not name.isidentifier(): raise ValueError('{!r} is not a valid parameter name'.format(name)) self._name = name def __reduce__(self): return (type(self), (self._name, self._kind), {'_default': self._default, '_annotation': self._annotation}) def __setstate__(self, state): self._default = state['_default'] self._annotation = state['_annotation'] @property def name(self): return self._name @property def default(self): return self._default @property def annotation(self): return self._annotation @property def kind(self): return self._kind def replace(self, *, name=_void, kind=_void, annotation=_void, default=_void): """Creates a customized copy of the Parameter.""" if name is _void: name = self._name if kind is _void: kind = self._kind if annotation is _void: annotation = self._annotation if default is _void: default = self._default return type(self)(name, kind, default=default, annotation=annotation) def __str__(self): kind = self.kind formatted = self._name # Add annotation and default value if self._annotation is not _empty: formatted = '{}:{}'.format(formatted, formatannotation(self._annotation)) if self._default is not _empty: formatted = '{}={}'.format(formatted, repr(self._default)) if kind == _VAR_POSITIONAL: formatted = '*' + formatted elif kind == _VAR_KEYWORD: formatted = '**' + formatted return formatted def __repr__(self): return '<{} "{}">'.format(self.__class__.__name__, self) def __hash__(self): return hash((self.name, self.kind, self.annotation, self.default)) def __eq__(self, other): if self is other: return True if not isinstance(other, Parameter): return NotImplemented return (self._name == other._name and self._kind == other._kind and self._default == other._default and self._annotation == other._annotation) class BoundArguments: """Result of `Signature.bind` call. Holds the mapping of arguments to the function's parameters. Has the following public attributes: * arguments : OrderedDict An ordered mutable mapping of parameters' names to arguments' values. Does not contain arguments' default values. * signature : Signature The Signature object that created this instance. * args : tuple Tuple of positional arguments values. * kwargs : dict Dict of keyword arguments values. """ __slots__ = ('arguments', '_signature', '__weakref__') def __init__(self, signature, arguments): self.arguments = arguments self._signature = signature @property def signature(self): return self._signature @property def args(self): args = [] for param_name, param in self._signature.parameters.items(): if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY): break try: arg = self.arguments[param_name] except KeyError: # We're done here. Other arguments # will be mapped in 'BoundArguments.kwargs' break else: if param.kind == _VAR_POSITIONAL: # *args args.extend(arg) else: # plain argument args.append(arg) return tuple(args) @property def kwargs(self): kwargs = {} kwargs_started = False for param_name, param in self._signature.parameters.items(): if not kwargs_started: if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY): kwargs_started = True else: if param_name not in self.arguments: kwargs_started = True continue if not kwargs_started: continue try: arg = self.arguments[param_name] except KeyError: pass else: if param.kind == _VAR_KEYWORD: # **kwargs kwargs.update(arg) else: # plain keyword argument kwargs[param_name] = arg return kwargs def apply_defaults(self): """Set default values for missing arguments. For variable-positional arguments (*args) the default is an empty tuple. For variable-keyword arguments (**kwargs) the default is an empty dict. """ arguments = self.arguments new_arguments = [] for name, param in self._signature.parameters.items(): try: new_arguments.append((name, arguments[name])) except KeyError: if param.default is not _empty: val = param.default elif param.kind is _VAR_POSITIONAL: val = () elif param.kind is _VAR_KEYWORD: val = {} else: # This BoundArguments was likely produced by # Signature.bind_partial(). continue new_arguments.append((name, val)) self.arguments = OrderedDict(new_arguments) def __eq__(self, other): if self is other: return True if not isinstance(other, BoundArguments): return NotImplemented return (self.signature == other.signature and self.arguments == other.arguments) def __setstate__(self, state): self._signature = state['_signature'] self.arguments = state['arguments'] def __getstate__(self): return {'_signature': self._signature, 'arguments': self.arguments} def __repr__(self): args = [] for arg, value in self.arguments.items(): args.append('{}={!r}'.format(arg, value)) return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args)) class Signature: """A Signature object represents the overall signature of a function. It stores a Parameter object for each parameter accepted by the function, as well as information specific to the function itself. A Signature object has the following public attributes and methods: * parameters : OrderedDict An ordered mapping of parameters' names to the corresponding Parameter objects (keyword-only arguments are in the same order as listed in `code.co_varnames`). * return_annotation : object The annotation for the return type of the function if specified. If the function has no annotation for its return type, this attribute is set to `Signature.empty`. * bind(*args, **kwargs) -> BoundArguments Creates a mapping from positional and keyword arguments to parameters. * bind_partial(*args, **kwargs) -> BoundArguments Creates a partial mapping from positional and keyword arguments to parameters (simulating 'functools.partial' behavior.) """ __slots__ = ('_return_annotation', '_parameters') _parameter_cls = Parameter _bound_arguments_cls = BoundArguments empty = _empty def __init__(self, parameters=None, *, return_annotation=_empty, __validate_parameters__=True): """Constructs Signature from the given list of Parameter objects and 'return_annotation'. All arguments are optional. """ if parameters is None: params = OrderedDict() else: if __validate_parameters__: params = OrderedDict() top_kind = _POSITIONAL_ONLY kind_defaults = False for idx, param in enumerate(parameters): kind = param.kind name = param.name if kind < top_kind: msg = 'wrong parameter order: {!r} before {!r}' msg = msg.format(top_kind, kind) raise ValueError(msg) elif kind > top_kind: kind_defaults = False top_kind = kind if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD): if param.default is _empty: if kind_defaults: # No default for this parameter, but the # previous parameter of the same kind had # a default msg = 'non-default argument follows default ' \ 'argument' raise ValueError(msg) else: # There is a default for this parameter. kind_defaults = True if name in params: msg = 'duplicate parameter name: {!r}'.format(name) raise ValueError(msg) params[name] = param else: params = OrderedDict(((param.name, param) for param in parameters)) self._parameters = types.MappingProxyType(params) self._return_annotation = return_annotation @classmethod def from_function(cls, func): """Constructs Signature for the given python function.""" warnings.warn("inspect.Signature.from_function() is deprecated, " "use Signature.from_callable()", DeprecationWarning, stacklevel=2) return _signature_from_function(cls, func) @classmethod def from_builtin(cls, func): """Constructs Signature for the given builtin function.""" warnings.warn("inspect.Signature.from_builtin() is deprecated, " "use Signature.from_callable()", DeprecationWarning, stacklevel=2) return _signature_from_builtin(cls, func) @classmethod def from_callable(cls, obj, *, follow_wrapped=True): """Constructs Signature for the given callable object.""" return _signature_from_callable(obj, sigcls=cls, follow_wrapper_chains=follow_wrapped) @property def parameters(self): return self._parameters @property def return_annotation(self): return self._return_annotation def replace(self, *, parameters=_void, return_annotation=_void): """Creates a customized copy of the Signature. Pass 'parameters' and/or 'return_annotation' arguments to override them in the new copy. """ if parameters is _void: parameters = self.parameters.values() if return_annotation is _void: return_annotation = self._return_annotation return type(self)(parameters, return_annotation=return_annotation) def _hash_basis(self): params = tuple(param for param in self.parameters.values() if param.kind != _KEYWORD_ONLY) kwo_params = {param.name: param for param in self.parameters.values() if param.kind == _KEYWORD_ONLY} return params, kwo_params, self.return_annotation def __hash__(self): params, kwo_params, return_annotation = self._hash_basis() kwo_params = frozenset(kwo_params.values()) return hash((params, kwo_params, return_annotation)) def __eq__(self, other): if self is other: return True if not isinstance(other, Signature): return NotImplemented return self._hash_basis() == other._hash_basis() def _bind(self, args, kwargs, *, partial=False): """Private method. Don't use directly.""" arguments = OrderedDict() parameters = iter(self.parameters.values()) parameters_ex = () arg_vals = iter(args) while True: # Let's iterate through the positional arguments and corresponding # parameters try: arg_val = next(arg_vals) except StopIteration: # No more positional arguments try: param = next(parameters) except StopIteration: # No more parameters. That's it. Just need to check that # we have no `kwargs` after this while loop break else: if param.kind == _VAR_POSITIONAL: # That's OK, just empty *args. Let's start parsing # kwargs break elif param.name in kwargs: if param.kind == _POSITIONAL_ONLY: msg = '{arg!r} parameter is positional only, ' \ 'but was passed as a keyword' msg = msg.format(arg=param.name) raise TypeError(msg) from None parameters_ex = (param,) break elif (param.kind == _VAR_KEYWORD or param.default is not _empty): # That's fine too - we have a default value for this # parameter. So, lets start parsing `kwargs`, starting # with the current parameter parameters_ex = (param,) break else: # No default, not VAR_KEYWORD, not VAR_POSITIONAL, # not in `kwargs` if partial: parameters_ex = (param,) break else: msg = 'missing a required argument: {arg!r}' msg = msg.format(arg=param.name) raise TypeError(msg) from None else: # We have a positional argument to process try: param = next(parameters) except StopIteration: raise TypeError('too many positional arguments') from None else: if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY): # Looks like we have no parameter for this positional # argument raise TypeError( 'too many positional arguments') from None if param.kind == _VAR_POSITIONAL: # We have an '*args'-like argument, let's fill it with # all positional arguments we have left and move on to # the next phase values = [arg_val] values.extend(arg_vals) arguments[param.name] = tuple(values) break if param.name in kwargs: raise TypeError( 'multiple values for argument {arg!r}'.format( arg=param.name)) from None arguments[param.name] = arg_val # Now, we iterate through the remaining parameters to process # keyword arguments kwargs_param = None for param in itertools.chain(parameters_ex, parameters): if param.kind == _VAR_KEYWORD: # Memorize that we have a '**kwargs'-like parameter kwargs_param = param continue if param.kind == _VAR_POSITIONAL: # Named arguments don't refer to '*args'-like parameters. # We only arrive here if the positional arguments ended # before reaching the last parameter before *args. continue param_name = param.name try: arg_val = kwargs.pop(param_name) except KeyError: # We have no value for this parameter. It's fine though, # if it has a default value, or it is an '*args'-like # parameter, left alone by the processing of positional # arguments. if (not partial and param.kind != _VAR_POSITIONAL and param.default is _empty): raise TypeError('missing a required argument: {arg!r}'. \ format(arg=param_name)) from None else: if param.kind == _POSITIONAL_ONLY: # This should never happen in case of a properly built # Signature object (but let's have this check here # to ensure correct behaviour just in case) raise TypeError('{arg!r} parameter is positional only, ' 'but was passed as a keyword'. \ format(arg=param.name)) arguments[param_name] = arg_val if kwargs: if kwargs_param is not None: # Process our '**kwargs'-like parameter arguments[kwargs_param.name] = kwargs else: raise TypeError( 'got an unexpected keyword argument {arg!r}'.format( arg=next(iter(kwargs)))) return self._bound_arguments_cls(self, arguments) def bind(*args, **kwargs): """Get a BoundArguments object, that maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. """ return args[0]._bind(args[1:], kwargs) def bind_partial(*args, **kwargs): """Get a BoundArguments object, that partially maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. """ return args[0]._bind(args[1:], kwargs, partial=True) def __reduce__(self): return (type(self), (tuple(self._parameters.values()),), {'_return_annotation': self._return_annotation}) def __setstate__(self, state): self._return_annotation = state['_return_annotation'] def __repr__(self): return '<{} {}>'.format(self.__class__.__name__, self) def __str__(self): result = [] render_pos_only_separator = False render_kw_only_separator = True for param in self.parameters.values(): formatted = str(param) kind = param.kind if kind == _POSITIONAL_ONLY: render_pos_only_separator = True elif render_pos_only_separator: # It's not a positional-only parameter, and the flag # is set to 'True' (there were pos-only params before.) result.append('/') render_pos_only_separator = False if kind == _VAR_POSITIONAL: # OK, we have an '*args'-like parameter, so we won't need # a '*' to separate keyword-only arguments render_kw_only_separator = False elif kind == _KEYWORD_ONLY and render_kw_only_separator: # We have a keyword-only parameter to render and we haven't # rendered an '*args'-like parameter before, so add a '*' # separator to the parameters list ("foo(arg1, *, arg2)" case) result.append('*') # This condition should be only triggered once, so # reset the flag render_kw_only_separator = False result.append(formatted) if render_pos_only_separator: # There were only positional-only parameters, hence the # flag was not reset to 'False' result.append('/') rendered = '({})'.format(', '.join(result)) if self.return_annotation is not _empty: anno = formatannotation(self.return_annotation) rendered += ' -> {}'.format(anno) return rendered def signature(obj, *, follow_wrapped=True): """Get a signature object for the passed callable.""" return Signature.from_callable(obj, follow_wrapped=follow_wrapped) def _main(): """ Logic for inspecting an object given at command line """ import argparse import importlib parser = argparse.ArgumentParser() parser.add_argument( 'object', help="The object to be analysed. " "It supports the 'module:qualname' syntax") parser.add_argument( '-d', '--details', action='store_true', help='Display info about the module rather than its source code') args = parser.parse_args() target = args.object mod_name, has_attrs, attrs = target.partition(":") try: obj = module = importlib.import_module(mod_name) except Exception as exc: msg = "Failed to import {} ({}: {})".format(mod_name, type(exc).__name__, exc) print(msg, file=sys.stderr) exit(2) if has_attrs: parts = attrs.split(".") obj = module for part in parts: obj = getattr(obj, part) if module.__name__ in sys.builtin_module_names: print("Can't get info for builtin modules.", file=sys.stderr) exit(1) if args.details: print('Target: {}'.format(target)) print('Origin: {}'.format(getsourcefile(module))) print('Cached: {}'.format(module.__cached__)) if obj is module: print('Loader: {}'.format(repr(module.__loader__))) if hasattr(module, '__path__'): print('Submodule search path: {}'.format(module.__path__)) else: try: __, lineno = findsource(obj) except Exception: pass else: print('Line: {}'.format(lineno)) print('\n') else: print(getsource(obj)) if __name__ == "__main__": _main()
{ "content_hash": "bcb4e9031d4380f947ce2893aec65249", "timestamp": "", "source": "github", "line_count": 3064, "max_line_length": 91, "avg_line_length": 37.21605744125326, "alnum_prop": 0.5834692624747874, "repo_name": "anbangleo/NlsdeWeb", "id": "e08e9f578eea50fa0d4fe50bccf74ecfb0af381f", "size": "114030", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Python-3.6.0/Lib/inspect.py", "mode": "33261", "license": "mit", "language": [ { "name": "Assembly", "bytes": "593890" }, { "name": "Batchfile", "bytes": "44928" }, { "name": "C", "bytes": "16572509" }, { "name": "C++", "bytes": "442285" }, { "name": "CSS", "bytes": "8574" }, { "name": "CoffeeScript", "bytes": "45748" }, { "name": "Common Lisp", "bytes": "24481" }, { "name": "DIGITAL Command Language", "bytes": "26402" }, { "name": "DTrace", "bytes": "2053" }, { "name": "HTML", "bytes": "259587" }, { "name": "JavaScript", "bytes": "87380" }, { "name": "M4", "bytes": "231072" }, { "name": "Makefile", "bytes": "278201" }, { "name": "Objective-C", "bytes": "26739" }, { "name": "PLSQL", "bytes": "22886" }, { "name": "PostScript", "bytes": "13803" }, { "name": "PowerShell", "bytes": "1420" }, { "name": "Python", "bytes": "26396189" }, { "name": "Roff", "bytes": "254982" }, { "name": "Shell", "bytes": "495563" }, { "name": "TeX", "bytes": "323102" }, { "name": "Visual Basic", "bytes": "70" } ], "symlink_target": "" }
FROM balenalib/coral-dev-debian:stretch-build ENV NODE_VERSION 15.7.0 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-arm64.tar.gz" \ && echo "72853eb858a93d53b0758b86eea0d466296ab275fbb73f2f4d40fad6cd1a0ff9 node-v$NODE_VERSION-linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-arm64.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-arm64.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \ && echo "Running test-stack@node" \ && chmod +x test-stack@node.sh \ && bash test-stack@node.sh \ && rm -rf test-stack@node.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Stretch \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.7.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "0dbfc9bd3a71c181212c404a61bfc7e9", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 694, "avg_line_length": 67.34146341463415, "alnum_prop": 0.7088011590003622, "repo_name": "nghiant2710/base-images", "id": "288a69e45d2c38cae1054aef61d769d575faeae8", "size": "2782", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/node/coral-dev/debian/stretch/15.7.0/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "symlink_target": "" }
using System.Collections.Generic; using Elasticsearch.Net; using Newtonsoft.Json; namespace Nest { [JsonObject] public class NodeInfo { [JsonProperty(PropertyName = "name")] public string Name { get; internal set; } [JsonProperty(PropertyName = "transport_address")] public string TransportAddress { get; internal set; } [JsonProperty(PropertyName = "host")] public string Hostname { get; internal set; } [JsonProperty(PropertyName = "ip")] public string Ip { get; internal set; } [JsonProperty(PropertyName = "version")] public string Version { get; internal set; } [JsonProperty(PropertyName = "build")] public string Build { get; internal set; } [JsonProperty(PropertyName = "http_address")] public string HttpAddress { get; internal set; } [JsonProperty(PropertyName = "settings")] [JsonConverter(typeof(VerbatimDictionaryKeysJsonConverter))] public DynamicResponse Settings { get; internal set; } [JsonProperty(PropertyName = "os")] public NodeOperatingSystemInfo OperatingSystem { get; internal set; } [JsonProperty(PropertyName = "process")] public NodeProcessInfo Process { get; internal set; } [JsonProperty(PropertyName = "jvm")] public NodeJvmInfo Jvm { get; internal set; } [JsonProperty(PropertyName = "thread_pool")] [JsonConverter(typeof(VerbatimDictionaryKeysJsonConverter))] public Dictionary<string, NodeThreadPoolInfo> ThreadPool { get; internal set; } [JsonProperty(PropertyName = "network")] public NodeInfoNetwork Network { get; internal set; } [JsonProperty(PropertyName = "transport")] public NodeInfoTransport Transport { get; internal set; } [JsonProperty(PropertyName = "http")] public NodeInfoHttp Http { get; internal set; } [JsonProperty("plugins")] public List<PluginStats> Plugins { get; internal set; } } [JsonObject] public class NodeOperatingSystemInfo { [JsonProperty(PropertyName = "name")] public string Name { get; internal set; } [JsonProperty(PropertyName = "arch")] public string Architecture { get; internal set; } [JsonProperty(PropertyName = "version")] public string Version { get; internal set; } [JsonProperty(PropertyName = "refresh_interval_in_millis")] public int RefreshInterval { get; internal set; } [JsonProperty(PropertyName = "available_processors")] public int AvailableProcessors { get; internal set; } [JsonProperty(PropertyName = "cpu")] public NodeInfoOSCPU Cpu { get; internal set; } [JsonProperty(PropertyName = "mem")] public NodeInfoMemory Mem { get; internal set; } [JsonProperty(PropertyName = "swap")] public NodeInfoMemory Swap { get; internal set; } } [JsonObject] public class NodeInfoOSCPU { [JsonProperty(PropertyName = "vendor")] public string Vendor { get; internal set; } [JsonProperty(PropertyName = "model")] public string Model { get; internal set; } [JsonProperty(PropertyName = "mhz")] public int Mhz { get; internal set; } [JsonProperty(PropertyName = "total_cores")] public int TotalCores { get; internal set; } [JsonProperty(PropertyName = "total_sockets")] public int TotalSockets { get; internal set; } [JsonProperty(PropertyName = "cores_per_socket")] public int CoresPerSocket { get; internal set; } [JsonProperty(PropertyName = "cache_size")] public string CacheSize { get; internal set; } [JsonProperty(PropertyName = "cache_size_in_bytes")] public int CacheSizeInBytes { get; internal set; } } [JsonObject] public class NodeInfoMemory { [JsonProperty(PropertyName = "total")] public string Total { get; internal set; } [JsonProperty(PropertyName = "total_in_bytes")] public long TotalInBytes { get; internal set; } } [JsonObject] public class NodeProcessInfo { [JsonProperty(PropertyName = "refresh_interval")] public string RefreshInterval { get; internal set; } [JsonProperty(PropertyName = "refresh_interval_in_millis")] public long RefreshIntervalInMilliseconds { get; internal set; } [JsonProperty(PropertyName = "id")] public long Id { get; internal set; } } [JsonObject] public class NodeJvmInfo { [JsonProperty(PropertyName = "pid")] public int PID { get; internal set; } [JsonProperty(PropertyName = "version")] public string Version { get; internal set; } [JsonProperty(PropertyName = "vm_name")] public string VMName { get; internal set; } [JsonProperty(PropertyName = "vm_version")] public string VMVersion { get; internal set; } [JsonProperty(PropertyName = "vm_vendor")] public string VMVendor { get; internal set; } [JsonProperty(PropertyName = "memory_pools")] public IEnumerable<string> MemoryPools { get; internal set; } [JsonProperty(PropertyName = "gc_collectors")] public IEnumerable<string> GCCollectors { get; internal set; } [JsonProperty(PropertyName = "start_time_in_millis")] public long StartTime { get; internal set; } [JsonProperty(PropertyName = "mem")] public NodeInfoJVMMemory Memory { get; internal set; } } [JsonObject] public class NodeInfoJVMMemory { [JsonProperty(PropertyName = "heap_init")] public string HeapInit { get; internal set; } [JsonProperty(PropertyName = "heap_init_in_bytes")] public long HeapInitInBytes { get; internal set; } [JsonProperty(PropertyName = "heap_max")] public string HeapMax { get; internal set; } [JsonProperty(PropertyName = "heap_max_in_bytes")] public long HeapMaxInBytes { get; internal set; } [JsonProperty(PropertyName = "non_heap_init")] public string NonHeapInit { get; internal set; } [JsonProperty(PropertyName = "non_heap_init_in_bytes")] public long NonHeapInitInBytes { get; internal set; } [JsonProperty(PropertyName = "non_heap_max")] public string NonHeapMax { get; internal set; } [JsonProperty(PropertyName = "non_heap_max_in_bytes")] public long NonHeapMaxInBytes { get; internal set; } [JsonProperty(PropertyName = "direct_max")] public string DirectMax { get; internal set; } [JsonProperty(PropertyName = "direct_max_in_bytes")] public long DirectMaxInBytes { get; internal set; } } [JsonObject] public class NodeThreadPoolInfo { [JsonProperty(PropertyName = "type")] public string Type { get; internal set; } [JsonProperty(PropertyName = "min")] public int? Min { get; internal set; } [JsonProperty(PropertyName = "max")] public int? Max { get; internal set; } [JsonProperty(PropertyName = "queue_size")] public int? QueueSize { get; internal set; } [JsonProperty(PropertyName = "keep_alive")] public string KeepAlive { get; internal set; } } [JsonObject] public class NodeInfoNetwork { [JsonProperty(PropertyName = "refresh_interval")] public int RefreshInterval { get; internal set; } [JsonProperty(PropertyName = "primary_interface")] public NodeInfoNetworkInterface PrimaryInterface { get; internal set; } } [JsonObject] public class NodeInfoNetworkInterface { [JsonProperty(PropertyName = "address")] public string Address { get; internal set; } [JsonProperty(PropertyName = "name")] public string Name { get; internal set; } [JsonProperty(PropertyName = "mac_address")] public string MacAddress { get; internal set; } } [JsonObject] public class NodeInfoTransport { [JsonProperty(PropertyName = "bound_address")] public IEnumerable<string> BoundAddress { get; internal set; } [JsonProperty(PropertyName = "publish_address")] public string PublishAddress { get; internal set; } } [JsonObject] public class NodeInfoHttp { [JsonProperty(PropertyName = "bound_address")] public IEnumerable<string> BoundAddress { get; internal set; } [JsonProperty(PropertyName = "publish_address")] public string PublishAddress { get; internal set; } [JsonProperty(PropertyName = "max_content_length")] public string MaxContentLength { get; internal set; } [JsonProperty(PropertyName = "max_content_length_in_bytes")] public long MaxContentLengthInBytes { get; internal set; } } }
{ "content_hash": "15dee60307fbe96f3fa616360070edd6", "timestamp": "", "source": "github", "line_count": 237, "max_line_length": 81, "avg_line_length": 33.45147679324894, "alnum_prop": 0.7230070635721494, "repo_name": "cstlaurent/elasticsearch-net", "id": "0fe4ee371dd2c6b37a87562cb1337b000eae58f4", "size": "7930", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Nest/Cluster/NodesInfo/NodeInfo.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1521" }, { "name": "C#", "bytes": "5625882" }, { "name": "F#", "bytes": "40135" }, { "name": "HTML", "bytes": "125310" }, { "name": "Shell", "bytes": "698" }, { "name": "Smalltalk", "bytes": "3426" } ], "symlink_target": "" }
package io.sitoolkit.util.tabledata; import java.io.File; import java.io.IOException; import java.nio.file.ClosedWatchServiceException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * ファイルの入力ソースに対する監視クラス実装です。 * * @author yuichi.kuwahara */ public class FileInputSourceWatcher extends InputSourceWatcher { private WatchService watcher; private final Set<String> watchingDirSet = new HashSet<>(); private final Map<String, InputSource> watchingFileMap = new HashMap<>(); private final Map<WatchKey, Path> pathMap = new HashMap<>(); /** * ファイルを監視対象に含めます。 * * @param inputSource * 監視対象ファイル */ @Override public void watchInputSource(String inputSource) { File file = new File(inputSource); if (!file.exists()) { log.warn(MessageManager.getMessage("filewatcher.fileNotFound"), file.getAbsolutePath()); return; } if (watchingFileMap.containsKey(file.getAbsolutePath())) { return; } log.info(MessageManager.getMessage("filewatcher.addFile"), file.getAbsolutePath()); watchingFileMap.put(file.getAbsolutePath(), new InputSource(inputSource, file.lastModified())); File dir = file.getParentFile(); if (watchingDirSet.contains(dir.getAbsolutePath())) { return; } log.info(MessageManager.getMessage("filewatcher.addDirectory"), dir.getAbsolutePath()); watchingDirSet.add(dir.getAbsolutePath()); Path dirPath = dir.toPath(); try { if (watcher == null) { // TODO ファイル監視方式の統一 watcher = FileSystems.getDefault().newWatchService(); } WatchKey watchKey = dirPath.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); pathMap.put(watchKey, dirPath); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void watching(ContinuousGeneratable cg) { WatchKey watchKey; try { watchKey = watcher.take(); } catch (InterruptedException e) { throw new IllegalStateException(e); } catch (ClosedWatchServiceException e) { if (isContinue()) { throw new IllegalStateException(e); } else { return; } } for (WatchEvent<?> event : watchKey.pollEvents()) { Path dir = pathMap.get(watchKey); File changedFile = dir.resolve((Path) event.context()).toFile(); log.debug(MessageManager.getMessage("filewatcher.detectedChangeEvent"), changedFile.getAbsolutePath()); InputSource inputSource = watchingFileMap.get(changedFile.getAbsolutePath()); if (inputSource != null && inputSource.lastModified != changedFile.lastModified()) { log.info(MessageManager.getMessage("filewatcher.regenerate"), changedFile.getAbsolutePath()); cg.regenerate(inputSource.name); inputSource.lastModified = changedFile.lastModified(); } } watchKey.reset(); } @Override protected void end(ContinuousGeneratable cg) { try { watcher.close(); } catch (IOException e) { log.warn(MessageManager.getMessage("exception.closingWatchService"), e); } for (InputSource inputSource : watchingFileMap.values()) { cg.regenerate(inputSource.name); } } class InputSource { String name; long lastModified; InputSource(String name, long lastModified) { this.name = name; this.lastModified = lastModified; } } }
{ "content_hash": "76446aa697bd0a491d952042d4154f16", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 100, "avg_line_length": 33.584, "alnum_prop": 0.5962363030014293, "repo_name": "sitoolkit/sit-util-td", "id": "19a62f8a1ec2ba332da5acaf993bfebec1fb7a15", "size": "4925", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/io/sitoolkit/util/tabledata/FileInputSourceWatcher.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "112848" } ], "symlink_target": "" }
""" Module used to extract Pycopia-QA test plan documentation from the set of automated test plans found in the test module location. """ import sys, os, re, shutil import textwrap # for checking base class from types import ModuleType import locale try: locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_file from pycopia.QA import core from pycopia.QA import config from pycopia.WWW import XHTML STYLESHEET = "/media/css/qa_tp.css" INDEX_STYLESHEET = "/media/css/qa_tp_index.css" def fix_path(): TESTHOME = os.environ.get("TESTHOME") if not TESTHOME: raise ValueError, "I don't know where to find tests. Try setting TESTHOME" sys.path.append(TESTHOME) return TESTHOME def build_testplans(argv): py_matcher = re.compile(r"(^[a-zA-Z]+)\.py$", re.M) HOME = fix_path() home_len = len(HOME)+1 if len(argv) > 1: DOCDIR = os.path.expanduser(os.path.expandvars(argv[1])) else: DOCDIR = "/var/www/localhost/htdocs/testplans" os.chdir(DOCDIR) index = XHTML.new_document() NM = index.nodemaker index.add_title("Package Index") index.stylesheet = INDEX_STYLESHEET index.add_header(1, "Package Index") index.new_para("""Here are the available packages.""") UL = index.get_unordered_list() index.append(UL) for dirname, dirs, files in os.walk(HOME): if "__init__.py" in files: pkgname = ".".join(dirname[home_len:].split("/")) if not pkgname: continue rstname = pkgname.replace(".", "_")+".rst" htmlname = pkgname.replace(".", "_")+".html" A = NM("A", {"href":htmlname}) A.add_text(pkgname) UL.add_item(A) fo = file(rstname, "w") extract_package(fo, pkgname) fo.close() publish_file(source_path=rstname, parser_name='restructuredtext', writer_name='html', destination_path=htmlname, settings_overrides={"link_stylesheet": True, "embed_stylesheet": False, "stylesheet_path": None, "stylesheet":STYLESHEET} ) for fname in files: # copy any included files to destination if fname[-3:] in ("jpg", "png", "gif", "rst"): shutil.copy(os.path.join(dirname, fname), DOCDIR) else: for fname in files: mo = py_matcher.match(fname) if mo: modname = mo.group(1) rstname = modname.replace(".", "_")+".rst" htmlname = modname.replace(".", "_")+".html" A = NM("A", {"href":htmlname}) A.add_text(modname) UL.add_item(A) fo = file(rstname, "w") extract_module(fo, modname) fo.close() publish_file(source_path=rstname, parser_name='restructuredtext', writer_name='html', destination_path=htmlname, settings_overrides={"link_stylesheet": True, "embed_stylesheet": False, "stylesheet_path": None, "stylesheet":STYLESHEET}, ) indexfile = file("testplan_index.html", "w") index.emit(indexfile) indexfile.close() # Scan the module for test cases defined in it and write them to the file # object. Also write the module level documentation. This will create a # structured document that closely matches the Python package structure. def mod_doc(fo, mod): setattr(mod, "_visited_", True) fo.write("\n.. _%s:\n" % (mod.__name__.split(".")[-1],)) if mod.__doc__: fo.write(mod.__doc__) # module doc, should be RST else: name = mod.__path__[0] fo.write(name) fo.write("\n") fo.write("-" * len(name)) fo.write("\n\n") fo.write("\n:Module Name:\n") fo.write(" %s\n" %(mod.__name__,)) if hasattr(mod, "__all__"): fo.write(":Test Modules:\n") for name in mod.__all__: fo.write(" - %s_\n" %(name,)) if hasattr(mod, "get_suite"): fo.write("\n:Default Tests:\n") cf = config.get_config() suite = mod.get_suite(cf) for test in suite: fo.write(" - %r\n" %(test,)) fo.write("\n") for name in dir(mod): obj = getattr(mod, name) if type(obj) is type(object) and issubclass(obj, core.Test): if mod.__name__ == obj.__module__: # defined in THIS module # test ID is full class path if obj.__doc__: tid = "%s.%s" % (obj.__module__, obj.__name__) head = "Test Case: %s" % (obj.__name__,) fo.write("\n.. _%s:\n\n%s\n" % (obj.__name__, head)) fo.write("*"*len(head)) # Test class header should be H2 fo.write("\n:Test Case ID:\n") fo.write(" %s\n" %(tid,)) fo.write(textwrap.dedent(obj.__doc__)) fo.write("\n") elif type(obj) is ModuleType: if (hasattr(obj, "__path__") and os.path.split(obj.__file__)[0].startswith(os.path.split(mod.__file__)[0])) or \ obj.__name__.startswith(mod.__name__): # sub package or module if not hasattr(obj, "_visited_"): mod_doc(fo, obj) def extract_module(fo, modname): """Extract a single modules test plan documents.""" mod = __import__(modname) mod_doc(fo, mod) def extract_package(fo, pkgname): """Create one large RST document from a package of test modules.""" pkg = __import__(pkgname, globals(), locals(), ['*']) assert hasattr(pkg, "__path__") mod_doc(fo, pkg) def extract_main(argv): """Reads the modules in the named package root, and writes RST (from the docstrings) to the given file (or stdout).""" close = lambda : None try: fname = argv[2] except IndexError: fo = sys.stdout else: if fname == "-": fo = sys.stdout else: fo = file(fname, "w") close = fo.close pkgname = argv[1] extract_package(fo, pkgname) close() # don't close stdout def _test(argv): build_testplans(["build_testplans"]) if __name__ == "__main__": _test(sys.argv)
{ "content_hash": "a500fcf282d073dea96ea243d5474fae", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 154, "avg_line_length": 35.169398907103826, "alnum_prop": 0.5368241143567433, "repo_name": "kdart/pycopia", "id": "8b2a9a731b2bf3d888c74f5458d04666b71ba577", "size": "6556", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "QA/pycopia/QA/gendoc.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "423794" }, { "name": "CSS", "bytes": "19522" }, { "name": "JavaScript", "bytes": "91759" }, { "name": "Makefile", "bytes": "6958" }, { "name": "Perl", "bytes": "271" }, { "name": "Python", "bytes": "6098633" }, { "name": "Roff", "bytes": "7289" }, { "name": "Shell", "bytes": "12778" }, { "name": "Vim script", "bytes": "50421" } ], "symlink_target": "" }
import clr clr.AddReference('RevitAPI') from Autodesk.Revit.DB import * faminsts = IN[0] elementlist = list() for item in faminsts: try: n = UnwrapElement(item).Name except: n = None if n == None: try: n = item.Name except: n = [] elementlist.append(n) OUT = elementlist
{ "content_hash": "bac9f04bcc25292c1dc41e08cf64f18c", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 31, "avg_line_length": 16.11111111111111, "alnum_prop": 0.6689655172413793, "repo_name": "andydandy74/ClockworkForDynamo", "id": "e3a007b06060d581f390551accdd73008ebf9d76", "size": "290", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "nodes/0.7.x/python/Element.Name (Universal).py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "717382" } ], "symlink_target": "" }
<?php return array ( '{displayNames} commented {contentTitle}.' => '{displayNames} ont commenté {contentTitle}.', '{displayName} commented {contentTitle}.' => '{displayName} a commenté {contentTitle}.', );
{ "content_hash": "35d4a5bab19ff3d8ef979d23fadc65e7", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 94, "avg_line_length": 42, "alnum_prop": 0.6952380952380952, "repo_name": "LeonidLyalin/vova", "id": "984256bbadaaa42c71b4174aff2d178b03d8891f", "size": "212", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/humhub/protected/humhub/modules/comment/messages/fr/notification.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "227" }, { "name": "Batchfile", "bytes": "3096" }, { "name": "CSS", "bytes": "824207" }, { "name": "HTML", "bytes": "25309" }, { "name": "JavaScript", "bytes": "1284304" }, { "name": "PHP", "bytes": "8757729" }, { "name": "Ruby", "bytes": "375" }, { "name": "Shell", "bytes": "3256" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Employee', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('last_name', models.CharField(max_length=100)), ('first_name', models.CharField(max_length=100)), ('birth_date', models.DateField()), ('joined_date', models.DateField()), ('salary', models.FloatField()), ('phone', models.CharField(max_length=50)), ('performance_indice', models.IntegerField()), ('gender', models.CharField(max_length=1)), ('children_number', models.IntegerField()), ('adress', models.TextField()), ('mail', models.EmailField(max_length=254)), ('married', models.BooleanField()), ], ), migrations.CreateModel( name='Notation', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('rating', models.IntegerField()), ('employee', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='API.Employee')), ], ), migrations.CreateModel( name='Widget', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('author', models.CharField(max_length=100)), ('description', models.TextField()), ], ), migrations.AddField( model_name='notation', name='widget', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='API.Widget'), ), ]
{ "content_hash": "ab7b580411d1b9f600e33aa16140dea6", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 114, "avg_line_length": 38.654545454545456, "alnum_prop": 0.5380997177798683, "repo_name": "goujonpa/sopraBigDataModule", "id": "1abef438ff79afb54d3dc1dd61d1eee41523f64e", "size": "2198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sopraBDM/API/migrations/0001_initial.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "7801" }, { "name": "Makefile", "bytes": "7735" }, { "name": "Python", "bytes": "32236" }, { "name": "R", "bytes": "11010" }, { "name": "Shell", "bytes": "221" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace SlimKit\PlusFeed\Tests\Feature\API2; use Illuminate\Foundation\Testing\DatabaseTransactions; use Zhiyi\Component\ZhiyiPlus\PlusComponentFeed\Models\Feed; use Zhiyi\Plus\Models\User as UserModel; use Zhiyi\Plus\Tests\TestCase; class GetFeedTest extends TestCase { use DatabaseTransactions; protected $user; protected $feed; public function setUp(): void { parent::setUp(); $this->user = UserModel::factory()->create(); $this->feed = Feed::factory()->create([ 'user_id' => $this->user->id, ]); } /** * 测试动态列表接口. * * @return mixed */ public function testGetFeeds() { $response = $this->actingAs($this->user, 'api') ->json('GET', '/api/v2/feeds'); $response ->assertStatus(200) ->assertJsonStructure(['pinned', 'feeds']); } /** * 测试动态详情接口. * * @return mixed */ public function testGetFeed() { $response = $this->actingAs($this->user, 'api') ->json('GET', '/api/v2/feeds/'.$this->feed->id); $response ->assertStatus(200); } /** * 测试未登录获取动态列表接口. */ public function testNotAuthGetFeeds() { $response = $this->json('GET', '/api/v2/feeds'); $response ->assertStatus(200) ->assertJsonStructure(['pinned', 'feeds']); } /** * 测试动态详情接口. * * @return mixed */ public function testNotAuthGetFeed() { $response = $this->json('GET', '/api/v2/feeds/'.$this->feed->id); $response ->assertStatus(200); } }
{ "content_hash": "08a51ca19bbac109a86282f706a4bff2", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 73, "avg_line_length": 20.76829268292683, "alnum_prop": 0.540223135642983, "repo_name": "slimkit/thinksns-plus", "id": "b7c8a79d8c830c191b8671f69e45a4f1c2fda9b6", "size": "2771", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/slimkit-plus-feed/tests/Feature/API2/GetFeedTest.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "182369" }, { "name": "PHP", "bytes": "2316503" }, { "name": "Vue", "bytes": "923819" } ], "symlink_target": "" }
@implementation UIButton (ImageTitleStyle) -(void)setButtonImageTitleStyle:(ButtonImageTitleStyle)style padding:(CGFloat)padding { if (self.imageView.image != nil && self.titleLabel.text != nil) { // if (self.frame.size.height == 0 && self.frame.size.width == 0) // [self sizeToFit]; // ButtonImageTitleStyleDefault = 0, //图片在左,文字在右,整体居中。 // ButtonImageTitleStyleLeft = 1, //图片在左,文字在右,整体居中。 // ButtonImageTitleStyleRight = 2, //图片在右,文字在左,整体居中。 // ButtonImageTitleStyleTop = 3, //图片在上,文字在下,整体居中。 // ButtonImageTitleStyleBottom = 4, //图片在下,文字在上,整体居中。 // ButtonImageTitleStyleCenterTop = 5, //图片居中,文字在上距离按钮顶部。 // ButtonImageTitleStyleCenterBottom = 6, //图片居中,文字在下距离按钮底部。 // ButtonImageTitleStyleCenterUp = 7, //图片居中,文字在图片上面。 // ButtonImageTitleStyleCenterDown = 8, //图片居中,文字在图片下面。 // ButtonImageTitleStyleRightLeft = 9, //图片在右,文字在左,距离按钮两边边距 // ButtonImageTitleStyleLeftRight = 10, //图片在左,文字在右,距离按钮两边边距 //先还原 self.titleEdgeInsets = UIEdgeInsetsZero; self.imageEdgeInsets = UIEdgeInsetsZero; CGRect imageRect = self.imageView.frame;// 1.5 14 30 1.5 CGRect titleRect = self.titleLabel.frame;// 9 5 32 20 CGFloat totalHeight = imageRect.size.height + padding + titleRect.size.height; CGFloat selfHeight = self.frame.size.height; CGFloat selfWidth = self.frame.size.width; switch (style) { case ButtonImageTitleStyleLeft: if (padding != 0) { self.titleEdgeInsets = UIEdgeInsetsMake(0, padding/2, 0, -padding/2); self.imageEdgeInsets = UIEdgeInsetsMake(0, -padding/2, 0, padding/2); } break; case ButtonImageTitleStyleRight: { //图片在右,文字在左 self.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageRect.size.width + padding/2), 0, (imageRect.size.width + padding/2)); self.imageEdgeInsets = UIEdgeInsetsMake(0, (titleRect.size.width+ padding/2), 0, -(titleRect.size.width+ padding/2)); } break; case ButtonImageTitleStyleTop: { //图片在上,文字在下 self.titleEdgeInsets = UIEdgeInsetsMake(((selfHeight - totalHeight)/2 + imageRect.size.height + padding - titleRect.origin.y), (selfWidth/2 - titleRect.origin.x - titleRect.size.width /2) - (selfWidth - titleRect.size.width) / 2, -((selfHeight - totalHeight)/2 + imageRect.size.height + padding - titleRect.origin.y), -(selfWidth/2 - titleRect.origin.x - titleRect.size.width /2) - (selfWidth - titleRect.size.width) / 2); self.imageEdgeInsets = UIEdgeInsetsMake(((selfHeight - totalHeight)/2 - imageRect.origin.y), (selfWidth /2 - imageRect.origin.x - imageRect.size.width / 2), -((selfHeight - totalHeight)/2 - imageRect.origin.y), -(selfWidth /2 - imageRect.origin.x - imageRect.size.width / 2)); } break; case ButtonImageTitleStyleBottom: { //图片在下,文字在上。 self.titleEdgeInsets = UIEdgeInsetsMake(((selfHeight - totalHeight)/2 - titleRect.origin.y), (selfWidth/2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, -((selfHeight - totalHeight)/2 - titleRect.origin.y), -(selfWidth/2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); self.imageEdgeInsets = UIEdgeInsetsMake(((selfHeight - totalHeight)/2 + titleRect.size.height + padding - imageRect.origin.y), (selfWidth /2 - imageRect.origin.x - imageRect.size.width / 2), -((selfHeight - totalHeight)/2 + titleRect.size.height + padding - imageRect.origin.y), -(selfWidth /2 - imageRect.origin.x - imageRect.size.width / 2)); } break; case ButtonImageTitleStyleCenterTop: { self.titleEdgeInsets = UIEdgeInsetsMake(-(titleRect.origin.y - padding), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, (titleRect.origin.y - padding), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); self.imageEdgeInsets = UIEdgeInsetsMake(0, (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), 0, -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); } break; case ButtonImageTitleStyleCenterBottom: { self.titleEdgeInsets = UIEdgeInsetsMake((selfHeight - padding - titleRect.origin.y - titleRect.size.height), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, -(selfHeight - padding - titleRect.origin.y - titleRect.size.height), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); self.imageEdgeInsets = UIEdgeInsetsMake(0, (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), 0, -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); } break; case ButtonImageTitleStyleCenterUp: { self.titleEdgeInsets = UIEdgeInsetsMake(-(titleRect.origin.y + titleRect.size.height - imageRect.origin.y + padding), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, (titleRect.origin.y + titleRect.size.height - imageRect.origin.y + padding), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); self.imageEdgeInsets = UIEdgeInsetsMake(0, (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), 0, -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); } break; case ButtonImageTitleStyleCenterDown: { self.titleEdgeInsets = UIEdgeInsetsMake((imageRect.origin.y + imageRect.size.height - titleRect.origin.y + padding), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, -(imageRect.origin.y + imageRect.size.height - titleRect.origin.y + padding), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); self.imageEdgeInsets = UIEdgeInsetsMake(0, (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), 0, -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); } break; case ButtonImageTitleStyleRightLeft: { //图片在右,文字在左,距离按钮两边边距 self.titleEdgeInsets = UIEdgeInsetsMake(0, -(titleRect.origin.x - padding), 0, (titleRect.origin.x - padding)); self.imageEdgeInsets = UIEdgeInsetsMake(0, (selfWidth - padding - imageRect.origin.x - imageRect.size.width), 0, -(selfWidth - padding - imageRect.origin.x - imageRect.size.width)); } break; case ButtonImageTitleStyleLeftRight: { //图片在左,文字在右,距离按钮两边边距 self.titleEdgeInsets = UIEdgeInsetsMake(0, (selfWidth - padding - titleRect.origin.x - titleRect.size.width), 0, -(selfWidth - padding - titleRect.origin.x - titleRect.size.width)); self.imageEdgeInsets = UIEdgeInsetsMake(0, -(imageRect.origin.x - padding), 0, (imageRect.origin.x - padding)); } break; case ButtonImageTitleStyleCenterRight: { self.titleEdgeInsets = UIEdgeInsetsMake(0, (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2), 0, -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2)); self.imageEdgeInsets = UIEdgeInsetsMake(0, selfWidth/2 + titleRect.size.width/2 + padding - imageRect.origin.x, 0, -1*(selfWidth/2 + titleRect.size.width/2 + padding - imageRect.origin.x)); } break; default: break; } } else { self.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0); self.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0); } } @end
{ "content_hash": "2fc85ed07db60adca98eb43fb9c764bd", "timestamp": "", "source": "github", "line_count": 206, "max_line_length": 164, "avg_line_length": 60.49029126213592, "alnum_prop": 0.41577722494181846, "repo_name": "loveNoodles/testPodFiles", "id": "1c3d722349b771d3703440e97b29ac2f23644831", "size": "13045", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "foundation/UIButton+ImageTitleStyle.m", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "9648" }, { "name": "Objective-C", "bytes": "107265" }, { "name": "Ruby", "bytes": "913" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Fusion.Engine.Frames; namespace Fusion.Engine.Frames.Layouts { public enum QuadLayoutStyle { SinglePanel, TwoPanelsSideBySide, TwoPanelsStacked, ThreePanelsSplitTop, ThreePanelsSplitBottom, ThreePanelsSplitLeft, ThreePanelsSplitRight, FourPanels, } }
{ "content_hash": "328013f51def07ca0e29f1fcc58200bc", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 40, "avg_line_length": 19.7, "alnum_prop": 0.799492385786802, "repo_name": "demiurghg/FusionEngine", "id": "5dfd8d1b5a22484df0b612767667bbfd38b426d0", "size": "396", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Fusion/Engine/Frames/Layouts/QuadLayoutStyle.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "973" }, { "name": "C", "bytes": "162373" }, { "name": "C#", "bytes": "3769196" }, { "name": "C++", "bytes": "3312278" }, { "name": "HLSL", "bytes": "115381" }, { "name": "NSIS", "bytes": "6689" }, { "name": "Objective-C", "bytes": "519" } ], "symlink_target": "" }
namespace TuiTche.Web.Migrations { using System; using System.Data.Entity.Migrations; public partial class TestePrimeiraMigration : DbMigration { public override void Up() { CreateTable( "dbo.AspNetRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId) .Index(t => t.RoleId); CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), Email = c.String(maxLength: 256), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.UserName, unique: true, name: "UserNameIndex"); CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(nullable: false, maxLength: 128), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); } public override void Down() { DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); DropIndex("dbo.AspNetUsers", "UserNameIndex"); DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); DropIndex("dbo.AspNetRoles", "RoleNameIndex"); DropTable("dbo.AspNetUserLogins"); DropTable("dbo.AspNetUserClaims"); DropTable("dbo.AspNetUsers"); DropTable("dbo.AspNetUserRoles"); DropTable("dbo.AspNetRoles"); } } }
{ "content_hash": "06f5ff16bd0068d16ac61b2cec316a59", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 82, "avg_line_length": 44.484848484848484, "alnum_prop": 0.4682107175295186, "repo_name": "ramonkroetz/tuitche-tcc", "id": "a4575b8787c4dc03cfcb291a6c5f14056cf401f2", "size": "4404", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/TuiTche/TuiTche.Web/Migrations/201506132041556_TestePrimeiraMigration.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "102" }, { "name": "C#", "bytes": "134737" }, { "name": "CSS", "bytes": "73423" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "14034" } ], "symlink_target": "" }
module Caulfield class Middleware @@instance = new attr_accessor :app, :session, :cookies, :request, :env, :status, :headers, :body class << self def new(app) @@instance.app = app @@instance.reset @@instance end def instance @@instance end end def call(env) @env = env @request = ActionDispatch::Request.new(env) merge_cookies unless @cookies_to_merge.empty? merge_session unless @session_to_merge.empty? @status, @headers, @body = @app.call(env) @cookies = @request.cookie_jar @session = @request.session [@status, @headers, @body] end def reset @cookies = @session = nil @request = @env = nil @status = @headers = @body = nil @cookies_to_merge = {} @session_to_merge = {} end def set_cookies(hash) @cookies_to_merge.merge!(hash) end def set_session(hash) @session_to_merge.merge!(hash) end private def merge_cookies @cookies_to_merge.each do |key, value| if value.nil? @request.cookie_jar.delete key else @request.cookie_jar.signed[key] = value end end @cookies_to_merge = {} end def merge_session @session_to_merge.each do |key, value| if value.nil? @request.session.delete key else @request.session[key] = value end end @session_to_merge = {} end end end
{ "content_hash": "48ada3bbd0016a203d00de1dff643f51", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 51, "avg_line_length": 19.935064935064936, "alnum_prop": 0.5478827361563517, "repo_name": "chanks/caulfield", "id": "6163c7862c5ea5febf134742b1475781f3c48df5", "size": "1535", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/caulfield/middleware.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "3617" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using log4net; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Framework.Client; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server { public delegate void OnIRCClientReadyDelegate(IRCClientView cv); public class IRCClientView : IClientAPI, IClientCore, IClientIPEndpoint { public event OnIRCClientReadyDelegate OnIRCReady; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly TcpClient m_client; private readonly Scene m_scene; private UUID m_agentID = UUID.Random(); private string m_username; private string m_nick; private bool m_hasNick = false; private bool m_hasUser = false; private bool m_connected = true; public IRCClientView(TcpClient client, Scene scene) { m_client = client; m_scene = scene; Watchdog.StartThread(InternalLoop, "IRCClientView", ThreadPriority.Normal, false); } private void SendServerCommand(string command) { SendCommand(":opensimircd " + command); } private void SendCommand(string command) { m_log.Info("[IRCd] Sending >>> " + command); byte[] buf = Util.UTF8.GetBytes(command + "\r\n"); m_client.GetStream().BeginWrite(buf, 0, buf.Length, SendComplete, null); } private void SendComplete(IAsyncResult result) { m_log.Info("[IRCd] Send Complete."); } private string IrcRegionName { // I know &Channel is more technically correct, but people are used to seeing #Channel // Dont shoot me! get { return "#" + m_scene.RegionInfo.RegionName.Replace(" ", "-"); } } private void InternalLoop() { try { string strbuf = String.Empty; while (m_connected && m_client.Connected) { byte[] buf = new byte[8]; // RFC1459 defines max message size as 512. int count = m_client.GetStream().Read(buf, 0, buf.Length); string line = Util.UTF8.GetString(buf, 0, count); strbuf += line; string message = ExtractMessage(strbuf); if (message != null) { // Remove from buffer strbuf = strbuf.Remove(0, message.Length); m_log.Info("[IRCd] Recieving <<< " + message); message = message.Trim(); // Extract command sequence string command = ExtractCommand(message); ProcessInMessage(message, command); } else { //m_log.Info("[IRCd] Recieved data, but not enough to make a message. BufLen is " + strbuf.Length + // "[" + strbuf + "]"); if (strbuf.Length == 0) { m_connected = false; m_log.Info("[IRCd] Buffer zero, closing..."); if (OnDisconnectUser != null) OnDisconnectUser(); } } Thread.Sleep(0); Watchdog.UpdateThread(); } } catch (IOException) { if (OnDisconnectUser != null) OnDisconnectUser(); m_log.Warn("[IRCd] Disconnected client."); } catch (SocketException) { if (OnDisconnectUser != null) OnDisconnectUser(); m_log.Warn("[IRCd] Disconnected client."); } Watchdog.RemoveThread(); } private void ProcessInMessage(string message, string command) { m_log.Info("[IRCd] Processing [MSG:" + message + "] [COM:" + command + "]"); if (command != null) { switch (command) { case "ADMIN": case "AWAY": case "CONNECT": case "DIE": case "ERROR": case "INFO": case "INVITE": case "ISON": case "KICK": case "KILL": case "LINKS": case "LUSERS": case "OPER": case "PART": case "REHASH": case "SERVICE": case "SERVLIST": case "SERVER": case "SQUERY": case "SQUIT": case "STATS": case "SUMMON": case "TIME": case "TRACE": case "VERSION": case "WALLOPS": case "WHOIS": case "WHOWAS": SendServerCommand("421 " + command + " :Command unimplemented"); break; // Connection Commands case "PASS": break; // Ignore for now. I want to implement authentication later however. case "JOIN": IRC_SendReplyJoin(); break; case "MODE": IRC_SendReplyModeChannel(); break; case "USER": IRC_ProcessUser(message); IRC_Ready(); break; case "USERHOST": string[] userhostArgs = ExtractParameters(message); if (userhostArgs[0] == ":" + m_nick) { SendServerCommand("302 :" + m_nick + "=+" + m_nick + "@" + ((IPEndPoint) m_client.Client.RemoteEndPoint).Address); } break; case "NICK": IRC_ProcessNick(message); IRC_Ready(); break; case "TOPIC": IRC_SendReplyTopic(); break; case "USERS": IRC_SendReplyUsers(); break; case "LIST": break; // TODO case "MOTD": IRC_SendMOTD(); break; case "NOTICE": // TODO break; case "WHO": // TODO IRC_SendNamesReply(); IRC_SendWhoReply(); break; case "PING": IRC_ProcessPing(message); break; // Special case, ignore this completely. case "PONG": break; case "QUIT": if (OnDisconnectUser != null) OnDisconnectUser(); break; case "NAMES": IRC_SendNamesReply(); break; case "PRIVMSG": IRC_ProcessPrivmsg(message); break; default: SendServerCommand("421 " + command + " :Unknown command"); break; } } } private void IRC_Ready() { if (m_hasUser && m_hasNick) { SendServerCommand("001 " + m_nick + " :Welcome to OpenSimulator IRCd"); SendServerCommand("002 " + m_nick + " :Running OpenSimVersion"); SendServerCommand("003 " + m_nick + " :This server was created over 9000 years ago"); SendServerCommand("004 " + m_nick + " :opensimirc r1 aoOirw abeiIklmnoOpqrstv"); SendServerCommand("251 " + m_nick + " :There are 0 users and 0 services on 1 servers"); SendServerCommand("252 " + m_nick + " 0 :operators online"); SendServerCommand("253 " + m_nick + " 0 :unknown connections"); SendServerCommand("254 " + m_nick + " 1 :channels formed"); SendServerCommand("255 " + m_nick + " :I have 1 users, 0 services and 1 servers"); SendCommand(":" + m_nick + " MODE " + m_nick + " :+i"); SendCommand(":" + m_nick + " JOIN :" + IrcRegionName); // Rename to 'Real Name' SendCommand(":" + m_nick + " NICK :" + m_username.Replace(" ", "")); m_nick = m_username.Replace(" ", ""); IRC_SendReplyJoin(); IRC_SendChannelPrivmsg("System", "Welcome to OpenSimulator."); IRC_SendChannelPrivmsg("System", "You are in a maze of twisty little passages, all alike."); IRC_SendChannelPrivmsg("System", "It is pitch black. You are likely to be eaten by a grue."); if (OnIRCReady != null) OnIRCReady(this); } } private void IRC_SendReplyJoin() { IRC_SendReplyTopic(); IRC_SendNamesReply(); } private void IRC_SendReplyModeChannel() { SendServerCommand("324 " + m_nick + " " + IrcRegionName + " +n"); //SendCommand(":" + IrcRegionName + " MODE +n"); } private void IRC_ProcessUser(string message) { string[] userArgs = ExtractParameters(message); // TODO: unused: string username = userArgs[0]; // TODO: unused: string hostname = userArgs[1]; // TODO: unused: string servername = userArgs[2]; string realname = userArgs[3].Replace(":", ""); m_username = realname; m_hasUser = true; } private void IRC_ProcessNick(string message) { string[] nickArgs = ExtractParameters(message); string nickname = nickArgs[0].Replace(":",""); m_nick = nickname; m_hasNick = true; } private void IRC_ProcessPing(string message) { string[] pingArgs = ExtractParameters(message); string pingHost = pingArgs[0]; SendCommand("PONG " + pingHost); } private void IRC_ProcessPrivmsg(string message) { string[] privmsgArgs = ExtractParameters(message); if (privmsgArgs[0] == IrcRegionName) { if (OnChatFromClient != null) { OSChatMessage msg = new OSChatMessage(); msg.Sender = this; msg.Channel = 0; msg.From = this.Name; msg.Message = privmsgArgs[1].Replace(":", ""); msg.Position = Vector3.Zero; msg.Scene = m_scene; msg.SenderObject = null; msg.SenderUUID = this.AgentId; msg.Type = ChatTypeEnum.Say; OnChatFromClient(this, msg); } } else { // Handle as an IM, later. } } private void IRC_SendNamesReply() { EntityBase[] users = m_scene.Entities.GetAllByType<ScenePresence>(); foreach (EntityBase user in users) { SendServerCommand("353 " + m_nick + " = " + IrcRegionName + " :" + user.Name.Replace(" ", "")); } SendServerCommand("366 " + IrcRegionName + " :End of /NAMES list"); } private void IRC_SendWhoReply() { EntityBase[] users = m_scene.Entities.GetAllByType<ScenePresence>(); foreach (EntityBase user in users) { /*SendServerCommand(String.Format("352 {0} {1} {2} {3} {4} {5} :0 {6}", IrcRegionName, user.Name.Replace(" ", ""), "nohost.com", "opensimircd", user.Name.Replace(" ", ""), 'H', user.Name));*/ SendServerCommand("352 " + m_nick + " " + IrcRegionName + " n=" + user.Name.Replace(" ", "") + " fakehost.com " + user.Name.Replace(" ", "") + " H " + ":0 " + user.Name); //SendServerCommand("352 " + IrcRegionName + " " + user.Name.Replace(" ", "") + " nohost.com irc.opensimulator " + user.Name.Replace(" ", "") + " H " + ":0 " + user.Name); } SendServerCommand("315 " + m_nick + " " + IrcRegionName + " :End of /WHO list"); } private void IRC_SendMOTD() { SendServerCommand("375 :- OpenSimulator Message of the day -"); SendServerCommand("372 :- Hiya!"); SendServerCommand("376 :End of /MOTD command"); } private void IRC_SendReplyTopic() { SendServerCommand("332 " + IrcRegionName + " :OpenSimulator IRC Server"); } private void IRC_SendReplyUsers() { EntityBase[] users = m_scene.Entities.GetAllByType<ScenePresence>(); SendServerCommand("392 :UserID Terminal Host"); if (users.Length == 0) { SendServerCommand("395 :Nobody logged in"); return; } foreach (EntityBase user in users) { char[] nom = new char[8]; char[] term = "terminal_".ToCharArray(); char[] host = "hostname".ToCharArray(); string userName = user.Name.Replace(" ",""); for (int i = 0; i < nom.Length; i++) { if (userName.Length < i) nom[i] = userName[i]; else nom[i] = ' '; } SendServerCommand("393 :" + nom + " " + term + " " + host + ""); } SendServerCommand("394 :End of users"); } private static string ExtractMessage(string buffer) { int pos = buffer.IndexOf("\r\n"); if (pos == -1) return null; string command = buffer.Substring(0, pos + 2); return command; } private static string ExtractCommand(string msg) { string[] msgs = msg.Split(' '); if (msgs.Length < 2) { m_log.Warn("[IRCd] Dropped msg: " + msg); return null; } if (msgs[0].StartsWith(":")) return msgs[1]; return msgs[0]; } private static string[] ExtractParameters(string msg) { string[] msgs = msg.Split(' '); List<string> parms = new List<string>(msgs.Length); bool foundCommand = false; string command = ExtractCommand(msg); for (int i=0;i<msgs.Length;i++) { if (msgs[i] == command) { foundCommand = true; continue; } if (foundCommand != true) continue; if (i != 0 && msgs[i].StartsWith(":")) { List<string> tmp = new List<string>(); for (int j=i;j<msgs.Length;j++) { tmp.Add(msgs[j]); } parms.Add(string.Join(" ", tmp.ToArray())); break; } parms.Add(msgs[i]); } return parms.ToArray(); } #region Implementation of IClientAPI public Vector3 StartPos { get { return new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 50); } set { } } public bool TryGet<T>(out T iface) { iface = default(T); return false; } public T Get<T>() { return default(T); } public UUID AgentId { get { return m_agentID; } } public void Disconnect(string reason) { IRC_SendChannelPrivmsg("System", "You have been eaten by a grue. (" + reason + ")"); m_connected = false; m_client.Close(); } public void Disconnect() { IRC_SendChannelPrivmsg("System", "You have been eaten by a grue."); m_connected = false; m_client.Close(); } public UUID SessionId { get { return m_agentID; } } public UUID SecureSessionId { get { return m_agentID; } } public UUID ActiveGroupId { get { return UUID.Zero; } } public string ActiveGroupName { get { return "IRCd User"; } } public ulong ActiveGroupPowers { get { return 0; } } public ulong GetGroupPowers(UUID groupID) { return 0; } public bool IsGroupMember(UUID GroupID) { return false; } public string FirstName { get { string[] names = m_username.Split(' '); return names[0]; } } public string LastName { get { string[] names = m_username.Split(' '); if (names.Length > 1) return names[1]; return names[0]; } } public IScene Scene { get { return m_scene; } } public int NextAnimationSequenceNumber { get { return 0; } } public string Name { get { return m_username; } } public bool IsActive { get { return true; } set { if (!value) Disconnect("IsActive Disconnected?"); } } public bool IsLoggingOut { get { return false; } set { } } public bool SendLogoutPacketWhenClosing { set { } } public uint CircuitCode { get { return (uint)Util.RandomClass.Next(0,int.MaxValue); } } public IPEndPoint RemoteEndPoint { get { return (IPEndPoint)m_client.Client.RemoteEndPoint; } } #pragma warning disable 67 public event GenericMessage OnGenericMessage; public event ImprovedInstantMessage OnInstantMessage; public event ChatMessage OnChatFromClient; public event TextureRequest OnRequestTexture; public event RezObject OnRezObject; public event ModifyTerrain OnModifyTerrain; public event BakeTerrain OnBakeTerrain; public event EstateChangeInfo OnEstateChangeInfo; public event SetAppearance OnSetAppearance; public event AvatarNowWearing OnAvatarNowWearing; public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv; public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv; public event UUIDNameRequest OnDetachAttachmentIntoInv; public event ObjectAttach OnObjectAttach; public event ObjectDeselect OnObjectDetach; public event ObjectDrop OnObjectDrop; public event StartAnim OnStartAnim; public event StopAnim OnStopAnim; public event LinkObjects OnLinkObjects; public event DelinkObjects OnDelinkObjects; public event RequestMapBlocks OnRequestMapBlocks; public event RequestMapName OnMapNameRequest; public event TeleportLocationRequest OnTeleportLocationRequest; public event DisconnectUser OnDisconnectUser; public event RequestAvatarProperties OnRequestAvatarProperties; public event SetAlwaysRun OnSetAlwaysRun; public event TeleportLandmarkRequest OnTeleportLandmarkRequest; public event DeRezObject OnDeRezObject; public event Action<IClientAPI> OnRegionHandShakeReply; public event GenericCall1 OnRequestWearables; public event GenericCall1 OnCompleteMovementToRegion; public event UpdateAgent OnPreAgentUpdate; public event UpdateAgent OnAgentUpdate; public event AgentRequestSit OnAgentRequestSit; public event AgentSit OnAgentSit; public event AvatarPickerRequest OnAvatarPickerRequest; public event Action<IClientAPI> OnRequestAvatarsData; public event AddNewPrim OnAddPrim; public event FetchInventory OnAgentDataUpdateRequest; public event TeleportLocationRequest OnSetStartLocationRequest; public event RequestGodlikePowers OnRequestGodlikePowers; public event GodKickUser OnGodKickUser; public event ObjectDuplicate OnObjectDuplicate; public event ObjectDuplicateOnRay OnObjectDuplicateOnRay; public event GrabObject OnGrabObject; public event DeGrabObject OnDeGrabObject; public event MoveObject OnGrabUpdate; public event SpinStart OnSpinStart; public event SpinObject OnSpinUpdate; public event SpinStop OnSpinStop; public event UpdateShape OnUpdatePrimShape; public event ObjectExtraParams OnUpdateExtraParams; public event ObjectRequest OnObjectRequest; public event ObjectSelect OnObjectSelect; public event ObjectDeselect OnObjectDeselect; public event GenericCall7 OnObjectDescription; public event GenericCall7 OnObjectName; public event GenericCall7 OnObjectClickAction; public event GenericCall7 OnObjectMaterial; public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily; public event UpdatePrimFlags OnUpdatePrimFlags; public event UpdatePrimTexture OnUpdatePrimTexture; public event UpdateVector OnUpdatePrimGroupPosition; public event UpdateVector OnUpdatePrimSinglePosition; public event UpdatePrimRotation OnUpdatePrimGroupRotation; public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition; public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; public event UpdateVector OnUpdatePrimScale; public event UpdateVector OnUpdatePrimGroupScale; public event StatusChange OnChildAgentStatus; public event GenericCall2 OnStopMovement; public event Action<UUID> OnRemoveAvatar; public event ObjectPermissions OnObjectPermissions; public event CreateNewInventoryItem OnCreateNewInventoryItem; public event LinkInventoryItem OnLinkInventoryItem; public event CreateInventoryFolder OnCreateNewInventoryFolder; public event UpdateInventoryFolder OnUpdateInventoryFolder; public event MoveInventoryFolder OnMoveInventoryFolder; public event FetchInventoryDescendents OnFetchInventoryDescendents; public event PurgeInventoryDescendents OnPurgeInventoryDescendents; public event FetchInventory OnFetchInventory; public event RequestTaskInventory OnRequestTaskInventory; public event UpdateInventoryItem OnUpdateInventoryItem; public event CopyInventoryItem OnCopyInventoryItem; public event MoveInventoryItem OnMoveInventoryItem; public event RemoveInventoryFolder OnRemoveInventoryFolder; public event RemoveInventoryItem OnRemoveInventoryItem; public event UDPAssetUploadRequest OnAssetUploadRequest; public event XferReceive OnXferReceive; public event RequestXfer OnRequestXfer; public event ConfirmXfer OnConfirmXfer; public event AbortXfer OnAbortXfer; public event RezScript OnRezScript; public event UpdateTaskInventory OnUpdateTaskInventory; public event MoveTaskInventory OnMoveTaskItem; public event RemoveTaskInventory OnRemoveTaskItem; public event RequestAsset OnRequestAsset; public event UUIDNameRequest OnNameFromUUIDRequest; public event ParcelAccessListRequest OnParcelAccessListRequest; public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest; public event ParcelPropertiesRequest OnParcelPropertiesRequest; public event ParcelDivideRequest OnParcelDivideRequest; public event ParcelJoinRequest OnParcelJoinRequest; public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; public event ParcelSelectObjects OnParcelSelectObjects; public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; public event ParcelAbandonRequest OnParcelAbandonRequest; public event ParcelGodForceOwner OnParcelGodForceOwner; public event ParcelReclaim OnParcelReclaim; public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest; public event ParcelDeedToGroup OnParcelDeedToGroup; public event RegionInfoRequest OnRegionInfoRequest; public event EstateCovenantRequest OnEstateCovenantRequest; public event FriendActionDelegate OnApproveFriendRequest; public event FriendActionDelegate OnDenyFriendRequest; public event FriendshipTermination OnTerminateFriendship; public event GrantUserFriendRights OnGrantUserRights; public event MoneyTransferRequest OnMoneyTransferRequest; public event EconomyDataRequest OnEconomyDataRequest; public event MoneyBalanceRequest OnMoneyBalanceRequest; public event UpdateAvatarProperties OnUpdateAvatarProperties; public event ParcelBuy OnParcelBuy; public event RequestPayPrice OnRequestPayPrice; public event ObjectSaleInfo OnObjectSaleInfo; public event ObjectBuy OnObjectBuy; public event BuyObjectInventory OnBuyObjectInventory; public event RequestTerrain OnRequestTerrain; public event RequestTerrain OnUploadTerrain; public event ObjectIncludeInSearch OnObjectIncludeInSearch; public event UUIDNameRequest OnTeleportHomeRequest; public event ScriptAnswer OnScriptAnswer; public event AgentSit OnUndo; public event AgentSit OnRedo; public event LandUndo OnLandUndo; public event ForceReleaseControls OnForceReleaseControls; public event GodLandStatRequest OnLandStatRequest; public event DetailedEstateDataRequest OnDetailedEstateDataRequest; public event SetEstateFlagsRequest OnSetEstateFlagsRequest; public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture; public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture; public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights; public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest; public event SetRegionTerrainSettings OnSetRegionTerrainSettings; public event EstateRestartSimRequest OnEstateRestartSimRequest; public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest; public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest; public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest; public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest; public event EstateDebugRegionRequest OnEstateDebugRegionRequest; public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest; public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest; public event UUIDNameRequest OnUUIDGroupNameRequest; public event RegionHandleRequest OnRegionHandleRequest; public event ParcelInfoRequest OnParcelInfoRequest; public event RequestObjectPropertiesFamily OnObjectGroupRequest; public event ScriptReset OnScriptReset; public event GetScriptRunning OnGetScriptRunning; public event SetScriptRunning OnSetScriptRunning; public event UpdateVector OnAutoPilotGo; public event TerrainUnacked OnUnackedTerrain; public event ActivateGesture OnActivateGesture; public event DeactivateGesture OnDeactivateGesture; public event ObjectOwner OnObjectOwner; public event DirPlacesQuery OnDirPlacesQuery; public event DirFindQuery OnDirFindQuery; public event DirLandQuery OnDirLandQuery; public event DirPopularQuery OnDirPopularQuery; public event DirClassifiedQuery OnDirClassifiedQuery; public event EventInfoRequest OnEventInfoRequest; public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime; public event MapItemRequest OnMapItemRequest; public event OfferCallingCard OnOfferCallingCard; public event AcceptCallingCard OnAcceptCallingCard; public event DeclineCallingCard OnDeclineCallingCard; public event SoundTrigger OnSoundTrigger; public event StartLure OnStartLure; public event TeleportLureRequest OnTeleportLureRequest; public event NetworkStats OnNetworkStatsUpdate; public event ClassifiedInfoRequest OnClassifiedInfoRequest; public event ClassifiedInfoUpdate OnClassifiedInfoUpdate; public event ClassifiedDelete OnClassifiedDelete; public event ClassifiedDelete OnClassifiedGodDelete; public event EventNotificationAddRequest OnEventNotificationAddRequest; public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest; public event EventGodDelete OnEventGodDelete; public event ParcelDwellRequest OnParcelDwellRequest; public event UserInfoRequest OnUserInfoRequest; public event UpdateUserInfo OnUpdateUserInfo; public event RetrieveInstantMessages OnRetrieveInstantMessages; public event PickDelete OnPickDelete; public event PickGodDelete OnPickGodDelete; public event PickInfoUpdate OnPickInfoUpdate; public event AvatarNotesUpdate OnAvatarNotesUpdate; public event MuteListRequest OnMuteListRequest; public event AvatarInterestUpdate OnAvatarInterestUpdate; public event PlacesQuery OnPlacesQuery; public event FindAgentUpdate OnFindAgent; public event TrackAgentUpdate OnTrackAgent; public event NewUserReport OnUserReport; public event SaveStateHandler OnSaveState; public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest; public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest; public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest; public event FreezeUserUpdate OnParcelFreezeUser; public event EjectUserUpdate OnParcelEjectUser; public event ParcelBuyPass OnParcelBuyPass; public event ParcelGodMark OnParcelGodMark; public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest; public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest; public event SimWideDeletesDelegate OnSimWideDeletes; public event SendPostcard OnSendPostcard; public event MuteListEntryUpdate OnUpdateMuteListEntry; public event MuteListEntryRemove OnRemoveMuteListEntry; public event GodlikeMessage onGodlikeMessage; public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate; #pragma warning restore 67 public void SetDebugPacketLevel(int newDebug) { } public void InPacket(object NewPack) { } public void ProcessInPacket(Packet NewPack) { } public void Close() { Disconnect(); } public void Kick(string message) { Disconnect(message); } public void Start() { Scene.AddNewClient(this); // Mimicking LLClientView which gets always set appearance from client. Scene scene = (Scene)Scene; AvatarAppearance appearance; scene.GetAvatarAppearance(this, out appearance); OnSetAppearance(this, appearance.Texture, (byte[])appearance.VisualParams.Clone()); } public void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args) { m_log.Info("[IRCd ClientStack] Completing Handshake to Region"); if (OnRegionHandShakeReply != null) { OnRegionHandShakeReply(this); } if (OnCompleteMovementToRegion != null) { OnCompleteMovementToRegion(this); } } public void Stop() { Disconnect(); } public void SendWearables(AvatarWearable[] wearables, int serial) { } public void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry) { } public void SendStartPingCheck(byte seq) { } public void SendKillObject(ulong regionHandle, uint localID) { } public void SendAnimations(UUID[] animID, int[] seqs, UUID sourceAgentId, UUID[] objectIDs) { } public void SendChatMessage(string message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible) { if (audible > 0 && message.Length > 0) IRC_SendChannelPrivmsg(fromName, message); } private void IRC_SendChannelPrivmsg(string fromName, string message) { SendCommand(":" + fromName.Replace(" ", "") + " PRIVMSG " + IrcRegionName + " :" + message); } public void SendInstantMessage(GridInstantMessage im) { // TODO } public void SendGenericMessage(string method, List<string> message) { } public void SendGenericMessage(string method, List<byte[]> message) { } public void SendLayerData(float[] map) { } public void SendLayerData(int px, int py, float[] map) { } public void SendWindData(Vector2[] windSpeeds) { } public void SendCloudData(float[] cloudCover) { } public void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look) { } public void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint) { } public AgentCircuitData RequestClientInfo() { return new AgentCircuitData(); } public void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL) { } public void SendMapBlock(List<MapBlockData> mapBlocks, uint flag) { } public void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags) { } public void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL) { } public void SendTeleportFailed(string reason) { } public void SendTeleportStart(uint flags) { } public void SendTeleportProgress(uint flags, string message) { } public void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance) { } public void SendPayPrice(UUID objectID, int[] payPrice) { } public void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations) { } public void SendAvatarDataImmediate(ISceneEntity avatar) { } public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { } public void ReprioritizeUpdates() { } public void FlushPrimUpdates() { } public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, int version, bool fetchFolders, bool fetchItems) { } public void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item) { } public void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackId) { } public void SendRemoveInventoryItem(UUID itemID) { } public void SendTakeControls(int controls, bool passToAgent, bool TakeControls) { } public void SendTaskInventory(UUID taskID, short serial, byte[] fileName) { } public void SendBulkUpdateInventory(InventoryNodeBase node) { } public void SendXferPacket(ulong xferID, uint packet, byte[] data) { } public void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent) { } public void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data) { } public void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle) { } public void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID) { } public void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain, byte flags) { } public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain) { } public void SendAttachedSoundGainChange(UUID objectID, float gain) { } public void SendNameReply(UUID profileId, string firstname, string lastname) { } public void SendAlertMessage(string message) { IRC_SendChannelPrivmsg("Alert",message); } public void SendAgentAlertMessage(string message, bool modal) { } public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) { IRC_SendChannelPrivmsg(objectname,url); } public void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels) { } public bool AddMoney(int debit) { return true; } public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear, float OrbitalPosition) { } public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks) { } public void SendViewerTime(int phase) { } public UUID GetDefaultAnimation(string name) { return UUID.Zero; } public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, byte[] charterMember, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID) { } public void SendScriptQuestion(UUID taskID, string taskName, string ownerName, UUID itemID, int question) { } public void SendHealth(float health) { } public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID) { } public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID) { } public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args) { } public void SendEstateCovenantInformation(UUID covenant) { } public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner) { } public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags) { } public void SendLandAccessListData(List<UUID> avatars, uint accessFlag, int localLandID) { } public void SendForceClientSelectObjects(List<uint> objectIDs) { } public void SendCameraConstraint(Vector4 ConstraintPlane) { } public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount) { } public void SendLandParcelOverlay(byte[] data, int sequence_id) { } public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time) { } public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop) { } public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID) { } public void SendConfirmXfer(ulong xferID, uint PacketID) { } public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName) { } public void SendInitiateDownload(string simFileName, string clientFileName) { } public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec) { } public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData) { } public void SendImageNotFound(UUID imageid) { } public void SendShutdownConnectionNotice() { // TODO } public void SendSimStats(SimStats stats) { } public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, UUID LastOwnerID, string ObjectName, string Description) { } public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, byte saleType, int salePrice) { } public void SendAgentOffline(UUID[] agentIDs) { } public void SendAgentOnline(UUID[] agentIDs) { } public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot, Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook) { } public void SendAdminResponse(UUID Token, uint AdminLevel) { } public void SendGroupMembership(GroupMembershipData[] GroupMembership) { } public void SendGroupNameReply(UUID groupLLUID, string GroupName) { } public void SendJoinGroupReply(UUID groupID, bool success) { } public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool success) { } public void SendLeaveGroupReply(UUID groupID, bool success) { } public void SendCreateGroupReply(UUID groupID, bool success, string message) { } public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia) { } public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running) { } public void SendAsset(AssetRequestToClient req) { } public void SendTexture(AssetBase TextureAsset) { } public virtual void SetChildAgentThrottle(byte[] throttle) { } public byte[] GetThrottlesPacked(float multiplier) { return new byte[0]; } public event ViewerEffectEventHandler OnViewerEffect; public event Action<IClientAPI> OnLogout; public event Action<IClientAPI> OnConnectionClosed; public void SendBlueBoxMessage(UUID FromAvatarID, string FromAvatarName, string Message) { IRC_SendChannelPrivmsg(FromAvatarName, Message); } public void SendLogoutPacket() { Disconnect(); } public EndPoint GetClientEP() { return null; } public ClientInfo GetClientInfo() { return new ClientInfo(); } public void SetClientInfo(ClientInfo info) { } public void SetClientOption(string option, string value) { } public string GetClientOption(string option) { return String.Empty; } public void Terminate() { Disconnect(); } public void SendSetFollowCamProperties(UUID objectID, SortedDictionary<int, float> parameters) { } public void SendClearFollowCamProperties(UUID objectID) { } public void SendRegionHandle(UUID regoinID, ulong handle) { } public void SendParcelInfo(RegionInfo info, LandData land, UUID parcelID, uint x, uint y) { } public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt) { } public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data) { } public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data) { } public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data) { } public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data) { } public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data) { } public void SendDirLandReply(UUID queryID, DirLandReplyData[] data) { } public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data) { } public void SendEventInfoReply(EventData info) { } public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags) { } public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data) { } public void SendOfferCallingCard(UUID srcID, UUID transactionID) { } public void SendAcceptCallingCard(UUID transactionID) { } public void SendDeclineCallingCard(UUID transactionID) { } public void SendTerminateFriend(UUID exFriendID) { } public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name) { } public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price) { } public void SendAgentDropGroup(UUID groupID) { } public void RefreshGroupMembership() { } public void SendAvatarNotesReply(UUID targetID, string text) { } public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks) { } public void SendPickInfoReply(UUID pickID, UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled) { } public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds) { } public void SendAvatarInterestUpdate(IClientAPI client, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages) { } public void SendParcelDwellReply(int localID, UUID parcelID, float dwell) { } public void SendUserInfoReply(bool imViaEmail, bool visible, string email) { } public void SendUseCachedMuteList() { } public void SendMuteListUpdate(string filename) { } public void KillEndDone() { } public bool AddGenericPacketHandler(string MethodName, GenericMessage handler) { return true; } #endregion #region Implementation of IClientIPEndpoint public IPAddress EndPoint { get { return ((IPEndPoint) m_client.Client.RemoteEndPoint).Address; } } #endregion public void SendRebakeAvatarTextures(UUID textureID) { } public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages) { } public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt) { } public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier) { } public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt) { } public void SendGroupVoteHistory(UUID groupID, UUID transactionID, GroupVoteHistory[] Votes) { } public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals) { } public void SendChangeUserRights(UUID agentID, UUID friendID, int rights) { } public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId) { } public void StopFlying(ISceneEntity presence) { } public void SendVoxelUpdate(int x, int y, int z, byte b) { } public void SendChunkUpdate(int x, int y, int z) { } } }
{ "content_hash": "98aae527aa564843d1d0538365751071", "timestamp": "", "source": "github", "line_count": 1668, "max_line_length": 435, "avg_line_length": 32.4916067146283, "alnum_prop": 0.577385784928777, "repo_name": "N3X15/VoxelSim", "id": "d56507b73b6cf4baa8276d1191cd16290fa83e3a", "size": "55813", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1777621" }, { "name": "C#", "bytes": "27073441" }, { "name": "C++", "bytes": "3294031" }, { "name": "JavaScript", "bytes": "556" }, { "name": "Lua", "bytes": "21421" }, { "name": "PHP", "bytes": "1640" }, { "name": "Perl", "bytes": "3578" }, { "name": "Python", "bytes": "6919" }, { "name": "Shell", "bytes": "252239" } ], "symlink_target": "" }
package org.sanelib.ils.core.dao.read.admin.mapper; import org.sanelib.ils.core.dao.read.DataResultSet; import org.sanelib.ils.core.dao.read.ViewMapper; import org.sanelib.ils.core.domain.view.admin.PatronCategoryView; import org.springframework.stereotype.Component; import java.sql.SQLException; import java.util.Objects; @Component public class PatronCategoryMapper implements ViewMapper<PatronCategoryView> { public PatronCategoryView map(final DataResultSet rs) throws SQLException { final String viewName = "patron_category"; final PatronCategoryView patronCategoryView = new PatronCategoryView(); patronCategoryView.setLibraryId(rs.getInt(viewName, "library_id")); patronCategoryView.setId(rs.getInt(viewName, "patron_category_id")); patronCategoryView.setName(rs.getString(viewName, "patron_category_name")); patronCategoryView.setAllowILLFromNet(Objects.equals(rs.getString(viewName, "ill_thru_net"), "Y")); patronCategoryView.setAllowRenewalFromNet(Objects.equals(rs.getString(viewName, "renewal_thru_net"), "Y")); patronCategoryView.setAllowMultipleCopies(Objects.equals(rs.getString(viewName, "allow_multiple_copies"), "Y")); patronCategoryView.setOverallLoanLimit(rs.getInt(viewName, "overall_loan_limit")); patronCategoryView.setAcqWorkflow(rs.getString(viewName, "acq_workflow")); return patronCategoryView; } }
{ "content_hash": "ec814f6388fca5ed21612c1c9a7d3672", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 120, "avg_line_length": 44.75, "alnum_prop": 0.763268156424581, "repo_name": "sanelib/springils", "id": "a8f2036f73c13fbe7aef8a91a6417cf0c5366270", "size": "1432", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "core/src/main/java/org/sanelib/ils/core/dao/read/admin/mapper/PatronCategoryMapper.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "700946" } ], "symlink_target": "" }
package com.amazonaws.services.elasticbeanstalk.model.transform; import java.util.ArrayList; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.elasticbeanstalk.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * SolutionStackDescription StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class SolutionStackDescriptionStaxUnmarshaller implements Unmarshaller<SolutionStackDescription, StaxUnmarshallerContext> { public SolutionStackDescription unmarshall(StaxUnmarshallerContext context) throws Exception { SolutionStackDescription solutionStackDescription = new SolutionStackDescription(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return solutionStackDescription; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("SolutionStackName", targetDepth)) { solutionStackDescription.setSolutionStackName(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("PermittedFileTypes", targetDepth)) { solutionStackDescription.withPermittedFileTypes(new ArrayList<String>()); continue; } if (context.testExpression("PermittedFileTypes/member", targetDepth)) { solutionStackDescription.withPermittedFileTypes(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return solutionStackDescription; } } } } private static SolutionStackDescriptionStaxUnmarshaller instance; public static SolutionStackDescriptionStaxUnmarshaller getInstance() { if (instance == null) instance = new SolutionStackDescriptionStaxUnmarshaller(); return instance; } }
{ "content_hash": "3e1b2f8692af0a09a0e70da60e2b9842", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 130, "avg_line_length": 37.014925373134325, "alnum_prop": 0.675, "repo_name": "aws/aws-sdk-java", "id": "8e2f7a7ec7a9eba48c6385b0b612d126984dc640", "size": "3060", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-elasticbeanstalk/src/main/java/com/amazonaws/services/elasticbeanstalk/model/transform/SolutionStackDescriptionStaxUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import { PluginObject } from 'vue'; import { Component } from 'vue-property-decorator'; import { ModulVue } from '../../utils/vue/vue'; import { SORTABLE_NAME } from '../directive-names'; import SortablePlugin, { MSortEvent } from './sortable'; import WithRender from './sortable.sandbox.html?style=./sortable.scss'; export type ElementSortable = { cle: number, titre: string }; @WithRender @Component export class MSortableSandbox extends ModulVue { peutEtreDrag: boolean = false; element1: ElementSortable = { cle: 1, titre: 'Element 1' }; element2: ElementSortable = { cle: 2, titre: 'Element 2' }; element3: ElementSortable = { cle: 3, titre: 'Element 3' }; element4: ElementSortable = { cle: 4, titre: 'Element 4' }; element5: ElementSortable = { cle: 5, titre: 'Element 5' }; element6: ElementSortable = { cle: 6, titre: 'Element 6 - draggable false' }; elementsWithHandleNoAttribut: Array<ElementSortable> = [this.element1, this.element2, this.element3, this.element4, this.element5]; elementsWithHandleWithAttribut: Array<ElementSortable> = [this.element1, this.element2, this.element3, this.element4, this.element5, this.element6]; elementsWithHandle: Array<ElementSortable> = [this.element1, this.element2, this.element3, this.element4, this.element5, this.element6]; elementsWithoutHandle: Array<ElementSortable> = [this.element1, this.element2, this.element3, this.element4, this.element5, this.element6]; get elementsSortableWithHandleNoAttribut(): ElementSortable[] { return this.elementsWithHandleNoAttribut; } get elementsSortableWithHandleWithAttribut(): ElementSortable[] { return this.elementsWithHandleWithAttribut; } get elementsSortableWithHandle(): ElementSortable[] { return this.elementsWithHandle; } get elementsSortableWithoutHandle(): ElementSortable[] { return this.elementsWithoutHandle; } isDraggable(cle: number): string { return cle === 6 ? 'false' : 'true'; } deplacerElementsWithHandleNoAttribut(event: MSortEvent): void { this.arraymove(this.elementsWithHandleNoAttribut, event.sortInfo.oldPosition, event.sortInfo.newPosition); } deplacerElementsWithHandleWithAttribut(event: MSortEvent): void { this.arraymove(this.elementsWithHandleWithAttribut, event.sortInfo.oldPosition, event.sortInfo.newPosition); } deplacerElementsWithHandle(event: MSortEvent): void { this.arraymove(this.elementsWithHandle, event.sortInfo.oldPosition, event.sortInfo.newPosition); } deplacerElementsWithoutHandle(event: MSortEvent): void { this.arraymove(this.elementsWithoutHandle, event.sortInfo.oldPosition, event.sortInfo.newPosition); } arraymove(arr, oldIndex, newIndex): void { let elements: Array<ElementSortable> = arr[oldIndex]; arr.splice(oldIndex, 1); arr.splice(newIndex, 0, elements); } basculePeutEtreDrag(valeur: boolean): void { this.peutEtreDrag = valeur; } } const SortableSandboxPlugin: PluginObject<any> = { install(v, options): void { v.use(SortablePlugin); v.component(`${SORTABLE_NAME}-sandbox`, MSortableSandbox); } }; export default SortableSandboxPlugin;
{ "content_hash": "84912680d1c5fa4c340e9276ee0fe346", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 152, "avg_line_length": 39.926829268292686, "alnum_prop": 0.7153329260843005, "repo_name": "ulaval/modul-components", "id": "2d9d292587916ecce7249289b4fafd02f3bcdcf5", "size": "3274", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/directives/sortable/sortable.sandbox.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3055" }, { "name": "CSS", "bytes": "273104" }, { "name": "Groovy", "bytes": "2030" }, { "name": "HTML", "bytes": "460968" }, { "name": "JavaScript", "bytes": "21149" }, { "name": "TypeScript", "bytes": "2028431" } ], "symlink_target": "" }
using namespace clang; namespace { /// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps /// into VLA and other protected scopes. For example, this rejects: /// goto L; /// int a[n]; /// L: /// class JumpScopeChecker { Sema &S; /// Permissive - True when recovering from errors, in which case precautions /// are taken to handle incomplete scope information. const bool Permissive; /// GotoScope - This is a record that we use to keep track of all of the /// scopes that are introduced by VLAs and other things that scope jumps like /// gotos. This scope tree has nothing to do with the source scope tree, /// because you can have multiple VLA scopes per compound statement, and most /// compound statements don't introduce any scopes. struct GotoScope { /// ParentScope - The index in ScopeMap of the parent scope. This is 0 for /// the parent scope is the function body. unsigned ParentScope; /// InDiag - The note to emit if there is a jump into this scope. unsigned InDiag; /// OutDiag - The note to emit if there is an indirect jump out /// of this scope. Direct jumps always clean up their current scope /// in an orderly way. unsigned OutDiag; /// Loc - Location to emit the diagnostic. SourceLocation Loc; GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag, SourceLocation L) : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {} }; SmallVector<GotoScope, 48> Scopes; llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes; SmallVector<Stmt*, 16> Jumps; SmallVector<IndirectGotoStmt*, 4> IndirectJumps; SmallVector<LabelDecl*, 4> IndirectJumpTargets; public: JumpScopeChecker(Stmt *Body, Sema &S); private: void BuildScopeInformation(Decl *D, unsigned &ParentScope); void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl, unsigned &ParentScope); void BuildScopeInformation(Stmt *S, unsigned &origParentScope); void VerifyJumps(); void VerifyIndirectJumps(); void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes); void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope, LabelDecl *Target, unsigned TargetScope); void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc, unsigned JumpDiag, unsigned JumpDiagWarning, unsigned JumpDiagCXX98Compat); void CheckGotoStmt(GotoStmt *GS); unsigned GetDeepestCommonScope(unsigned A, unsigned B); }; } // end anonymous namespace #define CHECK_PERMISSIVE(x) (assert(Permissive || !(x)), (Permissive && (x))) JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s), Permissive(s.hasAnyUnrecoverableErrorsInThisFunction()) { // Add a scope entry for function scope. Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation())); // Build information for the top level compound statement, so that we have a // defined scope record for every "goto" and label. unsigned BodyParentScope = 0; BuildScopeInformation(Body, BodyParentScope); // Check that all jumps we saw are kosher. VerifyJumps(); VerifyIndirectJumps(); } /// GetDeepestCommonScope - Finds the innermost scope enclosing the /// two scopes. unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) { while (A != B) { // Inner scopes are created after outer scopes and therefore have // higher indices. if (A < B) { assert(Scopes[B].ParentScope < B); B = Scopes[B].ParentScope; } else { assert(Scopes[A].ParentScope < A); A = Scopes[A].ParentScope; } } return A; } typedef std::pair<unsigned,unsigned> ScopePair; /// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a /// diagnostic that should be emitted if control goes over it. If not, return 0. static ScopePair GetDiagForGotoScopeDecl(Sema &S, const Decl *D) { if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { unsigned InDiag = 0; unsigned OutDiag = 0; if (VD->getType()->isVariablyModifiedType()) InDiag = diag::note_protected_by_vla; if (VD->hasAttr<BlocksAttr>()) return ScopePair(diag::note_protected_by___block, diag::note_exits___block); if (VD->hasAttr<CleanupAttr>()) return ScopePair(diag::note_protected_by_cleanup, diag::note_exits_cleanup); if (VD->hasLocalStorage()) { switch (VD->getType().isDestructedType()) { case QualType::DK_objc_strong_lifetime: case QualType::DK_objc_weak_lifetime: return ScopePair(diag::note_protected_by_objc_ownership, diag::note_exits_objc_ownership); case QualType::DK_cxx_destructor: OutDiag = diag::note_exits_dtor; break; case QualType::DK_none: break; } } const Expr *Init = VD->getInit(); if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) { // C++11 [stmt.dcl]p3: // A program that jumps from a point where a variable with automatic // storage duration is not in scope to a point where it is in scope // is ill-formed unless the variable has scalar type, class type with // a trivial default constructor and a trivial destructor, a // cv-qualified version of one of these types, or an array of one of // the preceding types and is declared without an initializer. // C++03 [stmt.dcl.p3: // A program that jumps from a point where a local variable // with automatic storage duration is not in scope to a point // where it is in scope is ill-formed unless the variable has // POD type and is declared without an initializer. InDiag = diag::note_protected_by_variable_init; // For a variable of (array of) class type declared without an // initializer, we will have call-style initialization and the initializer // will be the CXXConstructExpr with no intervening nodes. if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { const CXXConstructorDecl *Ctor = CCE->getConstructor(); if (Ctor->isTrivial() && Ctor->isDefaultConstructor() && VD->getInitStyle() == VarDecl::CallInit) { if (OutDiag) InDiag = diag::note_protected_by_variable_nontriv_destructor; else if (!Ctor->getParent()->isPOD()) InDiag = diag::note_protected_by_variable_non_pod; else InDiag = 0; } } } return ScopePair(InDiag, OutDiag); } if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { if (TD->getUnderlyingType()->isVariablyModifiedType()) return ScopePair(isa<TypedefDecl>(TD) ? diag::note_protected_by_vla_typedef : diag::note_protected_by_vla_type_alias, 0); } return ScopePair(0U, 0U); } /// \brief Build scope information for a declaration that is part of a DeclStmt. void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) { // If this decl causes a new scope, push and switch to it. std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S, D); if (Diags.first || Diags.second) { Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second, D->getLocation())); ParentScope = Scopes.size()-1; } // If the decl has an initializer, walk it with the potentially new // scope we just installed. if (VarDecl *VD = dyn_cast<VarDecl>(D)) if (Expr *Init = VD->getInit()) BuildScopeInformation(Init, ParentScope); } /// \brief Build scope information for a captured block literal variables. void JumpScopeChecker::BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl, unsigned &ParentScope) { // exclude captured __block variables; there's no destructor // associated with the block literal for them. if (D->hasAttr<BlocksAttr>()) return; QualType T = D->getType(); QualType::DestructionKind destructKind = T.isDestructedType(); if (destructKind != QualType::DK_none) { std::pair<unsigned,unsigned> Diags; switch (destructKind) { case QualType::DK_cxx_destructor: Diags = ScopePair(diag::note_enters_block_captures_cxx_obj, diag::note_exits_block_captures_cxx_obj); break; case QualType::DK_objc_strong_lifetime: Diags = ScopePair(diag::note_enters_block_captures_strong, diag::note_exits_block_captures_strong); break; case QualType::DK_objc_weak_lifetime: Diags = ScopePair(diag::note_enters_block_captures_weak, diag::note_exits_block_captures_weak); break; case QualType::DK_none: llvm_unreachable("non-lifetime captured variable"); } SourceLocation Loc = D->getLocation(); if (Loc.isInvalid()) Loc = BDecl->getLocation(); Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second, Loc)); ParentScope = Scopes.size()-1; } } /// BuildScopeInformation - The statements from CI to CE are known to form a /// coherent VLA scope with a specified parent node. Walk through the /// statements, adding any labels or gotos to LabelAndGotoScopes and recursively /// walking the AST as needed. void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned &origParentScope) { // If this is a statement, rather than an expression, scopes within it don't // propagate out into the enclosing scope. Otherwise we have to worry // about block literals, which have the lifetime of their enclosing statement. unsigned independentParentScope = origParentScope; unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S)) ? origParentScope : independentParentScope); bool SkipFirstSubStmt = false; // If we found a label, remember that it is in ParentScope scope. switch (S->getStmtClass()) { case Stmt::AddrLabelExprClass: IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel()); break; case Stmt::IndirectGotoStmtClass: // "goto *&&lbl;" is a special case which we treat as equivalent // to a normal goto. In addition, we don't calculate scope in the // operand (to avoid recording the address-of-label use), which // works only because of the restricted set of expressions which // we detect as constant targets. if (cast<IndirectGotoStmt>(S)->getConstantTarget()) { LabelAndGotoScopes[S] = ParentScope; Jumps.push_back(S); return; } LabelAndGotoScopes[S] = ParentScope; IndirectJumps.push_back(cast<IndirectGotoStmt>(S)); break; case Stmt::SwitchStmtClass: // Evaluate the condition variable before entering the scope of the switch // statement. if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) { BuildScopeInformation(Var, ParentScope); SkipFirstSubStmt = true; } // Fall through case Stmt::GotoStmtClass: // Remember both what scope a goto is in as well as the fact that we have // it. This makes the second scan not have to walk the AST again. LabelAndGotoScopes[S] = ParentScope; Jumps.push_back(S); break; case Stmt::CXXTryStmtClass: { CXXTryStmt *TS = cast<CXXTryStmt>(S); unsigned newParentScope; Scopes.push_back(GotoScope(ParentScope, diag::note_protected_by_cxx_try, diag::note_exits_cxx_try, TS->getSourceRange().getBegin())); if (Stmt *TryBlock = TS->getTryBlock()) BuildScopeInformation(TryBlock, (newParentScope = Scopes.size()-1)); // Jump from the catch into the try is not allowed either. for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) { CXXCatchStmt *CS = TS->getHandler(I); Scopes.push_back(GotoScope(ParentScope, diag::note_protected_by_cxx_catch, diag::note_exits_cxx_catch, CS->getSourceRange().getBegin())); BuildScopeInformation(CS->getHandlerBlock(), (newParentScope = Scopes.size()-1)); } return; } default: break; } for (Stmt::child_range CI = S->children(); CI; ++CI) { if (SkipFirstSubStmt) { SkipFirstSubStmt = false; continue; } Stmt *SubStmt = *CI; if (!SubStmt) continue; // Cases, labels, and defaults aren't "scope parents". It's also // important to handle these iteratively instead of recursively in // order to avoid blowing out the stack. while (true) { Stmt *Next; if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt)) Next = CS->getSubStmt(); else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt)) Next = DS->getSubStmt(); else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt)) Next = LS->getSubStmt(); else break; LabelAndGotoScopes[SubStmt] = ParentScope; SubStmt = Next; } // If this is a declstmt with a VLA definition, it defines a scope from here // to the end of the containing context. if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) { // The decl statement creates a scope if any of the decls in it are VLAs // or have the cleanup attribute. for (auto *I : DS->decls()) BuildScopeInformation(I, ParentScope); continue; } // Disallow jumps into any part of an @try statement by pushing a scope and // walking all sub-stmts in that scope. if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) { unsigned newParentScope; // Recursively walk the AST for the @try part. Scopes.push_back(GotoScope(ParentScope, diag::note_protected_by_objc_try, diag::note_exits_objc_try, AT->getAtTryLoc())); if (Stmt *TryPart = AT->getTryBody()) BuildScopeInformation(TryPart, (newParentScope = Scopes.size()-1)); // Jump from the catch to the finally or try is not valid. for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) { ObjCAtCatchStmt *AC = AT->getCatchStmt(I); Scopes.push_back(GotoScope(ParentScope, diag::note_protected_by_objc_catch, diag::note_exits_objc_catch, AC->getAtCatchLoc())); // @catches are nested and it isn't BuildScopeInformation(AC->getCatchBody(), (newParentScope = Scopes.size()-1)); } // Jump from the finally to the try or catch is not valid. if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) { Scopes.push_back(GotoScope(ParentScope, diag::note_protected_by_objc_finally, diag::note_exits_objc_finally, AF->getAtFinallyLoc())); BuildScopeInformation(AF, (newParentScope = Scopes.size()-1)); } continue; } unsigned newParentScope; // Disallow jumps into the protected statement of an @synchronized, but // allow jumps into the object expression it protects. if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){ // Recursively walk the AST for the @synchronized object expr, it is // evaluated in the normal scope. BuildScopeInformation(AS->getSynchExpr(), ParentScope); // Recursively walk the AST for the @synchronized part, protected by a new // scope. Scopes.push_back(GotoScope(ParentScope, diag::note_protected_by_objc_synchronized, diag::note_exits_objc_synchronized, AS->getAtSynchronizedLoc())); BuildScopeInformation(AS->getSynchBody(), (newParentScope = Scopes.size()-1)); continue; } // Disallow jumps into the protected statement of an @autoreleasepool. if (ObjCAutoreleasePoolStmt *AS = dyn_cast<ObjCAutoreleasePoolStmt>(SubStmt)){ // Recursively walk the AST for the @autoreleasepool part, protected by a new // scope. Scopes.push_back(GotoScope(ParentScope, diag::note_protected_by_objc_autoreleasepool, diag::note_exits_objc_autoreleasepool, AS->getAtLoc())); BuildScopeInformation(AS->getSubStmt(), (newParentScope = Scopes.size()-1)); continue; } // Disallow jumps past full-expressions that use blocks with // non-trivial cleanups of their captures. This is theoretically // implementable but a lot of work which we haven't felt up to doing. if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(SubStmt)) { for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) { const BlockDecl *BDecl = EWC->getObject(i); for (const auto &CI : BDecl->captures()) { VarDecl *variable = CI.getVariable(); BuildScopeInformation(variable, BDecl, ParentScope); } } } // Disallow jumps out of scopes containing temporaries lifetime-extended to // automatic storage duration. if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(SubStmt)) { if (MTE->getStorageDuration() == SD_Automatic) { SmallVector<const Expr *, 4> CommaLHS; SmallVector<SubobjectAdjustment, 4> Adjustments; const Expr *ExtendedObject = MTE->GetTemporaryExpr()->skipRValueSubobjectAdjustments( CommaLHS, Adjustments); if (ExtendedObject->getType().isDestructedType()) { Scopes.push_back(GotoScope(ParentScope, 0, diag::note_exits_temporary_dtor, ExtendedObject->getExprLoc())); ParentScope = Scopes.size()-1; } } } // Recursively walk the AST. BuildScopeInformation(SubStmt, ParentScope); } } /// VerifyJumps - Verify each element of the Jumps array to see if they are /// valid, emitting diagnostics if not. void JumpScopeChecker::VerifyJumps() { while (!Jumps.empty()) { Stmt *Jump = Jumps.pop_back_val(); // With a goto, if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) { // The label may not have a statement if it's coming from inline MS ASM. if (GS->getLabel()->getStmt()) { CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(), diag::err_goto_into_protected_scope, diag::ext_goto_into_protected_scope, diag::warn_cxx98_compat_goto_into_protected_scope); } CheckGotoStmt(GS); continue; } // We only get indirect gotos here when they have a constant target. if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) { LabelDecl *Target = IGS->getConstantTarget(); CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(), diag::err_goto_into_protected_scope, diag::ext_goto_into_protected_scope, diag::warn_cxx98_compat_goto_into_protected_scope); continue; } SwitchStmt *SS = cast<SwitchStmt>(Jump); for (SwitchCase *SC = SS->getSwitchCaseList(); SC; SC = SC->getNextSwitchCase()) { if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC))) continue; SourceLocation Loc; if (CaseStmt *CS = dyn_cast<CaseStmt>(SC)) Loc = CS->getLocStart(); else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) Loc = DS->getLocStart(); else Loc = SC->getLocStart(); CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0, diag::warn_cxx98_compat_switch_into_protected_scope); } } } /// VerifyIndirectJumps - Verify whether any possible indirect jump /// might cross a protection boundary. Unlike direct jumps, indirect /// jumps count cleanups as protection boundaries: since there's no /// way to know where the jump is going, we can't implicitly run the /// right cleanups the way we can with direct jumps. /// /// Thus, an indirect jump is "trivial" if it bypasses no /// initializations and no teardowns. More formally, an indirect jump /// from A to B is trivial if the path out from A to DCA(A,B) is /// trivial and the path in from DCA(A,B) to B is trivial, where /// DCA(A,B) is the deepest common ancestor of A and B. /// Jump-triviality is transitive but asymmetric. /// /// A path in is trivial if none of the entered scopes have an InDiag. /// A path out is trivial is none of the exited scopes have an OutDiag. /// /// Under these definitions, this function checks that the indirect /// jump between A and B is trivial for every indirect goto statement A /// and every label B whose address was taken in the function. void JumpScopeChecker::VerifyIndirectJumps() { if (IndirectJumps.empty()) return; // If there aren't any address-of-label expressions in this function, // complain about the first indirect goto. if (IndirectJumpTargets.empty()) { S.Diag(IndirectJumps[0]->getGotoLoc(), diag::err_indirect_goto_without_addrlabel); return; } // Collect a single representative of every scope containing an // indirect goto. For most code bases, this substantially cuts // down on the number of jump sites we'll have to consider later. typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope; SmallVector<JumpScope, 32> JumpScopes; { llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap; for (SmallVectorImpl<IndirectGotoStmt*>::iterator I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) { IndirectGotoStmt *IG = *I; if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG))) continue; unsigned IGScope = LabelAndGotoScopes[IG]; IndirectGotoStmt *&Entry = JumpScopesMap[IGScope]; if (!Entry) Entry = IG; } JumpScopes.reserve(JumpScopesMap.size()); for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I) JumpScopes.push_back(*I); } // Collect a single representative of every scope containing a // label whose address was taken somewhere in the function. // For most code bases, there will be only one such scope. llvm::DenseMap<unsigned, LabelDecl*> TargetScopes; for (SmallVectorImpl<LabelDecl*>::iterator I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end(); I != E; ++I) { LabelDecl *TheLabel = *I; if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt()))) continue; unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()]; LabelDecl *&Target = TargetScopes[LabelScope]; if (!Target) Target = TheLabel; } // For each target scope, make sure it's trivially reachable from // every scope containing a jump site. // // A path between scopes always consists of exitting zero or more // scopes, then entering zero or more scopes. We build a set of // of scopes S from which the target scope can be trivially // entered, then verify that every jump scope can be trivially // exitted to reach a scope in S. llvm::BitVector Reachable(Scopes.size(), false); for (llvm::DenseMap<unsigned,LabelDecl*>::iterator TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) { unsigned TargetScope = TI->first; LabelDecl *TargetLabel = TI->second; Reachable.reset(); // Mark all the enclosing scopes from which you can safely jump // into the target scope. 'Min' will end up being the index of // the shallowest such scope. unsigned Min = TargetScope; while (true) { Reachable.set(Min); // Don't go beyond the outermost scope. if (Min == 0) break; // Stop if we can't trivially enter the current scope. if (Scopes[Min].InDiag) break; Min = Scopes[Min].ParentScope; } // Walk through all the jump sites, checking that they can trivially // reach this label scope. for (SmallVectorImpl<JumpScope>::iterator I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) { unsigned Scope = I->first; // Walk out the "scope chain" for this scope, looking for a scope // we've marked reachable. For well-formed code this amortizes // to O(JumpScopes.size() / Scopes.size()): we only iterate // when we see something unmarked, and in well-formed code we // mark everything we iterate past. bool IsReachable = false; while (true) { if (Reachable.test(Scope)) { // If we find something reachable, mark all the scopes we just // walked through as reachable. for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope) Reachable.set(S); IsReachable = true; break; } // Don't walk out if we've reached the top-level scope or we've // gotten shallower than the shallowest reachable scope. if (Scope == 0 || Scope < Min) break; // Don't walk out through an out-diagnostic. if (Scopes[Scope].OutDiag) break; Scope = Scopes[Scope].ParentScope; } // Only diagnose if we didn't find something. if (IsReachable) continue; DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope); } } } /// Return true if a particular error+note combination must be downgraded to a /// warning in Microsoft mode. static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) { return (JumpDiag == diag::err_goto_into_protected_scope && (InDiagNote == diag::note_protected_by_variable_init || InDiagNote == diag::note_protected_by_variable_nontriv_destructor)); } /// Return true if a particular note should be downgraded to a compatibility /// warning in C++11 mode. static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) { return S.getLangOpts().CPlusPlus11 && InDiagNote == diag::note_protected_by_variable_non_pod; } /// Produce primary diagnostic for an indirect jump statement. static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump, LabelDecl *Target, bool &Diagnosed) { if (Diagnosed) return; S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope); S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target); Diagnosed = true; } /// Produce note diagnostics for a jump into a protected scope. void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) { if (CHECK_PERMISSIVE(ToScopes.empty())) return; for (unsigned I = 0, E = ToScopes.size(); I != E; ++I) if (Scopes[ToScopes[I]].InDiag) S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag); } /// Diagnose an indirect jump which is known to cross scopes. void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump, unsigned JumpScope, LabelDecl *Target, unsigned TargetScope) { if (CHECK_PERMISSIVE(JumpScope == TargetScope)) return; unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope); bool Diagnosed = false; // Walk out the scope chain until we reach the common ancestor. for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope) if (Scopes[I].OutDiag) { DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed); S.Diag(Scopes[I].Loc, Scopes[I].OutDiag); } SmallVector<unsigned, 10> ToScopesCXX98Compat; // Now walk into the scopes containing the label whose address was taken. for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope) if (IsCXX98CompatWarning(S, Scopes[I].InDiag)) ToScopesCXX98Compat.push_back(I); else if (Scopes[I].InDiag) { DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed); S.Diag(Scopes[I].Loc, Scopes[I].InDiag); } // Diagnose this jump if it would be ill-formed in C++98. if (!Diagnosed && !ToScopesCXX98Compat.empty()) { S.Diag(Jump->getGotoLoc(), diag::warn_cxx98_compat_indirect_goto_in_protected_scope); S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target); NoteJumpIntoScopes(ToScopesCXX98Compat); } } /// CheckJump - Validate that the specified jump statement is valid: that it is /// jumping within or out of its current scope, not into a deeper one. void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc, unsigned JumpDiagError, unsigned JumpDiagWarning, unsigned JumpDiagCXX98Compat) { if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From))) return; if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To))) return; unsigned FromScope = LabelAndGotoScopes[From]; unsigned ToScope = LabelAndGotoScopes[To]; // Common case: exactly the same scope, which is fine. if (FromScope == ToScope) return; unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope); // It's okay to jump out from a nested scope. if (CommonScope == ToScope) return; // Pull out (and reverse) any scopes we might need to diagnose skipping. SmallVector<unsigned, 10> ToScopesCXX98Compat; SmallVector<unsigned, 10> ToScopesError; SmallVector<unsigned, 10> ToScopesWarning; for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) { if (S.getLangOpts().MSVCCompat && JumpDiagWarning != 0 && IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag)) ToScopesWarning.push_back(I); else if (IsCXX98CompatWarning(S, Scopes[I].InDiag)) ToScopesCXX98Compat.push_back(I); else if (Scopes[I].InDiag) ToScopesError.push_back(I); } // Handle warnings. if (!ToScopesWarning.empty()) { S.Diag(DiagLoc, JumpDiagWarning); NoteJumpIntoScopes(ToScopesWarning); } // Handle errors. if (!ToScopesError.empty()) { S.Diag(DiagLoc, JumpDiagError); NoteJumpIntoScopes(ToScopesError); } // Handle -Wc++98-compat warnings if the jump is well-formed. if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) { S.Diag(DiagLoc, JumpDiagCXX98Compat); NoteJumpIntoScopes(ToScopesCXX98Compat); } } void JumpScopeChecker::CheckGotoStmt(GotoStmt *GS) { if (GS->getLabel()->isMSAsmLabel()) { S.Diag(GS->getGotoLoc(), diag::err_goto_ms_asm_label) << GS->getLabel()->getIdentifier(); S.Diag(GS->getLabel()->getLocation(), diag::note_goto_ms_asm_label) << GS->getLabel()->getIdentifier(); } } void Sema::DiagnoseInvalidJumps(Stmt *Body) { (void)JumpScopeChecker(Body, *this); }
{ "content_hash": "0f47bc020981d6ec181a89655e3c78a8", "timestamp": "", "source": "github", "line_count": 787, "max_line_length": 83, "avg_line_length": 39.67725540025413, "alnum_prop": 0.6442387753794915, "repo_name": "Rapier-Foundation/rapier-script", "id": "fd75c02bb1ed30650a8db0a2be200514659eee5b", "size": "32012", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/rapierlang/lib/Sema/JumpDiagnostics.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "AppleScript", "bytes": "1429" }, { "name": "Assembly", "bytes": "13988" }, { "name": "Batchfile", "bytes": "10286" }, { "name": "C", "bytes": "7566017" }, { "name": "C#", "bytes": "12133" }, { "name": "C++", "bytes": "39435677" }, { "name": "CMake", "bytes": "69644" }, { "name": "CSS", "bytes": "22918" }, { "name": "Cuda", "bytes": "31200" }, { "name": "Emacs Lisp", "bytes": "15377" }, { "name": "FORTRAN", "bytes": "7033" }, { "name": "Groff", "bytes": "9943" }, { "name": "HTML", "bytes": "1148463" }, { "name": "JavaScript", "bytes": "24233" }, { "name": "LLVM", "bytes": "688" }, { "name": "Limbo", "bytes": "755" }, { "name": "M", "bytes": "2529" }, { "name": "Makefile", "bytes": "93929" }, { "name": "Mathematica", "bytes": "5122" }, { "name": "Matlab", "bytes": "40309" }, { "name": "Mercury", "bytes": "1222" }, { "name": "Objective-C", "bytes": "4355070" }, { "name": "Objective-C++", "bytes": "1428214" }, { "name": "Perl", "bytes": "102454" }, { "name": "Python", "bytes": "470720" }, { "name": "Shell", "bytes": "6997" } ], "symlink_target": "" }
/** * MonthSelector pure component. * @flow */ import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { LayoutAnimation, TouchableHighlight, View, Text, StyleSheet, } from 'react-native'; import ViewPropTypes from '../util/ViewPropTypes'; // Component specific libraries. import _ from 'lodash'; import Moment from 'moment'; type Props = { selected?: Moment, // Styling style?: ViewPropTypes.style, // Controls the focus of the calendar. focus: Moment, onFocus?: (date: Moment) => void, // Minimum and maximum valid dates. minDate: Moment, maxDate: Moment, // Styling properties. monthText?: Text.propTypes.style, monthDisabledText?: Text.propTypes.style, selectedText?: Text.propTypes.style, }; type State = { months: Array<Array<Object>>, }; export default class MonthSelector extends Component { props: Props; state: State; static defaultProps: Props; constructor(props: Object) { super(props); const months = Moment.monthsShort(); let groups = []; let group = []; _.map(months, (month, index) => { if (index % 3 === 0) { group = []; groups.push(group); } // Check if the month is valid. let maxChoice = Moment(this.props.focus).month(index).endOf('month'); let minChoice = Moment(this.props.focus).month(index).startOf('month'); group.push({ valid: this.props.maxDate.diff(minChoice, 'seconds') >= 0 && this.props.minDate.diff(maxChoice, 'seconds') <= 0, name: month, index, }); }) this.state = { months: groups, }; } _onFocus = (index : number) : void => { let focus = Moment(this.props.focus); focus.month(index); this.props.onFocus && this.props.onFocus(focus); } render() { return ( <View style={[{ // Wrapper view default style. },this.props.style]}> {_.map(this.state.months, (group, i) => <View key={i} style={[styles.group]}> {_.map(group, (month, j) => <TouchableHighlight key={j} style={{flexGrow: 1}} activeOpacity={1} underlayColor='transparent' onPress={() => month.valid && this._onFocus(month.index)}> <Text style={[ styles.monthText, this.props.monthText, month.valid ? null : styles.disabledText, month.valid ? null : this.props.monthDisabledText, month.index === (this.props.selected && this.props.selected.month()) ? this.props.selectedText : null, ]}> {month.name} </Text> </TouchableHighlight> )} </View> )} </View> ); } } MonthSelector.defaultProps = { focus: Moment(), minDate: Moment(), maxDate: Moment(), }; const styles = StyleSheet.create({ group: { //flexGrow: 1, flexDirection: 'row', }, disabledText: { borderColor: 'grey', color: 'grey', }, monthText: { borderRadius: 5, borderWidth: 1, flexGrow: 1, margin: 5, padding: 10, textAlign: 'center', }, });
{ "content_hash": "e73f21dae589e760a5cca3f0c65ef4ae", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 121, "avg_line_length": 24.778625954198475, "alnum_prop": 0.5625385089340728, "repo_name": "vlad-doru/react-native-calendar-datepicker", "id": "237373ad9693655863c6154e48fd5da5c5dc0833", "size": "3246", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/pure/MonthSelector.react.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "24480" } ], "symlink_target": "" }
\newpage \section{Latex-Details} \subsection{Verwendete Software, Editor und Zusatzpakete} \subsubsection{Windows 8+} \begin{itemize} \item MikTex: 2.9, 32-bit \item Biblatex: 3.5, Zusatz: Biber.exe \item Editor: TexStudio (kann ich empfehlen), Notepad++ \end{itemize} \subsubsection{Mac OSX und iOS} \begin{itemize} \item MacTeX: \url{https://tug.org/mactex} \item Editor: TexPad \url{https://www.texpadapp.com} \end{itemize} \subsubsection{Online} Overleaf ist eine Online-Anwendung mit der Ihr direkt im Browser an eurer Thesis schreiben könnt. Bis 1GB Größe und maximal 60 Einzeldateien könnt ihr Overleaf kostenlos nutzen: \url{https://www.overleaf.com/} \subsection{Dokumentenklasse} Eigentlich hatte Prof. Finke empfohlen die Dokumentklassen \enquote{Book} oder \enquote{Report} für die Erstellung der Bachelor-Thesis zu verwenden, da diese über weitere Gliederungsebenen verfügen. Ich verwende dennoch eine leicht modifizierte Komaskript-Klasse \enquote{scrartcl}, mit der Erweiterung um eine Ebene. Siehe (skripte/weitereEbene.tex). Das Skript stammt irgendwo aus den Netz und übersteigt meine \LaTeX{}-Fähigkeiten. Dadurch kann ich über eine weitere Ebene in der Arbeit verfügen, ohne mich mit der Modifikation von Kapitel-Seiten rumschlagen~\footcite[Vgl. ][Seite 5]{Tanenbaum.2003} zu müssen. Diese Quelle ist nur zur Demonstration und hat keinen inhaltlichen Bezug hierzu. Es werden übrigens nur die Quellen im Literaturverzeichnis angezeigt, die auch referenziert sind. \subsection{Grafiken} Das Paket \textbackslash usepackage\{float\} ermöglicht es die Grafiken und Tabellen an der Stelle im Text zu positionieren, wo diese im Quelltext stehen (Option H). Ansonsten würde \LaTeX{} diese dort unterbringen, wo es typographisch sinnvoll wäre - das wollen wir ja nicht ;-). Die Breite der Grafiken am Besten relativ zum Text angeben. \subsection{Quellcode} Quellcode kann auf unterschiedliche Arten eingebaut werden. Zum einen kann es hier durch direktives Einbinden in der Kapitel-Datei geschehen. \begin{lstlisting} % Hier wird aufgezeigt, wie man eine Grafik einbindet, es wird also in der PDF angezeigt, % da es in einem Quellcode-Listing steht. % Auch wenn es hier faelschlicherweise als LaTeX-Befehl angezeigt wird. \includegraphics[width=0.9\textwidth]{sup} \end{lstlisting} Bei längeren Quellcode-Listings empfiehlt es sich jedoch auf eine externe Datei im Ordner Quellcode zu verlinken und diese einzubauen: \lstinputlisting[language=HTML]{./Quellcode/Beispiel.html} Da der Pfad zu den Abbildungen im Hauptdokument definiert wurde, muss hier nur noch der Name des Bildes ohne Dateiendung stehen (sup). \begin{figure}[H] \begin{center} \includegraphics[width=0.9\textwidth]{sup} \caption{Titel der Abbildung hier} \end{center} \end{figure} \subsection{Tabellen} \begin{table}[H] \centering \begin{tabular}[ht]{|l|l|l|} \hline \textbf{Abkürzung} & \textbf{Beschreibung} & \textbf{Berechnung}\\ \hline\hline MEK & Materialeinzelkosten & \\ MGK & Materialgemeinkosten & $+ \uparrow$~*\\ FEK & Fertigungseinzelkosten & \\ FGK & Fertigungsgemeinkosten & $+ \uparrow$~*\\ SEKF & Sondereinzelkosten der Fertigung & \\ \hline\hline \multicolumn{3}{|l|}{\textbf{= Herstellungskosten}} \\ \hline\hline VwGK & Verwaltungsgemeinkosten & $+ \uparrow$~*\\ VtGK & Vertriebsgemeinkosten & $+ \uparrow$~*\\ SEKVt & Sondereinzelkosten des Vertriebes & \\ \hline\hline \multicolumn{3}{|l|}{\textbf{= Selbstkosten}} \\ \hline\hline \multicolumn{3}{|l|}{+ Gewinnaufschlag} \\ \multicolumn{3}{|l|}{+ Rabatte} \\ \hline\hline \multicolumn{3}{|l|}{\textbf{= Nettoverkaufspreis (NVP)}} \\ \hline \multicolumn{3}{|l|}{+ Umsatzsteuer} \\ \hline\hline \multicolumn{3}{|l|}{\textbf{= Bruttoverkaufspreis (BVP)}} \\ \hline \end{tabular} \\ \caption{Beispieltabelle 1} \label{tbl:beispieltabelle2} \end{table} %\clearpage % hiermit werden alle Bilder Tabellen ausgeworfen \subsection{Biblatex} Von den vielen verfügbaren Literatur-Paketen habe ich mich für Biblatex entschieden. Die Anforderungen der FOM sollten hiermit erfüllt sein. Ich habe bisher nur Einträge \enquote{@book} getestet. Wie immer steckt der Teufel hier im Detail und es wird sich später herausstellen, ob Biblatex eine gute Wahl war. Die Anpassungen hierfür liegen unter skripte/modsBiblatex. Ich verwende das Backend Biber, welches bib-Dateien in UTF-8 verarbeiten kann. \subsection{Listen und Aufzählungen} \subsubsection{Listen} \begin{itemize} \item ein wichtiger Punkt \item noch ein wichtiger Punkt \item und so weiter \end{itemize} \subsubsection{Aufzählungen} \begin{enumerate} \item Reihenfolge ist hier wichtig \item Dieser Punkt kommt nach dem ersten \item Da sollte jetzt eine 3 vorne stehen \end{enumerate} \paragraph{Tiefste Ebene 1} Dies ist die tiefste Gliederungsebene. Sollten doch mehr Ebenen benötigt werden, muss eine andere Dokumentenklasse verwendet werden. \paragraph{Tiefste Ebene 2} Der zweite Punkt in dieser Ebene ist zur Erinnerung daran, dass es nie nie niemals nur einen Unterpunkt geben darf. \subsection{Skript zum Kompilieren} Latex will ja bekanntlich in einer bestimmten Reihenfolge aufgerufen werden: \begin{lstlisting} pdflatex thesis_main.tex makeindex thesis_main.nlo -s nomencl.ist -o thesis_main.nls biber thesis_main pdflatex thesis_main.tex pdflatex thesis_main.tex thesis_main.pdf \end{lstlisting} Dies ist der Inhalt der Batchdatei \enquote{compile.bat}.
{ "content_hash": "e213e24c1f730cb4cd4640cad023eeed", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 793, "avg_line_length": 43.448, "alnum_prop": 0.775547781255754, "repo_name": "simic21/Hausarbeit_SE", "id": "e6c88f8d82acf631903504a6d939c6ed7b50fb4b", "size": "5458", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "kapitel/vorlagen/kapitel_2/kapitel_2.tex", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "225" }, { "name": "Shell", "bytes": "894" }, { "name": "TeX", "bytes": "68801" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_20) on Wed Feb 16 05:11:25 PST 2011 --> <TITLE> Uses of Class org.apache.pig.piggybank.evaluation.math.SINH (Pig 0.8.0-CDH3B4-SNAPSHOT API) </TITLE> <META NAME="date" CONTENT="2011-02-16"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.pig.piggybank.evaluation.math.SINH (Pig 0.8.0-CDH3B4-SNAPSHOT API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/pig/piggybank/evaluation/math/SINH.html" title="class in org.apache.pig.piggybank.evaluation.math"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/pig/piggybank/evaluation/math//class-useSINH.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SINH.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.pig.piggybank.evaluation.math.SINH</B></H2> </CENTER> No usage of org.apache.pig.piggybank.evaluation.math.SINH <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/pig/piggybank/evaluation/math/SINH.html" title="class in org.apache.pig.piggybank.evaluation.math"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/pig/piggybank/evaluation/math//class-useSINH.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SINH.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &copy; ${year} The Apache Software Foundation </BODY> </HTML>
{ "content_hash": "9c36c06a388aae7860577c256ad42937", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 248, "avg_line_length": 43.020833333333336, "alnum_prop": 0.6080710250201775, "repo_name": "simplegeo/hadoop-pig", "id": "36defaf67a937591f83696a4c8d444fe0ea86d1a", "size": "6195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/api/org/apache/pig/piggybank/evaluation/math/class-use/SINH.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "13034958" }, { "name": "JavaScript", "bytes": "35260" }, { "name": "Perl", "bytes": "2766" }, { "name": "Shell", "bytes": "32379" } ], "symlink_target": "" }
<?php namespace Symplify\PHP7_CodeSniffer\Application; use Symplify\PHP7_CodeSniffer\File\File; final class Fixer { /** * @var File */ private $currentFile; /** * @var string[]|array<int, string> */ private $tokens = []; public function startFile(File $file) { $this->currentFile = $file; $tokens = $file->getTokens(); $this->tokens = []; foreach ($tokens as $index => $token) { if (isset($token['orig_content']) === true) { $this->tokens[$index] = $token['orig_content']; } else { $this->tokens[$index] = $token['content']; } } } public function getContents() : string { return implode($this->tokens); } public function getTokenContent(int $stackPtr) : string { return $this->tokens[$stackPtr]; } public function replaceToken(int $stackPtr, string $content) : bool { $this->tokens[$stackPtr] = $content; return true; } public function addContent(int $stackPtr, string $content) : bool { $current = $this->getTokenContent($stackPtr); return $this->replaceToken($stackPtr, $current.$content); } public function addContentBefore(int $stackPtr, string $content) : bool { $current = $this->getTokenContent($stackPtr); return $this->replaceToken($stackPtr, $content.$current); } public function addNewline(int $stackPtr) : bool { return $this->addContent($stackPtr, $this->currentFile->eolChar); } public function addNewlineBefore(int $stackPtr) : bool { return $this->addContentBefore($stackPtr, $this->currentFile->eolChar); } public function substrToken(int $stackPtr, int $start, int $length = null) : bool { $current = $this->getTokenContent($stackPtr); if ($length !== null) { $newContent = substr($current, $start, $length); } else { $newContent = substr($current, $start); } return $this->replaceToken($stackPtr, $newContent); } /** * Needed for legacy compatibility. */ public function beginChangeset() { } /** * Needed for legacy compatibility. */ public function endChangeset() { } }
{ "content_hash": "217ad448eea4c8f11d824d2923ffa598", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 85, "avg_line_length": 23.356435643564357, "alnum_prop": 0.5684612123781263, "repo_name": "Symplify/PHP7_CodeSniffer", "id": "38c3cc26b248e4fe14a96f2fab85aa8c7450a886", "size": "2460", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Application/Fixer.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "144809" } ], "symlink_target": "" }
#ifndef INVERSESCALINGLEARNINGRATE_H #define INVERSESCALINGLEARNINGRATE_H #include <shogun/optimization/LearningRate.h> namespace shogun { /** @brief The implements the inverse scaling learning rate. * * The learning rate is computed in the following way: * \f[ * \frac{\eta_0}{{(a+b \times iter)}^k} * \f] * where \f$\eta_0\f$ is the initial learning rate, * \f$a\f$ is the intercept term, * \f$b\f$ is the slope term, * \f$iter\f$ is the number of times to call get_learning_rate(), * and \f$k\f$ is the exponent term. * */ class InverseScalingLearningRate: public LearningRate { public: /* Constructor */ InverseScalingLearningRate():LearningRate() { init(); } /* Destructor */ ~InverseScalingLearningRate() override {} /** returns the name of the class * * @return name InverseScalingLearningRate */ const char* get_name() const override { return "InverseScalingLearningRate"; } /** Get the learning rate for descent direction * @param iter_counter the number of iterations * * @return the learning rate (A.K.A step size/length) */ float64_t get_learning_rate(int32_t iter_counter) override; /** Set the initial learning rate * * @param initial_learning_rate initial_learning_rate must be positive */ virtual void set_initial_learning_rate(float64_t initial_learning_rate); /** Set the exponent term * * @param exponent exponent term should be positive */ virtual void set_exponent(float64_t exponent); /** Set the slope term * * @param slope slope term should be positive */ virtual void set_slope(float64_t slope); /** Set the intercept term * * @param intercept intercept term should be positive */ virtual void set_intercept(float64_t intercept); protected: /** exponent */ float64_t m_exponent; /** slope */ float64_t m_slope; /** intercept */ float64_t m_intercept; /** init_learning_rate */ float64_t m_initial_learning_rate; private: /** Init */ void init(); }; } #endif
{ "content_hash": "2c4836a209e333b06c8289d629b3d7ce", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 79, "avg_line_length": 23.726190476190474, "alnum_prop": 0.6899147014550928, "repo_name": "shogun-toolbox/shogun", "id": "5b4e1762bf4dee25acd64059a23ca0a4d8093873", "size": "3640", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "src/shogun/optimization/InverseScalingLearningRate.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "64" }, { "name": "Batchfile", "bytes": "615" }, { "name": "C", "bytes": "12178" }, { "name": "C++", "bytes": "10278013" }, { "name": "CMake", "bytes": "196539" }, { "name": "Dockerfile", "bytes": "2046" }, { "name": "GDB", "bytes": "89" }, { "name": "HTML", "bytes": "2060" }, { "name": "MATLAB", "bytes": "8755" }, { "name": "Makefile", "bytes": "244" }, { "name": "Python", "bytes": "286749" }, { "name": "SWIG", "bytes": "386485" }, { "name": "Shell", "bytes": "7267" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ro"> <head> <!-- Generated by javadoc (version 1.7.0_07) on Tue May 27 14:37:24 EEST 2014 --> <title>Uses of Interface net.sf.jasperreports.components.charts.ChartComponent (JasperReports 5.6.0 API)</title> <meta name="date" content="2014-05-27"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface net.sf.jasperreports.components.charts.ChartComponent (JasperReports 5.6.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../net/sf/jasperreports/components/charts/ChartComponent.html" title="interface in net.sf.jasperreports.components.charts">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?net/sf/jasperreports/components/charts/class-use/ChartComponent.html" target="_top">Frames</a></li> <li><a href="ChartComponent.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface net.sf.jasperreports.components.charts.ChartComponent" class="title">Uses of Interface<br>net.sf.jasperreports.components.charts.ChartComponent</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../net/sf/jasperreports/components/charts/ChartComponent.html" title="interface in net.sf.jasperreports.components.charts">ChartComponent</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#net.sf.jasperreports.components.charts">net.sf.jasperreports.components.charts</a></td> <td class="colLast"> <div class="block">Contains interfaces and base classes for the built-in Spider Chart component.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#net.sf.jasperreports.components.spiderchart">net.sf.jasperreports.components.spiderchart</a></td> <td class="colLast"> <div class="block">Contains classes for the built-in Spider Chart component.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="net.sf.jasperreports.components.charts"> <!-- --> </a> <h3>Uses of <a href="../../../../../../net/sf/jasperreports/components/charts/ChartComponent.html" title="interface in net.sf.jasperreports.components.charts">ChartComponent</a> in <a href="../../../../../../net/sf/jasperreports/components/charts/package-summary.html">net.sf.jasperreports.components.charts</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../net/sf/jasperreports/components/charts/package-summary.html">net.sf.jasperreports.components.charts</a> with parameters of type <a href="../../../../../../net/sf/jasperreports/components/charts/ChartComponent.html" title="interface in net.sf.jasperreports.components.charts">ChartComponent</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">ChartCustomizer.</span><code><strong><a href="../../../../../../net/sf/jasperreports/components/charts/ChartCustomizer.html#customize(org.jfree.chart.JFreeChart, net.sf.jasperreports.components.charts.ChartComponent)">customize</a></strong>(org.jfree.chart.JFreeChart&nbsp;chart, <a href="../../../../../../net/sf/jasperreports/components/charts/ChartComponent.html" title="interface in net.sf.jasperreports.components.charts">ChartComponent</a>&nbsp;chartComponent)</code> <div class="block">This method is called at fill time, before the chart is rendered.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="net.sf.jasperreports.components.spiderchart"> <!-- --> </a> <h3>Uses of <a href="../../../../../../net/sf/jasperreports/components/charts/ChartComponent.html" title="interface in net.sf.jasperreports.components.charts">ChartComponent</a> in <a href="../../../../../../net/sf/jasperreports/components/spiderchart/package-summary.html">net.sf.jasperreports.components.spiderchart</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../net/sf/jasperreports/components/spiderchart/package-summary.html">net.sf.jasperreports.components.spiderchart</a> that implement <a href="../../../../../../net/sf/jasperreports/components/charts/ChartComponent.html" title="interface in net.sf.jasperreports.components.charts">ChartComponent</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/components/spiderchart/SpiderChartComponent.html" title="class in net.sf.jasperreports.components.spiderchart">SpiderChartComponent</a></strong></code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../net/sf/jasperreports/components/charts/ChartComponent.html" title="interface in net.sf.jasperreports.components.charts">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?net/sf/jasperreports/components/charts/class-use/ChartComponent.html" target="_top">Frames</a></li> <li><a href="ChartComponent.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">&copy; 2001-2010 Jaspersoft Corporation <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span> </small></p> </body> </html>
{ "content_hash": "245f99044cd9f201342aeb71231eb726", "timestamp": "", "source": "github", "line_count": 189, "max_line_length": 398, "avg_line_length": 47.629629629629626, "alnum_prop": 0.6684070206620751, "repo_name": "phurtado1112/cnaemvc", "id": "8a70582b8743ea8edd809e3138973dfdea932fb7", "size": "9002", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/JasperReport__5.6/docs/api/net/sf/jasperreports/components/charts/class-use/ChartComponent.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11139" }, { "name": "HTML", "bytes": "112926414" }, { "name": "Java", "bytes": "532942" } ], "symlink_target": "" }
<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package Pu-ente */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
{ "content_hash": "459d973d97d33fab48a86f467b433530", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 90, "avg_line_length": 24.764705882352942, "alnum_prop": 0.6068883610451307, "repo_name": "stefmtz/pu-ente", "id": "0bd19df4e746be7d4fd2d8aaf43245701b163fbf", "size": "842", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "page.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "62425" }, { "name": "JavaScript", "bytes": "21807" }, { "name": "PHP", "bytes": "52931" } ], "symlink_target": "" }
import { SpyOn, Test, TestFixture, } from "alsatian"; import { ChildProcess } from "child_process"; import { Container, injectable } from "inversify"; import CliGenerateFacade from "../../../src/cli/CliGenerateFacade"; import IConfigManager from "../../../src/config/IConfigManager"; import IConfigOverrider from "../../../src/config/IConfigOverrider"; import { IProjectConfig } from "../../../src/config/IProjectConfig"; import { ProjectConfig } from "../../../src/config/ProjectConfig"; import IDocumentationGenerator from "../../../src/generator/IDocumentationGenerator"; import IGMProject from "../../../src/gm_project/IGMProject"; import IGMProjectLoader from "../../../src/gm_project/IGMProjectLoader"; import { IOpen } from "../../../src/npmmodules"; import IReporter from "../../../src/reporter/IReporter"; import { TYPES } from "../../../src/types"; import MockGMProject from "../__mock__/MockGMProject.mock"; import MockReporter from "../__mock__/MockReporter.mock"; /* tslint:disable:max-classes-per-file completed-docs */ const config = new ProjectConfig(); const project = new MockGMProject("project", []); @injectable() class MockGMProjectLoader implements IGMProjectLoader { public async load(_file: string): Promise<IGMProject> { return project; } } @injectable() class MockConfigManager implements IConfigManager { public async exportConfig(_outputPath: string): Promise<string> { return "foo"; } public async loadConfig(jsonOrProjectPath: string): Promise<IProjectConfig | undefined> { return jsonOrProjectPath === "." ? config : undefined; } } @injectable() class MockDocumentationGenerator implements IDocumentationGenerator { public async generate(p: IGMProject, c?: IProjectConfig | undefined): Promise<string> { if (project === p && config === c) { return "my_output_folder/"; } return ""; } } @injectable() class MockConfigOverrider implements IConfigOverrider { public override(conf: IProjectConfig, _overrideConfig: { [key: string]: string; }): IProjectConfig { return conf; } } @TestFixture("CliGenerateFacade") export class CliGenerateFacadeFixture { @Test() public async generate_default() { return this._getCgf().generate(); } @Test() public async generate_noDefaultConfig() { return this._getCgf().generate("other/path/with/no/config"); } @Test() public async generate_noOpen() { return this._getCgf().generate("other/path/with/no/config", {noOpen: true}); } @Test() public async generate_init() { return this._getCgf().init(); } private _getCgf(): CliGenerateFacade { const container = new Container(); const reporter = new MockReporter(); SpyOn(reporter, "info").andStub(); container.bind<IReporter>(TYPES.IReporter).toConstantValue(reporter); container.bind<IGMProjectLoader>(TYPES.IGMProjectLoader).to(MockGMProjectLoader); container.bind<IConfigManager>(TYPES.IConfigManager).to(MockConfigManager); container.bind<IDocumentationGenerator>(TYPES.IDocumentationGenerator).to(MockDocumentationGenerator); container.bind<IConfigOverrider>(TYPES.IConfigOverrider).to(MockConfigOverrider); container.bind<IOpen>(TYPES.IOpen).toFunction((target) => this._mockOpen(target)); return container.resolve(CliGenerateFacade); } private _mockOpen(target: string): Promise<ChildProcess> { if (!target.includes("my_output_folder") && !target.includes("index.html")) { throw new Error("Invalid target: " + target); } return null as unknown as Promise<ChildProcess>; } }
{ "content_hash": "8f78afbf154a05ab0918df8563899776", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 104, "avg_line_length": 34.81, "alnum_prop": 0.7288135593220338, "repo_name": "jhm-ciberman/docs_gm", "id": "e8275f037d393e7338f7d252180d45aaa9a2cc89", "size": "3481", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/unit/cli/CliGenerateFacade.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "453" }, { "name": "Game Maker Language", "bytes": "313" }, { "name": "HTML", "bytes": "10423" }, { "name": "JavaScript", "bytes": "267" }, { "name": "TypeScript", "bytes": "227605" } ], "symlink_target": "" }
package com.maxifier.mxcache.caches; /** * THIS IS GENERATED CLASS! DON'T EDIT IT MANUALLY! * * GENERATED FROM P2PCalculatable.template * * @author Andrey Yakoushin (andrey.yakoushin@maxifier.com) * @author Alexander Kochurov (alexander.kochurov@maxifier.com) */ public interface ObjectShortCalculatable<E> extends Calculable { short calculate(Object owner, E o); }
{ "content_hash": "b0882072ec0003ecdc2b968454e311f6", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 64, "avg_line_length": 27.928571428571427, "alnum_prop": 0.731457800511509, "repo_name": "akochurov/mxcache", "id": "4f220257eb416833e98ef3f53e4b213a52948f0c", "size": "461", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "mxcache-runtime/src/main/java/com/maxifier/mxcache/caches/ObjectShortCalculatable.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2922119" } ], "symlink_target": "" }
from __future__ import print_function import os import sys import time from subprocess import Popen, PIPE __doc__ = """ ufo2pfa v2.0 - Feb 03 2016 This script takes a path to a folder as input, finds all the UFO fonts inside that folder and its subdirectories, and converts them to Type 1 fonts (.pfa files). If a path is not provided, the script will use the current path as the top-most directory. ================================================== Versions: v1.0 - Feb 23 2013 - Initial release v2.0 - Feb 03 2016 - Modernized and removed defcon and ufo2fdk dependencies. """ def getFontPaths(path): fontsList = [] for r, folders, files in os.walk(path): for folder in folders: fileName, extension = os.path.splitext(folder) extension = extension.lower() if extension == ".ufo": fontsList.append(os.path.join(r, folder)) return fontsList def doTask(fonts): totalFonts = len(fonts) print("%d fonts found" % totalFonts) i = 1 for font in fonts: folderPath, fontFileName = os.path.split(font) styleName = os.path.basename(folderPath) # Change current directory to the folder where the font is contained os.chdir(folderPath) print('\n*******************************') print('Processing %s...(%d/%d)' % (styleName, i, totalFonts)) # Assemble PFA file name fileNameNoExtension, fileExtension = os.path.splitext(fontFileName) pfaPath = fileNameNoExtension + '.pfa' # Convert UFO to PFA using tx cmd = 'tx -t1 "%s" "%s"' % (fontFileName, pfaPath) popen = Popen(cmd, shell=True, stdout=PIPE) popenout, popenerr = popen.communicate() if popenout: print(popenout) if popenerr: print(popenerr) i += 1 def run(): # if a path is provided if len(sys.argv[1:]): baseFolderPath = os.path.normpath(sys.argv[1]) # make sure the path is valid if not os.path.isdir(baseFolderPath): print('Invalid directory.') return # if a path is not provided, use the current directory else: baseFolderPath = os.getcwd() t1 = time.time() fontsList = getFontPaths(os.path.abspath(baseFolderPath)) if len(fontsList): doTask(fontsList) else: print("No fonts found.") return t2 = time.time() elapsedSeconds = t2 - t1 elapsedMinutes = elapsedSeconds / 60 if elapsedMinutes < 1: print('Completed in %.1f seconds.' % elapsedSeconds) else: print('Completed in %.1f minutes.' % elapsedMinutes) if __name__ == '__main__': run()
{ "content_hash": "a936af362c594bacd310db8abe71c16f", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 76, "avg_line_length": 27.03, "alnum_prop": 0.6011838697743248, "repo_name": "adobe-type-tools/python-scripts", "id": "47c0f6884b1f56f611bdee60f27f80b3b5ed44b7", "size": "2726", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ufo2pfa.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "267212" } ], "symlink_target": "" }
package org.apereo.cas.web.flow; import org.apereo.cas.authentication.Credential; import org.apereo.cas.authentication.UsernamePasswordCredential; import org.apereo.cas.authentication.adaptive.AdaptiveAuthenticationPolicy; import org.apereo.cas.web.flow.actions.AbstractNonInteractiveCredentialsAction; import org.apereo.cas.web.flow.resolver.CasDelegatingWebflowEventResolver; import org.apereo.cas.web.flow.resolver.CasWebflowEventResolver; import org.apereo.cas.web.support.WebUtils; import org.pac4j.core.context.WebContext; import org.pac4j.core.credentials.UsernamePasswordCredentials; import org.pac4j.core.credentials.extractor.BasicAuthExtractor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.webflow.execution.RequestContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This is {@link BasicAuthenticationAction} that extracts basic authN credentials from the request. * * @author Misagh Moayyed * @since 4.2.0 */ public class BasicAuthenticationAction extends AbstractNonInteractiveCredentialsAction { private static final Logger LOGGER = LoggerFactory.getLogger(BasicAuthenticationAction.class); public BasicAuthenticationAction(final CasDelegatingWebflowEventResolver initialAuthenticationAttemptWebflowEventResolver, final CasWebflowEventResolver serviceTicketRequestWebflowEventResolver, final AdaptiveAuthenticationPolicy adaptiveAuthenticationPolicy) { super(initialAuthenticationAttemptWebflowEventResolver, serviceTicketRequestWebflowEventResolver, adaptiveAuthenticationPolicy); } @Override protected Credential constructCredentialsFromRequest(final RequestContext requestContext) { try { final HttpServletRequest request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext); final HttpServletResponse response = WebUtils.getHttpServletResponseFromExternalWebflowContext(requestContext); final BasicAuthExtractor extractor = new BasicAuthExtractor(this.getClass().getSimpleName()); final WebContext webContext = WebUtils.getPac4jJ2EContext(request, response); final UsernamePasswordCredentials credentials = extractor.extract(webContext); if (credentials != null) { LOGGER.debug("Received basic authentication request from credentials [{}]", credentials); return new UsernamePasswordCredential(credentials.getUsername(), credentials.getPassword()); } } catch (final Exception e) { LOGGER.warn(e.getMessage(), e); } return null; } }
{ "content_hash": "121045b66e9acda2249e5c27ef2787bc", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 136, "avg_line_length": 51.75471698113208, "alnum_prop": 0.7725118483412322, "repo_name": "Unicon/cas", "id": "e4523700e542cb4d218a77428dee0f4376a392d3", "size": "2743", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "support/cas-server-support-basic/src/main/java/org/apereo/cas/web/flow/BasicAuthenticationAction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "281434" }, { "name": "Groovy", "bytes": "4742" }, { "name": "HTML", "bytes": "249429" }, { "name": "Java", "bytes": "7882824" }, { "name": "JavaScript", "bytes": "171051" }, { "name": "Shell", "bytes": "15678" }, { "name": "TypeScript", "bytes": "254507" } ], "symlink_target": "" }
package lila.app package templating import java.util.Locale import scala.collection.mutable import org.joda.time.format._ import org.joda.time.{ Period, PeriodType, DurationFieldType, DateTime } import play.twirl.api.Html import lila.api.Context trait DateHelper { self: I18nHelper => private val dateTimeStyle = "MS" private val dateStyle = "M-" private val dateTimeFormatters = mutable.Map[String, DateTimeFormatter]() private val dateFormatters = mutable.Map[String, DateTimeFormatter]() private val periodFormatters = mutable.Map[String, PeriodFormatter]() private val periodType = PeriodType forFields Array( DurationFieldType.days, DurationFieldType.hours, DurationFieldType.minutes) private val isoFormatter = ISODateTimeFormat.dateTime private def dateTimeFormatter(ctx: Context): DateTimeFormatter = dateTimeFormatters.getOrElseUpdate( lang(ctx).language, DateTimeFormat forStyle dateTimeStyle withLocale new Locale(lang(ctx).language)) private def dateFormatter(ctx: Context): DateTimeFormatter = dateFormatters.getOrElseUpdate( lang(ctx).language, DateTimeFormat forStyle dateStyle withLocale new Locale(lang(ctx).language)) private def periodFormatter(ctx: Context): PeriodFormatter = periodFormatters.getOrElseUpdate( lang(ctx).language, PeriodFormat wordBased new Locale(lang(ctx).language)) def showDateTime(date: DateTime)(implicit ctx: Context): String = dateTimeFormatter(ctx) print date def showDate(date: DateTime)(implicit ctx: Context): String = dateFormatter(ctx) print date def semanticDate(date: DateTime)(implicit ctx: Context) = Html { s"""<time datetime="${isoFormatter print date}">${showDate(date)}</time>""" } def showPeriod(period: Period)(implicit ctx: Context): String = periodFormatter(ctx) print period.normalizedStandard(periodType) def isoDate(date: DateTime): String = isoFormatter print date def momentFormat(date: DateTime, format: String): Html = Html { s"""<time class="moment" datetime="${isoFormatter print date}" data-format="$format"></time>""" } def momentFormat(date: DateTime): Html = momentFormat(date, "calendar") def momentFromNow(date: DateTime) = Html { s"""<time class="moment-from-now" datetime="${isoFormatter print date}"></time>""" } def secondsFromNow(seconds: Int) = momentFromNow(DateTime.now plusSeconds seconds) }
{ "content_hash": "aaaabe24f0f4cbf38c5fd82671e6e040", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 99, "avg_line_length": 35.661764705882355, "alnum_prop": 0.7463917525773196, "repo_name": "danilovsergey/i-bur", "id": "90bc1c20d04a797479c80c15bd67e5ca099f08f8", "size": "2425", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/templating/DateHelper.scala", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "55" }, { "name": "CSS", "bytes": "196185" }, { "name": "Cycript", "bytes": "3792" }, { "name": "Emacs Lisp", "bytes": "25777" }, { "name": "Erlang", "bytes": "16630" }, { "name": "Fancy", "bytes": "119" }, { "name": "GAP", "bytes": "11478" }, { "name": "GLSL", "bytes": "2526" }, { "name": "HTML", "bytes": "292494" }, { "name": "Hy", "bytes": "20725" }, { "name": "Io", "bytes": "5015" }, { "name": "Java", "bytes": "21183" }, { "name": "JavaScript", "bytes": "334690" }, { "name": "Makefile", "bytes": "15382" }, { "name": "Mathematica", "bytes": "15413" }, { "name": "NewLisp", "bytes": "16074" }, { "name": "OCaml", "bytes": "1709" }, { "name": "Perl6", "bytes": "16438" }, { "name": "PostScript", "bytes": "2705" }, { "name": "Python", "bytes": "1959" }, { "name": "Ruby", "bytes": "26262" }, { "name": "Scala", "bytes": "1283987" }, { "name": "Shell", "bytes": "9258" }, { "name": "Slash", "bytes": "15290" }, { "name": "Smalltalk", "bytes": "16146" }, { "name": "SystemVerilog", "bytes": "15894" } ], "symlink_target": "" }
<?php namespace tests\unit\models; use app\models\ContactForm; use Codeception\Test\Unit as UnitTest; use UnitTester; use yii\mail\MessageInterface; /** * Class ContactFormTest. * * @author {author} */ class ContactFormTest extends UnitTest { /** @var UnitTester */ public $tester; private $model; public function testEmailIsSentOnContact() { /* @var $model ContactForm */ $this->model = $this->getMockBuilder(ContactForm::class) ->setMethods(['validate']) ->getMock(); $this->model->expects($this->once()) ->method('validate') ->willReturn(true); $this->model->attributes = [ 'name' => 'Tester', 'email' => 'tester@example.com', 'subject' => 'very important letter subject', 'body' => 'body of current message', ]; expect_that($this->model->contact('admin@example.com')); // using Yii2 module actions to check email was sent $this->tester->seeEmailIsSent(); /* @var $emailMessage MessageInterface */ $emailMessage = $this->tester->grabLastSentEmail(); expect('valid email is sent', $emailMessage)->isInstanceOf(MessageInterface::class); expect($emailMessage->getTo())->hasKey('admin@example.com'); expect($emailMessage->getFrom())->hasKey('noreply@example.com'); expect($emailMessage->getReplyTo())->hasKey('tester@example.com'); expect($emailMessage->getSubject())->equals('very important letter subject'); expect($emailMessage->toString())->stringContainsString('body of current message'); } }
{ "content_hash": "fabbc1e7e580071b7af0fad3cbd0ac0d", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 86, "avg_line_length": 27.79245283018868, "alnum_prop": 0.6924643584521385, "repo_name": "rob006/yii2-app-extended", "id": "1831430592309555903b218f34bfb37a1e70519c", "size": "1473", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/unit/models/ContactFormTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "218" }, { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "1364" }, { "name": "PHP", "bytes": "42351" } ], "symlink_target": "" }
title: Circular Progress, Linear Progress React component components: CircularProgress, LinearProgress --- # Прогресс <p class="description">Progress indicators commonly known as spinners, express an unspecified wait time or display the length of a process. The animation works with CSS, not JavaScript.</p> [Индикаторы прогресса](https://material.io/design/components/progress-indicators.html) информируют пользователей о состоянии текущих процессов, таких как загрузка приложения, отправка формы или сохранение обновлений. Они сообщают о состоянии приложения и указывают возможные действия, например, могут ли пользователи уходить с текущего экрана. **Детерменированные** индикаторы показывают, сколько времени займет операция. **Недетерминированные** индикаторы отображают неопределенное время ожидания. #### Групповой прогресс Отображая прогресс последовательности процессов, укажите общий прогресс, а не прогресс каждого отдельного действия. ## Circular [Circular progress](https://material.io/design/components/progress-indicators.html#circular-progress-indicators) support both determinate and indeterminate processes. - **Determinate** circular indicators fill the invisible, circular track with color, as the indicator moves from 0 to 360 degrees. - **Indeterminate** circular indicators grow and shrink in size while moving along the invisible track. ### Circular Indeterminate {{"demo": "pages/components/progress/CircularIndeterminate.js"}} ### Interactive Integration {{"demo": "pages/components/progress/CircularIntegration.js"}} ### Circular Determinate {{"demo": "pages/components/progress/CircularDeterminate.js"}} ### Circular Static {{"demo": "pages/components/progress/CircularStatic.js"}} ## Linear [Linear progress](https://material.io/design/components/progress-indicators.html#linear-progress-indicators) indicators. ### Linear Indeterminate {{"demo": "pages/components/progress/LinearIndeterminate.js"}} ### Linear Determinate {{"demo": "pages/components/progress/LinearDeterminate.js"}} ### Linear Buffer {{"demo": "pages/components/progress/LinearBuffer.js"}} ### Linear Query {{"demo": "pages/components/progress/LinearQuery.js"}} ## Non-standard ranges Компоненты прогресса принимают значение в диапазоне от 0 до 100. Это упрощает работу с программами для чтения с экрана ("скринридеры"), где это минимальные и максимальные значения по умолчанию. Однако иногда вы можете работать с данными, значения которых выходят за пределы этого диапазона. Вот так можно легко преобразовать значение из любого диапазона в шкалу от 0 до 100: ```jsx // MIN = Minimum expected value // MAX = Maximium expected value // Function to normalise the values (MIN / MAX could be integrated) const normalise = value => (value - MIN) * 100 / (MAX - MIN); // Example component that utilizes the `normalise` function at the point of render. function Progress(props) { return ( <React.Fragment> <CircularProgress variant="determinate" value={normalise(props.value)} /> <LinearProgress variant="determinate" value={normalise(props.value)} /> </React.Fragment> ) } ``` ## Customized progress bars Ниже находятся примеры кастомизации компонента. You can learn more about this in the [overrides documentation page](/customization/components/). {{"demo": "pages/components/progress/CustomizedProgressBars.js"}} ## Delaying appearance There are [3 important limits](https://www.nngroup.com/articles/response-times-3-important-limits/) to know around response time. The ripple effect of the `ButtonBase` component ensures that the user feels that the system is reacting instantaneously. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second. After 1.0 second, you can display a loader to keep user's flow of thought uninterrupted. {{"demo": "pages/components/progress/DelayingAppearance.js"}} ## Ограничения Under heavy load, you might lose the stroke dash animation or see random CircularProgress ring widths. You should run processor intensive operations in a web worker or by batch in order not to block the main rendering thread. ![heavy load](/static/images/progress/heavy-load.gif) When it's not possible, you can leverage the `disableShrink` property to mitigate the issue. See [this issue](https://github.com/mui-org/material-ui/issues/10327). {{"demo": "pages/components/progress/CircularUnderLoad.js"}}
{ "content_hash": "8213a5831d265c451ed3aaba97b2c5d0", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 439, "avg_line_length": 42.89320388349515, "alnum_prop": 0.7797645993662291, "repo_name": "kybarg/material-ui", "id": "2f729776404e989f28061cb1e10a82f2fe918d5a", "size": "5269", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/src/pages/components/progress/progress-ru.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "304" }, { "name": "JavaScript", "bytes": "4412500" }, { "name": "Shell", "bytes": "144" }, { "name": "TypeScript", "bytes": "92028" } ], "symlink_target": "" }
package com.zwy.kutils.eventbus; import java.lang.reflect.Method; /** Used internally by EventBus and generated subscriber indexes. */ public class SubscriberMethod { final Method method; final ThreadMode threadMode; final Class<?> eventType; final int priority; final boolean sticky; final String tag; /** Used for efficient comparison */ String methodString; public SubscriberMethod(Method method, Class<?> eventType, ThreadMode threadMode, int priority, boolean sticky,String tag) { this.method = method; this.threadMode = threadMode; this.eventType = eventType; this.priority = priority; this.sticky = sticky; this.tag = tag; } @Override public boolean equals(Object other) { if (other == this) { return true; } else if (other instanceof SubscriberMethod) { checkMethodString(); SubscriberMethod otherSubscriberMethod = (SubscriberMethod)other; otherSubscriberMethod.checkMethodString(); // Don't use method.equals because of http://code.google.com/p/android/issues/detail?id=7811#c6 return methodString.equals(otherSubscriberMethod.methodString); } else { return false; } } private synchronized void checkMethodString() { if (methodString == null) { // Method.toString has more overhead, just take relevant parts of the method StringBuilder builder = new StringBuilder(64); builder.append(method.getDeclaringClass().getName()); builder.append('#').append(method.getName()); builder.append('(').append(eventType.getName()); methodString = builder.toString(); } } @Override public int hashCode() { return method.hashCode(); } }
{ "content_hash": "138251eb686b07e0fd0dc15e1e33a5bb", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 128, "avg_line_length": 33.375, "alnum_prop": 0.6361690743713215, "repo_name": "devzwy/KUtils", "id": "1655f75ad40ad2a5b430a7e1080dac4feef5ed2b", "size": "2514", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kutils/src/main/java/com/zwy/kutils/eventbus/SubscriberMethod.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "874887" } ], "symlink_target": "" }
package seedu.taskmanager.logic.commands; import seedu.taskmanager.logic.commands.exceptions.CommandException; // @@author A0140538J /** * Sets a preferred duration where PotaTodo will remind the user of expiring tasks within the stipulated duration. User * preference is saved upon changing the settings. */ public class SetNotificationCommand extends Command { public static final String COMMAND_WORD = "set"; public static final String MESSAGE_SUCCESS = "New notification time has been set.\n" + "Please refresh PotaTodo to apply the changes.\n" + "New set duration: %1$s"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Sets a visual notification for tasks expiring within the stipulated time.\n" + "Example: " + COMMAND_WORD + " 1 week\n" + "This means you will be reminded 1 week in advance for expiring tasks."; public String duration; public SetNotificationCommand(String duration) { this.duration = duration; } @Override public CommandResult execute() throws CommandException { model.setNotification(duration); return new CommandResult(String.format(MESSAGE_SUCCESS, duration)); } @Override public boolean mutatesTaskManager() { return false; } }
{ "content_hash": "05403ca5038b1e8610fc741ab500f0f1", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 119, "avg_line_length": 34.18421052631579, "alnum_prop": 0.7059276366435719, "repo_name": "kennyngdsc/addressbook-level4", "id": "ee3ff5047905959c5ceada90326e3cb8130758e5", "size": "1299", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/main/java/seedu/taskmanager/logic/commands/SetNotificationCommand.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6347" }, { "name": "Java", "bytes": "438992" }, { "name": "Shell", "bytes": "1525" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_111) on Mon Dec 12 16:34:14 EST 2016 --> <title>org.plexian.grumy.effect</title> <meta name="date" content="2016-12-12"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.plexian.grumy.effect"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/plexian/grumy/configuration/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../org/plexian/grumy/entity/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/plexian/grumy/effect/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;org.plexian.grumy.effect</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../org/plexian/grumy/effect/EffectRenderer.html" title="class in org.plexian.grumy.effect">EffectRenderer</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation"> <caption><span>Enum Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Enum</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../org/plexian/grumy/effect/EffectRenderer.EffectType.html" title="enum in org.plexian.grumy.effect">EffectRenderer.EffectType</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/plexian/grumy/configuration/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../org/plexian/grumy/entity/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/plexian/grumy/effect/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "d123ff9f7dd641795f4a20372aa517b2", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 174, "avg_line_length": 35.07643312101911, "alnum_prop": 0.6290176139458871, "repo_name": "ThePlexianNetwork/Grumy", "id": "b08b3b9967a29bd8f22b93f85b2b9f051e902572", "size": "5507", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "doc/org/plexian/grumy/effect/package-summary.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2271672" }, { "name": "C++", "bytes": "3076" }, { "name": "GLSL", "bytes": "4415" }, { "name": "Java", "bytes": "9012727" }, { "name": "Objective-C", "bytes": "87796" }, { "name": "Shell", "bytes": "155" } ], "symlink_target": "" }
package org.linkedin.util.codec; /** * A one way codec simply define a method to encode. * * @author ypujante@linkedin.com */ public interface OneWayCodec { /** * Encode the array into a <code>String</code> * * @param byteArray the array to encode * @return the encoded <code>String</code> */ String encode(byte[] byteArray); }
{ "content_hash": "434d249d096abf75521783c53fd99437", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 52, "avg_line_length": 19.444444444444443, "alnum_prop": 0.6714285714285714, "repo_name": "linkedin/linkedin-utils", "id": "2aae987cdc52a6bab19faf33ff4a41e43655fa59", "size": "947", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "org.linkedin.util-core/src/main/java/org/linkedin/util/codec/OneWayCodec.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "207738" }, { "name": "Java", "bytes": "505371" }, { "name": "Shell", "bytes": "7484" } ], "symlink_target": "" }
%% CLASS bot.internal.cache - Cache and cloud access class for Brain Observatory Toolbox % % This class is used internally by the Brain Observatory Toolbox to access % data from the Allen Brain Observatory resource [1] via the Allen Brain % Atlas API [2]. % % [1] Copyright 2016 Allen Institute for Brain Science. Allen Brain Observatory. Available from: portal.brain-map.org/explore/circuits % [2] Copyright 2015 Allen Institute for Brain Science. Allen Brain Atlas API. Available from: brain-map.org/api/index.html %% Class definition classdef cache < handle properties (SetAccess = immutable) strVersion = '0.5'; % Version string for cache class end properties (SetAccess = private) strCacheDir; % Path to location of cached data from the Allen Brain Observatory resource ccCache; % Cloud data cache ocCache; % Object cache end properties strABOBaseUrl = 'http://api.brain-map.org'; % Base URL for the Allen Brain Observatory resource end %% Constructor methods function oCache = cache(strCacheDir) % CONSTRUCTOR - Returns an object for managing data access from an Allen Brain Observatory dataset % % Usage: oCache = bot.internal.cache(<strCacheDir>) % - Check if a cache directory has been provided if ~exist('strCacheDir', 'var') || isempty(strCacheDir) % - Get the default cache directory strBOTDir = fileparts(which('bot.fetchSessions')); oCache.strCacheDir = [strBOTDir filesep 'Cache']; else oCache.strCacheDir = strCacheDir; end % - Find and return the global cache object, if one exists sUserData = get(0, 'UserData'); if isfield(sUserData, 'BOT_GLOBAL_CACHE') && ... isa(sUserData.BOT_GLOBAL_CACHE, 'bot.internal.cache') && ... isequal(sUserData.BOT_GLOBAL_CACHE.strVersion, oCache.strVersion) && ... (~exist('strCacheDir', 'var') || isempty(strCacheDir)) % - A global class instance exists, and is the correct version, % and no "user" cache directory has been provided oCache = sUserData.BOT_GLOBAL_CACHE; return; end %% - Set up a cache object, if no object exists % - Ensure the cache directory exists if ~exist(oCache.strCacheDir, 'dir') mkdir(oCache.strCacheDir); end % - Set up cloud and ojbect caches oCache.ccCache = bot.internal.CloudCacher(oCache.strCacheDir); oCache.ocCache = bot.internal.ObjectCacher(oCache.strCacheDir); % - Assign the cache object to a global cache sUserData.BOT_GLOBAL_CACHE = oCache; set(0, 'UserData', sUserData); end end %% Methods to manage manifests and caching methods function InsertObject(oCache, strKey, object) % InsertObject - METHOD Insert an object into the object cache % % Usage: oCache.Insert(strKey, object) % % `strKey` is a string, which will be associated with the object % in the cache. You should take care that the key is unique % enough. % % `object` is an arbitrary MATLAB object, that can be serialised % and saved. % % `object` will be inserted into the object cache, and can be % retrieved later using `strKey`. oCache.ocCache.Insert(strKey, object); end function object = RetrieveObject(oCache, strKey) % RetrieveObject - METHOD Retrieve an object (key) from the object cache % % Usage: object = oCache.Rerieve(strKey) % % `strKey` is a string which identifies an object in the cache. % % If the key `strKey` exists in the cache, the corresponding % object will be retrieved. Otherwise an error will be raised. object = oCache.ocCache.Retrieve(strKey); end function bIsInCache = IsObjectInCache(oCache, strKey) % IsObjectInCache - METHOD Check if an object (key) is in the object cahce % % Usage: bIsInCache = oCache.IsObjectInCache(strKey) % % `strKey` is a string to be queried in the object cache. If the % key exists in the cache, then `True` is returned. Otherwise % `False` is returned. bIsInCache = oCache.ocCache.IsInCache(strKey); end function RemoveObject(oCache, strKey) % RemoveObject - METHOD Remove an object (key) from the object cache % % Usage: oCache.RemoveObject(strKey) % % `strKey` is a string identifying an object key. If the key % exists in the cache, then the corresponding object data will be % removed form the cache. oCache.ocCache.Remove(strKey); end function ClearObjectCache(oCache) keys = oCache.ocCache.mapCachedData.keys(); for key = string(keys) oCache.RemoveObject(key); end end function strFile = CacheFile(oCache, strURL, strLocalFile) % CacheFile - METHOD Check for cached version of Allen Brain Observatory dataset file, and return local location on disk % % Usage: strFile = oCache.CacheFile(strURL, strLocalFile) strFile = oCache.ccCache.websave(strLocalFile, strURL); end function bIsURLInCache = IsURLInCache(oCache, strURL) % IsURLInCache - METHOD Is the provided URL already cached? % % Usage: bIsURLInCache = oCache.IsURLInCache(strURL) bIsURLInCache = oCache.ccCache.IsInCache(strURL); end function tResponse = CachedAPICall(oCache, strModel, strQueryString, nPageSize, strFormat, strRMAPrefix, strHost, strScheme, strID) % CachedAPICall - METHOD Return the (hopefully cached) contents of an Allen Brain Atlas API call % % Usage: tResponse = CachedAPICall(oCache, strModel, strQueryString, ...) % tResponse = CachedAPICall(..., <nPageSize>, <strFormat>, <strRMAPrefix>, <strHost>, <strScheme>, <strID>) DEF_strScheme = "http"; DEF_strHost = "api.brain-map.org"; DEF_strRMAPrefix = "api/v2/data"; DEF_nPageSize = 5000; DEF_strFormat = "query.json"; DEF_strID = "id"; % -- Default arguments if ~exist('strScheme', 'var') || isempty(strScheme) strScheme = DEF_strScheme; end if ~exist('strHost', 'var') || isempty(strHost) strHost = DEF_strHost; end if ~exist('strRMAPrefix', 'var') || isempty(strRMAPrefix) strRMAPrefix = DEF_strRMAPrefix; end if ~exist('nPageSize', 'var') || isempty(nPageSize) nPageSize = DEF_nPageSize; end if ~exist('strFormat', 'var') || isempty(strFormat) strFormat = DEF_strFormat; end if ~exist('strID', 'var') || isempty(strID) strID = DEF_strID; end % - Build a URL strURL = string(strScheme) + "://" + string(strHost) + "/" + ... string(strRMAPrefix) + "/" + string(strFormat) + "?" + ... string(strModel); if ~isempty(strQueryString) strURL = strURL + "," + strQueryString; end % - Set up options options = weboptions('ContentType', 'JSON', 'TimeOut', 60); nTotalRows = []; nStartRow = 0; tResponse = table(); while isempty(nTotalRows) || nStartRow < nTotalRows % - Add page parameters strURLQueryPage = strURL + ",rma::options[start_row$eq" + nStartRow + "][num_rows$eq" + nPageSize + "][order$eq'" + strID + "']"; % - Perform query response_raw = oCache.ccCache.webread(strURLQueryPage, [], options); % - Was there an error? if ~response_raw.success error('BOT:DataAccess', 'Error querying Allen Brain Atlas API for URL [%s]', strURLQueryPage); end % - Convert response to a table if isa(response_raw.msg, 'cell') response_page = cell_messages_to_table(response_raw.msg); else response_page = struct2table(response_raw.msg); end % - Append response page to table if isempty(tResponse) tResponse = response_page; else tResponse = bot.internal.merge_tables(tResponse, response_page); end % - Get total number of rows if isempty(nTotalRows) nTotalRows = response_raw.total_rows; end % - Move to next page nStartRow = nStartRow + nPageSize; % - Display progress if we didn't finish if (nStartRow < nTotalRows) fprintf('Fetching.... [%.0f%%]\n', round(nStartRow / nTotalRows * 100)) end end function tMessages = cell_messages_to_table(cMessages) % - Get an exhaustive list of fieldnames cFieldnames = cellfun(@fieldnames, cMessages, 'UniformOutput', false); cFieldnames = unique(vertcat(cFieldnames{:}), 'stable'); % - Make sure every message has all required field names function sData = enforce_fields(sData) vbHasField = cellfun(@(c)isfield(sData, c), cFieldnames); for strField = cFieldnames(~vbHasField)' sData.(strField{1}) = []; end end cMessages = cellfun(@(c)enforce_fields(c), cMessages, 'UniformOutput', false); % - Convert to a table tMessages = struct2table([cMessages{:}]); end end end end
{ "content_hash": "4c299340116a6ce6d27819a528eb016e", "timestamp": "", "source": "github", "line_count": 275, "max_line_length": 145, "avg_line_length": 40.85090909090909, "alnum_prop": 0.5218087947302831, "repo_name": "emeyers/Brain-Observatory-Toolbox", "id": "b2226b498dec233ca591936d91e2ae7fde25bb50", "size": "11234", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "+bot/+internal/cache.m", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "14315" }, { "name": "MATLAB", "bytes": "394506" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <env-entry> <env-entry-name>TicketEncryptionKey</env-entry-name> <env-entry-type>java.lang.String</env-entry-type> <env-entry-value>YOU MUST CHANGE THIS VALUE TO SOMETHING SECURE</env-entry-value> </env-entry> <env-entry> <env-entry-name>TicketSecret</env-entry-name> <env-entry-type>java.lang.String</env-entry-type> <env-entry-value>YOU MUST CHANGE THIS VALUE TO SOMETHING SECURE</env-entry-value> </env-entry> </web-app>
{ "content_hash": "8e26e7064bd235b69db8f7c589dd0eac", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 108, "avg_line_length": 44.8235294117647, "alnum_prop": 0.6745406824146981, "repo_name": "itlenergy/server-api", "id": "8830ab293948073a672246f44a8eb83cb085526c", "size": "762", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "itlenergy-web/src/main/webapp/WEB-INF/web.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "217" }, { "name": "Java", "bytes": "148499" }, { "name": "Shell", "bytes": "6972" } ], "symlink_target": "" }
@ECHO ON REM Starting to minify JS & CSS files ... @ECHO OFF REM don't watch the sausage being made REM the folder SET TOOLS=%~DP0 SET SRC=%TOOLS%\.. SET OUT=%TOOLS%\..\release rd /S /Q %OUT% md "%OUT%\" REM Combine JS & CSS files into one file type "%SRC%\vendor\shim.js" "%SRC%\vendor\Blob.js" "%SRC%\vendor\FileSaver.js" "%SRC%\vendor\Export2Excel.js" "%SRC%\vendor\xlsx.core.min.js" "%SRC%\common.js" "%SRC%\polyfill.js" "%SRC%\excel-app.js" > "%OUT%\app.js" type "%SRC%\style.css" > "%OUT%\app.css" REM Index Files copy "%SRC%\index_release.html" "%OUT%\index.html" copy "%SRC%\ProjectSubList.xlsx" "%OUT%\ProjectSubList.xlsx" copy "%SRC%\ProjectTracker.xlsx" "%OUT%\ProjectTracker.xlsx" @ECHO ON
{ "content_hash": "3ae8e930e8361a153a29871c9b115e48", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 217, "avg_line_length": 29.5, "alnum_prop": 0.6807909604519774, "repo_name": "hui-w/misc-fragment", "id": "d0bd43681e25e2bef680d8f2a1370d3f37bae26d", "size": "708", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javascript-excel/browser-version/build/build.bat", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1820" }, { "name": "CSS", "bytes": "28912" }, { "name": "HTML", "bytes": "137283" }, { "name": "JavaScript", "bytes": "456680" }, { "name": "PHP", "bytes": "475841" }, { "name": "Python", "bytes": "1466" } ], "symlink_target": "" }
import React, { PropTypes } from 'react'; import styles from './UnpublishedListingCardMeta.css'; const UnpublishedListingCardMeta = ({ meta, label }) => <div className={styles.cardMeta}> <span className={styles.meta}>{meta}</span> {(label && label.length > 0) ? <span className={styles.label}>{label}</span> : ""} </div>; UnpublishedListingCardMeta.propTypes = { meta: PropTypes.string.isRequired, label: PropTypes.string, }; export default UnpublishedListingCardMeta;
{ "content_hash": "0704b770ad66966b5fba8f0df6e22ec9", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 55, "avg_line_length": 29.41176470588235, "alnum_prop": 0.694, "repo_name": "radekzz/netlify-cms-test", "id": "fb4c23ad2e6a75b4972371834790407572c1d557", "size": "500", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/UnpublishedListing/UnpublishedListingCardMeta.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "43677" }, { "name": "HTML", "bytes": "76558" }, { "name": "JavaScript", "bytes": "341102" } ], "symlink_target": "" }
FROM ubuntu:latest ENV package grafana-1.9.1 RUN apt-get update RUN DEBIAN_FRONTEND=noninteractive apt-get install -y curl mini-httpd uuid-runtime RUN curl -s http://grafanarel.s3.amazonaws.com/$package.tar.gz | tar -xz --strip-components=1 -C /srv COPY config.js /srv/ RUN rm /srv/config.sample.js WORKDIR / LABEL \ com.opentable.sous.repo_url=https://github.com/opentable/docker-grafana.git \ com.opentable.sous.repo_offset= \ com.opentable.sous.version=0.0.17-maybeuseful \ com.opentable.sous.revision=91495f1b1630084e301241100ecf2e775f6b672c CMD mini-httpd -d /srv -p $PORT0 -D
{ "content_hash": "23a9d9dca14f9ce8bc6fa0ced5473c5b", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 101, "avg_line_length": 31.31578947368421, "alnum_prop": 0.7647058823529411, "repo_name": "nyarly/sous", "id": "d9101032ebc01e23e72c0a009f8d20ee9149e174", "size": "595", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "integration/grafana-labels/Dockerfile", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "635809" }, { "name": "JavaScript", "bytes": "13572" }, { "name": "Shell", "bytes": "46894" } ], "symlink_target": "" }
""" Created on Sat Apr 16 12:45:23 2016 @author: Perk """ import os import json from sklearn.feature_extraction.text import TfidfVectorizer tfidf = TfidfVectorizer(input='filename',stop_words='english', ngram_range=(1,5),max_features=50000) npr_dir = 'npr articles/npr articles/' npr = os.listdir(npr_dir) files = [] for txt in npr: files.append(npr_dir + txt) npr = [y.lstrip('npr_') for y in npr] npr = [y.rstrip('.txt') for y in npr] tfs = tfidf.fit_transform(files) feature_names = tfidf.get_feature_names() dense = tfs.todense() phrase_dict = {} for i in range(len(dense.tolist())): article = dense[i].tolist()[0] phrase_scores = [pair for pair in zip(range(0, len(article)),article) if pair[1]>0] sorted_phrase_scores = sorted(phrase_scores, key=lambda x: x[1], reverse=True) top_phrases = [feature_names[word_id] for (word_id,score) in sorted_phrase_scores][:10] phrase_dict[npr[i]] = top_phrases with open('top_article_phrases.json','w') as outfile: json.dump(phrase_dict,outfile)
{ "content_hash": "f0434e74d07b0ab2f0eadc9b01544151", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 68, "avg_line_length": 33.878787878787875, "alnum_prop": 0.6332737030411449, "repo_name": "perkinsbt/cse-6242", "id": "5991627fe3d4d9235647356ab25a0a3292448233", "size": "1143", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tfidf.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "14813" } ], "symlink_target": "" }
#include <folly/lang/ColdClass.h> #include <folly/portability/GTest.h> #include <type_traits> using folly::ColdClass; template <class TestClass> static void validateInheritedClass() { // The only verifiable property of ColdClass is that it must not disrupt the // default constructor/destructor, default copy/move constructors and default // copy/move assignment operators when a class derives from it. EXPECT_TRUE(std::is_nothrow_default_constructible<TestClass>::value); #if !defined(__GLIBCXX__) || __GNUC__ >= 5 EXPECT_TRUE(std::is_trivially_copy_constructible<TestClass>::value); EXPECT_TRUE(std::is_trivially_move_constructible<TestClass>::value); EXPECT_TRUE(std::is_trivially_copy_assignable<TestClass>::value); EXPECT_TRUE(std::is_trivially_move_assignable<TestClass>::value); #endif EXPECT_TRUE(std::is_nothrow_copy_constructible<TestClass>::value); EXPECT_TRUE(std::is_nothrow_move_constructible<TestClass>::value); EXPECT_TRUE(std::is_nothrow_copy_assignable<TestClass>::value); EXPECT_TRUE(std::is_nothrow_move_assignable<TestClass>::value); EXPECT_TRUE(std::is_trivially_destructible<TestClass>::value); } TEST(ColdClassTest, publicInheritance) { struct TestPublic : ColdClass {}; validateInheritedClass<TestPublic>(); } TEST(ColdClassTest, protectedInheritance) { // Same again, but protected inheritance. Should make no difference. class TestProtected : protected ColdClass {}; validateInheritedClass<TestProtected>(); } TEST(ColdClassTest, privateInheritance) { // Same again, but private inheritance. Should make no difference. class TestPrivate : ColdClass {}; validateInheritedClass<TestPrivate>(); }
{ "content_hash": "9e4ea3574863528e661f17dbb9bbddf2", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 79, "avg_line_length": 37.97727272727273, "alnum_prop": 0.760622381807301, "repo_name": "rklabs/folly", "id": "6d7b56e2090d6441acfa53d21fea070a81bc265f", "size": "2274", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "folly/lang/test/ColdClassTest.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "4324" }, { "name": "C", "bytes": "60105" }, { "name": "C++", "bytes": "8788694" }, { "name": "CMake", "bytes": "64027" }, { "name": "CSS", "bytes": "165" }, { "name": "M4", "bytes": "86030" }, { "name": "Makefile", "bytes": "37861" }, { "name": "Python", "bytes": "40677" }, { "name": "Ruby", "bytes": "1531" }, { "name": "Shell", "bytes": "8546" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Allarthonia bohlinii H. Magn. ### Remarks null
{ "content_hash": "750f5e51b2aaf1ac47ae71b2535e565c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 29, "avg_line_length": 10.307692307692308, "alnum_prop": 0.7014925373134329, "repo_name": "mdoering/backbone", "id": "3028fd812b64bcb70ccf7bb271d11cf16e304cbb", "size": "187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Arthoniomycetes/Arthoniales/Arthoniaceae/Allarthonia/Allarthonia bohlinii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace Skrz\Bundle\BunnyBundle\Tests\Command; use Bunny\Client; use Bunny\Message as BunnyMessage; use Skrz\Bundle\BunnyBundle\ContentTypes; use Skrz\Bundle\BunnyBundle\SkrzBunnyBundle; use Skrz\Bundle\BunnyBundle\Tests\Fixtures\Message; use Skrz\Bundle\BunnyBundle\Tests\Fixtures\Meta\MessageMeta; use Skrz\Bundle\BunnyBundle\Tests\Fixtures\TestKernel; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; class ProducerCommandTest extends \PHPUnit_Framework_TestCase { private function runWithConfig($config, $input) { $kernel = new TestKernel($config); $kernel->boot(); /** @var SkrzBunnyBundle $bundle */ $bundle = $kernel->getBundle("SkrzBunnyBundle"); $application = new Application($kernel); $bundle->registerCommands($application); $tester = new CommandTester($application->find("bunny:producer")); $tester->execute($input); return $kernel->getContainer(); } protected function setUp() { $client = new Client(); $client->connect(); $channel = $client->channel(); $channel->queueDelete("producer_test_queue"); $channel->exchangeDelete("producer_test_exchange"); $client->disconnect(); } protected function tearDown() { $this->setUp(); } public function testProducerWithJson() { $this->runWithConfig(__DIR__ . "/../Fixtures/producer.yml", [ "producer-name" => "JsonMessage", "message" => MessageMeta::toJson( (new Message()) ->setIntValue(234) ->setFloatValue(2.41) ->setStringValue("test") ) ]); $client = new Client(); $client->connect(); $channel = $client->channel(); /** @var BunnyMessage $msg */ $msg = $channel->get("producer_test_queue", true); $this->assertNotNull($msg); $this->assertEquals(ContentTypes::APPLICATION_JSON, $msg->getHeader("content-type")); $object = MessageMeta::fromJson($msg->content); $this->assertNotNull($object); $this->assertEquals(234, $object->getIntValue()); $this->assertEquals(2.41, $object->getFloatValue()); $this->assertEquals("test", $object->getStringValue()); } public function testProducerWithProtobuf() { $this->runWithConfig(__DIR__ . "/../Fixtures/producer.yml", [ "producer-name" => "ProtobufMessage", "message" => MessageMeta::toJson( (new Message()) ->setIntValue(234) ->setFloatValue(2.41) ->setStringValue("test") ) ]); $client = new Client(); $client->connect(); $channel = $client->channel(); /** @var BunnyMessage $msg */ $msg = $channel->get("producer_test_queue", true); $this->assertNotNull($msg); $this->assertEquals(ContentTypes::APPLICATION_PROTOBUF, $msg->getHeader("content-type")); $object = MessageMeta::fromProtobuf($msg->content); $this->assertNotNull($object); $this->assertEquals(234, $object->getIntValue()); $this->assertEquals(2.41, $object->getFloatValue()); $this->assertEquals("test", $object->getStringValue()); } public function testEmptyExchangeProducer() { $this->runWithConfig(__DIR__ . "/../Fixtures/producer.yml", [ "producer-name" => "EmptyExchange", "message" => MessageMeta::toJson( (new Message()) ->setIntValue(234) ->setFloatValue(2.41) ->setStringValue("test") ) ]); $client = new Client(); $client->connect(); $channel = $client->channel(); /** @var BunnyMessage $msg */ $msg = $channel->get("producer_test_queue", true); $this->assertNotNull($msg); $this->assertEquals(ContentTypes::APPLICATION_JSON, $msg->getHeader("content-type")); $object = MessageMeta::fromJson($msg->content); $this->assertNotNull($object); $this->assertEquals(234, $object->getIntValue()); $this->assertEquals(2.41, $object->getFloatValue()); $this->assertEquals("test", $object->getStringValue()); } }
{ "content_hash": "2c94170279423ff0f65473d44a72fa92", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 91, "avg_line_length": 28.32330827067669, "alnum_prop": 0.6795858773559862, "repo_name": "skrz/bunny-bundle", "id": "02c37e8b71c923b7ece9a78476d084c82463f140", "size": "3767", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tests/Command/ProducerCommandTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "72312" } ], "symlink_target": "" }
<div> <input type='text' ng-model='searchUser' /> <table border='1'> <tr ng-repeat="item in users | filter:searchUser"> <td ng-click='selectUser(item.username)'><i ng-if='item.gender=="male"' class='icon-man'></i><i ng-if='item.gender=="female"' class='icon-woman'></i><i ng-if='item.gender=="DESKTOP"' class='icon-laptop'></i>{{item.username}}</td> </tr> </table> </div>
{ "content_hash": "153e5015e3be945dadcdbb989f1ddb73", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 231, "avg_line_length": 41.888888888888886, "alnum_prop": 0.6445623342175066, "repo_name": "newlearnpro/learnpro", "id": "16bafd55ff5098184bc3fd541e9566cf0210ecbc", "size": "378", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "public/partials/templates/users_tmpl.html", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "749" }, { "name": "CSS", "bytes": "222857" }, { "name": "HTML", "bytes": "8278659" }, { "name": "JavaScript", "bytes": "212020" }, { "name": "PHP", "bytes": "2200678" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Mesa Release Notes</title> <link rel="stylesheet" type="text/css" href="../mesa.css"> </head> <body> <div class="header"> <h1>The Mesa 3D Graphics Library</h1> </div> <iframe src="../contents.html"></iframe> <div class="content"> <h1>Mesa 9.0.2 Release Notes / January 22th, 2013</h1> <p> Mesa 9.0.2 is a bug fix release which fixes bugs found since the 9.0.1 release. </p> <p> Mesa 9.0 implements the OpenGL 3.1 API, but the version reported by glGetString(GL_VERSION) or glGetIntegerv(GL_MAJOR_VERSION) / glGetIntegerv(GL_MINOR_VERSION) depends on the particular driver being used. Some drivers don't support all the features required in OpenGL 3.1. OpenGL 3.1 is <strong>only</strong> available if requested at context creation because GL_ARB_compatibility is not supported. </p> <h2>MD5 checksums</h2> <pre> 5ae216ca9fecfa349f14ecb83aa3f124 MesaLib-9.0.2.tar.gz dc45d1192203e418163e0017640e1cfc MesaLib-9.0.2.tar.bz2 93d40ec77d656dd04b561ba203ffbb91 MesaLib-9.0.2.zip </pre> <h2>New features</h2> <p>None.</p> <h2>Bug fixes</h2> <p>This list is likely incomplete.</p> <ul> <li><a href="https://bugs.freedesktop.org/show_bug.cgi?id=22576">Bug 22576</a> - [KMS] mesa demo spectex broken on rv280</li> <li><a href="https://bugs.freedesktop.org/show_bug.cgi?id=26809">Bug 26809</a> - KMS/R200: Bad shading in NWN since Mesa rewrite</li> <li><a href="https://bugs.freedesktop.org/show_bug.cgi?id=45877">Bug 45877</a> - [bisected regression] Oglc fbo(negative.invalidParams3) Segmentation fault</li> <li><a href="https://bugs.freedesktop.org/show_bug.cgi?id=54402">Bug 54402</a> - st_glsl_to_tgsi.cpp:4006:dst_register: Assertion `index &lt; VERT_RESULT_MAX' failed</li> <li><a href="https://bugs.freedesktop.org/show_bug.cgi?id=55175">Bug 55175</a> - Memoryleak with glPopAttrib only on Intel GM45</li> <li><a href="https://bugs.freedesktop.org/show_bug.cgi?id=56442">Bug 56442</a> - glcpp accepts junk after #else/#elif/#endif tokens</li> <li><a href="https://bugs.freedesktop.org/show_bug.cgi?id=56706">Bug 56706</a> - EGL sets error to EGL_SUCCESS when DRI driver fails to create context</li> <li><a href="https://bugs.freedesktop.org/show_bug.cgi?id=57622">Bug 57622</a> - Webgl conformance shader-with-non-reserved-words crash.</li> <li><a href="https://bugs.freedesktop.org/show_bug.cgi?id=57842">Bug 57842</a> - r200: Culling is broken when rendering to an FBO</li> <li><a href="https://bugs.freedesktop.org/show_bug.cgi?id=57984">Bug 57984</a> - r300g: blend sfactor=GL_DST_COLOR fails with FBOs</li> <li><a href="https://bugs.freedesktop.org/show_bug.cgi?id=58545">Bug 58545</a> - [llvmpipe] src/gallium/auxiliary/gallivm/lp_bld_tgsi_info.c:75:analyse_src: Assertion `src-&gt;Index &lt; (sizeof(ctx-&gt;imm)/sizeof((ctx-&gt;imm)[0]))' failed.</li> <li><a href="https://bugs.freedesktop.org/show_bug.cgi?id=59383">Bug 59383</a> - src/glsl/tests/Makefile.am missing $(top_srcdir)/include</li> <!-- <li><a href="https://bugs.freedesktop.org/show_bug.cgi?id=">Bug </a> - </li> --> </ul> <h2>Changes</h2> <p>The full set of changes can be viewed by using the following GIT command:</p> <pre> git log mesa-9.0.1..mesa-9.0.2 </pre> <p>Abdiel Janulgue (1):</p> <ul> <li>mesa: Fix a crash in update_texture_state() for external texture type</li> </ul> <p>Adam Jackson (4):</p> <ul> <li>glcpp: Fix visibility CFLAGS in automake</li> <li>glcpp: Typo fix.</li> <li>galahad, noop: Fix visibility CFLAGS in automake</li> <li>r300g: Fix visibility CFLAGS in automake</li> </ul> <p>Alex Deucher (2):</p> <ul> <li>radeonsi: add some new SI pci ids</li> <li>radeonsi: add a new SI pci id</li> </ul> <p>Ander Conselvan de Oliveira (2):</p> <ul> <li>egl/wayland: Don't invalidate drawable on swap buffers</li> <li>egl/wayland: Dispatch the event queue before get_buffers</li> <li>egl/wayland: Destroy the pending buffer callback with the egl surface</li> </ul> <p>Andreas Boll (9):</p> <ul> <li>docs: fix release date of 9.0.1</li> <li>docs: add news item for 9.0.1 release</li> <li>Add .dirstamp to toplevel .gitignore</li> <li>build: use git ls-files for adding all Makefile.in into the release tarball</li> <li>build: Fix GLES linkage without libglapi</li> <li>Revert "r600g: try to fix streamout for the cases where BURST_COUNT &gt; 0"</li> <li>mesa: update .cherry-ignore list</li> <li>mesa: Bump version to 9.0.2</li> <li>docs: Add 9.0.2 release notes</li> </ul> <p>Anuj Phogat (2):</p> <ul> <li>mesa: Generate invalid operation in glGenerateMipMap for integer textures</li> <li>meta: Remove redundant code in _mesa_meta_GenerateMipmap</li> </ul> <p>Ben Skeggs (3):</p> <ul> <li>nvc0: fix missing permanent bo reference on poly cache</li> <li>nvc0: point vertex runout at a valid address</li> <li>nv50: point vertex runout at a valid address</li> </ul> <p>Brian Paul (5):</p> <ul> <li>svga: don't use uninitialized framebuffer state</li> <li>st/mesa: replace REALLOC() with realloc()</li> <li>st/mesa: free TGSI tokens with ureg_free_tokens()</li> <li>util: added pipe_surface_release() function</li> <li>gallivm: support more immediates in lp_build_tgsi_info()</li> </ul> <p>Bryan Cain (1):</p> <ul> <li>glsl_to_tgsi: set correct register type for array and structure elements</li> </ul> <p>Chad Versace (2):</p> <ul> <li>i965: Validate requested GLES context version in brwCreateContext</li> <li>egl/dri2: Set error code when dri2CreateContextAttribs fails</li> </ul> <p>Chris Fester (1):</p> <ul> <li>util: null-out the node's prev/next pointers in list_del()</li> </ul> <p>Christoph Bumiller (5):</p> <ul> <li>nv50/ir/tgsi: fix srcMask for TXP with SHADOW1D</li> <li>nvc0: add missing call to map edge flag in push_vbo</li> <li>nv50/ir: wrap assertion using typeid in #ifndef NDEBUG</li> <li>nouveau: fix undefined behaviour when testing sample_count</li> <li>nv50/ir: restore use of long immediate encodings</li> </ul> <p>Dave Airlie (5):</p> <ul> <li>r600g: fix lod bias/explicit lod with cube maps.</li> <li>glsl_to_tgsi: fix dst register for texturing fetches.</li> <li>glsl: fix cut-n-paste error in error handling. (v2)</li> <li>glsl: initialise killed_all field.</li> <li>glsl: fix uninitialised variable from constructor</li> </ul> <p>Eric Anholt (4):</p> <ul> <li>mesa: Fix the core GL genned-name handling for glBindBufferBase()/Range().</li> <li>mesa: Fix core GL genned-name handling for glBeginQuery().</li> <li>mesa: Fix segfault on reading from a missing color read buffer.</li> <li>i965/gen4: Fix memory leak each time compile_gs_prog() is called.</li> </ul> <p>Ian Romanick (2):</p> <ul> <li>docs: Add 9.0.1 release md5sums</li> <li>glsl: Don't add structure fields to the symbol table</li> </ul> <p>Johannes Obermayr (4):</p> <ul> <li>clover: Install CL headers.</li> <li>gallium/auxiliary: Add -fno-rtti to CXXFLAGS on LLVM &gt;= 3.2.</li> <li>clover: Adapt libclc's INCLUDEDIR and LIBEXECDIR to make use of the new introduced libclc.pc.</li> <li>tests: AM_CPPFLAGS must include $(top_srcdir) instead of $(top_builddir).</li> </ul> <p>Jonas Ådahl (1):</p> <ul> <li>wayland: Don't cancel a roundtrip when any event is received</li> </ul> <p>José Fonseca (1):</p> <ul> <li>llvmpipe: Obey back writemask.</li> </ul> <p>Kenneth Graunke (8):</p> <ul> <li>i965/vs: Fix unit mismatch in scratch base_offset parameter.</li> <li>i965/vs: Implement register spilling.</li> <li>mesa: Don't flatten IF statements by default.</li> <li>glcpp: Don't use infinite lookhead for #define differentiation.</li> <li>i965/vs: Don't lose the MRF writemask when doing compute-to-MRF.</li> <li>i965/vs: Preserve the type when copy propagating into an instruction.</li> <li>mesa: Fix glGetVertexAttribI[u]iv now that we have real integer attribs.</li> <li>i965: Fix AA Line Distance Mode in 3DSTATE_SF on Ivybridge.</li> </ul> <p>Kristian Høgsberg (1):</p> <ul> <li>egl/wayland: Add invalidate back in eglSwapBuffers()</li> </ul> <p>Maarten Lankhorst (2):</p> <ul> <li>makefiles: use configured name for -ldrm* where possible</li> <li>automake: strip LLVM_CXXFLAGS and LLVM_CPPFLAGS too</li> </ul> <p>Marek Olšák (17):</p> <ul> <li>st/mesa: fix integer texture border color for some formats (v2)</li> <li>r300g: fix texture border color for sRGB formats</li> <li>mesa: bump MAX_VARYING to 32</li> <li>draw: fix assertion failure in draw_emit_vertex_attr</li> <li>vbo: fix glVertexAttribI* functions</li> <li>mesa: add MaxNumLevels to gl_texture_image, remove MaxLog2</li> <li>mesa: fix error checking of TexStorage(levels) for array and rect textures</li> <li>st/mesa: fix guessing the base level size</li> <li>st/mesa: fix computation of last_level during texture creation</li> <li>st/mesa: fix computation of last_level in GenerateMipmap</li> <li>r600g: fix streamout on RS780 and RS880</li> <li>r600g: advertise 32 streamout vec4 outputs</li> <li>r600g: fix broken streamout if streamout_begin caused a context flush</li> <li>mesa: fix BlitFramebuffer between linear and sRGB formats</li> <li>r600g: try to fix streamout for the cases where BURST_COUNT &gt; 0</li> <li>r600g: always use a tiled resource as the destination of MSAA resolve</li> <li>mesa: add MaxNumLevels to gl_texture_image, remove MaxLog2</li> </ul> <p>Mario Kleiner (1):</p> <ul> <li>mesa: Don't glPopAttrib() GL_POINT_SPRITE_COORD_ORIGIN on &lt; OpenGL-2.0</li> </ul> <p>Matt Turner (1):</p> <ul> <li>glcpp: Reject garbage after #else and #endif tokens</li> </ul> <p>Stefan Dösinger (1):</p> <ul> <li>r300: Don't disable destination read if the src blend factor needs it</li> </ul> <p>Tapani Pälli (1):</p> <ul> <li>android: generate matching remap_helper to dispatch table</li> </ul> <p>Tom Stellard (1):</p> <ul> <li>r600g: Use LOOP_START_DX10 for loops</li> </ul> <p>Vinson Lee (1):</p> <ul> <li>i915: Fix wrong sizeof argument in i915_update_tex_unit.</li> </ul> <p>smoki (2):</p> <ul> <li>r200: fix broken tcl lighting</li> <li>radeon/r200: Fix tcl culling</li> </ul> </div> </body> </html>
{ "content_hash": "44de775782c2a7fa586c3497a179e242", "timestamp": "", "source": "github", "line_count": 290, "max_line_length": 247, "avg_line_length": 35.55862068965517, "alnum_prop": 0.6956943366951125, "repo_name": "devlato/kolibrios-llvm", "id": "affc23d8bd9000801dfdcba122c8fd06de73e4da", "size": "10319", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "contrib/sdk/sources/Mesa/docs/relnotes/9.0.2.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "15418643" }, { "name": "C", "bytes": "126021466" }, { "name": "C++", "bytes": "11476220" }, { "name": "CSS", "bytes": "1230161" }, { "name": "JavaScript", "bytes": "687" }, { "name": "Logos", "bytes": "905" }, { "name": "Lua", "bytes": "2055" }, { "name": "Objective-C", "bytes": "482461" }, { "name": "Pascal", "bytes": "6692" }, { "name": "Perl", "bytes": "317449" }, { "name": "Puppet", "bytes": "161697" }, { "name": "Python", "bytes": "1036533" }, { "name": "Shell", "bytes": "448869" }, { "name": "Verilog", "bytes": "2829" }, { "name": "Visual Basic", "bytes": "4346" }, { "name": "XSLT", "bytes": "4325" } ], "symlink_target": "" }
<template name="Loading"> <div class="spinner"> <div class="bounce1"></div> <div class="bounce2"></div> <div class="bounce3"></div> </div> </template>
{ "content_hash": "1fbe39bde690ea4e30ca454547e6c2f4", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 35, "avg_line_length": 26.142857142857142, "alnum_prop": 0.5409836065573771, "repo_name": "npvn/meteor-url-shortener", "id": "7e096f1b5a57085f4a4014b1ce7065ff26a8cafe", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/views/loading/loading.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "604" }, { "name": "HTML", "bytes": "8993" }, { "name": "JavaScript", "bytes": "49627" } ], "symlink_target": "" }
"use strict"; var fluid = fluid || require("infusion"); var path = require("path"); require("gpii-express"); require("gpii-handlebars"); require("../../node_modules/gpii-pouch/src/js/pouch"); require("gpii-mail-test"); require("../../src/js/server"); // We use just the request-handling bits of the kettle stack in our tests, but we include the whole thing to pick up the base grades require("../../node_modules/kettle"); require("../../node_modules/kettle/lib/test/KettleTestUtils"); fluid.registerNamespace("gpii.express.couchuser.tests.server.environment"); var bowerDir = path.resolve(__dirname, "../../../bower_components"); var jsDir = path.resolve(__dirname, "../../js"); var mailTemplateDir = path.resolve(__dirname, "../templates"); var modulesDir = path.resolve(__dirname, "../../../node_modules"); //var userDataFile = path.resolve(__dirname, "../data/users/users.json"); var viewDir = path.resolve(__dirname, "../views"); fluid.defaults("gpii.express.couchuser.tests.server.environment", { gradeNames: ["fluid.test.testEnvironment", "autoInit"], port: 7532, baseUrl: "http://localhost/", components: { express: { type: "gpii.express", createOnEvent: "constructServer", options: { listeners: { onStarted: "{testEnvironment}.events.expressStarted.fire" }, config: { express: { port : "{testEnvironment}.options.port", baseUrl: "{testEnvironment}.options.baseUrl", views: viewDir, session: { secret: "Printer, printer take a hint-ter." } }, app: { name: "GPII Express Couchuser Test Server", url: "{testEnvironment}.options.baseUrl" }, users: "http://localhost:5984/_users", // Use Couchdb for now request_defaults: { auth: { user: "admin", pass: "admin" } }, email: { from: "no-reply@ul.gpii.net", service: "SMTP", SMTP: { host: "localhost", port: 4029 }, templateDir: mailTemplateDir }, verify: true, safeUserFields: "name email displayName", adminRoles: [ "admin"] }, components: { json: { type: "gpii.express.middleware.bodyparser.json" }, urlencoded: { type: "gpii.express.middleware.bodyparser.urlencoded" }, cookieparser: { type: "gpii.express.middleware.cookieparser" }, session: { type: "gpii.express.middleware.session" }, user: { type: "gpii.express.couchuser.server" }, modules: { type: "gpii.express.router.static", options: { path: "/modules", content: modulesDir } }, js: { type: "gpii.express.router.static", options: { path: "/js", content: jsDir } }, bc: { type: "gpii.express.router.static", options: { path: "/bc", content: bowerDir } }, handlebars: { type: "gpii.express.hb" }, content: { type: "gpii.express.hb.dispatcher", options: { path: "/content/:template" } }, inline: { type: "gpii.express.hb.inline", options: { path: "/hbs" } } } } }, // TODO: Reenable once we get pouch working with express-couchuser //pouch: { // type: "gpii.express", // options: { // listeners: { // "onStarted": "{testEnvironment}.events.pouchStarted.fire" // }, // config: { // express: { // "port" : 7534, // baseUrl: "http://localhost:7534/" // }, // app: { // name: "Pouch Test Server", // url: "http://localhost:7534/" // } // }, // components: { // pouch: { // type: "gpii.pouch", // options: { // path: "/", // model: { // databases: { // _users: { // data: userDataFile // } // } // } // } // } // } // } //}, smtp: { type: "gpii.test.mail.smtp", createOnEvent: "constructServer", options: { listeners: { "ready": "{testEnvironment}.events.smtpReady.fire" }, port: 4029 } }, testCaseHolder: { type: "gpii.express.couchuser.test.server.caseHolder" } }, events: { constructServer: null, messageReceived: null, expressStarted: null, pouchStarted: null, smtpReady: null, onReady: { events: { expressStarted: "expressStarted", // TODO: Reenable once we get pouch working... //pouchStarted: "{pouch}.events.onStarted", smtpReady: "smtpReady" } } } });
{ "content_hash": "04951c4830d1c661f4315e3b0f19c851", "timestamp": "", "source": "github", "line_count": 190, "max_line_length": 132, "avg_line_length": 36.584210526315786, "alnum_prop": 0.36627823334771975, "repo_name": "the-t-in-rtf/gpii-express-couchuser", "id": "01f83d80b1224aad15c668803207cc6a23a8b785", "size": "7062", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/js/server-test-environment.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2436" }, { "name": "Handlebars", "bytes": "15601" }, { "name": "JavaScript", "bytes": "114144" } ], "symlink_target": "" }
include "shared.lua" DEFINE_BASECLASS( "mp_service_browser" ) local JS_SetVolume = "if(window.MediaPlayer) MediaPlayer.setVolume(%s);" local JS_Seek = "if(window.MediaPlayer) MediaPlayer.seek(%s);" local function VimeoSetVolume( self ) if not self.Browser then return end local js = JS_SetVolume:format( MediaPlayer.Volume() ) self.Browser:RunJavascript(js) end local function VimeoSeek( self, seekTime ) if not self.Browser then return end local js = JS_Seek:format( seekTime ) self.Browser:RunJavascript(js) end function SERVICE:SetVolume( volume ) VimeoSetVolume( self ) end function SERVICE:OnBrowserReady( browser ) BaseClass.OnBrowserReady( self, browser ) local videoId = self:GetVimeoVideoId() -- local url = VimeoVideoUrl:format( videoId ) -- browser:OpenURL( url ) -- browser:QueueJavascript( JS_Init ) -- local html = EmbedHTML:format( videoId ) -- html = self.WrapHTML( html ) -- browser:SetHTML( html ) local url = "http://localhost/vimeo.html#" .. videoId browser:OpenURL( url ) end function SERVICE:Sync() local seekTime = self:CurrentTime() if seekTime > 0 then VimeoSeek( self, seekTime ) end end
{ "content_hash": "f3004eeb75ae87b053c5c66954e47fa5", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 72, "avg_line_length": 23.46938775510204, "alnum_prop": 0.7339130434782609, "repo_name": "pixeltailgames/gm-mediaplayer", "id": "c3f0baf2c4a11545a306eaa9f20611c8c4518268", "size": "1150", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lua/mediaplayer/services/vimeo/cl_init.lua", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2803" }, { "name": "HTML", "bytes": "10332" }, { "name": "JavaScript", "bytes": "11708" }, { "name": "Lua", "bytes": "275301" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "e0f5a81bd31e11f8703d40758e10312a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "35d5ed8df363054ae0e1fc810de042d695b54dbc", "size": "217", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Cotoneaster/Cotoneaster melanocarpus/Cotoneaster melanocarpus daghestanicus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>put.ci</groupId> <artifactId>cevo</artifactId> <version>1.0</version> </parent> <artifactId>cevo-utils</artifactId> <repositories> <repository> <id>edwardraff-repo</id> <url>http://www.edwardraff.com/maven-repo/</url> </repository> </repositories> <dependencies> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.reflections</groupId> <artifactId>reflections</artifactId> <version>0.9.9-RC2</version> </dependency> <dependency> <groupId>junit-addons</groupId> <artifactId>junit-addons</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>com.carrotsearch</groupId> <artifactId>junit-benchmarks</artifactId> <version>0.5.0</version> <scope>test</scope> </dependency> <dependency> <groupId>jsat</groupId> <artifactId>jsat</artifactId> <version>r932</version> </dependency> </dependencies> </project>
{ "content_hash": "cd9c0f1fd8ba84c983a68c301ce62b77", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 104, "avg_line_length": 30.73076923076923, "alnum_prop": 0.6276595744680851, "repo_name": "pliskowski/ECJ-2015", "id": "fc421ab9b73c5f5c765c1319356d35d3add95d46", "size": "1598", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cevo-utils/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1272" }, { "name": "Java", "bytes": "862698" } ], "symlink_target": "" }
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.gs.toast" > <application android:allowBackup="true" android:label="@string/app_name" android:supportsRtl="true" > </application> </manifest>
{ "content_hash": "fa14a9dedcb8f8fb897c0a0d1f41a012", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 68, "avg_line_length": 24.166666666666668, "alnum_prop": 0.6103448275862069, "repo_name": "gslovemy/ToastCompat", "id": "3e2a2f81df3abb7f9cc0fc1ae07c6f0d3a25320d", "size": "290", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/src/main/AndroidManifest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "14262" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset=utf-8> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="description" content="A browser based contact application with IndexedDB" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" href="data:,"> <title>Simple Contacts | IndexedDB powered browser based contacts manager</title> </head> <body> <section class="section"> <div class="container"> <header> <h2 class="title">IndexedDB Powered Contact Manager</h2> <div class="field is-grouped is-grouped-multiline"> <div class="control"> <div class="tags has-addons"> <span class="tag">Version</span> <span class="tag is-warning">3.0.0</span> </div> </div> </div> <hr /> </header> <div id="app"></div> <footer class="footer"> <div class="content"> <p> Made with <span class="icon has-text-danger" style="vertical-align: middle;"> <span class="icon"><i class="fas fa-heart"></i></span> </span> by <a href="//shibbir.io" target="_blank">Shibbir Ahmed.</a> The source code is licensed under <a href="http://opensource.org/licenses/mit-license.php" target="_blank">MIT</a>. </p> <p>Made with <strong>IndexedDB</strong>, <strong>Vue</strong>, <strong>Bulma</strong>, <strong>Rollup</strong>.</p> <div class="field has-addons"> <p class="control"> <a href="https://github.com/shibbir/simple-contacts" target="_blank" class="button"> <span class="icon"><i class="fab fa-github"></i></span> <span>GitHub</span> </a> </p> </div> </div> </footer> </div> </section> </body> </html>
{ "content_hash": "ef0c75126736bda6cf1732cae4794c05", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 135, "avg_line_length": 38.47540983606557, "alnum_prop": 0.4486578610992757, "repo_name": "shibbir/SimpleContactManager", "id": "ae02c050b1b9344395bb8946462c52014506efc2", "size": "2347", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2250" }, { "name": "HTML", "bytes": "12049" }, { "name": "JavaScript", "bytes": "10457" } ], "symlink_target": "" }
var timesince = function timeSince(selector) { var templates = { prefix: "", future: "", suffix: " ago.", seconds: "Less than a minute", minute: "About a minute", minutes: "%d minutes", hour: "About an hour", hours: "About %d hours", day: "One day", days: "%d days", month: "About a month", months: "%d months", year: "About a year", years: "%d years" }; var template = function(t, n) { return templates[t] && templates[t].replace(/%d/i, Math.abs(Math.round(n))); }; var timer = function(time) { if (!time) return; time = parseInt(time) * 1000; // Change to milliseconds time = new Date(time); var now = new Date(); var seconds = ((now.getTime() - time) * .001) >> 0; var minutes = seconds / 60; var hours = minutes / 60; var days = hours / 24; var years = days / 365; return templates.prefix + ( seconds < 0 && template('future') || seconds < 45 && template('seconds', seconds) || seconds < 90 && template('minute', 1) || minutes < 45 && template('minutes', minutes) || minutes < 90 && template('hour', 1) || hours < 24 && template('hours', hours) || hours < 42 && template('day', 1) || days < 30 && template('days', days) || days < 45 && template('month', 1) || days < 365 && template('months', days / 30) || years < 1.5 && template('year', 1) || template('years', years) ) + (seconds < 0 && "" || templates.suffix); }; var elements = document.getElementsByClassName('timesince'); for (var i in elements) { var $this = elements[i]; if (typeof $this === 'object') { $this.innerHTML = timer($this.dataset.timesince || $this.dataset.timesince); } } // update time every minute setTimeout(timesince, 60000); };
{ "content_hash": "26d69c95316b9f1c3948c743cd65d406", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 88, "avg_line_length": 35.21666666666667, "alnum_prop": 0.4841457643161382, "repo_name": "Reedyn/timeSince.js", "id": "ba261025b10f02d072dd9b063b7065cce0b0cba4", "size": "2113", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "timeSince.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2113" } ], "symlink_target": "" }
.class public abstract Lnet/sqlcipher/IContentObserver$Stub; .super Landroid/os/Binder; .source "IContentObserver.java" # interfaces .implements Lnet/sqlcipher/IContentObserver; # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Lnet/sqlcipher/IContentObserver; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x409 name = "Stub" .end annotation .annotation system Ldalvik/annotation/MemberClasses; value = { Lnet/sqlcipher/IContentObserver$Stub$Proxy; } .end annotation # static fields .field private static final DESCRIPTOR:Ljava/lang/String; = "net.sqlcipher.IContentObserver" .field static final TRANSACTION_onChange:I = 0x1 # direct methods .method public constructor <init>()V .locals 1 .prologue .line 17 invoke-direct {p0}, Landroid/os/Binder;-><init>()V .line 18 const-string v0, "net.sqlcipher.IContentObserver" invoke-virtual {p0, p0, v0}, Lnet/sqlcipher/IContentObserver$Stub;->attachInterface(Landroid/os/IInterface;Ljava/lang/String;)V .line 19 return-void .end method .method public static asInterface(Landroid/os/IBinder;)Lnet/sqlcipher/IContentObserver; .locals 2 .param p0, "obj" # Landroid/os/IBinder; .prologue .line 26 if-nez p0, :cond_0 .line 27 const/4 v0, 0x0 .line 33 :goto_0 return-object v0 .line 29 :cond_0 const-string v1, "net.sqlcipher.IContentObserver" invoke-interface {p0, v1}, Landroid/os/IBinder;->queryLocalInterface(Ljava/lang/String;)Landroid/os/IInterface; move-result-object v0 .line 30 .local v0, "iin":Landroid/os/IInterface; if-eqz v0, :cond_1 instance-of v1, v0, Lnet/sqlcipher/IContentObserver; if-eqz v1, :cond_1 .line 31 check-cast v0, Lnet/sqlcipher/IContentObserver; goto :goto_0 .line 33 :cond_1 new-instance v0, Lnet/sqlcipher/IContentObserver$Stub$Proxy; .end local v0 # "iin":Landroid/os/IInterface; invoke-direct {v0, p0}, Lnet/sqlcipher/IContentObserver$Stub$Proxy;-><init>(Landroid/os/IBinder;)V goto :goto_0 .end method # virtual methods .method public asBinder()Landroid/os/IBinder; .locals 0 .prologue .line 37 return-object p0 .end method .method public onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z .locals 3 .param p1, "code" # I .param p2, "data" # Landroid/os/Parcel; .param p3, "reply" # Landroid/os/Parcel; .param p4, "flags" # I .annotation system Ldalvik/annotation/Throws; value = { Landroid/os/RemoteException; } .end annotation .prologue const/4 v1, 0x1 .line 41 sparse-switch p1, :sswitch_data_0 .line 57 invoke-super {p0, p1, p2, p3, p4}, Landroid/os/Binder;->onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z move-result v1 :goto_0 return v1 .line 45 :sswitch_0 const-string v2, "net.sqlcipher.IContentObserver" invoke-virtual {p3, v2}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V goto :goto_0 .line 50 :sswitch_1 const-string v2, "net.sqlcipher.IContentObserver" invoke-virtual {p2, v2}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V .line 52 invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I move-result v2 if-eqz v2, :cond_0 move v0, v1 .line 53 .local v0, "_arg0":Z :goto_1 invoke-virtual {p0, v0}, Lnet/sqlcipher/IContentObserver$Stub;->onChange(Z)V goto :goto_0 .line 52 .end local v0 # "_arg0":Z :cond_0 const/4 v0, 0x0 goto :goto_1 .line 41 nop :sswitch_data_0 .sparse-switch 0x1 -> :sswitch_1 0x5f4e5446 -> :sswitch_0 .end sparse-switch .end method
{ "content_hash": "23577a09fb69fa2be278f1ff12940028", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 131, "avg_line_length": 22.71590909090909, "alnum_prop": 0.6373186593296648, "repo_name": "x5y/SparkNZ-Xposed", "id": "872e33951394d163aebc5a2b81d84dd1fab1a6b1", "size": "3998", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TelecomApp_Decompiled/smali/net/sqlcipher/IContentObserver$Stub.smali", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2972" } ], "symlink_target": "" }
<div ng-controller="LotteryCtrl"> <nav class="breadcrumb"> <a href="#/bowlers">Switch to Bowlers View</a> <ul> <li><a href="#/leagues">Leagues</a></li> <li><span>&nbsp;&#10148;&nbsp;</span></li> <li><a ng-href="#/leagues/{{leagueId}}">League</a></li> <li><span>&nbsp;&#10148;&nbsp;</span></li> <li><a ng-href="#/leagues/{{leagueId}}/lotteries/{{lotteryId}}">Lottery</a></li> </ul> </nav> <h4>Tickets for Lottery <span class="featured">{{lotteryId}}</span></h4> <div class="loading" ng-show="dataLoading">LOADING<span>.</span><span>.</span><span>.</span></div> <table> <thead> <th class="index">Ticket #</th> <th class="index">Bowler ID</th> <th class="string">Bowler Name</th> </thead> <tbody> <tr ng-repeat="ticket in tickets"> <td ng-class="{winner: ticket.is_winner}" class="index">{{ticket.id}}</td> <td ng-class="{winner: ticket.is_winner}" class="index">{{ticket.bowler_id}}</td> <td ng-class="{winner: ticket.is_winner}" class="string">{{ticket.bowler_name}}</td> </tr> </tbody> </table> <h4>Tickets sold: <span class="featured">{{numTickets}}</span>&nbsp;&nbsp;&nbsp; Jackpot: <span class="featured">{{jackpot | currency}}</span></h4> <div class="lucky"> <div ng-show="showPayout">Payout: <span class="featured">{{payout | currency}}</span></div> <div ng-hide="showPayout" ng-cloak class="select" ng-class="{pressedSelect: hover}" ng-mouseenter="hover=true" ng-mouseleave="hover=false" ng-click=select()>{{buttonText}}</div> </div> </div>
{ "content_hash": "4c8a623aeae5452b909a0cec7822251b", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 102, "avg_line_length": 43.86842105263158, "alnum_prop": 0.5752849430113978, "repo_name": "davidlhayes/lucky-strike", "id": "d0967dcf9c814f9cc08334ddd44330b95aca6605", "size": "1667", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/lottery/lottery.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13565" }, { "name": "HTML", "bytes": "13975" }, { "name": "JavaScript", "bytes": "25034" } ], "symlink_target": "" }
'use strict'; var DoQmentDB = require('..'); var CONFIG = require('../config'); var connection = new (require('documentdb').DocumentClient)(CONFIG.HOST, CONFIG.OPTIONS); var db = new DoQmentDB(connection, CONFIG.DB); var users = db.use('users'); // The order is important // create/save its the same thing users.pre('save', function(next) { var doc = this; console.log('doc', 1); next(); }, function(next) { // some async thing console.log(2); setTimeout(next, 3000); }); // one more.. users.pre('create', function(next) { console.log(3); next(); }); users.post('save', function(doc) { console.log(doc._self); }, function(doc) { // ... }); users.create({ name: 'Ariel', age: 26 }) .then(console.log);
{ "content_hash": "9e866a3f786ea3ddb1305ce4ebe3d41b", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 89, "avg_line_length": 21.558823529411764, "alnum_prop": 0.6316507503410641, "repo_name": "phfsantos/doqmentdb", "id": "a770a7e4eed6cf8f6f734f7557499458770ff2ee", "size": "733", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "example/index.js", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "113527" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Wed Jan 16 10:54:26 MST 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.wildfly.swarm.jaxrs.validator.detect.ValidatorPackageDetector (BOM: * : All 2.3.0.Final-SNAPSHOT API)</title> <meta name="date" content="2019-01-16"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.wildfly.swarm.jaxrs.validator.detect.ValidatorPackageDetector (BOM: * : All 2.3.0.Final-SNAPSHOT API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/wildfly/swarm/jaxrs/validator/detect/ValidatorPackageDetector.html" title="class in org.wildfly.swarm.jaxrs.validator.detect">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.3.0.Final-SNAPSHOT</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/wildfly/swarm/jaxrs/validator/detect/class-use/ValidatorPackageDetector.html" target="_top">Frames</a></li> <li><a href="ValidatorPackageDetector.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.wildfly.swarm.jaxrs.validator.detect.ValidatorPackageDetector" class="title">Uses of Class<br>org.wildfly.swarm.jaxrs.validator.detect.ValidatorPackageDetector</h2> </div> <div class="classUseContainer">No usage of org.wildfly.swarm.jaxrs.validator.detect.ValidatorPackageDetector</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/wildfly/swarm/jaxrs/validator/detect/ValidatorPackageDetector.html" title="class in org.wildfly.swarm.jaxrs.validator.detect">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.3.0.Final-SNAPSHOT</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/wildfly/swarm/jaxrs/validator/detect/class-use/ValidatorPackageDetector.html" target="_top">Frames</a></li> <li><a href="ValidatorPackageDetector.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "14f1e451f83e9ff8e7ec346594457b00", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 193, "avg_line_length": 40.890625, "alnum_prop": 0.6207489491784486, "repo_name": "wildfly-swarm/wildfly-swarm-javadocs", "id": "7737218e5fcaff58136b972aeda9bf8f132fd89d", "size": "5234", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2.3.0.Final-SNAPSHOT/apidocs/org/wildfly/swarm/jaxrs/validator/detect/class-use/ValidatorPackageDetector.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- ~ Copyright (c) 2018 Citrus-CAF Project ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. ~ --> <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="?android:attr/colorAccent"> <path android:pathData="M23 12A11 11 0 0 1 12 23 11 11 0 0 1 1 12 11 11 0 0 1 12 1 11 11 0 0 1 23 12Z" android:strokeWidth="1" android:strokeLineJoin="round" android:strokeColor="#ffffff" android:strokeMiterLimit="1.5" android:strokeLineCap="round" /> <path android:pathData="M21 12a9 9 0 0 1 -9 9 9 9 0 0 1 -9 -9 9 9 0 0 1 9 -9 9 9 0 0 1 9 9z" android:fillType="evenOdd" android:fillColor="#4dffffff" android:strokeLineJoin="round" android:strokeMiterLimit="1.5" android:strokeLineCap="round" /> <path android:pathData="M7.824 16.176l3.722 -3.722" android:strokeWidth="1" android:strokeLineJoin="round" android:strokeColor="#ffffff" android:strokeMiterLimit="1.5" android:strokeLineCap="round" /> <path android:pathData="M9.548 10.116l4.336 4.336" android:strokeWidth="1" android:strokeLineJoin="round" android:strokeColor="#ffffff" android:strokeMiterLimit="1.5" android:strokeLineCap="round" /> <path android:pathData="M15.876 10.544c0.4 -0.401 0.4 -1.051 0 -1.452L14.908 8.124c-0.401 -0.4 -1.051 -0.4 -1.452 0l-2.737 2.737 2.42 2.42 2.737 -2.737z" android:fillType="evenOdd" android:fillColor="#ffffff" android:strokeLineJoin="round" android:strokeMiterLimit="1.5" android:strokeLineCap="round" /> </vector>
{ "content_hash": "6121060470ba9b038b29afcd5bcc6098", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 155, "avg_line_length": 39.114754098360656, "alnum_prop": 0.6437552388935457, "repo_name": "Citrus-CAF/packages_apps_Margarita", "id": "6e3b6f75fec7e1743a1aa05435f9c2be9ffcc7cd", "size": "2386", "binary": false, "copies": "1", "ref": "refs/heads/p9x-exp", "path": "app/src/main/assets/overlays/org.telegram.messenger/type3-common/drawable-anydpi/chats_pin.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "10218" }, { "name": "Kotlin", "bytes": "16507" }, { "name": "Shell", "bytes": "2251" } ], "symlink_target": "" }
{% extends "commerce/base.html" %} {% load static %} {% load commerce_extras %} {% block title %} Item Detail - {{ item_info.name }} {% endblock %} {% block content %} <h1 class="{{ item_info.rarity|lower }}">{{ item_info.name }}</h1> <dl class="dl-horizontal"> <dt>Item ID:</dt><dd>{{ item_info.item_id }}</dd> <dt>Icon:</dt><dd><img src="{% static commerce %}commerce/items/{{ item_info.icon.static_id }}" height="35" width="35" alt="item icon" /></dd> <dt>Chat Link:</dt><dd>{{ item_info.chat_link }}</dd> <dt>Description:</dt><dd>{{ item_info.description }}</dd> <dt>Type:</dt><dd>{{ item_info.type }}</dd> <dt>Rarity:</dt><dd>{{ item_info.rarity }}</dd> <dt>Level:</dt><dd>{{ item_info.level }}</dd> <dt>Tradeable:</dt><dd> {% if item_info.seen_on_trading_post %} Yes {% else %} No {% endif %} </dd> {% if item_info.seen_on_trading_post %} <dt>Purchase Price:</dt><dd>{% show_coins item_info.get_market_buy %}</dd> {% endif %} {% if item_info.vendor_value %} <dt>Vendor Value:</dt><dd>{% show_coins item_info.vendor_value %}</dd> {% endif %} <dt>Added:</dt><dd>{{ item_info.date_added }}</dd> </dl> {% for recipe in item_info.recipe_set.all %} {% if forloop.first %}<h3>Recipe{% if item_info.recipe_set.all|length > 1 %}s{% endif %} for {{ item_info.name }}</h3>{% endif %} <dl class="dl-horizontal"> <dt>Recipe ID:</dt><dd>{{ recipe.recipe_id }}</dd> <dt>Type:</dt><dd>{{ recipe.type }}</dd> <dt>Number Created</dt><dd>{{ recipe.output_item_count }}</dd> <dt>Disciplines:</dt><dd> {% for discipline, exists in recipe.recipediscipline.get_disciplines %} {% if exists %} <img src="{% static commerce %}commerce/{{ discipline|lower }}.png" height="26" alt="{{ discipline|lower }} icon" /> {% endif %} {% endfor %} </dd> <dt>Minimum Rating</dt><dd>{{ recipe.min_rating }}</dd> <dt>Learned:</dt><dd> {% if recipe.AutoLearned %}Automatically {% elif recipe.LearnedFromItem %}From Item {% else %}By Discovery {% endif %} </dd> <dt>Added:</dt><dd>{{ recipe.date_added }}</dd> <dt>Ingredients:</dt><dd> <div class="col-md-7"> <table class="table table-hover table-condensed text-right"> <tr> <th class="text-left"></th> <th class="text-left">Name</th> <th class="text-left">Count</th> <th class="text-right">Unit Cost</th> </tr> {% for ingredient in recipe.recipeingredient_set.all %} <tr class="{{ ingredient.item_id.rarity|lower }}"> <td class="text-left"><img src="{% static commerce %}commerce/items/{{ ingredient.item_id.icon.static_id }}" height="25" width="25" alt="item icon" /></td> <td class="text-left"><a href="{% url 'commerce:item_detail' ingredient.item_id.item_id %}"><strong>{{ ingredient.item_id.name }}</strong></a></td> <td class="text-left">{{ ingredient.count }}</td> <td> {% if ingredient.item_id.selllisting_set.first.unit_price %} {% show_coins ingredient.item_id.selllisting_set.first.unit_price %} {% else %} Not Available {% endif %} </td> </tr> {% endfor %} </table> </div> </dd> </dl> {% endfor %} {% if item_info.seen_on_trading_post and item_info.can_be_crafted %} <h3>Cheapest method to obtain:</h3> {% show_crafting_tree item_info.buy_or_craft %} {% endif %} {% endblock %}
{ "content_hash": "6d258d3f206466882c53071b5db43be6", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 179, "avg_line_length": 47.68539325842696, "alnum_prop": 0.4677191328934967, "repo_name": "Wilsh/goldwarsplus", "id": "b139a8f89ab8b82541b804e0240e72e09c5ef5c2", "size": "4244", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "commerce/templates/commerce/item_detail.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2222" }, { "name": "HTML", "bytes": "29789" }, { "name": "Python", "bytes": "97992" } ], "symlink_target": "" }
#include "lib.h" #include "istream-private.h" #include "ostream.h" #include "base64.h" #include "buffer.h" #include "str.h" #include "hash-format.h" #include "rfc822-parser.h" #include "message-parser.h" #include "istream-attachment-extractor.h" #define BASE64_ATTACHMENT_MAX_EXTRA_BYTES 1024 enum mail_attachment_state { MAIL_ATTACHMENT_STATE_NO, MAIL_ATTACHMENT_STATE_MAYBE, MAIL_ATTACHMENT_STATE_YES }; enum base64_state { BASE64_STATE_0 = 0, BASE64_STATE_1, BASE64_STATE_2, BASE64_STATE_3, BASE64_STATE_CR, BASE64_STATE_EOB, BASE64_STATE_EOM }; struct attachment_istream_part { char *content_type, *content_disposition; enum mail_attachment_state state; /* start offset of the message part in the original input stream */ uoff_t start_offset; /* for saving attachments base64-decoded: */ enum base64_state base64_state; unsigned int base64_line_blocks, cur_base64_blocks; uoff_t base64_bytes; bool base64_have_crlf; /* CRLF linefeeds */ bool base64_failed; int temp_fd; struct ostream *temp_output; buffer_t *part_buf; }; struct attachment_istream { struct istream_private istream; pool_t pool; struct istream_attachment_settings set; void *context; struct message_parser_ctx *parser; struct message_part *cur_part; struct attachment_istream_part part; bool retry_read; bool failed; }; static void stream_add_data(struct attachment_istream *astream, const void *data, size_t size) { if (size > 0) { memcpy(i_stream_alloc(&astream->istream, size), data, size); astream->istream.pos += size; } } static void parse_content_type(struct attachment_istream *astream, const struct message_header_line *hdr) { struct rfc822_parser_context parser; string_t *content_type; rfc822_parser_init(&parser, hdr->full_value, hdr->full_value_len, NULL); rfc822_skip_lwsp(&parser); T_BEGIN { content_type = t_str_new(64); if (rfc822_parse_content_type(&parser, content_type) >= 0) { i_free(astream->part.content_type); astream->part.content_type = i_strdup(str_c(content_type)); } } T_END; } static void parse_content_disposition(struct attachment_istream *astream, const struct message_header_line *hdr) { /* just pass it without parsing to is_attachment() callback */ i_free(astream->part.content_disposition); astream->part.content_disposition = i_strndup(hdr->full_value, hdr->full_value_len); } static void astream_parse_header(struct attachment_istream *astream, struct message_header_line *hdr) { if (!hdr->continued) { stream_add_data(astream, hdr->name, hdr->name_len); stream_add_data(astream, hdr->middle, hdr->middle_len); } stream_add_data(astream, hdr->value, hdr->value_len); if (!hdr->no_newline) { if (hdr->crlf_newline) stream_add_data(astream, "\r\n", 2); else stream_add_data(astream, "\n", 1); } if (hdr->continues) { hdr->use_full_value = TRUE; return; } if (strcasecmp(hdr->name, "Content-Type") == 0) parse_content_type(astream, hdr); else if (strcasecmp(hdr->name, "Content-Disposition") == 0) parse_content_disposition(astream, hdr); } static bool astream_want_attachment(struct attachment_istream *astream, struct message_part *part) { struct istream_attachment_header ahdr; if ((part->flags & MESSAGE_PART_FLAG_MULTIPART) != 0) { /* multiparts may contain attachments as children, but they're never themselves */ return FALSE; } if (astream->set.want_attachment == NULL) return TRUE; memset(&ahdr, 0, sizeof(ahdr)); ahdr.part = part; ahdr.content_type = astream->part.content_type; ahdr.content_disposition = astream->part.content_disposition; return astream->set.want_attachment(&ahdr, astream->context); } static int astream_base64_decode_lf(struct attachment_istream_part *part) { part->base64_state = BASE64_STATE_0; if (part->cur_base64_blocks < part->base64_line_blocks) { /* last line */ part->base64_state = BASE64_STATE_EOM; return 0; } else if (part->base64_line_blocks == 0) { /* first line */ if (part->cur_base64_blocks == 0) return -1; part->base64_line_blocks = part->cur_base64_blocks; } else if (part->cur_base64_blocks == part->base64_line_blocks) { /* line is ok */ } else { return -1; } part->cur_base64_blocks = 0; return 1; } static int astream_try_base64_decode_char(struct attachment_istream_part *part, size_t pos, char chr) { switch (part->base64_state) { case BASE64_STATE_0: if (base64_is_valid_char(chr)) part->base64_state++; else if (chr == '\r') part->base64_state = BASE64_STATE_CR; else if (chr == '\n') { return astream_base64_decode_lf(part); } else { return -1; } break; case BASE64_STATE_1: if (!base64_is_valid_char(chr)) return -1; part->base64_state++; break; case BASE64_STATE_2: if (base64_is_valid_char(chr)) part->base64_state++; else if (chr == '=') part->base64_state = BASE64_STATE_EOB; else return -1; break; case BASE64_STATE_3: part->base64_bytes = part->temp_output->offset + pos + 1; if (base64_is_valid_char(chr)) { part->base64_state = BASE64_STATE_0; part->cur_base64_blocks++; } else if (chr == '=') { part->base64_state = BASE64_STATE_EOM; part->cur_base64_blocks++; return 0; } else { return -1; } break; case BASE64_STATE_CR: if (chr != '\n') return -1; part->base64_have_crlf = TRUE; return astream_base64_decode_lf(part); case BASE64_STATE_EOB: if (chr != '=') return -1; part->base64_bytes = part->temp_output->offset + pos + 1; part->base64_state = BASE64_STATE_EOM; part->cur_base64_blocks++; return 0; case BASE64_STATE_EOM: i_unreached(); } return 1; } static void astream_try_base64_decode(struct attachment_istream_part *part, const unsigned char *data, size_t size) { size_t i; int ret; if (part->base64_failed || part->base64_state == BASE64_STATE_EOM) return; for (i = 0; i < size; i++) { ret = astream_try_base64_decode_char(part, i, (char)data[i]); if (ret <= 0) { if (ret < 0) part->base64_failed = TRUE; break; } } } static int astream_open_output(struct attachment_istream *astream) { int fd; i_assert(astream->part.temp_fd == -1); fd = astream->set.open_temp_fd(astream->context); if (fd == -1) return -1; astream->part.temp_fd = fd; astream->part.temp_output = o_stream_create_fd(fd, 0, FALSE); o_stream_cork(astream->part.temp_output); return 0; } static void astream_add_body(struct attachment_istream *astream, const struct message_block *block) { struct attachment_istream_part *part = &astream->part; buffer_t *part_buf; size_t new_size; switch (part->state) { case MAIL_ATTACHMENT_STATE_NO: stream_add_data(astream, block->data, block->size); break; case MAIL_ATTACHMENT_STATE_MAYBE: /* we'll write data to in-memory buffer until we reach attachment min_size */ if (part->part_buf == NULL) { part->part_buf = buffer_create_dynamic(default_pool, astream->set.min_size); } part_buf = part->part_buf; new_size = part_buf->used + block->size; if (new_size < astream->set.min_size) { buffer_append(part_buf, block->data, block->size); break; } /* attachment is large enough. we'll first copy the buffered data from memory to temp file */ if (astream_open_output(astream) < 0) { /* failed, fallback to just saving it inline */ part->state = MAIL_ATTACHMENT_STATE_NO; stream_add_data(astream, part_buf->data, part_buf->used); stream_add_data(astream, block->data, block->size); break; } part->state = MAIL_ATTACHMENT_STATE_YES; astream_try_base64_decode(part, part_buf->data, part_buf->used); hash_format_loop(astream->set.hash_format, part_buf->data, part_buf->used); o_stream_nsend(part->temp_output, part_buf->data, part_buf->used); buffer_set_used_size(part_buf, 0); /* fall through to write the new data to temp file */ case MAIL_ATTACHMENT_STATE_YES: astream_try_base64_decode(part, block->data, block->size); hash_format_loop(astream->set.hash_format, block->data, block->size); o_stream_nsend(part->temp_output, block->data, block->size); break; } } static int astream_decode_base64(struct attachment_istream *astream) { struct attachment_istream_part *part = &astream->part; buffer_t *extra_buf = NULL; struct istream *input, *base64_input; struct ostream *output; const unsigned char *data; size_t size; ssize_t ret; buffer_t *buf; int outfd; bool failed = FALSE; if (part->base64_bytes < astream->set.min_size || part->temp_output->offset > part->base64_bytes + BASE64_ATTACHMENT_MAX_EXTRA_BYTES) { /* only a small part of the MIME part is base64-encoded. */ return -1; } if (part->base64_line_blocks == 0) { /* only one line of base64 */ part->base64_line_blocks = part->cur_base64_blocks; i_assert(part->base64_line_blocks > 0); } /* decode base64 data and write it to another temp file */ outfd = astream->set.open_temp_fd(astream->context); if (outfd == -1) return -1; buf = buffer_create_dynamic(default_pool, 1024); input = i_stream_create_fd(part->temp_fd, IO_BLOCK_SIZE, FALSE); base64_input = i_stream_create_limit(input, part->base64_bytes); output = o_stream_create_fd_file(outfd, 0, FALSE); o_stream_cork(output); hash_format_reset(astream->set.hash_format); while ((ret = i_stream_read(base64_input)) > 0) { data = i_stream_get_data(base64_input, &size); buffer_set_used_size(buf, 0); if (base64_decode(data, size, &size, buf) < 0) { i_error("istream-attachment: BUG: " "Attachment base64 data unexpectedly broke"); failed = TRUE; break; } i_stream_skip(base64_input, size); o_stream_nsend(output, buf->data, buf->used); hash_format_loop(astream->set.hash_format, buf->data, buf->used); } if (ret != -1) { i_assert(failed); } else if (base64_input->stream_errno != 0) { i_error("istream-attachment: read(%s) failed: %m", i_stream_get_name(base64_input)); failed = TRUE; } if (o_stream_nfinish(output) < 0) { i_error("istream-attachment: write(%s) failed: %m", o_stream_get_name(output)); failed = TRUE; } buffer_free(&buf); i_stream_unref(&base64_input); o_stream_unref(&output); if (input->v_offset != part->temp_output->offset && !failed) { /* write the rest of the data to the message stream */ extra_buf = buffer_create_dynamic(default_pool, 1024); while ((ret = i_stream_read_data(input, &data, &size, 0)) > 0) { buffer_append(extra_buf, data, size); i_stream_skip(input, size); } i_assert(ret == -1); if (input->stream_errno != 0) { i_error("istream-attachment: read(%s) failed: %m", i_stream_get_name(base64_input)); failed = TRUE; } } i_stream_unref(&input); if (failed) { i_close_fd(&outfd); return -1; } /* successfully wrote it. switch to using it. */ o_stream_destroy(&part->temp_output); i_close_fd(&part->temp_fd); part->temp_fd = outfd; if (extra_buf != NULL) { stream_add_data(astream, extra_buf->data, extra_buf->used); buffer_free(&extra_buf); } return 0; } static int astream_part_finish(struct attachment_istream *astream, const char **error_r) { struct attachment_istream_part *part = &astream->part; struct istream_attachment_info info; struct istream *input; struct ostream *output; string_t *digest_str; const unsigned char *data; size_t size; int ret = 0; if (o_stream_nfinish(part->temp_output) < 0) { *error_r = t_strdup_printf("write(%s) failed: %s", o_stream_get_name(part->temp_output), o_stream_get_error(part->temp_output)); return -1; } memset(&info, 0, sizeof(info)); info.start_offset = astream->part.start_offset; /* base64_bytes contains how many valid base64 bytes there are so far. if the base64 ends properly, it'll specify how much of the MIME part is saved as an attachment. the rest of the data (typically linefeeds) is added back to main stream */ info.encoded_size = part->base64_bytes; /* get the hash before base64-decoder resets it */ digest_str = t_str_new(128); hash_format_write(astream->set.hash_format, digest_str); info.hash = str_c(digest_str); /* if it looks like we can decode base64 without any data loss, do it and write the decoded data to another temp file. */ if (!part->base64_failed) { if (part->base64_state == BASE64_STATE_0 && part->base64_bytes > 0) { /* there is no trailing LF or '=' characters, but it's not completely empty */ part->base64_state = BASE64_STATE_EOM; } if (part->base64_state == BASE64_STATE_EOM) { /* base64 data looks ok. */ if (astream_decode_base64(astream) < 0) part->base64_failed = TRUE; } else { part->base64_failed = TRUE; } } /* open attachment output file */ info.part = astream->cur_part; if (!part->base64_failed) { info.base64_blocks_per_line = part->base64_line_blocks; info.base64_have_crlf = part->base64_have_crlf; /* base64-decoder updated the hash, use it */ str_truncate(digest_str, 0); hash_format_write(astream->set.hash_format, digest_str); info.hash = str_c(digest_str); } else { /* couldn't decode base64, so write the entire MIME part as attachment */ info.encoded_size = part->temp_output->offset; } if (astream->set.open_attachment_ostream(&info, &output, error_r, astream->context) < 0) return -1; /* copy data to attachment from temp file */ input = i_stream_create_fd(part->temp_fd, IO_BLOCK_SIZE, FALSE); while (i_stream_read_data(input, &data, &size, 0) > 0) { o_stream_nsend(output, data, size); i_stream_skip(input, size); } if (input->stream_errno != 0) { *error_r = t_strdup_printf("read(%s) failed: %s", i_stream_get_name(input), i_stream_get_error(input)); ret = -1; } i_stream_destroy(&input); if (astream->set.close_attachment_ostream(output, ret == 0, error_r, astream->context) < 0) ret = -1; return ret; } static void astream_part_reset(struct attachment_istream *astream) { struct attachment_istream_part *part = &astream->part; if (part->temp_output != NULL) o_stream_destroy(&part->temp_output); if (part->temp_fd != -1) i_close_fd(&part->temp_fd); i_free_and_null(part->content_type); i_free_and_null(part->content_disposition); if (part->part_buf != NULL) buffer_free(&part->part_buf); memset(part, 0, sizeof(*part)); part->temp_fd = -1; hash_format_reset(astream->set.hash_format); } static int astream_end_of_part(struct attachment_istream *astream, const char **error_r) { struct attachment_istream_part *part = &astream->part; size_t old_size; int ret = 0; /* MIME part changed. we're now parsing the end of a boundary, possibly followed by message epilogue */ switch (part->state) { case MAIL_ATTACHMENT_STATE_NO: break; case MAIL_ATTACHMENT_STATE_MAYBE: /* MIME part wasn't large enough to be an attachment */ if (part->part_buf != NULL) { stream_add_data(astream, part->part_buf->data, part->part_buf->used); ret = part->part_buf->used > 0 ? 1 : 0; } break; case MAIL_ATTACHMENT_STATE_YES: old_size = astream->istream.pos - astream->istream.skip; if (astream_part_finish(astream, error_r) < 0) ret = -1; else { /* finished base64 may have added a few more trailing bytes to the stream */ ret = astream->istream.pos - astream->istream.skip - old_size; } break; } part->state = MAIL_ATTACHMENT_STATE_NO; astream_part_reset(astream); return ret; } static int astream_read_next(struct attachment_istream *astream, bool *retry_r) { struct istream_private *stream = &astream->istream; struct message_block block; size_t old_size, new_size; const char *error; int ret; *retry_r = FALSE; if (stream->pos - stream->skip >= stream->max_buffer_size) return -2; if (astream->failed) { stream->istream.stream_errno = EINVAL; return -1; } old_size = stream->pos - stream->skip; switch (message_parser_parse_next_block(astream->parser, &block)) { case -1: /* done / error */ ret = astream_end_of_part(astream, &error); if (ret > 0) { /* final data */ new_size = stream->pos - stream->skip; return new_size - old_size; } stream->istream.eof = TRUE; stream->istream.stream_errno = stream->parent->stream_errno; if (ret < 0) { io_stream_set_error(&stream->iostream, "%s", error); stream->istream.stream_errno = EINVAL; astream->failed = TRUE; } astream->cur_part = NULL; return -1; case 0: /* need more data */ return 0; default: break; } if (block.part != astream->cur_part && astream->cur_part != NULL) { /* end of a MIME part */ if (astream_end_of_part(astream, &error) < 0) { io_stream_set_error(&stream->iostream, "%s", error); stream->istream.stream_errno = EINVAL; astream->failed = TRUE; return -1; } } astream->cur_part = block.part; if (block.hdr != NULL) { /* parsing a header */ astream_parse_header(astream, block.hdr); } else if (block.size == 0) { /* end of headers */ if (astream_want_attachment(astream, block.part)) { astream->part.state = MAIL_ATTACHMENT_STATE_MAYBE; astream->part.start_offset = stream->parent->v_offset; } } else { astream_add_body(astream, &block); } new_size = stream->pos - stream->skip; *retry_r = new_size == old_size; return new_size - old_size; } static ssize_t i_stream_attachment_extractor_read(struct istream_private *stream) { struct attachment_istream *astream = (struct attachment_istream *)stream; bool retry; ssize_t ret; do { ret = astream_read_next(astream, &retry); } while (retry && astream->set.drain_parent_input); astream->retry_read = retry; return ret; } static void i_stream_attachment_extractor_close(struct iostream_private *stream, bool close_parent) { struct attachment_istream *astream = (struct attachment_istream *)stream; struct message_part *parts; int ret; if (astream->parser != NULL) { ret = message_parser_deinit(&astream->parser, &parts); i_assert(ret == 0); /* we didn't use preparsed message_parts */ } hash_format_deinit_free(&astream->set.hash_format); if (astream->pool != NULL) pool_unref(&astream->pool); if (close_parent) i_stream_close(astream->istream.parent); } struct istream * i_stream_create_attachment_extractor(struct istream *input, struct istream_attachment_settings *set, void *context) { struct attachment_istream *astream; i_assert(set->min_size > 0); i_assert(set->hash_format != NULL); i_assert(set->open_attachment_ostream != NULL); i_assert(set->close_attachment_ostream != NULL); astream = i_new(struct attachment_istream, 1); astream->part.temp_fd = -1; astream->set = *set; astream->context = context; astream->retry_read = TRUE; /* make sure the caller doesn't try to double-free this */ set->hash_format = NULL; astream->istream.max_buffer_size = input->real_stream->max_buffer_size; astream->istream.read = i_stream_attachment_extractor_read; astream->istream.iostream.close = i_stream_attachment_extractor_close; astream->istream.istream.readable_fd = FALSE; astream->istream.istream.blocking = input->blocking; astream->istream.istream.seekable = FALSE; astream->pool = pool_alloconly_create("istream attachment", 1024); astream->parser = message_parser_init(astream->pool, input, 0, MESSAGE_PARSER_FLAG_INCLUDE_MULTIPART_BLOCKS | MESSAGE_PARSER_FLAG_INCLUDE_BOUNDARIES); return i_stream_create(&astream->istream, input, i_stream_get_fd(input)); } bool i_stream_attachment_extractor_can_retry(struct istream *input) { struct attachment_istream *astream = (struct attachment_istream *)input->real_stream; return astream->retry_read; }
{ "content_hash": "ffd0e160ef9a9ad041b59cd2d2b224e8", "timestamp": "", "source": "github", "line_count": 715, "max_line_length": 80, "avg_line_length": 27.478321678321677, "alnum_prop": 0.673334351300453, "repo_name": "oposs/dovecot-extensions", "id": "991db649f14c809b9703137d530156a391b5ce19", "size": "19723", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/lib-mail/istream-attachment-extractor.c", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>UNL AIAA | Welcome</title> <link rel="stylesheet" href="assets/_css/site.css"> <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script>window.jQuery || document.write('<script src="assets/_js/jquery-2.1.1.min.js">\x3C/script>')</script> <script src="assets/_js/jquery.vide.min.js"></script> </head> <body class="our-team"> <header> <div class="row"> <div class="medium-1 columns text-left"> <i class="fa fa-bars fa-2x icon-light cursor-pointer nav-toggle"></i> </div> </div> <nav class="dropdown"> <div class="row"> <div class="medium-2 medium-offset-1 small-10 small-offset-1 columns nav-list"> <ul> <li><a href="">Our Story</a></li> <li><a href="">The Team</a></li> <li><a href="">Projects</a></li> <li><a href="">Contact Us</a></li> </ul> </div><!-- end nav-list --> <div class="medium-3 small-10 small-offset-1 medium-offset-0 columns nav-item-featured"> <a href=""> <i class="fa fa-calendar-o fa-3x icon-light"></i> <div class="nav-item-featured-text"> <span class="nav-subhead">Stay up-to-date in</span> <span class="nav-headline">Events</span> </div> </a> </div><!-- end nav-item-featured --> <div class="medium-3 small-10 small-offset-1 medium-offset-0 columns nav-item-featured"> <a href=""> <i class="fa fa-book fa-3x icon-light"></i> <div class="nav-item-featured-text"> <span class="nav-subhead">Follus us in our</span> <span class="nav-headline">Journal</span> </div> </a> </div><!-- end nav-item-featured --> <div class="medium-2 columns end nav-social-media text-center"> <ul> <li><a href=""><i class="fa fa-facebook fa-lg"></i></a></li> <li><a href=""><i class="fa fa-twitter fa-lg"></i></a></li> <li><a href=""><i class="fa fa-google fa-lg"></i></a></li> </ul> </div><!-- end nav-social-media --> </div><!-- end row --> </nav> </header> <div class="panel masthead" data-vide-bg="assets/_videos/our-team/our-team"> <div class="row"> <div class="small-10 small-offset-1 medium-8 medium-offset-2 columns end"> <div class="title">Our Team</div> <p class="lead"> The members of AIAA range from math to civil engineering majors. The club takes pride in this diversity as it brings different ways of thinking and knowledge to our clubs competitions and research. If there was one charactersitic that puts a UNL-AIAA Student Chapter member above everyone else it would be charismatic dedication. </p> </div> </div> </div> <div class="panel members"> <div class="row"> <div class="small-12 columns small-only-text-center text-right"> <div class="member-filter"> <input class="team-member-filter" type="text"> <span class="team-filter-list-toggle"><i class="fa fa-sort-desc fa-lg"></i></span> <div class="team-filter-list"> <ul> <li>ALL MEMBERS</li> <li>OFFICERS</li> <li>DBF</li> <li>ROCKSAT</li> <li></li> </ul> </div> </div> </div> </div> <div class="member-group"> <div class="row"> <div class="small-12 columns member-title"> Our Officers </div> </div> <div class="row"> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/bryan.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">Bryan Kubitschek</div> <div class="position">President</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/cj.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">CJ O'Hara</div> <div class="position">Web Developer</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/bryan.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">Bryan Kubitschek</div> <div class="position">President</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/cj.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">CJ O'Hara</div> <div class="position">Web Developer</div> </div> </div><!-- end team member --> </div> </div><!-- end row --> </div> <div class="member-group"> <div class="row"> <div class="small-12 columns member-title"> Team DBF </div> </div> <div class="row"> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/bryan.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">Bryan Kubitschek</div> <div class="position">President</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/cj.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">CJ O'Hara</div> <div class="position">Web Developer</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/bryan.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">Bryan Kubitschek</div> <div class="position">President</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/cj.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">CJ O'Hara</div> <div class="position">Web Developer</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/bryan.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">Bryan Kubitschek</div> <div class="position">President</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/cj.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">CJ O'Hara</div> <div class="position">Web Developer</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/bryan.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">Bryan Kubitschek</div> <div class="position">President</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/cj.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">CJ O'Hara</div> <div class="position">Web Developer</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/bryan.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">Bryan Kubitschek</div> <div class="position">President</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/cj.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">CJ O'Hara</div> <div class="position">Web Developer</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/bryan.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">Bryan Kubitschek</div> <div class="position">President</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/cj.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">CJ O'Hara</div> <div class="position">Web Developer</div> </div> </div><!-- end team member --> </div> </div><!-- end row --> </div> <div class="member-group"> <div class="row"> <div class="small-12 columns member-title"> Team Rocksat </div> </div> <div class="row"> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/bryan.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">Bryan Kubitschek</div> <div class="position">President</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/cj.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">CJ O'Hara</div> <div class="position">Web Developer</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/bryan.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">Bryan Kubitschek</div> <div class="position">President</div> </div> </div><!-- end team member --> </div> <div class="small-6 medium-3 columns"> <div class="team-member"> <div class="team-member-photo"> <div class="member-photo"><img src="assets/_img/members/cj.jpg"></div> <a class="member-social-link google-plus" href=""><i class="fa fa-google-plus"></i></a> <a class="member-social-link facebook" href=""><i class="fa fa-facebook"></i></a> <a class="member-social-link linkedin" href=""><i class="fa fa-linkedin"></i></a> <a class="member-social-link twitter" href=""><i class="fa fa-twitter"></i></a> </div> <div class="team-member-info"> <div class="name">CJ O'Hara</div> <div class="position">Web Developer</div> </div> </div><!-- end team member --> </div> </div><!-- end row --> </div> </div> <script src="assets/_js/site.min.js"></script> </body> </html>
{ "content_hash": "33889227b751eeb5119b4d8fddfc98af", "timestamp": "", "source": "github", "line_count": 462, "max_line_length": 339, "avg_line_length": 45.833333333333336, "alnum_prop": 0.5224557260920897, "repo_name": "mmonkey/unlaiaa", "id": "91059e739d7dbedaeebf9424e12f9c7b6ae57d4a", "size": "21175", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/team.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "394356" }, { "name": "HTML", "bytes": "29469" }, { "name": "JavaScript", "bytes": "4404" } ], "symlink_target": "" }
package org.keycloak.testsuite.model; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.keycloak.admin.client.resource.UserResource; import org.keycloak.common.util.Time; import org.keycloak.connections.infinispan.InfinispanConnectionProvider; import org.keycloak.models.*; import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.services.managers.UserSessionManager; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; import org.keycloak.testsuite.arquillian.annotation.ModelTest; import org.keycloak.testsuite.runonserver.RunOnServerDeployment; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT; /** * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> * @author <a href="mailto:mabartos@redhat.com">Martin Bartos</a> */ public class UserSessionInitializerTest extends AbstractTestRealmKeycloakTest { private final String realmName = "test"; @Deployment @TargetsContainer(AUTH_SERVER_CURRENT) public static WebArchive deploy() { return RunOnServerDeployment.create(UserResource.class, org.keycloak.testsuite.model.UserSessionInitializerTest.class) .addPackages(true, "org.keycloak.testsuite", "org.keycloak.testsuite.model"); } @Before public void before() { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealm("test"); session.users().addUser(realm, "user1").setEmail("user1@localhost"); session.users().addUser(realm, "user2").setEmail("user2@localhost"); }); } @After public void after() { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); session.sessions().removeUserSessions(realm); UserModel user1 = session.users().getUserByUsername("user1", realm); UserModel user2 = session.users().getUserByUsername("user2", realm); UserManager um = new UserManager(session); if (user1 != null) um.removeUser(realm, user1); if (user2 != null) um.removeUser(realm, user2); }); } @Test @ModelTest public void testUserSessionInitializer(KeycloakSession session) { AtomicReference<Integer> startedAtomic = new AtomicReference<>(); AtomicReference<UserSessionModel[]> origSessionsAtomic = new AtomicReference<>(); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession SessionInit1) -> { KeycloakSession currentSession = SessionInit1; UserSessionManager sessionManager = new UserSessionManager(currentSession); int started = Time.currentTime(); startedAtomic.set(started); UserSessionModel[] origSessions = createSessionsInPersisterOnly(currentSession); origSessionsAtomic.set(origSessions); // Load sessions from persister into infinispan/memory UserSessionProviderFactory userSessionFactory = (UserSessionProviderFactory) currentSession.getKeycloakSessionFactory().getProviderFactory(UserSessionProvider.class); userSessionFactory.loadPersistentSessions(currentSession.getKeycloakSessionFactory(), 1, 2); }); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession SessionInit2) -> { KeycloakSession currentSession = SessionInit2; RealmModel realm = currentSession.realms().getRealmByName(realmName); int started = startedAtomic.get(); UserSessionModel[] origSessions = origSessionsAtomic.get(); // Assert sessions are in ClientModel testApp = realm.getClientByClientId("test-app"); ClientModel thirdparty = realm.getClientByClientId("third-party"); assertThat("Count of offline sesions for client 'test-app'", currentSession.sessions().getOfflineSessionsCount(realm, testApp), is((long) 3)); assertThat("Count of offline sesions for client 'third-party'", currentSession.sessions().getOfflineSessionsCount(realm, thirdparty), is((long) 1)); List<UserSessionModel> loadedSessions = currentSession.sessions().getOfflineUserSessions(realm, testApp, 0, 10); UserSessionProviderTest.assertSessions(loadedSessions, origSessions); assertSessionLoaded(loadedSessions, origSessions[0].getId(), currentSession.users().getUserByUsername("user1", realm), "127.0.0.1", started, started, "test-app", "third-party"); assertSessionLoaded(loadedSessions, origSessions[1].getId(), currentSession.users().getUserByUsername("user1", realm), "127.0.0.2", started, started, "test-app"); assertSessionLoaded(loadedSessions, origSessions[2].getId(), currentSession.users().getUserByUsername("user2", realm), "127.0.0.3", started, started, "test-app"); }); } @Test @ModelTest public void testUserSessionInitializerWithDeletingClient(KeycloakSession session) { AtomicReference<Integer> startedAtomic = new AtomicReference<>(); AtomicReference<UserSessionModel[]> origSessionsAtomic = new AtomicReference<>(); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession SessionInitWithDeleting1) -> { KeycloakSession currentSession = SessionInitWithDeleting1; UserSessionManager sessionManager = new UserSessionManager(currentSession); RealmModel realm = currentSession.realms().getRealmByName(realmName); int started = Time.currentTime(); startedAtomic.set(started); origSessionsAtomic.set(createSessionsInPersisterOnly(currentSession)); // Delete one of the clients now. Delete it directly in DB just for the purpose of simulating the issue (normally clients should be removed through ClientManager) ClientModel testApp = realm.getClientByClientId("test-app"); realm.removeClient(testApp.getId()); }); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession SessionInitWithDeleting2) -> { KeycloakSession currentSession = SessionInitWithDeleting2; // Load sessions from persister into infinispan/memory UserSessionProviderFactory userSessionFactory = (UserSessionProviderFactory) currentSession.getKeycloakSessionFactory().getProviderFactory(UserSessionProvider.class); userSessionFactory.loadPersistentSessions(currentSession.getKeycloakSessionFactory(), 1, 2); }); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession SessionInitWithDeleting3) -> { KeycloakSession currentSession = SessionInitWithDeleting3; RealmModel realm = currentSession.realms().getRealmByName(realmName); int started = startedAtomic.get(); UserSessionModel[] origSessions = origSessionsAtomic.get(); // Assert sessions are in ClientModel thirdparty = realm.getClientByClientId("third-party"); assertThat("Count of offline sesions for client 'third-party'", currentSession.sessions().getOfflineSessionsCount(realm, thirdparty), is((long) 1)); List<UserSessionModel> loadedSessions = currentSession.sessions().getOfflineUserSessions(realm, thirdparty, 0, 10); assertThat("Size of loaded Sessions", loadedSessions.size(), is(1)); assertSessionLoaded(loadedSessions, origSessions[0].getId(), currentSession.users().getUserByUsername("user1", realm), "127.0.0.1", started, started, "third-party"); // Revert client realm.addClient("test-app"); }); } // Create sessions in persister + infinispan, but then delete them from infinispan cache. This is to allow later testing of initializer. Return the list of "origSessions" private UserSessionModel[] createSessionsInPersisterOnly(KeycloakSession session) { AtomicReference<UserSessionModel[]> origSessionsAtomic = new AtomicReference<>(); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession createSessionPersister1) -> { KeycloakSession currentSession = createSessionPersister1; UserSessionModel[] origSessions = createSessions(currentSession); origSessionsAtomic.set(origSessions); }); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession createSessionPersister2) -> { KeycloakSession currentSession = createSessionPersister2; RealmModel realm = currentSession.realms().getRealmByName(realmName); UserSessionManager sessionManager = new UserSessionManager(currentSession); UserSessionModel[] origSessions = origSessionsAtomic.get(); for (UserSessionModel origSession : origSessions) { UserSessionModel userSession = currentSession.sessions().getUserSession(realm, origSession.getId()); for (AuthenticatedClientSessionModel clientSession : userSession.getAuthenticatedClientSessions().values()) { sessionManager.createOrUpdateOfflineSession(clientSession, userSession); } } }); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession createSessionPersister3) -> { KeycloakSession currentSession = createSessionPersister3; RealmModel realm = currentSession.realms().getRealmByName(realmName); // Delete cache (persisted sessions are still kept) currentSession.sessions().onRealmRemoved(realm); // Clear ispn cache to ensure initializerState is removed as well InfinispanConnectionProvider infinispan = currentSession.getProvider(InfinispanConnectionProvider.class); infinispan.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME).clear(); }); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession createSessionPersister4) -> { KeycloakSession currentSession = createSessionPersister4; RealmModel realm = currentSession.realms().getRealmByName(realmName); ClientModel testApp = realm.getClientByClientId("test-app"); ClientModel thirdparty = realm.getClientByClientId("third-party"); assertThat("Count of offline sessions for client 'test-app'", currentSession.sessions().getOfflineSessionsCount(realm, testApp), is((long) 0)); assertThat("Count of offline sessions for client 'third-party'", currentSession.sessions().getOfflineSessionsCount(realm, thirdparty), is((long) 0)); }); return origSessionsAtomic.get(); } private AuthenticatedClientSessionModel createClientSession(KeycloakSession session, ClientModel client, UserSessionModel userSession, String redirect, String state) { RealmModel realm = session.realms().getRealmByName(realmName); AuthenticatedClientSessionModel clientSession = session.sessions().createClientSession(realm, client, userSession); clientSession.setRedirectUri(redirect); if (state != null) clientSession.setNote(OIDCLoginProtocol.STATE_PARAM, state); return clientSession; } private UserSessionModel[] createSessions(KeycloakSession session) { RealmModel realm = session.realms().getRealmByName(realmName); UserSessionModel[] sessions = new UserSessionModel[3]; sessions[0] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.1", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[0], "http://redirect", "state"); createClientSession(session, realm.getClientByClientId("third-party"), sessions[0], "http://redirect", "state"); sessions[1] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.2", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[1], "http://redirect", "state"); sessions[2] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user2", realm), "user2", "127.0.0.3", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[2], "http://redirect", "state"); return sessions; } private void assertSessionLoaded(List<UserSessionModel> sessions, String id, UserModel user, String ipAddress, int started, int lastRefresh, String... clients) { for (UserSessionModel session : sessions) { if (session.getId().equals(id)) { UserSessionProviderTest.assertSession(session, user, ipAddress, started, lastRefresh, clients); return; } } Assert.fail("Session with ID " + id + " not found in the list"); } @Override public void configureTestRealm(RealmRepresentation testRealm) { } }
{ "content_hash": "2efe28c5f83b32f290cd75d1cf2ff772", "timestamp": "", "source": "github", "line_count": 265, "max_line_length": 189, "avg_line_length": 52.369811320754714, "alnum_prop": 0.7109093529326992, "repo_name": "brat000012001/keycloak", "id": "2934dcaea92383f707c66f22f205ffd405c56e98", "size": "14552", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionInitializerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "4656" }, { "name": "Batchfile", "bytes": "8572" }, { "name": "CSS", "bytes": "86367" }, { "name": "Dockerfile", "bytes": "3788" }, { "name": "FreeMarker", "bytes": "167125" }, { "name": "Gnuplot", "bytes": "1817" }, { "name": "Groovy", "bytes": "4973" }, { "name": "HTML", "bytes": "959360" }, { "name": "Java", "bytes": "24141870" }, { "name": "JavaScript", "bytes": "2163842" }, { "name": "Scala", "bytes": "67175" }, { "name": "Shell", "bytes": "70659" }, { "name": "TypeScript", "bytes": "131455" }, { "name": "XSLT", "bytes": "35968" } ], "symlink_target": "" }
const PlotCard = require('../../plotcard.js'); class WardensOfTheWest extends PlotCard { setupCardAbilities(ability) { this.reaction({ when: { afterChallenge: event => event.challenge.winner === this.controller && event.challenge.challengeType === 'intrigue' }, cost: ability.costs.payGold(2), handler: () => { this.game.promptForSelect(this.game.currentChallenge.loser, { numCards: 2, activePromptTitle: 'Select 2 cards to discard', source: this, cardCondition: card => card.controller === this.game.currentChallenge.loser && card.location === 'hand', onSelect: (player, cards) => this.onSelect(player, cards), onCancel: (player) => this.cancelSelection(player) }); this.game.addMessage('{0} uses {1} and pay 2 gold to have {2} discard 2 cards from their hand', this.controller, this, this.game.currentChallenge.loser); } }); } onSelect(player, cards) { player.discardCards(cards, false); this.game.addMessage('{0} chooses {1} to discard from their hand', player, cards); return true; } cancelSelection(player) { this.game.addAlert('danger', '{0} cancels the resolution of {1}', player, this); return true; } } WardensOfTheWest.code = '02030'; module.exports = WardensOfTheWest;
{ "content_hash": "fc32de8f09f070b96c2177d5bff71f8c", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 169, "avg_line_length": 35.29545454545455, "alnum_prop": 0.5569864777849324, "repo_name": "ystros/throneteki", "id": "0066bd0820134c8a45026411d5cbbad4c27ea717", "size": "1553", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/game/cards/02.2-TRtW/WardensOfTheWest.js", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "430" }, { "name": "Gherkin", "bytes": "5971" }, { "name": "JavaScript", "bytes": "3252073" } ], "symlink_target": "" }
import * as utils from '../src/utils.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { parse as parseUrl } from '../src/url.js'; const BIDDER_CODE = 'theadx'; const ENDPOINT_URL = 'https://ssp.theadx.com/request'; const NATIVEASSETNAMES = { 0: 'title', 1: 'cta', 2: 'icon', 3: 'image', 4: 'body', 5: 'sponsoredBy', 6: 'body2', 7: 'phone', 8: 'privacyLink', 9: 'displayurl', 10: 'rating', 11: 'address', 12: 'downloads', 13: 'likes', 14: 'price', 15: 'saleprice', }; const NATIVEPROBS = { title: { id: 0, name: 'title' }, body: { id: 4, name: 'data', type: 2 }, body2: { id: 6, name: 'data', type: 10 }, privacyLink: { id: 8, name: 'data', type: 501 }, sponsoredBy: { id: 5, name: 'data', type: 1 }, image: { id: 3, type: 3, name: 'img' }, icon: { id: 2, type: 1, name: 'img' }, displayurl: { id: 9, name: 'data', type: 11 }, cta: { id: 1, type: 12, name: 'data' }, rating: { id: 7, name: 'data', type: 3 }, address: { id: 11, name: 'data', type: 5 }, downloads: { id: 12, name: 'data', type: 5 }, likes: { id: 13, name: 'data', type: 4 }, phone: { id: 7, name: 'data', type: 8 }, price: { id: 14, name: 'data', type: 6 }, saleprice: { id: 15, name: 'data', type: 7 }, }; export const spec = { code: BIDDER_CODE, aliases: ['theadx'], // short code supportedMediaTypes: [BANNER, VIDEO, NATIVE], /** * Determines whether or not the given bid request is valid. * * @param {BidRequest} bid The bid params to validate. * @return boolean True if this is a valid bid, and false otherwise. */ isBidRequestValid: function (bid) { utils.logInfo('theadx.isBidRequestValid', bid); let res = false; if (bid && bid.params) { res = !!(bid.params.pid && bid.params.tagId); } return res; }, /** * Make a server request from the list of BidRequests. * * @param {validBidRequests[]} - an array of bids * @return ServerRequest Info describing the request to the server. */ buildRequests: function (validBidRequests, bidderRequest) { utils.logInfo('theadx.buildRequests', 'validBidRequests', validBidRequests, 'bidderRequest', bidderRequest); let results = []; const requestType = 'POST'; if (!utils.isEmpty(validBidRequests)) { results = validBidRequests.map( bidRequest => { return { method: requestType, type: requestType, url: `${ENDPOINT_URL}?tagid=${bidRequest.params.tagId}`, options: { withCredentials: true, }, bidder: 'theadx', referrer: encodeURIComponent(bidderRequest.refererInfo.referer), data: generatePayload(bidRequest, bidderRequest), mediaTypes: bidRequest['mediaTypes'], requestId: bidderRequest.bidderRequestId, bidId: bidRequest.bidId, adUnitCode: bidRequest['adUnitCode'], auctionId: bidRequest['auctionId'], }; } ); } return results; }, /** * Unpack the response from the server into a list of bids. * * @param {ServerResponse} serverResponse A successful response from the server. * @return {Bid[]} An array of bids which were nested inside the server. */ interpretResponse: (serverResponse, request) => { utils.logInfo('theadx.interpretResponse', 'serverResponse', serverResponse, ' request', request); let responses = []; if (serverResponse.body) { let responseBody = serverResponse.body; let seatBids = responseBody.seatbid; if (!(utils.isEmpty(seatBids) || utils.isEmpty(seatBids[0].bid))) { let seatBid = seatBids[0]; let bid = seatBid.bid[0]; // handle any values that may end up undefined let nullify = (value) => typeof value === 'undefined' ? null : parseInt(value); let ttl = null; if (bid.ext) { ttl = nullify(bid.ext.ttl) ? nullify(bid.ext.ttl) : 2000; } let bidWidth = nullify(bid.w); let bidHeight = nullify(bid.h); let creative = null let videoXml = null; let mediaType = null; let native = null; if (request.mediaTypes && request.mediaTypes.video) { videoXml = bid.ext.vast_url; mediaType = VIDEO; } else if (request.mediaTypes && request.mediaTypes.banner) { mediaType = BANNER; creative = bid.adm; } else if (request.mediaTypes && request.mediaTypes.native) { mediaType = NATIVE; const { assets, link, imptrackers, jstracker } = bid.ext.native; native = { clickUrl: link.url, clickTrackers: link.clicktrackers || bid.ext.cliu ? [] : undefined, impressionTrackers: imptrackers || bid.nurl ? [] : undefined, javascriptTrackers: jstracker ? [jstracker] : undefined }; if (bid.nurl) { native.impressionTrackers.unshift(bid.ext.impu); native.impressionTrackers.unshift(bid.nurl); if (native.clickTrackers) { native.clickTrackers.unshift(bid.ext.cliu); } } assets.forEach(asset => { const kind = NATIVEASSETNAMES[asset.id]; const content = kind && asset[NATIVEPROBS[kind].name]; if (content) { native[kind] = content.text || content.value || { url: content.url, width: content.w, height: content.h }; } }); } let response = { bidderCode: BIDDER_CODE, requestId: request.bidId, cpm: bid.price, width: bidWidth | 0, height: bidHeight | 0, ad: creative, ttl: ttl || 3000, creativeId: bid.crid, netRevenue: true, currency: responseBody.cur, mediaType: mediaType, native: native, }; if (mediaType == VIDEO && videoXml) { response.vastUrl = videoXml; response.videoCacheKey = bid.ext.rid; } responses.push(response); } } return responses; }, /** * Register the user sync pixels which should be dropped after the auction. * * @param {SyncOptions} syncOptions Which user syncs are allowed? * @param {ServerResponse[]} serverResponses List of server's responses. * @return {UserSync[]} The user syncs which should be dropped. */ getUserSyncs: function (syncOptions, serverResponses) { utils.logInfo('theadx.getUserSyncs', 'syncOptions', syncOptions, 'serverResponses', serverResponses) const syncs = []; if (!syncOptions.iframeEnabled && !syncOptions.pixelEnabled) { return syncs; } serverResponses.forEach(resp => { const syncIframeUrls = utils.deepAccess(resp, 'body.ext.sync.iframe'); const syncImageUrls = utils.deepAccess(resp, 'body.ext.sync.image'); if (syncOptions.iframeEnabled && syncIframeUrls) { syncIframeUrls.forEach(syncIframeUrl => { syncs.push({ type: 'iframe', url: syncIframeUrl }); }); } if (syncOptions.pixelEnabled && syncImageUrls) { syncImageUrls.forEach(syncImageUrl => { syncs.push({ type: 'image', url: syncImageUrl }); }); } }); return syncs; }, } let buildSiteComponent = (bidRequest, bidderRequest) => { let loc = parseUrl(bidderRequest.refererInfo.referer, { decodeSearchAsString: true }); let site = { domain: loc.hostname, page: loc.href, id: bidRequest.params.wid, publisher: { id: bidRequest.params.pid, } }; if (loc.search) { site.search = loc.search; } if (document) { let keywords = document.getElementsByTagName('meta')['keywords']; if (keywords && keywords.content) { site.keywords = keywords.content; } } return site; } function isMobile() { return (/(ios|ipod|ipad|iphone|android)/i).test(navigator.userAgent); } function isConnectedTV() { return (/(smart[-]?tv|hbbtv|appletv|googletv|hdmi|netcast\.tv|viera|nettv|roku|\bdtv\b|sonydtv|inettvbrowser|\btv\b)/i).test(navigator.userAgent); } let buildDeviceComponent = (bidRequest, bidderRequest) => { let device = { js: 1, language: ('language' in navigator) ? navigator.language : null, ua: ('userAgent' in navigator) ? navigator.userAgent : null, devicetype: isMobile() ? 1 : isConnectedTV() ? 3 : 2, dnt: utils.getDNT() ? 1 : 0, }; // Include connection info if available const CONNECTION = navigator.connection || navigator.webkitConnection; if (CONNECTION && CONNECTION.type) { device['connectiontype'] = CONNECTION.type; if (CONNECTION.downlinkMax) { device['connectionDownlinkMax'] = CONNECTION.downlinkMax; } } return device; }; let determineOptimalRequestId = (bidRequest, bidderRequest) => { return bidRequest.bidId; } let extractValidSize = (bidRequest, bidderRequest) => { let width = null; let height = null; let requestedSizes = []; let mediaTypes = bidRequest.mediaTypes; if (mediaTypes && ((mediaTypes.banner && mediaTypes.banner.sizes) || (mediaTypes.video && mediaTypes.video.sizes))) { if (mediaTypes.banner) { requestedSizes = mediaTypes.banner.sizes; } else { requestedSizes = mediaTypes.video.sizes; } } else if (!utils.isEmpty(bidRequest.sizes)) { requestedSizes = bidRequest.sizes } // Ensure the size array is normalized let conformingSize = utils.parseSizesInput(requestedSizes); if (!utils.isEmpty(conformingSize) && conformingSize[0] != null) { // Currently only the first size is utilized let splitSizes = conformingSize[0].split('x'); width = parseInt(splitSizes[0]); height = parseInt(splitSizes[1]); } return { w: width, h: height }; }; let generateVideoComponent = (bidRequest, bidderRequest) => { let impSize = extractValidSize(bidRequest); return { w: impSize.w, h: impSize.h } } let generateBannerComponent = (bidRequest, bidderRequest) => { let impSize = extractValidSize(bidRequest); return { w: impSize.w, h: impSize.h } } let generateNativeComponent = (bidRequest, bidderRequest) => { const assets = utils._map(bidRequest.mediaTypes.native, (bidParams, key) => { const props = NATIVEPROBS[key]; const asset = { required: bidParams.required & 1, }; if (props) { asset.id = props.id; asset[props.name] = { len: bidParams.len, wmin: bidParams.sizes && bidParams.sizes[0], hmin: bidParams.sizes && bidParams.sizes[1], type: props.type }; return asset; } }).filter(Boolean); return { request: { assets } } } let generateImpBody = (bidRequest, bidderRequest) => { let mediaTypes = bidRequest.mediaTypes; let banner = null; let video = null; let native = null; if (mediaTypes && mediaTypes.video) { video = generateVideoComponent(bidRequest, bidderRequest); } else if (mediaTypes && mediaTypes.banner) { banner = generateBannerComponent(bidRequest, bidderRequest); } else if (mediaTypes && mediaTypes.native) { native = generateNativeComponent(bidRequest, bidderRequest); } const result = { id: bidRequest.index, tagid: bidRequest.params.tagId + '', }; if (banner) { result['banner'] = banner; } if (video) { result['video'] = video; } if (native) { result['native'] = native; } return result; } let generatePayload = (bidRequest, bidderRequest) => { // Generate the expected OpenRTB payload let payload = { id: determineOptimalRequestId(bidRequest, bidderRequest), site: buildSiteComponent(bidRequest, bidderRequest), device: buildDeviceComponent(bidRequest, bidderRequest), imp: [generateImpBody(bidRequest, bidderRequest)], }; // return payload; return JSON.stringify(payload); }; registerBidder(spec);
{ "content_hash": "51eefc36fdf62cf3939a66b8790fbb31", "timestamp": "", "source": "github", "line_count": 498, "max_line_length": 148, "avg_line_length": 24.997991967871485, "alnum_prop": 0.594987549200739, "repo_name": "varashellov/Prebid.js", "id": "5306b89a5dae9daad7aa10e7917e931c5b3c83a3", "size": "12449", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/theAdxBidAdapter.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "435" }, { "name": "HTML", "bytes": "173043" }, { "name": "JavaScript", "bytes": "6351454" } ], "symlink_target": "" }
package annis.gui.admin.controller; import annis.gui.admin.model.UserManagement; import annis.gui.admin.view.UIView; import annis.gui.admin.view.UserListView; import annis.security.User; import com.google.common.base.Joiner; import com.sun.jersey.api.client.WebResource; import java.util.LinkedList; import java.util.Set; /** * * @author Thomas Krause <krauseto@hu-berlin.de> */ public class UserController implements UserListView.Listener, UIView.Listener { private final UserManagement model; private final UserListView view; private final UIView uiView; private boolean isLoggedIn = false; public UserController(UserManagement model, UserListView view, UIView uiView, boolean isLoggedIn) { this.model = model; this.view = view; this.uiView = uiView; this.isLoggedIn = isLoggedIn; view.addListener(UserController.this); uiView.addListener(UserController.this); } private void clearModel() { model.clear(); view.setUserList(model.getUsers()); } private void fetchFromService() { if(model.fetchFromService()) { view.setUserList(model.getUsers()); } else { uiView.showWarning("Cannot get the user list", null); view.setUserList(new LinkedList<User>()); } } @Override public void userUpdated(User user) { model.createOrUpdateUser(user); } @Override public void passwordChanged(String userName, String newPassword) { model.setPassword(userName, newPassword); view.setUserList(model.getUsers()); } @Override public void addNewUser(String userName) { if(userName == null || userName.isEmpty()) { uiView.showError("User name is empty", null); } else if(model.getUser(userName) != null) { uiView.showError("User already exists", null); } else { // create new user with empty password User u = new User(userName); if(model.createOrUpdateUser(u)) { view.askForPasswordChange(userName); view.setUserList(model.getUsers()); view.emptyNewUserNameTextField(); } } } @Override public void deleteUsers(Set<String> userName) { for(String u : userName) { model.deleteUser(u); } view.setUserList(model.getUsers()); if(userName.size() == 1) { uiView.showInfo("User \"" + userName.iterator().next() + "\" was deleted", null); } else { uiView.showInfo("Deleted users: " + Joiner.on(", ").join(userName), null); } } @Override public void loginChanged(WebResource annisRootResource, boolean isLoggedIn) { this.isLoggedIn = isLoggedIn; model.setRootResource(annisRootResource); if(isLoggedIn) { fetchFromService(); } else { clearModel(); } } @Override public void selectedTabChanged(Object selectedTab) { if(isLoggedIn && selectedTab == view) { fetchFromService(); } } }
{ "content_hash": "e21700cfc2dcee55decc6991785b1d35", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 88, "avg_line_length": 21.163120567375888, "alnum_prop": 0.6528150134048257, "repo_name": "pixeldrama/ANNIS", "id": "56c3131593f29a00be3f6a7bf50dcf5829d42283", "size": "3626", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "annis-gui/src/main/java/annis/gui/admin/controller/UserController.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "7777" }, { "name": "Awk", "bytes": "1314" }, { "name": "Batchfile", "bytes": "97" }, { "name": "CSS", "bytes": "348951" }, { "name": "HTML", "bytes": "923114" }, { "name": "Java", "bytes": "2737167" }, { "name": "JavaScript", "bytes": "667219" }, { "name": "PHP", "bytes": "524645" }, { "name": "PLpgSQL", "bytes": "409" }, { "name": "Python", "bytes": "1841" }, { "name": "SQLPL", "bytes": "560" }, { "name": "Shell", "bytes": "6309" } ], "symlink_target": "" }
@media only screen and (min-device-width: 320px) and (-webkit-min-device-pixel-ratio: 2) { .rule-without-background-image { line-height: 1.4; background: red; } .rule-with-background-image { background-image: url(/path/to/picture.png); } } @supports (display: flex) { .rule-without-background-image { color: red; } .rule-with-background-shorthand::after { content: ''; background: #f30 url(/path/to/picture.png); } } @media (max-width: 600px) { @supports (display: flex) { .rule-with-background-shorthand { display: flex; background: red url(/path/to/picture.png) 50%; color: #345; } .rule-ignored { /* bgImage: ignore */ background-image: url(/path/to/picture.png); } } .rule-with-background-image { display: block; background-image: url(/path/to/picture.png); } } @media (max-width: 600px) { /* bgImage: ignore */ @supports (display: flex) { .rule-with-background-shorthand-ignored { display: flex; background: red url(/path/to/picture.png) 50%; color: #345; } .rule-with-background-image-ignored { background-image: url(/path/to/picture.png); } } .rule-with-background-image-ignored { display: block; background-image: url(/path/to/picture.png); } } @media (min-device-width: 320px) { .rule-with-background-image-ignored { /* bgImage: ignore */ background-image: url(/path/to/picture.png); overflow: hidden; } }
{ "content_hash": "71e0f2a86b0ccfa6e1552bf402581944", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 58, "avg_line_length": 23.15068493150685, "alnum_prop": 0.5526627218934911, "repo_name": "ahtohbi4/postcss-bgimage", "id": "9aadac24b94a254aa92434051f7ceaf95fc1c0fa", "size": "1690", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/fixtures/nested_at-rules.source.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2761" }, { "name": "JavaScript", "bytes": "10459" } ], "symlink_target": "" }
package org.cellularautomaton.sample.wireworldscripted; import java.io.PrintWriter; import java.io.StringWriter; import org.cellularautomaton.CellularAutomaton; import org.cellularautomaton.space.builder.ScriptSpaceBuilder; public class WireWorldScriptedAutomatonFactory { public static CellularAutomaton<Character> createAutomaton() { StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); out.println("[config]"); out.println("states=X_o."); out.println("[rule]"); out.println("(0,0)=_ & ((-1,-1)+(-1,+0)+(-1,+1)+(+0,-1)+(+0,+1)+(+1,-1)+(+1,+0)+(+1,+1)=1o | (-1,-1)+(-1,+0)+(-1,+1)+(+0,-1)+(+0,+1)+(+1,-1)+(+1,+0)+(+1,+1)=2o) : o"); out.println("(0,0)=o:."); out.println("(0,0)=.:_"); out.println("[cells]"); out.println("XXXXXXXXXXXXXXX"); out.println("XXXXX__XX____XX"); out.println("_____X___XXXXoX"); out.println("XXXXX__XX___.XX"); out.println("XXXXXXXXXXXXXXX"); out.println("XXXXX__XX____XX"); out.println("______X__XXXXoX"); out.println("XXXXX__XX___.XX"); out.println("XXXXXXXXXXXXXXX"); out.close(); ScriptSpaceBuilder builder = new ScriptSpaceBuilder(); builder.createSpaceFromString(sw.getBuffer().toString()); CellularAutomaton<Character> automaton = new CellularAutomaton<Character>( builder.getSpaceOfCell()); return automaton; } }
{ "content_hash": "7bb1fc402b9cd4b737ee30f7a829f615", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 169, "avg_line_length": 34.25, "alnum_prop": 0.6386861313868614, "repo_name": "matthieu-vergne/Cellular-Automaton", "id": "d4b5e21ef1443616f522f28975608cce848a7ab7", "size": "1370", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cellularautomaton-samples/src/main/java/org/cellularautomaton/sample/wireworldscripted/WireWorldScriptedAutomatonFactory.java", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "366763" } ], "symlink_target": "" }
package org.apache.hadoop.hdfs.tools; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RemoteIterator; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.protocol.AddErasureCodingPolicyResponse; import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy; import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicyInfo; import org.apache.hadoop.hdfs.protocol.NoECPolicySetException; import org.apache.hadoop.hdfs.util.ECPolicyLoader; import org.apache.hadoop.io.erasurecode.ErasureCodeConstants; import org.apache.hadoop.tools.TableListing; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * CLI for the erasure code encoding operations. */ @InterfaceAudience.Private public class ECAdmin extends Configured implements Tool { public static final String NAME = "ec"; public static void main(String[] args) throws Exception { final ECAdmin admin = new ECAdmin(new Configuration()); int res = ToolRunner.run(admin, args); System.exit(res); } public ECAdmin(Configuration conf) { super(conf); } @Override public int run(String[] args) throws Exception { if (args.length == 0) { AdminHelper.printUsage(false, NAME, COMMANDS); ToolRunner.printGenericCommandUsage(System.err); return 1; } final AdminHelper.Command command = AdminHelper.determineCommand(args[0], COMMANDS); if (command == null) { System.err.println("Can't understand command '" + args[0] + "'"); if (!args[0].startsWith("-")) { System.err.println("Command names must start with dashes."); } AdminHelper.printUsage(false, NAME, COMMANDS); ToolRunner.printGenericCommandUsage(System.err); return 1; } final List<String> argsList = new LinkedList<>(); argsList.addAll(Arrays.asList(args).subList(1, args.length)); try { return command.run(getConf(), argsList); } catch (IllegalArgumentException e) { System.err.println(AdminHelper.prettifyException(e)); return -1; } } /** Command to list the set of enabled erasure coding policies. */ private static class ListECPoliciesCommand implements AdminHelper.Command { @Override public String getName() { return "-listPolicies"; } @Override public String getShortUsage() { return "[" + getName() + "]\n"; } @Override public String getLongUsage() { return getShortUsage() + "\n" + "Get the list of all erasure coding policies.\n"; } @Override public int run(Configuration conf, List<String> args) throws IOException { if (args.size() > 0) { System.err.println(getName() + ": Too many arguments"); return 1; } final DistributedFileSystem dfs = AdminHelper.getDFS(conf); try { final Collection<ErasureCodingPolicyInfo> policies = dfs.getAllErasureCodingPolicies(); if (policies.isEmpty()) { System.out.println("There is no erasure coding policies in the " + "cluster."); } else { System.out.println("Erasure Coding Policies:"); for (ErasureCodingPolicyInfo policy : policies) { if (policy != null) { System.out.println(policy); } } } } catch (IOException e) { System.err.println(AdminHelper.prettifyException(e)); return 2; } return 0; } } /** Command to add a set of erasure coding policies. */ private static class AddECPoliciesCommand implements AdminHelper.Command { @Override public String getName() { return "-addPolicies"; } @Override public String getShortUsage() { return "[" + getName() + " -policyFile <file>]\n"; } @Override public String getLongUsage() { final TableListing listing = AdminHelper.getOptionDescriptionListing(); listing.addRow("<file>", "The path of the xml file which defines the EC policies to add"); return getShortUsage() + "\n" + "Add a list of user defined erasure coding policies.\n" + listing.toString(); } @Override public int run(Configuration conf, List<String> args) throws IOException { final String filePath = StringUtils.popOptionWithArgument("-policyFile", args); if (filePath == null) { System.err.println("Please specify the path with -policyFile.\nUsage: " + getLongUsage()); return 1; } if (args.size() > 0) { System.err.println(getName() + ": Too many arguments"); return 1; } final DistributedFileSystem dfs = AdminHelper.getDFS(conf); try { List<ErasureCodingPolicy> policies = new ECPolicyLoader().loadPolicy(filePath); if (policies.size() > 0) { AddErasureCodingPolicyResponse[] responses = dfs.addErasureCodingPolicies( policies.toArray(new ErasureCodingPolicy[policies.size()])); for (AddErasureCodingPolicyResponse response : responses) { System.out.println(response); } } else { System.out.println("No EC policy parsed out from " + filePath); } } catch (IOException e) { System.err.println(AdminHelper.prettifyException(e)); return 2; } return 0; } } /** Command to get the erasure coding policy for a file or directory. */ private static class GetECPolicyCommand implements AdminHelper.Command { @Override public String getName() { return "-getPolicy"; } @Override public String getShortUsage() { return "[" + getName() + " -path <path>]\n"; } @Override public String getLongUsage() { final TableListing listing = AdminHelper.getOptionDescriptionListing(); listing.addRow("<path>", "The path of the file/directory for getting the erasure coding " + "policy"); return getShortUsage() + "\n" + "Get the erasure coding policy of a file/directory.\n\n" + listing.toString(); } @Override public int run(Configuration conf, List<String> args) throws IOException { final String path = StringUtils.popOptionWithArgument("-path", args); if (path == null) { System.err.println("Please specify the path with -path.\nUsage: " + getLongUsage()); return 1; } if (args.size() > 0) { System.err.println(getName() + ": Too many arguments"); return 1; } final Path p = new Path(path); final DistributedFileSystem dfs = AdminHelper.getDFS(p.toUri(), conf); try { ErasureCodingPolicy ecPolicy = dfs.getErasureCodingPolicy(p); if (ecPolicy != null) { System.out.println(ecPolicy.getName()); } else { System.out.println("The erasure coding policy of " + path + " is " + "unspecified"); } } catch (Exception e) { System.err.println(AdminHelper.prettifyException(e)); return 2; } return 0; } } /** Command to remove an erasure coding policy. */ private static class RemoveECPolicyCommand implements AdminHelper.Command { @Override public String getName() { return "-removePolicy"; } @Override public String getShortUsage() { return "[" + getName() + " -policy <policy>]\n"; } @Override public String getLongUsage() { TableListing listing = AdminHelper.getOptionDescriptionListing(); listing.addRow("<policy>", "The name of the erasure coding policy"); return getShortUsage() + "\n" + "Remove an user defined erasure coding policy.\n" + listing.toString(); } @Override public int run(Configuration conf, List<String> args) throws IOException { final String ecPolicyName = StringUtils.popOptionWithArgument( "-policy", args); if (ecPolicyName == null) { System.err.println("Please specify the policy name.\nUsage: " + getLongUsage()); return 1; } if (args.size() > 0) { System.err.println(getName() + ": Too many arguments"); return 1; } final DistributedFileSystem dfs = AdminHelper.getDFS(conf); try { dfs.removeErasureCodingPolicy(ecPolicyName); System.out.println("Erasure coding policy " + ecPolicyName + "is removed"); } catch (IOException e) { System.err.println(AdminHelper.prettifyException(e)); return 2; } return 0; } } /** Command to set the erasure coding policy to a file/directory. */ private static class SetECPolicyCommand implements AdminHelper.Command { @Override public String getName() { return "-setPolicy"; } @Override public String getShortUsage() { return "[" + getName() + " -path <path> [-policy <policy>] [-replicate]]\n"; } @Override public String getLongUsage() { TableListing listing = AdminHelper.getOptionDescriptionListing(); listing.addRow("<path>", "The path of the file/directory to set " + "the erasure coding policy"); listing.addRow("<policy>", "The name of the erasure coding policy"); listing.addRow("-replicate", "force 3x replication scheme on the directory"); return getShortUsage() + "\n" + "Set the erasure coding policy for a file/directory.\n\n" + listing.toString() + "\n" + "-replicate and -policy are optional arguments. They cannot been " + "used at the same time"; } @Override public int run(Configuration conf, List<String> args) throws IOException { final String path = StringUtils.popOptionWithArgument("-path", args); if (path == null) { System.err.println("Please specify the path for setting the EC " + "policy.\nUsage: " + getLongUsage()); return 1; } String ecPolicyName = StringUtils.popOptionWithArgument("-policy", args); final boolean replicate = StringUtils.popOption("-replicate", args); if (args.size() > 0) { System.err.println(getName() + ": Too many arguments"); return 1; } if (replicate) { if (ecPolicyName != null) { System.err.println(getName() + ": -replicate and -policy cannot been used at the same time"); return 2; } ecPolicyName = ErasureCodeConstants.REPLICATION_POLICY_NAME; } final Path p = new Path(path); final DistributedFileSystem dfs = AdminHelper.getDFS(p.toUri(), conf); try { dfs.setErasureCodingPolicy(p, ecPolicyName); if (ecPolicyName == null){ ecPolicyName = "default"; } System.out.println("Set " + ecPolicyName + " erasure coding policy on" + " " + path); RemoteIterator<FileStatus> dirIt = dfs.listStatusIterator(p); if (dirIt.hasNext()) { System.out.println("Warning: setting erasure coding policy on a " + "non-empty directory will not automatically convert existing " + "files to " + ecPolicyName + " erasure coding policy"); } } catch (Exception e) { System.err.println(AdminHelper.prettifyException(e)); return 3; } return 0; } } /** Command to unset the erasure coding policy set for a file/directory. */ private static class UnsetECPolicyCommand implements AdminHelper.Command { @Override public String getName() { return "-unsetPolicy"; } @Override public String getShortUsage() { return "[" + getName() + " -path <path>]\n"; } @Override public String getLongUsage() { TableListing listing = AdminHelper.getOptionDescriptionListing(); listing.addRow("<path>", "The path of the directory " + "from which the erasure coding policy will be unset."); return getShortUsage() + "\n" + "Unset the erasure coding policy for a directory.\n\n" + listing.toString(); } @Override public int run(Configuration conf, List<String> args) throws IOException { final String path = StringUtils.popOptionWithArgument("-path", args); if (path == null) { System.err.println("Please specify a path.\nUsage: " + getLongUsage()); return 1; } if (args.size() > 0) { System.err.println(getName() + ": Too many arguments"); return 1; } final Path p = new Path(path); final DistributedFileSystem dfs = AdminHelper.getDFS(p.toUri(), conf); try { dfs.unsetErasureCodingPolicy(p); System.out.println("Unset erasure coding policy from " + path); RemoteIterator<FileStatus> dirIt = dfs.listStatusIterator(p); if (dirIt.hasNext()) { System.out.println("Warning: unsetting erasure coding policy on a " + "non-empty directory will not automatically convert existing" + " files to replicated data."); } } catch (NoECPolicySetException e) { System.err.println(AdminHelper.prettifyException(e)); System.err.println("Use '-setPolicy -path <PATH> -replicate' to enforce" + " default replication policy irrespective of EC policy" + " defined on parent."); return 2; } catch (Exception e) { System.err.println(AdminHelper.prettifyException(e)); return 2; } return 0; } } /** Command to list the set of supported erasure coding codecs and coders. */ private static class ListECCodecsCommand implements AdminHelper.Command { @Override public String getName() { return "-listCodecs"; } @Override public String getShortUsage() { return "[" + getName() + "]\n"; } @Override public String getLongUsage() { return getShortUsage() + "\n" + "Get the list of supported erasure coding codecs and coders.\n" + "A coder is an implementation of a codec. A codec can have " + "different implementations, thus different coders.\n" + "The coders for a codec are listed in a fall back order.\n"; } @Override public int run(Configuration conf, List<String> args) throws IOException { if (args.size() > 0) { System.err.println(getName() + ": Too many arguments"); return 1; } final DistributedFileSystem dfs = AdminHelper.getDFS(conf); try { Map<String, String> codecs = dfs.getAllErasureCodingCodecs(); if (codecs.isEmpty()) { System.out.println("No erasure coding codecs are supported on the " + "cluster."); } else { System.out.println("Erasure Coding Codecs: Codec [Coder List]"); for (Map.Entry<String, String> codec : codecs.entrySet()) { if (codec != null) { System.out.println("\t" + codec.getKey().toUpperCase() + " [" + codec.getValue().toUpperCase() +"]"); } } } } catch (IOException e) { System.err.println(AdminHelper.prettifyException(e)); return 2; } return 0; } } /** Command to enable an existing erasure coding policy. */ private static class EnableECPolicyCommand implements AdminHelper.Command { @Override public String getName() { return "-enablePolicy"; } @Override public String getShortUsage() { return "[" + getName() + " -policy <policy>]\n"; } @Override public String getLongUsage() { TableListing listing = AdminHelper.getOptionDescriptionListing(); listing.addRow("<policy>", "The name of the erasure coding policy"); return getShortUsage() + "\n" + "Enable the erasure coding policy.\n\n" + listing.toString(); } @Override public int run(Configuration conf, List<String> args) throws IOException { final String ecPolicyName = StringUtils.popOptionWithArgument("-policy", args); if (ecPolicyName == null) { System.err.println("Please specify the policy name.\nUsage: " + getLongUsage()); return 1; } if (args.size() > 0) { System.err.println(getName() + ": Too many arguments"); return 1; } final DistributedFileSystem dfs = AdminHelper.getDFS(conf); try { dfs.enableErasureCodingPolicy(ecPolicyName); System.out.println("Erasure coding policy " + ecPolicyName + " is enabled"); } catch (IOException e) { System.err.println(AdminHelper.prettifyException(e)); return 2; } return 0; } } /** Command to disable an existing erasure coding policy. */ private static class DisableECPolicyCommand implements AdminHelper.Command { @Override public String getName() { return "-disablePolicy"; } @Override public String getShortUsage() { return "[" + getName() + " -policy <policy>]\n"; } @Override public String getLongUsage() { TableListing listing = AdminHelper.getOptionDescriptionListing(); listing.addRow("<policy>", "The name of the erasure coding policy"); return getShortUsage() + "\n" + "Disable the erasure coding policy.\n\n" + listing.toString(); } @Override public int run(Configuration conf, List<String> args) throws IOException { final String ecPolicyName = StringUtils.popOptionWithArgument("-policy", args); if (ecPolicyName == null) { System.err.println("Please specify the policy name.\nUsage: " + getLongUsage()); return 1; } if (args.size() > 0) { System.err.println(getName() + ": Too many arguments"); return 1; } final DistributedFileSystem dfs = AdminHelper.getDFS(conf); try { dfs.disableErasureCodingPolicy(ecPolicyName); System.out.println("Erasure coding policy " + ecPolicyName + " is disabled"); } catch (IOException e) { System.err.println(AdminHelper.prettifyException(e)); return 2; } return 0; } } private static final AdminHelper.Command[] COMMANDS = { new ListECPoliciesCommand(), new AddECPoliciesCommand(), new GetECPolicyCommand(), new RemoveECPolicyCommand(), new SetECPolicyCommand(), new UnsetECPolicyCommand(), new ListECCodecsCommand(), new EnableECPolicyCommand(), new DisableECPolicyCommand() }; }
{ "content_hash": "e887cc5bb052757fcaef5f81c81f34c9", "timestamp": "", "source": "github", "line_count": 587, "max_line_length": 80, "avg_line_length": 32.65758091993186, "alnum_prop": 0.6192488262910798, "repo_name": "littlezhou/hadoop", "id": "5f8626e07021e101295fd3abfbb3a20edc7ebcd8", "size": "19966", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/ECAdmin.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "77936" }, { "name": "C", "bytes": "1688744" }, { "name": "C++", "bytes": "2802413" }, { "name": "CMake", "bytes": "111456" }, { "name": "CSS", "bytes": "109405" }, { "name": "Dockerfile", "bytes": "6880" }, { "name": "HTML", "bytes": "394726" }, { "name": "Java", "bytes": "89103548" }, { "name": "JavaScript", "bytes": "1149751" }, { "name": "PLpgSQL", "bytes": "13964" }, { "name": "Python", "bytes": "65367" }, { "name": "Shell", "bytes": "512720" }, { "name": "TLA", "bytes": "14997" }, { "name": "TeX", "bytes": "19322" }, { "name": "XSLT", "bytes": "18026" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Mycologia 63(4): 840 (1971) #### Original name Manglicola Kohlm. & E. Kohlm. ### Remarks null
{ "content_hash": "8c89ae2e0d7caa47ae856ff3ba6c30d4", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 14, "alnum_prop": 0.6868131868131868, "repo_name": "mdoering/backbone", "id": "7a00b3e9a75dc4baf31c5bd036e4f94133f1ba87", "size": "233", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Jahnulales/Aliquandostipitaceae/Manglicola/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version="1.0" ?><!DOCTYPE TS><TS language="nb" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Bitcoin</source> <translation>Om Bitcoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Bitcoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Bitcoin&lt;/b&gt; versjon</translation> </message> <message> <location line="+57"/> <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 (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Dette er eksperimentell programvare. Distribuert under MIT/X11 programvarelisensen, se medfølgende fil COPYING eller http://www.opensource.org/licenses/mit-license.php. Dette produktet inneholder programvare utviklet av OpenSSL prosjektet for bruk i OpenSSL Toolkit (http://www.openssl.org/) og kryptografisk programvare skrevet av Eric Young (eay@cryptsoft.com) og UPnP programvare skrevet av Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The Bitcoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adressebok</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dobbeltklikk for å redigere adresse eller merkelapp</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Lag en ny adresse</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopier den valgte adressen til systemets utklippstavle</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Ny Adresse</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Bitcoin 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>Dette er dine Bitcoin-adresser for mottak av betalinger. Du kan gi forskjellige adresser til alle som skal betale deg for å holde bedre oversikt.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopier Adresse</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Vis &amp;QR Kode</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Bitcoin address</source> <translation>Signer en melding for å bevise at du eier en Bitcoin-adresse</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Signér &amp;Melding</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Slett den valgte adressen fra listen.</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Eksporter data fra nåværende fane til fil</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Bitcoin address</source> <translation>Verifiser en melding for å være sikker på at den ble signert av en angitt Bitcoin-adresse</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verifiser Melding</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Slett</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopier &amp;Merkelapp</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Rediger</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Send &amp;Coins</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Eksporter adressebok</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommaseparert fil (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Feil ved eksportering</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kunne ikke skrive til filen %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Merkelapp</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresse</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(ingen merkelapp)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Dialog for Adgangsfrase</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Angi adgangsfrase</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Ny adgangsfrase</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Gjenta ny adgangsfrase</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>Skriv inn den nye adgangsfrasen for lommeboken.&lt;br/&gt;Vennligst bruk en adgangsfrase med &lt;b&gt;10 eller flere tilfeldige tegn&lt;/b&gt;, eller &lt;b&gt;åtte eller flere ord&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Krypter lommebok</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Denne operasjonen krever adgangsfrasen til lommeboken for å låse den opp.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Lås opp lommebok</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Denne operasjonen krever adgangsfrasen til lommeboken for å dekryptere den.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Dekrypter lommebok</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Endre adgangsfrase</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Skriv inn gammel og ny adgangsfrase for lommeboken.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Bekreft kryptering av lommebok</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;!</source> <translation>Advarsel: Hvis du krypterer lommeboken og mister adgangsfrasen, så vil du &lt;b&gt;MISTE ALLE DINE BITCOINS&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Er du sikker på at du vil kryptere lommeboken?</translation> </message> <message> <location line="+15"/> <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>VIKTIG: Tidligere sikkerhetskopier av din lommebok-fil, bør erstattes med den nylig genererte, krypterte filen, da de blir ugyldiggjort av sikkerhetshensyn så snart du begynner å bruke den nye krypterte lommeboken.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Advarsel: Caps Lock er på !</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Lommebok kryptert</translation> </message> <message> <location line="-56"/> <source>Bitcoin 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>Bitcoin vil nå lukkes for å fullføre krypteringsprosessen. Husk at kryptering av lommeboken ikke fullt ut kan beskytte dine bitcoins fra å bli stjålet om skadevare infiserer datamaskinen.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Kryptering av lommebok feilet</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Kryptering av lommebok feilet på grunn av en intern feil. Din lommebok ble ikke kryptert.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>De angitte adgangsfrasene er ulike.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Opplåsing av lommebok feilet</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Adgangsfrasen angitt for dekryptering av lommeboken var feil.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Dekryptering av lommebok feilet</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Adgangsfrase for lommebok endret.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Signer &amp;melding...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Synkroniserer med nettverk...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Oversikt</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Vis generell oversikt over lommeboken</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transaksjoner</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Vis transaksjonshistorikk</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Rediger listen over adresser og deres merkelapper</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Vis listen over adresser for mottak av betalinger</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Avslutt</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Avslutt applikasjonen</translation> </message> <message> <location line="+4"/> <source>Show information about Bitcoin</source> <translation>Vis informasjon om Bitcoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Om &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Vis informasjon om Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Innstillinger...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Krypter Lommebok...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>Lag &amp;Sikkerhetskopi av Lommebok...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Endre Adgangsfrase...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importere blokker...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Re-indekserer blokker på disk...</translation> </message> <message> <location line="-347"/> <source>Send coins to a Bitcoin address</source> <translation>Send til en Bitcoin-adresse</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Bitcoin</source> <translation>Endre oppsett for Bitcoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Sikkerhetskopiér lommebok til annet sted</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Endre adgangsfrasen brukt for kryptering av lommebok</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Feilsøkingsvindu</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Åpne konsoll for feilsøk og diagnostikk</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verifiser melding...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Bitcoin</source> <translation>Bitcoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Lommebok</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Send</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Motta</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Adressebok</translation> </message> <message> <location line="+22"/> <source>&amp;About Bitcoin</source> <translation>&amp;Om Bitcoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Gjem / vis</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Vis eller skjul hovedvinduet</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Krypter de private nøklene som tilhører lommeboken din</translation> </message> <message> <location line="+7"/> <source>Sign messages with your Bitcoin addresses to prove you own them</source> <translation>Signér en melding for å bevise at du eier denne adressen</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Bitcoin addresses</source> <translation>Bekreft meldinger for å være sikker på at de ble signert av en angitt Bitcoin-adresse</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Fil</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Innstillinger</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Hjelp</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Verktøylinje for faner</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnett]</translation> </message> <message> <location line="+47"/> <source>Bitcoin client</source> <translation>Bitcoinklient</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Bitcoin network</source> <translation><numerusform>%n aktiv forbindelse til Bitcoin-nettverket</numerusform><numerusform>%n aktive forbindelser til Bitcoin-nettverket</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Lastet %1 blokker med transaksjonshistorikk.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Transaksjoner etter dette vil ikke være synlige enda.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <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>Denne transaksjonen overstiger størrelsesbegrensningen. Du kan likevel sende den med et gebyr på %1, som går til nodene som prosesserer transaksjonen din og støtter nettverket. Vil du betale gebyret?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Ajour</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Kommer ajour...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Bekreft transaksjonsgebyr</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Sendt transaksjon</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Innkommende transaksjon</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Dato: %1 Beløp: %2 Type: %3 Adresse: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI håndtering</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Bitcoin address or malformed URI parameters.</source> <translation>URI kunne ikke tolkes! Dette kan forårsakes av en ugyldig Bitcoin-adresse eller feil i URI-parametere.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Lommeboken er &lt;b&gt;kryptert&lt;/b&gt; og for tiden &lt;b&gt;ulåst&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Lommeboken er &lt;b&gt;kryptert&lt;/b&gt; og for tiden &lt;b&gt;låst&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Bitcoin can no longer continue safely and will quit.</source> <translation>En fatal feil har inntruffet. Det er ikke trygt å fortsette og Bitcoin må derfor avslutte.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Nettverksvarsel</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Rediger adresse</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Merkelapp</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Merkelappen koblet til denne adressen i adresseboken</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adresse</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adressen til denne oppføringen i adresseboken. Denne kan kun endres for utsendingsadresser.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Ny mottaksadresse</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Ny utsendingsadresse</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Rediger mottaksadresse</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Rediger utsendingsadresse</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Den oppgitte adressen &quot;%1&quot; er allerede i adresseboken.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Bitcoin address.</source> <translation>Den angitte adressed &quot;%1&quot; er ikke en gyldig Bitcoin-adresse.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Kunne ikke låse opp lommeboken.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Generering av ny nøkkel feilet.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Bitcoin-Qt</source> <translation>Bitcoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versjon</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Bruk:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>kommandolinjevalg</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>valg i brukergrensesnitt</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Sett språk, for eksempel &quot;nb_NO&quot; (standardverdi: fra operativsystem)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Start minimert </translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Vis splashskjerm ved oppstart (standardverdi: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Innstillinger</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Hoved</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Betal transaksjons&amp;gebyr</translation> </message> <message> <location line="+31"/> <source>Automatically start Bitcoin after logging in to the system.</source> <translation>Start Bitcoin automatisk etter innlogging.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Bitcoin on system login</source> <translation>&amp;Start Bitcoin ved systeminnlogging</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Nettverk</translation> </message> <message> <location line="+6"/> <source>Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Åpne automatisk Bitcoin klientporten på ruteren. Dette virker kun om din ruter støtter UPnP og dette er påslått.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Sett opp port vha. &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the Bitcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Koble til Bitcoin-nettverket gjennom en SOCKS proxy (f.eks. ved tilkobling gjennom Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Koble til gjenom SOCKS proxy:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP-adresse for mellomtjener (f.eks. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Port:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Proxyens port (f.eks. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Versjon:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Proxyens SOCKS versjon (f.eks. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Vindu</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Vis kun ikon i systemkurv etter minimering av vinduet.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimer til systemkurv istedenfor oppgavelinjen</translation> </message> <message> <location line="+7"/> <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>Minimerer vinduet istedenfor å avslutte applikasjonen når vinduet lukkes. Når dette er slått på avsluttes applikasjonen kun ved å velge avslutt i menyen.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimer ved lukking</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Visning</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Språk for brukergrensesnitt</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Bitcoin.</source> <translation>Språket for brukergrensesnittet kan settes her. Innstillingen trer i kraft ved omstart av Bitcoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Enhet for visning av beløper:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Velg standard delt enhet for visning i grensesnittet og for sending av bitcoins.</translation> </message> <message> <location line="+9"/> <source>Whether to show Bitcoin addresses in the transaction list or not.</source> <translation>Om Bitcoin-adresser skal vises i transaksjonslisten eller ikke.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Vis adresser i transaksjonslisten</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Avbryt</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Bruk</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>standardverdi</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Advarsel</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Bitcoin.</source> <translation>Denne innstillingen trer i kraft etter omstart av Bitcoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Angitt proxyadresse er ugyldig.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Skjema</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Bitcoin network after a connection is established, but this process has not completed yet.</source> <translation>Informasjonen som vises kan være foreldet. Din lommebok synkroniseres automatisk med Bitcoin-nettverket etter at tilkobling er opprettet, men denne prosessen er ikke ferdig enda.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Ubekreftet</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Lommebok</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Umoden:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Minet saldo har ikke modnet enda</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Siste transaksjoner&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Din nåværende saldo</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Totalt antall ubekreftede transaksjoner som ikke telles med i saldo enda</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>ute av synk</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start bitcoin: click-to-pay handler</source> <translation>Kan ikke starte Bit-coin: klikk-og-betal håndterer</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Dialog for QR Kode</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Etterspør Betaling</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Beløp:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Merkelapp:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Melding:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Lagre Som...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Feil ved koding av URI i QR kode.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Angitt beløp er ugyldig.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Resulterende URI for lang, prøv å redusere teksten for merkelapp / melding.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Lagre QR Kode</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG bilder (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Klientnavn</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>-</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Klientversjon</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informasjon</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Bruker OpenSSL versjon</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Oppstartstidspunkt</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Nettverk</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Antall tilkoblinger</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>På testnett</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Blokkjeden</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Nåværende antall blokker</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Estimert totalt antall blokker</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Tidspunkt for siste blokk</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Åpne</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Kommandolinjevalg</translation> </message> <message> <location line="+7"/> <source>Show the Bitcoin-Qt help message to get a list with possible Bitcoin command-line options.</source> <translation>Vis Bitcoin-Qt hjelpemelding for å få en liste med mulige kommandolinjevalg.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Vis</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konsoll</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Byggedato</translation> </message> <message> <location line="-104"/> <source>Bitcoin - Debug window</source> <translation>Bitcoin - vindu for feilsøk</translation> </message> <message> <location line="+25"/> <source>Bitcoin Core</source> <translation>Bitcoin Kjerne</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Loggfil for feilsøk</translation> </message> <message> <location line="+7"/> <source>Open the Bitcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Åpne Bitcoin loggfil for feilsøk fra datamappen. Dette kan ta noen sekunder for store loggfiler.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Tøm konsoll</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Bitcoin RPC console.</source> <translation>Velkommen til Bitcoin RPC konsoll.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Bruk opp og ned pil for å navigere historikken, og &lt;b&gt;Ctrl-L&lt;/b&gt; for å tømme skjermen.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Skriv &lt;b&gt;help&lt;/b&gt; for en oversikt over kommandoer.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Send Bitcoins</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Send til flere enn én mottaker</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Legg til Mottaker</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Fjern alle transaksjonsfelter</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Fjern &amp;Alt</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Bekreft sending</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>S&amp;avslutt</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; til %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Bekreft sending av bitcoins</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Er du sikker på at du vil sende %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> og </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Adresse for mottaker er ugyldig.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Beløpen som skal betales må være over 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Beløpet overstiger saldo.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Totalbeløpet overstiger saldo etter at %1 transaksjonsgebyr er lagt til.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Duplikate adresser funnet. Kan bare sende én gang til hver adresse per operasjon.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Feil: Opprettelse av transaksjon feilet </translation> </message> <message> <location line="+5"/> <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>Feil: Transaksjonen ble avvist. Dette kan skje om noe av beløpet allerede var brukt, f.eks. hvis du kopierte wallet.dat og noen bitcoins ble brukt i kopien men ikke ble markert som brukt her.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Skjema</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Beløp:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Betal &amp;Til:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Adressen betalingen skal sendes til (f.eks. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Skriv inn en merkelapp for denne adressen for å legge den til i din adressebok</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Merkelapp:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Velg adresse fra adresseboken</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Lim inn adresse fra utklippstavlen</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Fjern denne mottakeren</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Skriv inn en Bitcoin adresse (f.eks. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Signaturer - Signer / Verifiser en melding</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Signér Melding</translation> </message> <message> <location line="+6"/> <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>Du kan signere meldinger med dine adresser for å bevise at du eier dem. Ikke signér vage meldinger da phishing-angrep kan prøve å lure deg til å signere din identitet over til andre. Signér kun fullt detaljerte utsagn som du er enig i.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Adressen for signering av meldingen (f.eks. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Velg en adresse fra adresseboken</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Lim inn adresse fra utklippstavlen</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Skriv inn meldingen du vil signere her</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Kopier valgt signatur til utklippstavle</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Bitcoin address</source> <translation>Signer meldingen for å bevise at du eier denne Bitcoin-adressen</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Tilbakestill alle felter for meldingssignering</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Fjern &amp;Alt</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Verifiser Melding</translation> </message> <message> <location line="+6"/> <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>Angi adresse for signering, melding (vær sikker på at du kopierer linjeskift, mellomrom, tab, etc. helt nøyaktig) og signatur under for å verifisere meldingen. Vær forsiktig med at du ikke gir signaturen mer betydning enn det som faktisk står i meldingen, for å unngå å bli lurt av såkalte &quot;man-in-the-middle&quot; angrep.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Adressen meldingen var signert med (f.eks. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Bitcoin address</source> <translation>Verifiser meldingen for å være sikker på at den ble signert av den angitte Bitcoin-adressen</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Tilbakestill alle felter for meldingsverifikasjon</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Skriv inn en Bitcoin adresse (f.eks. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Klikk &quot;Signer Melding&quot; for å generere signatur</translation> </message> <message> <location line="+3"/> <source>Enter Bitcoin signature</source> <translation>Angi Bitcoin signatur</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Angitt adresse er ugyldig.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Vennligst sjekk adressen og prøv igjen.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Angitt adresse refererer ikke til en nøkkel.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Opplåsing av lommebok ble avbrutt.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Privat nøkkel for den angitte adressen er ikke tilgjengelig.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Signering av melding feilet.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Melding signert.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Signaturen kunne ikke dekodes.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Vennligst sjekk signaturen og prøv igjen.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Signaturen passer ikke til meldingen.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verifikasjon av melding feilet.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Melding verifisert.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Bitcoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnett]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Åpen til %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/frakoblet</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/ubekreftet</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 bekreftelser</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, kringkast gjennom %n node</numerusform><numerusform>, kringkast gjennom %n noder</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Kilde</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generert</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Fra</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Til</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>egen adresse</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>merkelapp</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Kredit</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>blir moden om %n blokk</numerusform><numerusform>blir moden om %n blokker</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>ikke akseptert</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debet</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Transaksjonsgebyr</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Nettobeløp</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Melding</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Kommentar</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Transaksjons-ID</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature a certain number of 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>Genererte bitcoins må modnes 120 blokker før de kan brukes. Da du genererte denne blokken ble den kringkastet til nettverket for å legges til i blokkjeden. Hvis den ikke kommer inn i kjeden får den tilstanden &quot;ikke akseptert&quot; og vil ikke kunne brukes. Dette skjer noen ganger hvis en annen node genererer en blokk noen sekunder fra din.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informasjon for feilsøk</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transaksjon</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Inndata</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Beløp</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>sann</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>usann</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, har ikke blitt kringkastet uten problemer enda.</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>ukjent</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Transaksjonsdetaljer</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Her vises en detaljert beskrivelse av transaksjonen</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresse</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Beløp</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Åpen til %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Frakoblet (%1 bekreftelser)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Ubekreftet (%1 av %2 bekreftelser)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Bekreftet (%1 bekreftelser)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Minet saldo blir tilgjengelig når den modner om %n blokk</numerusform><numerusform>Minet saldo blir tilgjengelig når den modner om %n blokker</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Denne blokken har ikke blitt mottatt av noen andre noder og vil sannsynligvis ikke bli akseptert!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generert men ikke akseptert</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Mottatt med</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Mottatt fra</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Sendt til</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Betaling til deg selv</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Utvunnet</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>-</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Transaksjonsstatus. Hold muspekeren over dette feltet for å se antall bekreftelser.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Dato og tid for da transaksjonen ble mottat.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Type transaksjon.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Mottaksadresse for transaksjonen</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Beløp fjernet eller lagt til saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Alle</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>I dag</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Denne uken</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Denne måneden</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Forrige måned</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Dette året</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Intervall...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Mottatt med</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Sendt til</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Til deg selv</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Utvunnet</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Andre</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Skriv inn adresse eller merkelapp for søk</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Minimumsbeløp</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopier adresse</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopier merkelapp</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopiér beløp</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Kopier transaksjons-ID</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Rediger merkelapp</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Vis transaksjonsdetaljer</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Eksporter transaksjonsdata</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommaseparert fil (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Bekreftet</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Merkelapp</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresse</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Beløp</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Feil ved eksport</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kunne ikke skrive til filen %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Intervall:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>til</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Send Bitcoins</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Eksporter data fra nåværende fane til fil</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Sikkerhetskopier lommebok</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Lommebokdata (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Sikkerhetskopiering feilet</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>En feil oppstod under lagringen av lommeboken til den nye plasseringen.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Sikkerhetskopiering fullført</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Lommebokdata ble lagret til den nye plasseringen. </translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Bitcoin version</source> <translation>Bitcoin versjon</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Bruk:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or bitcoind</source> <translation>Send kommando til -server eller bitcoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>List opp kommandoer</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Vis hjelpetekst for en kommando</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Innstillinger:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: bitcoin.conf)</source> <translation>Angi konfigurasjonsfil (standardverdi: bitcoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: bitcoind.pid)</source> <translation>Angi pid-fil (standardverdi: bitcoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Angi mappe for datafiler</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Sett størrelse på mellomlager for database i megabytes (standardverdi: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>Lytt etter tilkoblinger på &lt;port&gt; (standardverdi: 8333 eller testnet: 18333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Hold maks &lt;n&gt; koblinger åpne til andre noder (standardverdi: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Koble til node for å hente adresser til andre noder, koble så fra igjen</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Angi din egen offentlige adresse</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Grenseverdi for å koble fra noder med dårlig oppførsel (standardverdi: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Antall sekunder noder med dårlig oppførsel hindres fra å koble til på nytt (standardverdi: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>En feil oppstod ved opprettelse av RPC port %u for lytting: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation>Lytt etter JSON-RPC tilkoblinger på &lt;port&gt; (standardverdi: 8332 or testnet: 18332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Ta imot kommandolinje- og JSON-RPC-kommandoer</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Kjør i bakgrunnen som daemon og ta imot kommandoer</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Bruk testnettverket</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Ta imot tilkoblinger fra utsiden (standardverdi: 1 hvis uten -proxy eller -connect)</translation> </message> <message> <location line="-80"/> <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;Bitcoin Alert&quot; admin@foo.com </source> <translation>%s, du må angi rpcpassord i konfigurasjonsfilen. %s Det anbefales at du bruker det følgende tilfeldige passordet: rpcbruker=bitcoinrpc rpcpassord=%s (du behøver ikke å huske passordet) Brukernavnet og passordet MÅ IKKE være like. Om filen ikke eksisterer, opprett den nå med eier-kun-les filrettigheter. Det er også anbefalt at å sette varselsmelding slik du får melding om problemer. For eksempel: varselmelding=echo %%s | mail -s &quot;Bitcoin varsel&quot; admin@foo.com</translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>En feil oppstod under oppsettet av RPC port %u for IPv6, tilbakestilles til IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Bind til angitt adresse. Bruk [vertsmaskin]:port notasjon for IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Bitcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <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> <message> <location line="+4"/> <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 line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Kjør kommando når relevant varsel blir mottatt (%s i cmd er erstattet med TxID)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Kjør kommando når en lommeboktransaksjon endres (%s i cmd er erstattet med TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Sett maks størrelse for transaksjoner med høy prioritet / lavt gebyr, i bytes (standardverdi: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Advarsel: -paytxfee er satt veldig høyt! Dette er transaksjonsgebyret du betaler når du sender transaksjoner.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Advarsel: Viste transaksjoner kan være feil! Du, eller andre noder, kan trenge en oppgradering.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Bitcoin will not work properly.</source> <translation>Advarsel: Vennligst undersøk at din datamaskin har riktig dato og klokkeslett! Hvis klokken er stilt feil vil ikke Bitcoin fungere riktig.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <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 type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Valg for opprettelse av blokker:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Koble kun til angitt(e) node(r)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Oppdaget korrupt blokkdatabase</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Oppdag egen IP-adresse (standardverdi: 1 ved lytting og uten -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Ønsker du å gjenopprette blokkdatabasen nå?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Feil under oppstart av lommebokdatabasemiljø %s!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Feil under åpning av blokkdatabase</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Kunne ikke lytte på noen port. Bruk -listen=0 hvis det er dette du vil.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Finn andre noder gjennom DNS-oppslag (standardverdi: 1 med mindre -connect er oppgit)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Gjenopprett blokkjedeindex fra blk000??.dat filer</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Verifiserer blokker...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Verifiserer lommebok...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Ugyldig -tor adresse: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maks mottaksbuffer per forbindelse, &lt;n&gt;*1000 bytes (standardverdi: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maks sendebuffer per forbindelse, &lt;n&gt;*1000 bytes (standardverdi: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Koble kun til noder i nettverket &lt;nett&gt; (IPv4, IPv6 eller Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Skriv ekstra informasjon for feilsøk. Medfører at alle -debug* valg tas med</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Skriv ekstra informasjon for feilsøk av nettverk</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Sett tidsstempel på debugmeldinger</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>SSL valg: (se Bitcoin Wiki for instruksjoner for oppsett av SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Velg versjon av socks proxy (4-5, standardverdi 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Send spor/debug informasjon til konsollet istedenfor debug.log filen</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Send spor/debug informasjon til debugger</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Sett maks blokkstørrelse i bytes (standardverdi: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Sett minimum blokkstørrelse i bytes (standardverdi: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Krymp debug.log filen når klienten starter (standardverdi: 1 hvis uten -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Angi tidsavbrudd for forbindelse i millisekunder (standardverdi: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Bruk UPnP for lytteport (standardverdi: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Bruk UPnP for lytteport (standardverdi: 1 ved lytting)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Bruk en proxy for å nå skjulte tor tjenester (standardverdi: samme som -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Brukernavn for JSON-RPC forbindelser</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Advarsel: Denne versjonen er foreldet, oppgradering kreves!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Passord for JSON-RPC forbindelser</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Tillat JSON-RPC tilkoblinger fra angitt IP-adresse</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Send kommandoer til node på &lt;ip&gt; (standardverdi: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Eksekvér kommando når beste blokk endrer seg (%s i kommandoen erstattes med blokkens hash)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Oppgradér lommebok til nyeste format</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Angi størrelse på nøkkel-lager til &lt;n&gt; (standardverdi: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Se gjennom blokk-kjeden etter manglende lommeboktransaksjoner</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Bruk OpenSSL (https) for JSON-RPC forbindelser</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Servers sertifikat (standardverdi: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Servers private nøkkel (standardverdi: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Akseptable krypteringsmetoder (standardverdi: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Denne hjelpemeldingen</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Kan ikke binde til %s på denne datamaskinen (bind returnerte feil %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Koble til gjennom socks proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Tillat DNS oppslag for -addnode, -seednode og -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Laster adresser...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Feil ved lasting av wallet.dat: Lommeboken er skadet</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Bitcoin</source> <translation>Feil ved lasting av wallet.dat: Lommeboken krever en nyere versjon av Bitcoin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Bitcoin to complete</source> <translation>Lommeboken måtte skrives om: start Bitcoin på nytt for å fullføre</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Feil ved lasting av wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Ugyldig -proxy adresse: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Ukjent nettverk angitt i -onlynet &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Ukjent -socks proxy versjon angitt: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Kunne ikke slå opp -bind adresse: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Kunne ikke slå opp -externalip adresse: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ugyldig beløp for -paytxfee=&lt;beløp&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Ugyldig beløp</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Utilstrekkelige midler</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Laster blokkindeks...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Legg til node for tilkobling og hold forbindelsen åpen</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Bitcoin is probably already running.</source> <translation>Kan ikke binde til %s på denne datamaskinen. Sannsynligvis kjører Bitcoin allerede.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Gebyr per KB for transaksjoner du sender</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Laster lommebok...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Kan ikke nedgradere lommebok</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Kan ikke skrive standardadresse</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Leser gjennom...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Ferdig med lasting</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>For å bruke %s opsjonen</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Feil</translation> </message> <message> <location line="-31"/> <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>Du må sette rpcpassword=&lt;passord&gt; i konfigurasjonsfilen: %s Hvis filen ikke finnes, opprett den med leserettighet kun for eier av filen.</translation> </message> </context> </TS>
{ "content_hash": "95587de4d1c34a3f39ad19e2474365a6", "timestamp": "", "source": "github", "line_count": 2938, "max_line_length": 411, "avg_line_length": 38.44213750850919, "alnum_prop": 0.6262893672029254, "repo_name": "memorycoin/memorycoin", "id": "71354d8add8d1dd149771d2d9a097f5d1386c8ed", "size": "113173", "binary": false, "copies": "1", "ref": "refs/heads/psforkinit", "path": "src/qt/locale/bitcoin_nb.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "31173" }, { "name": "C++", "bytes": "2752100" }, { "name": "CMake", "bytes": "11458" }, { "name": "CSS", "bytes": "1127" }, { "name": "Groff", "bytes": "18284" }, { "name": "HTML", "bytes": "50615" }, { "name": "Makefile", "bytes": "12919" }, { "name": "NSIS", "bytes": "6155" }, { "name": "Objective-C", "bytes": "1138" }, { "name": "Objective-C++", "bytes": "3817" }, { "name": "Python", "bytes": "67649" }, { "name": "QMake", "bytes": "27706" }, { "name": "Shell", "bytes": "13688" }, { "name": "TypeScript", "bytes": "546556" } ], "symlink_target": "" }